diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..3cb5c25 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,349 @@ +Copyright (c) 2015 Kinvey Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +in compliance with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under the License +is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +or implied. See the License for the specific language governing permissions and limitations under +the License. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + +Summary + + >>> coffee-script-1.7.1 [MIT-style] - CoffeeScript library + >>> config-0.4.36 [MIT-style] - Library for managing configurations + >>> async-0.9.0 [MIT-Style] - used to provide an asynchronous library + >>> mocha [MIT-style] - unit testing framework + >>> should [MIT-style] - assertions framework + >>> coffeelint [MIT-style] - Linter for CoffeeScript + +SECTION 1: BSD-STYLE, MIT-STYLE, OR SIMILAR STYLE LICENSES + +>>> coffee-script-1.7.1 +>>> config-0.4.36 +>>> async-0.9.0 +>>> mocha +>>> should +>>> coffeelint + +--------------- SECTION 1: BSD-STYLE, MIT-STYLE, OR SIMILAR STYLE LICENSES ---------- +BSD-STYLE, MIT-STYLE, OR SIMILAR STYLE is applicable to the following component(s). + +>>> coffee-script-1.7.1 + + Copyright (c) 2009-2015 Jeremy Ashkenas + + 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. + +>>> config-0.4.36 + +// Copyright 2010-2015, Loren West and other contributors + +// 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. + +>>> async-0.9.0 + +Copyright (c) 2010-2014 Caolan McMahon + +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. + +>>> mocha + +(The MIT License) + +Copyright (c) 2011-2015 TJ Holowaychuk + +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. + +>>> should + +Copyright (c) 2010-2014 TJ Holowaychuk + +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. + +>>> coffeelint + +CoffeeLint +Copyright (c) 2011 Matthew Perpick + +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/lib/receiver.coffee b/lib/receiver.coffee index 1f16486..278cfe4 100644 --- a/lib/receiver.coffee +++ b/lib/receiver.coffee @@ -1,15 +1,14 @@ -# Copyright (c) 2015, Kinvey, Inc. All rights reserved. +# Copyright (c) 2015 Kinvey Inc. # -# This software is licensed to you under the Kinvey terms of service located at -# http://www.kinvey.com/terms-of-use. By downloading, accessing and/or using this -# software, you hereby accept such terms of service (and any agreement referenced -# therein) and agree that you have read, understand and agree to be bound by such -# terms of service and are of legal age to agree to such terms with Kinvey. +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# This software contains valuable confidential and proprietary information of -# KINVEY, INC and is subject to applicable licensing agreements. -# Unauthorized reproduction, transmission or distribution of this file and its -# contents is a violation of applicable laws. +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. receiver = require './receivers/tcpReceiver' diff --git a/lib/receivers/tcpReceiver.coffee b/lib/receivers/tcpReceiver.coffee index 6e829d8..2ded0e5 100644 --- a/lib/receivers/tcpReceiver.coffee +++ b/lib/receivers/tcpReceiver.coffee @@ -1,15 +1,14 @@ -# Copyright (c) 2014, Kinvey, Inc. All rights reserved. +# Copyright (c) 2015 Kinvey Inc. # -# This software is licensed to you under the Kinvey terms of service located at -# http://www.kinvey.com/terms-of-use. By downloading, accessing and/or using this -# software, you hereby accept such terms of service (and any agreement referenced -# therein) and agree that you have read, understand and agree to be bound by such -# terms of service and are of legal age to agree to such terms with Kinvey. +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at # -# This software contains valuable confidential and proprietary information of -# KINVEY, INC and is subject to applicable licensing agreements. -# Unauthorized reproduction, transmission or distribution of this file and its -# contents is a violation of applicable laws. +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. net = require 'net' config = require 'config' diff --git a/node_modules/.bin/_mocha b/node_modules/.bin/_mocha deleted file mode 120000 index f2a54ff..0000000 --- a/node_modules/.bin/_mocha +++ /dev/null @@ -1 +0,0 @@ -../mocha/bin/_mocha \ No newline at end of file diff --git a/node_modules/.bin/cake b/node_modules/.bin/cake deleted file mode 120000 index d95f32a..0000000 --- a/node_modules/.bin/cake +++ /dev/null @@ -1 +0,0 @@ -../coffee-script/bin/cake \ No newline at end of file diff --git a/node_modules/.bin/coffee b/node_modules/.bin/coffee deleted file mode 120000 index b57f275..0000000 --- a/node_modules/.bin/coffee +++ /dev/null @@ -1 +0,0 @@ -../coffee-script/bin/coffee \ No newline at end of file diff --git a/node_modules/.bin/coffeelint b/node_modules/.bin/coffeelint deleted file mode 120000 index 26121d1..0000000 --- a/node_modules/.bin/coffeelint +++ /dev/null @@ -1 +0,0 @@ -../coffeelint/bin/coffeelint \ No newline at end of file diff --git a/node_modules/.bin/mocha b/node_modules/.bin/mocha deleted file mode 120000 index 43c668d..0000000 --- a/node_modules/.bin/mocha +++ /dev/null @@ -1 +0,0 @@ -../mocha/bin/mocha \ No newline at end of file diff --git a/node_modules/async/.travis.yml b/node_modules/async/.travis.yml deleted file mode 100644 index 6e5919d..0000000 --- a/node_modules/async/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: node_js -node_js: - - "0.10" diff --git a/node_modules/async/LICENSE b/node_modules/async/LICENSE deleted file mode 100644 index 8f29698..0000000 --- a/node_modules/async/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010-2014 Caolan McMahon - -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/node_modules/async/README.md b/node_modules/async/README.md deleted file mode 100644 index 0bea531..0000000 --- a/node_modules/async/README.md +++ /dev/null @@ -1,1646 +0,0 @@ -# Async.js - -[![Build Status via Travis CI](https://travis-ci.org/caolan/async.svg?branch=master)](https://travis-ci.org/caolan/async) - - -Async is a utility module which provides straight-forward, powerful functions -for working with asynchronous JavaScript. Although originally designed for -use with [Node.js](http://nodejs.org), it can also be used directly in the -browser. Also supports [component](https://github.com/component/component). - -Async provides around 20 functions that include the usual 'functional' -suspects (`map`, `reduce`, `filter`, `each`…) as well as some common patterns -for asynchronous control flow (`parallel`, `series`, `waterfall`…). All these -functions assume you follow the Node.js convention of providing a single -callback as the last argument of your `async` function. - - -## Quick Examples - -```javascript -async.map(['file1','file2','file3'], fs.stat, function(err, results){ - // results is now an array of stats for each file -}); - -async.filter(['file1','file2','file3'], fs.exists, function(results){ - // results now equals an array of the existing files -}); - -async.parallel([ - function(){ ... }, - function(){ ... } -], callback); - -async.series([ - function(){ ... }, - function(){ ... } -]); -``` - -There are many more functions available so take a look at the docs below for a -full list. This module aims to be comprehensive, so if you feel anything is -missing please create a GitHub issue for it. - -## Common Pitfalls - -### Binding a context to an iterator - -This section is really about `bind`, not about `async`. If you are wondering how to -make `async` execute your iterators in a given context, or are confused as to why -a method of another library isn't working as an iterator, study this example: - -```js -// Here is a simple object with an (unnecessarily roundabout) squaring method -var AsyncSquaringLibrary = { - squareExponent: 2, - square: function(number, callback){ - var result = Math.pow(number, this.squareExponent); - setTimeout(function(){ - callback(null, result); - }, 200); - } -}; - -async.map([1, 2, 3], AsyncSquaringLibrary.square, function(err, result){ - // result is [NaN, NaN, NaN] - // This fails because the `this.squareExponent` expression in the square - // function is not evaluated in the context of AsyncSquaringLibrary, and is - // therefore undefined. -}); - -async.map([1, 2, 3], AsyncSquaringLibrary.square.bind(AsyncSquaringLibrary), function(err, result){ - // result is [1, 4, 9] - // With the help of bind we can attach a context to the iterator before - // passing it to async. Now the square function will be executed in its - // 'home' AsyncSquaringLibrary context and the value of `this.squareExponent` - // will be as expected. -}); -``` - -## Download - -The source is available for download from -[GitHub](http://github.com/caolan/async). -Alternatively, you can install using Node Package Manager (`npm`): - - npm install async - -__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 29.6kb Uncompressed - -## In the Browser - -So far it's been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. - -Usage: - -```html - - -``` - -## Documentation - -### Collections - -* [`each`](#each) -* [`eachSeries`](#eachSeries) -* [`eachLimit`](#eachLimit) -* [`map`](#map) -* [`mapSeries`](#mapSeries) -* [`mapLimit`](#mapLimit) -* [`filter`](#filter) -* [`filterSeries`](#filterSeries) -* [`reject`](#reject) -* [`rejectSeries`](#rejectSeries) -* [`reduce`](#reduce) -* [`reduceRight`](#reduceRight) -* [`detect`](#detect) -* [`detectSeries`](#detectSeries) -* [`sortBy`](#sortBy) -* [`some`](#some) -* [`every`](#every) -* [`concat`](#concat) -* [`concatSeries`](#concatSeries) - -### Control Flow - -* [`series`](#seriestasks-callback) -* [`parallel`](#parallel) -* [`parallelLimit`](#parallellimittasks-limit-callback) -* [`whilst`](#whilst) -* [`doWhilst`](#doWhilst) -* [`until`](#until) -* [`doUntil`](#doUntil) -* [`forever`](#forever) -* [`waterfall`](#waterfall) -* [`compose`](#compose) -* [`seq`](#seq) -* [`applyEach`](#applyEach) -* [`applyEachSeries`](#applyEachSeries) -* [`queue`](#queue) -* [`priorityQueue`](#priorityQueue) -* [`cargo`](#cargo) -* [`auto`](#auto) -* [`retry`](#retry) -* [`iterator`](#iterator) -* [`apply`](#apply) -* [`nextTick`](#nextTick) -* [`times`](#times) -* [`timesSeries`](#timesSeries) - -### Utils - -* [`memoize`](#memoize) -* [`unmemoize`](#unmemoize) -* [`log`](#log) -* [`dir`](#dir) -* [`noConflict`](#noConflict) - - -## Collections - - - -### each(arr, iterator, callback) - -Applies the function `iterator` to each item in `arr`, in parallel. -The `iterator` is called with an item from the list, and a callback for when it -has finished. If the `iterator` passes an error to its `callback`, the main -`callback` (for the `each` function) is immediately called with the error. - -Note, that since this function applies `iterator` to each item in parallel, -there is no guarantee that the iterator functions will complete in order. - -__Arguments__ - -* `arr` - An array to iterate over. -* `iterator(item, callback)` - A function to apply to each item in `arr`. - The iterator is passed a `callback(err)` which must be called once it has - completed. If no error has occured, the `callback` should be run without - arguments or with an explicit `null` argument. -* `callback(err)` - A callback which is called when all `iterator` functions - have finished, or an error occurs. - -__Examples__ - - -```js -// assuming openFiles is an array of file names and saveFile is a function -// to save the modified contents of that file: - -async.each(openFiles, saveFile, function(err){ - // if any of the saves produced an error, err would equal that error -}); -``` - -```js -// assuming openFiles is an array of file names - -async.each(openFiles, function( file, callback) { - - // Perform operation on file here. - console.log('Processing file ' + file); - - if( file.length > 32 ) { - console.log('This file name is too long'); - callback('File name too long'); - } else { - // Do work to process file here - console.log('File processed'); - callback(); - } -}, function(err){ - // if any of the file processing produced an error, err would equal that error - if( err ) { - // One of the iterations produced an error. - // All processing will now stop. - console.log('A file failed to process'); - } else { - console.log('All files have been processed successfully'); - } -}); -``` - ---------------------------------------- - - - -### eachSeries(arr, iterator, callback) - -The same as [`each`](#each), only `iterator` is applied to each item in `arr` in -series. The next `iterator` is only called once the current one has completed. -This means the `iterator` functions will complete in order. - - ---------------------------------------- - - - -### eachLimit(arr, limit, iterator, callback) - -The same as [`each`](#each), only no more than `limit` `iterator`s will be simultaneously -running at any time. - -Note that the items in `arr` are not processed in batches, so there is no guarantee that -the first `limit` `iterator` functions will complete before any others are started. - -__Arguments__ - -* `arr` - An array to iterate over. -* `limit` - The maximum number of `iterator`s to run at any time. -* `iterator(item, callback)` - A function to apply to each item in `arr`. - The iterator is passed a `callback(err)` which must be called once it has - completed. If no error has occured, the callback should be run without - arguments or with an explicit `null` argument. -* `callback(err)` - A callback which is called when all `iterator` functions - have finished, or an error occurs. - -__Example__ - -```js -// Assume documents is an array of JSON objects and requestApi is a -// function that interacts with a rate-limited REST api. - -async.eachLimit(documents, 20, requestApi, function(err){ - // if any of the saves produced an error, err would equal that error -}); -``` - ---------------------------------------- - - -### map(arr, iterator, callback) - -Produces a new array of values by mapping each value in `arr` through -the `iterator` function. The `iterator` is called with an item from `arr` and a -callback for when it has finished processing. Each of these callback takes 2 arguments: -an `error`, and the transformed item from `arr`. If `iterator` passes an error to this -callback, the main `callback` (for the `map` function) is immediately called with the error. - -Note, that since this function applies the `iterator` to each item in parallel, -there is no guarantee that the `iterator` functions will complete in order. -However, the results array will be in the same order as the original `arr`. - -__Arguments__ - -* `arr` - An array to iterate over. -* `iterator(item, callback)` - A function to apply to each item in `arr`. - The iterator is passed a `callback(err, transformed)` which must be called once - it has completed with an error (which can be `null`) and a transformed item. -* `callback(err, results)` - A callback which is called when all `iterator` - functions have finished, or an error occurs. Results is an array of the - transformed items from the `arr`. - -__Example__ - -```js -async.map(['file1','file2','file3'], fs.stat, function(err, results){ - // results is now an array of stats for each file -}); -``` - ---------------------------------------- - - -### mapSeries(arr, iterator, callback) - -The same as [`map`](#map), only the `iterator` is applied to each item in `arr` in -series. The next `iterator` is only called once the current one has completed. -The results array will be in the same order as the original. - - ---------------------------------------- - - -### mapLimit(arr, limit, iterator, callback) - -The same as [`map`](#map), only no more than `limit` `iterator`s will be simultaneously -running at any time. - -Note that the items are not processed in batches, so there is no guarantee that -the first `limit` `iterator` functions will complete before any others are started. - -__Arguments__ - -* `arr` - An array to iterate over. -* `limit` - The maximum number of `iterator`s to run at any time. -* `iterator(item, callback)` - A function to apply to each item in `arr`. - The iterator is passed a `callback(err, transformed)` which must be called once - it has completed with an error (which can be `null`) and a transformed item. -* `callback(err, results)` - A callback which is called when all `iterator` - calls have finished, or an error occurs. The result is an array of the - transformed items from the original `arr`. - -__Example__ - -```js -async.mapLimit(['file1','file2','file3'], 1, fs.stat, function(err, results){ - // results is now an array of stats for each file -}); -``` - ---------------------------------------- - - - -### filter(arr, iterator, callback) - -__Alias:__ `select` - -Returns a new array of all the values in `arr` which pass an async truth test. -_The callback for each `iterator` call only accepts a single argument of `true` or -`false`; it does not accept an error argument first!_ This is in-line with the -way node libraries work with truth tests like `fs.exists`. This operation is -performed in parallel, but the results array will be in the same order as the -original. - -__Arguments__ - -* `arr` - An array to iterate over. -* `iterator(item, callback)` - A truth test to apply to each item in `arr`. - The `iterator` is passed a `callback(truthValue)`, which must be called with a - boolean argument once it has completed. -* `callback(results)` - A callback which is called after all the `iterator` - functions have finished. - -__Example__ - -```js -async.filter(['file1','file2','file3'], fs.exists, function(results){ - // results now equals an array of the existing files -}); -``` - ---------------------------------------- - - - -### filterSeries(arr, iterator, callback) - -__Alias:__ `selectSeries` - -The same as [`filter`](#filter) only the `iterator` is applied to each item in `arr` in -series. The next `iterator` is only called once the current one has completed. -The results array will be in the same order as the original. - ---------------------------------------- - - -### reject(arr, iterator, callback) - -The opposite of [`filter`](#filter). Removes values that pass an `async` truth test. - ---------------------------------------- - - -### rejectSeries(arr, iterator, callback) - -The same as [`reject`](#reject), only the `iterator` is applied to each item in `arr` -in series. - - ---------------------------------------- - - -### reduce(arr, memo, iterator, callback) - -__Aliases:__ `inject`, `foldl` - -Reduces `arr` into a single value using an async `iterator` to return -each successive step. `memo` is the initial state of the reduction. -This function only operates in series. - -For performance reasons, it may make sense to split a call to this function into -a parallel map, and then use the normal `Array.prototype.reduce` on the results. -This function is for situations where each step in the reduction needs to be async; -if you can get the data before reducing it, then it's probably a good idea to do so. - -__Arguments__ - -* `arr` - An array to iterate over. -* `memo` - The initial state of the reduction. -* `iterator(memo, item, callback)` - A function applied to each item in the - array to produce the next step in the reduction. The `iterator` is passed a - `callback(err, reduction)` which accepts an optional error as its first - argument, and the state of the reduction as the second. If an error is - passed to the callback, the reduction is stopped and the main `callback` is - immediately called with the error. -* `callback(err, result)` - A callback which is called after all the `iterator` - functions have finished. Result is the reduced value. - -__Example__ - -```js -async.reduce([1,2,3], 0, function(memo, item, callback){ - // pointless async: - process.nextTick(function(){ - callback(null, memo + item) - }); -}, function(err, result){ - // result is now equal to the last value of memo, which is 6 -}); -``` - ---------------------------------------- - - -### reduceRight(arr, memo, iterator, callback) - -__Alias:__ `foldr` - -Same as [`reduce`](#reduce), only operates on `arr` in reverse order. - - ---------------------------------------- - - -### detect(arr, iterator, callback) - -Returns the first value in `arr` that passes an async truth test. The -`iterator` is applied in parallel, meaning the first iterator to return `true` will -fire the detect `callback` with that result. That means the result might not be -the first item in the original `arr` (in terms of order) that passes the test. - -If order within the original `arr` is important, then look at [`detectSeries`](#detectSeries). - -__Arguments__ - -* `arr` - An array to iterate over. -* `iterator(item, callback)` - A truth test to apply to each item in `arr`. - The iterator is passed a `callback(truthValue)` which must be called with a - boolean argument once it has completed. -* `callback(result)` - A callback which is called as soon as any iterator returns - `true`, or after all the `iterator` functions have finished. Result will be - the first item in the array that passes the truth test (iterator) or the - value `undefined` if none passed. - -__Example__ - -```js -async.detect(['file1','file2','file3'], fs.exists, function(result){ - // result now equals the first file in the list that exists -}); -``` - ---------------------------------------- - - -### detectSeries(arr, iterator, callback) - -The same as [`detect`](#detect), only the `iterator` is applied to each item in `arr` -in series. This means the result is always the first in the original `arr` (in -terms of array order) that passes the truth test. - - ---------------------------------------- - - -### sortBy(arr, iterator, callback) - -Sorts a list by the results of running each `arr` value through an async `iterator`. - -__Arguments__ - -* `arr` - An array to iterate over. -* `iterator(item, callback)` - A function to apply to each item in `arr`. - The iterator is passed a `callback(err, sortValue)` which must be called once it - has completed with an error (which can be `null`) and a value to use as the sort - criteria. -* `callback(err, results)` - A callback which is called after all the `iterator` - functions have finished, or an error occurs. Results is the items from - the original `arr` sorted by the values returned by the `iterator` calls. - -__Example__ - -```js -async.sortBy(['file1','file2','file3'], function(file, callback){ - fs.stat(file, function(err, stats){ - callback(err, stats.mtime); - }); -}, function(err, results){ - // results is now the original array of files sorted by - // modified date -}); -``` - -__Sort Order__ - -By modifying the callback parameter the sorting order can be influenced: - -```js -//ascending order -async.sortBy([1,9,3,5], function(x, callback){ - callback(err, x); -}, function(err,result){ - //result callback -} ); - -//descending order -async.sortBy([1,9,3,5], function(x, callback){ - callback(err, x*-1); //<- x*-1 instead of x, turns the order around -}, function(err,result){ - //result callback -} ); -``` - ---------------------------------------- - - -### some(arr, iterator, callback) - -__Alias:__ `any` - -Returns `true` if at least one element in the `arr` satisfies an async test. -_The callback for each iterator call only accepts a single argument of `true` or -`false`; it does not accept an error argument first!_ This is in-line with the -way node libraries work with truth tests like `fs.exists`. Once any iterator -call returns `true`, the main `callback` is immediately called. - -__Arguments__ - -* `arr` - An array to iterate over. -* `iterator(item, callback)` - A truth test to apply to each item in the array - in parallel. The iterator is passed a callback(truthValue) which must be - called with a boolean argument once it has completed. -* `callback(result)` - A callback which is called as soon as any iterator returns - `true`, or after all the iterator functions have finished. Result will be - either `true` or `false` depending on the values of the async tests. - -__Example__ - -```js -async.some(['file1','file2','file3'], fs.exists, function(result){ - // if result is true then at least one of the files exists -}); -``` - ---------------------------------------- - - -### every(arr, iterator, callback) - -__Alias:__ `all` - -Returns `true` if every element in `arr` satisfies an async test. -_The callback for each `iterator` call only accepts a single argument of `true` or -`false`; it does not accept an error argument first!_ This is in-line with the -way node libraries work with truth tests like `fs.exists`. - -__Arguments__ - -* `arr` - An array to iterate over. -* `iterator(item, callback)` - A truth test to apply to each item in the array - in parallel. The iterator is passed a callback(truthValue) which must be - called with a boolean argument once it has completed. -* `callback(result)` - A callback which is called after all the `iterator` - functions have finished. Result will be either `true` or `false` depending on - the values of the async tests. - -__Example__ - -```js -async.every(['file1','file2','file3'], fs.exists, function(result){ - // if result is true then every file exists -}); -``` - ---------------------------------------- - - -### concat(arr, iterator, callback) - -Applies `iterator` to each item in `arr`, concatenating the results. Returns the -concatenated list. The `iterator`s are called in parallel, and the results are -concatenated as they return. There is no guarantee that the results array will -be returned in the original order of `arr` passed to the `iterator` function. - -__Arguments__ - -* `arr` - An array to iterate over. -* `iterator(item, callback)` - A function to apply to each item in `arr`. - The iterator is passed a `callback(err, results)` which must be called once it - has completed with an error (which can be `null`) and an array of results. -* `callback(err, results)` - A callback which is called after all the `iterator` - functions have finished, or an error occurs. Results is an array containing - the concatenated results of the `iterator` function. - -__Example__ - -```js -async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){ - // files is now a list of filenames that exist in the 3 directories -}); -``` - ---------------------------------------- - - -### concatSeries(arr, iterator, callback) - -Same as [`concat`](#concat), but executes in series instead of parallel. - - -## Control Flow - - -### series(tasks, [callback]) - -Run the functions in the `tasks` array in series, each one running once the previous -function has completed. If any functions in the series pass an error to its -callback, no more functions are run, and `callback` is immediately called with the value of the error. -Otherwise, `callback` receives an array of results when `tasks` have completed. - -It is also possible to use an object instead of an array. Each property will be -run as a function, and the results will be passed to the final `callback` as an object -instead of an array. This can be a more readable way of handling results from -[`series`](#series). - -**Note** that while many implementations preserve the order of object properties, the -[ECMAScript Language Specifcation](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) -explicitly states that - -> The mechanics and order of enumerating the properties is not specified. - -So if you rely on the order in which your series of functions are executed, and want -this to work on all platforms, consider using an array. - -__Arguments__ - -* `tasks` - An array or object containing functions to run, each function is passed - a `callback(err, result)` it must call on completion with an error `err` (which can - be `null`) and an optional `result` value. -* `callback(err, results)` - An optional callback to run once all the functions - have completed. This function gets a results array (or object) containing all - the result arguments passed to the `task` callbacks. - -__Example__ - -```js -async.series([ - function(callback){ - // do some stuff ... - callback(null, 'one'); - }, - function(callback){ - // do some more stuff ... - callback(null, 'two'); - } -], -// optional callback -function(err, results){ - // results is now equal to ['one', 'two'] -}); - - -// an example using an object instead of an array -async.series({ - one: function(callback){ - setTimeout(function(){ - callback(null, 1); - }, 200); - }, - two: function(callback){ - setTimeout(function(){ - callback(null, 2); - }, 100); - } -}, -function(err, results) { - // results is now equal to: {one: 1, two: 2} -}); -``` - ---------------------------------------- - - -### parallel(tasks, [callback]) - -Run the `tasks` array of functions in parallel, without waiting until the previous -function has completed. If any of the functions pass an error to its -callback, the main `callback` is immediately called with the value of the error. -Once the `tasks` have completed, the results are passed to the final `callback` as an -array. - -It is also possible to use an object instead of an array. Each property will be -run as a function and the results will be passed to the final `callback` as an object -instead of an array. This can be a more readable way of handling results from -[`parallel`](#parallel). - - -__Arguments__ - -* `tasks` - An array or object containing functions to run. Each function is passed - a `callback(err, result)` which it must call on completion with an error `err` - (which can be `null`) and an optional `result` value. -* `callback(err, results)` - An optional callback to run once all the functions - have completed. This function gets a results array (or object) containing all - the result arguments passed to the task callbacks. - -__Example__ - -```js -async.parallel([ - function(callback){ - setTimeout(function(){ - callback(null, 'one'); - }, 200); - }, - function(callback){ - setTimeout(function(){ - callback(null, 'two'); - }, 100); - } -], -// optional callback -function(err, results){ - // the results array will equal ['one','two'] even though - // the second function had a shorter timeout. -}); - - -// an example using an object instead of an array -async.parallel({ - one: function(callback){ - setTimeout(function(){ - callback(null, 1); - }, 200); - }, - two: function(callback){ - setTimeout(function(){ - callback(null, 2); - }, 100); - } -}, -function(err, results) { - // results is now equals to: {one: 1, two: 2} -}); -``` - ---------------------------------------- - - -### parallelLimit(tasks, limit, [callback]) - -The same as [`parallel`](#parallel), only `tasks` are executed in parallel -with a maximum of `limit` tasks executing at any time. - -Note that the `tasks` are not executed in batches, so there is no guarantee that -the first `limit` tasks will complete before any others are started. - -__Arguments__ - -* `tasks` - An array or object containing functions to run, each function is passed - a `callback(err, result)` it must call on completion with an error `err` (which can - be `null`) and an optional `result` value. -* `limit` - The maximum number of `tasks` to run at any time. -* `callback(err, results)` - An optional callback to run once all the functions - have completed. This function gets a results array (or object) containing all - the result arguments passed to the `task` callbacks. - ---------------------------------------- - - -### whilst(test, fn, callback) - -Repeatedly call `fn`, while `test` returns `true`. Calls `callback` when stopped, -or an error occurs. - -__Arguments__ - -* `test()` - synchronous truth test to perform before each execution of `fn`. -* `fn(callback)` - A function which is called each time `test` passes. The function is - passed a `callback(err)`, which must be called once it has completed with an - optional `err` argument. -* `callback(err)` - A callback which is called after the test fails and repeated - execution of `fn` has stopped. - -__Example__ - -```js -var count = 0; - -async.whilst( - function () { return count < 5; }, - function (callback) { - count++; - setTimeout(callback, 1000); - }, - function (err) { - // 5 seconds have passed - } -); -``` - ---------------------------------------- - - -### doWhilst(fn, test, callback) - -The post-check version of [`whilst`](#whilst). To reflect the difference in -the order of operations, the arguments `test` and `fn` are switched. - -`doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - ---------------------------------------- - - -### until(test, fn, callback) - -Repeatedly call `fn` until `test` returns `true`. Calls `callback` when stopped, -or an error occurs. - -The inverse of [`whilst`](#whilst). - ---------------------------------------- - - -### doUntil(fn, test, callback) - -Like [`doWhilst`](#doWhilst), except the `test` is inverted. Note the argument ordering differs from `until`. - ---------------------------------------- - - -### forever(fn, errback) - -Calls the asynchronous function `fn` with a callback parameter that allows it to -call itself again, in series, indefinitely. - -If an error is passed to the callback then `errback` is called with the -error, and execution stops, otherwise it will never be called. - -```js -async.forever( - function(next) { - // next is suitable for passing to things that need a callback(err [, whatever]); - // it will result in this function being called again. - }, - function(err) { - // if next is called with a value in its first parameter, it will appear - // in here as 'err', and execution will stop. - } -); -``` - ---------------------------------------- - - -### waterfall(tasks, [callback]) - -Runs the `tasks` array of functions in series, each passing their results to the next in -the array. However, if any of the `tasks` pass an error to their own callback, the -next function is not executed, and the main `callback` is immediately called with -the error. - -__Arguments__ - -* `tasks` - An array of functions to run, each function is passed a - `callback(err, result1, result2, ...)` it must call on completion. The first - argument is an error (which can be `null`) and any further arguments will be - passed as arguments in order to the next task. -* `callback(err, [results])` - An optional callback to run once all the functions - have completed. This will be passed the results of the last task's callback. - - - -__Example__ - -```js -async.waterfall([ - function(callback){ - callback(null, 'one', 'two'); - }, - function(arg1, arg2, callback){ - // arg1 now equals 'one' and arg2 now equals 'two' - callback(null, 'three'); - }, - function(arg1, callback){ - // arg1 now equals 'three' - callback(null, 'done'); - } -], function (err, result) { - // result now equals 'done' -}); -``` - ---------------------------------------- - -### compose(fn1, fn2...) - -Creates a function which is a composition of the passed asynchronous -functions. Each function consumes the return value of the function that -follows. Composing functions `f()`, `g()`, and `h()` would produce the result of -`f(g(h()))`, only this version uses callbacks to obtain the return values. - -Each function is executed with the `this` binding of the composed function. - -__Arguments__ - -* `functions...` - the asynchronous functions to compose - - -__Example__ - -```js -function add1(n, callback) { - setTimeout(function () { - callback(null, n + 1); - }, 10); -} - -function mul3(n, callback) { - setTimeout(function () { - callback(null, n * 3); - }, 10); -} - -var add1mul3 = async.compose(mul3, add1); - -add1mul3(4, function (err, result) { - // result now equals 15 -}); -``` - ---------------------------------------- - -### seq(fn1, fn2...) - -Version of the compose function that is more natural to read. -Each following function consumes the return value of the latter function. - -Each function is executed with the `this` binding of the composed function. - -__Arguments__ - -* functions... - the asynchronous functions to compose - - -__Example__ - -```js -// Requires lodash (or underscore), express3 and dresende's orm2. -// Part of an app, that fetches cats of the logged user. -// This example uses `seq` function to avoid overnesting and error -// handling clutter. -app.get('/cats', function(request, response) { - function handleError(err, data, callback) { - if (err) { - console.error(err); - response.json({ status: 'error', message: err.message }); - } - else { - callback(data); - } - } - var User = request.models.User; - async.seq( - _.bind(User.get, User), // 'User.get' has signature (id, callback(err, data)) - handleError, - function(user, fn) { - user.getCats(fn); // 'getCats' has signature (callback(err, data)) - }, - handleError, - function(cats) { - response.json({ status: 'ok', message: 'Cats found', data: cats }); - } - )(req.session.user_id); - } -}); -``` - ---------------------------------------- - -### applyEach(fns, args..., callback) - -Applies the provided arguments to each function in the array, calling -`callback` after all functions have completed. If you only provide the first -argument, then it will return a function which lets you pass in the -arguments as if it were a single function call. - -__Arguments__ - -* `fns` - the asynchronous functions to all call with the same arguments -* `args...` - any number of separate arguments to pass to the function -* `callback` - the final argument should be the callback, called when all - functions have completed processing - - -__Example__ - -```js -async.applyEach([enableSearch, updateSchema], 'bucket', callback); - -// partial application example: -async.each( - buckets, - async.applyEach([enableSearch, updateSchema]), - callback -); -``` - ---------------------------------------- - - -### applyEachSeries(arr, iterator, callback) - -The same as [`applyEach`](#applyEach) only the functions are applied in series. - ---------------------------------------- - - -### queue(worker, concurrency) - -Creates a `queue` object with the specified `concurrency`. Tasks added to the -`queue` are processed in parallel (up to the `concurrency` limit). If all -`worker`s are in progress, the task is queued until one becomes available. -Once a `worker` completes a `task`, that `task`'s callback is called. - -__Arguments__ - -* `worker(task, callback)` - An asynchronous function for processing a queued - task, which must call its `callback(err)` argument when finished, with an - optional `error` as an argument. -* `concurrency` - An `integer` for determining how many `worker` functions should be - run in parallel. - -__Queue objects__ - -The `queue` object returned by this function has the following properties and -methods: - -* `length()` - a function returning the number of items waiting to be processed. -* `started` - a function returning whether or not any items have been pushed and processed by the queue -* `running()` - a function returning the number of items currently being processed. -* `idle()` - a function returning false if there are items waiting or being processed, or true if not. -* `concurrency` - an integer for determining how many `worker` functions should be - run in parallel. This property can be changed after a `queue` is created to - alter the concurrency on-the-fly. -* `push(task, [callback])` - add a new task to the `queue`. Calls `callback` once - the `worker` has finished processing the task. Instead of a single task, a `tasks` array - can be submitted. The respective callback is used for every task in the list. -* `unshift(task, [callback])` - add a new task to the front of the `queue`. -* `saturated` - a callback that is called when the `queue` length hits the `concurrency` limit, - and further tasks will be queued. -* `empty` - a callback that is called when the last item from the `queue` is given to a `worker`. -* `drain` - a callback that is called when the last item from the `queue` has returned from the `worker`. -* `paused` - a boolean for determining whether the queue is in a paused state -* `pause()` - a function that pauses the processing of tasks until `resume()` is called. -* `resume()` - a function that resumes the processing of queued tasks when the queue is paused. -* `kill()` - a function that empties remaining tasks from the queue forcing it to go idle. - -__Example__ - -```js -// create a queue object with concurrency 2 - -var q = async.queue(function (task, callback) { - console.log('hello ' + task.name); - callback(); -}, 2); - - -// assign a callback -q.drain = function() { - console.log('all items have been processed'); -} - -// add some items to the queue - -q.push({name: 'foo'}, function (err) { - console.log('finished processing foo'); -}); -q.push({name: 'bar'}, function (err) { - console.log('finished processing bar'); -}); - -// add some items to the queue (batch-wise) - -q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) { - console.log('finished processing bar'); -}); - -// add some items to the front of the queue - -q.unshift({name: 'bar'}, function (err) { - console.log('finished processing bar'); -}); -``` - - ---------------------------------------- - - -### priorityQueue(worker, concurrency) - -The same as [`queue`](#queue) only tasks are assigned a priority and completed in ascending priority order. There are two differences between `queue` and `priorityQueue` objects: - -* `push(task, priority, [callback])` - `priority` should be a number. If an array of - `tasks` is given, all tasks will be assigned the same priority. -* The `unshift` method was removed. - ---------------------------------------- - - -### cargo(worker, [payload]) - -Creates a `cargo` object with the specified payload. Tasks added to the -cargo will be processed altogether (up to the `payload` limit). If the -`worker` is in progress, the task is queued until it becomes available. Once -the `worker` has completed some tasks, each callback of those tasks is called. -Check out [this animation](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) for how `cargo` and `queue` work. - -While [queue](#queue) passes only one task to one of a group of workers -at a time, cargo passes an array of tasks to a single worker, repeating -when the worker is finished. - -__Arguments__ - -* `worker(tasks, callback)` - An asynchronous function for processing an array of - queued tasks, which must call its `callback(err)` argument when finished, with - an optional `err` argument. -* `payload` - An optional `integer` for determining how many tasks should be - processed per round; if omitted, the default is unlimited. - -__Cargo objects__ - -The `cargo` object returned by this function has the following properties and -methods: - -* `length()` - A function returning the number of items waiting to be processed. -* `payload` - An `integer` for determining how many tasks should be - process per round. This property can be changed after a `cargo` is created to - alter the payload on-the-fly. -* `push(task, [callback])` - Adds `task` to the `queue`. The callback is called - once the `worker` has finished processing the task. Instead of a single task, an array of `tasks` - can be submitted. The respective callback is used for every task in the list. -* `saturated` - A callback that is called when the `queue.length()` hits the concurrency and further tasks will be queued. -* `empty` - A callback that is called when the last item from the `queue` is given to a `worker`. -* `drain` - A callback that is called when the last item from the `queue` has returned from the `worker`. - -__Example__ - -```js -// create a cargo object with payload 2 - -var cargo = async.cargo(function (tasks, callback) { - for(var i=0; i -### auto(tasks, [callback]) - -Determines the best order for running the functions in `tasks`, based on their -requirements. Each function can optionally depend on other functions being completed -first, and each function is run as soon as its requirements are satisfied. - -If any of the functions pass an error to their callback, it will not -complete (so any other functions depending on it will not run), and the main -`callback` is immediately called with the error. Functions also receive an -object containing the results of functions which have completed so far. - -Note, all functions are called with a `results` object as a second argument, -so it is unsafe to pass functions in the `tasks` object which cannot handle the -extra argument. - -For example, this snippet of code: - -```js -async.auto({ - readData: async.apply(fs.readFile, 'data.txt', 'utf-8') -}, callback); -``` - -will have the effect of calling `readFile` with the results object as the last -argument, which will fail: - -```js -fs.readFile('data.txt', 'utf-8', cb, {}); -``` - -Instead, wrap the call to `readFile` in a function which does not forward the -`results` object: - -```js -async.auto({ - readData: function(cb, results){ - fs.readFile('data.txt', 'utf-8', cb); - } -}, callback); -``` - -__Arguments__ - -* `tasks` - An object. Each of its properties is either a function or an array of - requirements, with the function itself the last item in the array. The object's key - of a property serves as the name of the task defined by that property, - i.e. can be used when specifying requirements for other tasks. - The function receives two arguments: (1) a `callback(err, result)` which must be - called when finished, passing an `error` (which can be `null`) and the result of - the function's execution, and (2) a `results` object, containing the results of - the previously executed functions. -* `callback(err, results)` - An optional callback which is called when all the - tasks have been completed. It receives the `err` argument if any `tasks` - pass an error to their callback. Results are always returned; however, if - an error occurs, no further `tasks` will be performed, and the results - object will only contain partial results. - - -__Example__ - -```js -async.auto({ - get_data: function(callback){ - console.log('in get_data'); - // async code to get some data - callback(null, 'data', 'converted to array'); - }, - make_folder: function(callback){ - console.log('in make_folder'); - // async code to create a directory to store a file in - // this is run at the same time as getting the data - callback(null, 'folder'); - }, - write_file: ['get_data', 'make_folder', function(callback, results){ - console.log('in write_file', JSON.stringify(results)); - // once there is some data and the directory exists, - // write the data to a file in the directory - callback(null, 'filename'); - }], - email_link: ['write_file', function(callback, results){ - console.log('in email_link', JSON.stringify(results)); - // once the file is written let's email a link to it... - // results.write_file contains the filename returned by write_file. - callback(null, {'file':results.write_file, 'email':'user@example.com'}); - }] -}, function(err, results) { - console.log('err = ', err); - console.log('results = ', results); -}); -``` - -This is a fairly trivial example, but to do this using the basic parallel and -series functions would look like this: - -```js -async.parallel([ - function(callback){ - console.log('in get_data'); - // async code to get some data - callback(null, 'data', 'converted to array'); - }, - function(callback){ - console.log('in make_folder'); - // async code to create a directory to store a file in - // this is run at the same time as getting the data - callback(null, 'folder'); - } -], -function(err, results){ - async.series([ - function(callback){ - console.log('in write_file', JSON.stringify(results)); - // once there is some data and the directory exists, - // write the data to a file in the directory - results.push('filename'); - callback(null); - }, - function(callback){ - console.log('in email_link', JSON.stringify(results)); - // once the file is written let's email a link to it... - callback(null, {'file':results.pop(), 'email':'user@example.com'}); - } - ]); -}); -``` - -For a complicated series of `async` tasks, using the [`auto`](#auto) function makes adding -new tasks much easier (and the code more readable). - - ---------------------------------------- - - -### retry([times = 5], task, [callback]) - -Attempts to get a successful response from `task` no more than `times` times before -returning an error. If the task is successful, the `callback` will be passed the result -of the successfull task. If all attemps fail, the callback will be passed the error and -result (if any) of the final attempt. - -__Arguments__ - -* `times` - An integer indicating how many times to attempt the `task` before giving up. Defaults to 5. -* `task(callback, results)` - A function which receives two arguments: (1) a `callback(err, result)` - which must be called when finished, passing `err` (which can be `null`) and the `result` of - the function's execution, and (2) a `results` object, containing the results of - the previously executed functions (if nested inside another control flow). -* `callback(err, results)` - An optional callback which is called when the - task has succeeded, or after the final failed attempt. It receives the `err` and `result` arguments of the last attempt at completing the `task`. - -The [`retry`](#retry) function can be used as a stand-alone control flow by passing a -callback, as shown below: - -```js -async.retry(3, apiMethod, function(err, result) { - // do something with the result -}); -``` - -It can also be embeded within other control flow functions to retry individual methods -that are not as reliable, like this: - -```js -async.auto({ - users: api.getUsers.bind(api), - payments: async.retry(3, api.getPayments.bind(api)) -}, function(err, results) { - // do something with the results -}); -``` - - ---------------------------------------- - - -### iterator(tasks) - -Creates an iterator function which calls the next function in the `tasks` array, -returning a continuation to call the next one after that. It's also possible to -“peek” at the next iterator with `iterator.next()`. - -This function is used internally by the `async` module, but can be useful when -you want to manually control the flow of functions in series. - -__Arguments__ - -* `tasks` - An array of functions to run. - -__Example__ - -```js -var iterator = async.iterator([ - function(){ sys.p('one'); }, - function(){ sys.p('two'); }, - function(){ sys.p('three'); } -]); - -node> var iterator2 = iterator(); -'one' -node> var iterator3 = iterator2(); -'two' -node> iterator3(); -'three' -node> var nextfn = iterator2.next(); -node> nextfn(); -'three' -``` - ---------------------------------------- - - -### apply(function, arguments..) - -Creates a continuation function with some arguments already applied. - -Useful as a shorthand when combined with other control flow functions. Any arguments -passed to the returned function are added to the arguments originally passed -to apply. - -__Arguments__ - -* `function` - The function you want to eventually apply all arguments to. -* `arguments...` - Any number of arguments to automatically apply when the - continuation is called. - -__Example__ - -```js -// using apply - -async.parallel([ - async.apply(fs.writeFile, 'testfile1', 'test1'), - async.apply(fs.writeFile, 'testfile2', 'test2'), -]); - - -// the same process without using apply - -async.parallel([ - function(callback){ - fs.writeFile('testfile1', 'test1', callback); - }, - function(callback){ - fs.writeFile('testfile2', 'test2', callback); - } -]); -``` - -It's possible to pass any number of additional arguments when calling the -continuation: - -```js -node> var fn = async.apply(sys.puts, 'one'); -node> fn('two', 'three'); -one -two -three -``` - ---------------------------------------- - - -### nextTick(callback) - -Calls `callback` on a later loop around the event loop. In Node.js this just -calls `process.nextTick`; in the browser it falls back to `setImmediate(callback)` -if available, otherwise `setTimeout(callback, 0)`, which means other higher priority -events may precede the execution of `callback`. - -This is used internally for browser-compatibility purposes. - -__Arguments__ - -* `callback` - The function to call on a later loop around the event loop. - -__Example__ - -```js -var call_order = []; -async.nextTick(function(){ - call_order.push('two'); - // call_order now equals ['one','two'] -}); -call_order.push('one') -``` - - -### times(n, callback) - -Calls the `callback` function `n` times, and accumulates results in the same manner -you would use with [`map`](#map). - -__Arguments__ - -* `n` - The number of times to run the function. -* `callback` - The function to call `n` times. - -__Example__ - -```js -// Pretend this is some complicated async factory -var createUser = function(id, callback) { - callback(null, { - id: 'user' + id - }) -} -// generate 5 users -async.times(5, function(n, next){ - createUser(n, function(err, user) { - next(err, user) - }) -}, function(err, users) { - // we should now have 5 users -}); -``` - - -### timesSeries(n, callback) - -The same as [`times`](#times), only the iterator is applied to each item in `arr` in -series. The next `iterator` is only called once the current one has completed. -The results array will be in the same order as the original. - - -## Utils - - -### memoize(fn, [hasher]) - -Caches the results of an `async` function. When creating a hash to store function -results against, the callback is omitted from the hash and an optional hash -function can be used. - -The cache of results is exposed as the `memo` property of the function returned -by `memoize`. - -__Arguments__ - -* `fn` - The function to proxy and cache results from. -* `hasher` - Tn optional function for generating a custom hash for storing - results. It has all the arguments applied to it apart from the callback, and - must be synchronous. - -__Example__ - -```js -var slow_fn = function (name, callback) { - // do something - callback(null, result); -}; -var fn = async.memoize(slow_fn); - -// fn can now be used as if it were slow_fn -fn('some name', function () { - // callback -}); -``` - - -### unmemoize(fn) - -Undoes a [`memoize`](#memoize)d function, reverting it to the original, unmemoized -form. Handy for testing. - -__Arguments__ - -* `fn` - the memoized function - - -### log(function, arguments) - -Logs the result of an `async` function to the `console`. Only works in Node.js or -in browsers that support `console.log` and `console.error` (such as FF and Chrome). -If multiple arguments are returned from the async function, `console.log` is -called on each argument in order. - -__Arguments__ - -* `function` - The function you want to eventually apply all arguments to. -* `arguments...` - Any number of arguments to apply to the function. - -__Example__ - -```js -var hello = function(name, callback){ - setTimeout(function(){ - callback(null, 'hello ' + name); - }, 1000); -}; -``` -```js -node> async.log(hello, 'world'); -'hello world' -``` - ---------------------------------------- - - -### dir(function, arguments) - -Logs the result of an `async` function to the `console` using `console.dir` to -display the properties of the resulting object. Only works in Node.js or -in browsers that support `console.dir` and `console.error` (such as FF and Chrome). -If multiple arguments are returned from the async function, `console.dir` is -called on each argument in order. - -__Arguments__ - -* `function` - The function you want to eventually apply all arguments to. -* `arguments...` - Any number of arguments to apply to the function. - -__Example__ - -```js -var hello = function(name, callback){ - setTimeout(function(){ - callback(null, {hello: name}); - }, 1000); -}; -``` -```js -node> async.dir(hello, 'world'); -{hello: 'world'} -``` - ---------------------------------------- - - -### noConflict() - -Changes the value of `async` back to its original value, returning a reference to the -`async` object. diff --git a/node_modules/async/component.json b/node_modules/async/component.json deleted file mode 100644 index bbb0115..0000000 --- a/node_modules/async/component.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "async", - "repo": "caolan/async", - "description": "Higher-order functions and common patterns for asynchronous code", - "version": "0.1.23", - "keywords": [], - "dependencies": {}, - "development": {}, - "main": "lib/async.js", - "scripts": [ "lib/async.js" ] -} diff --git a/node_modules/async/lib/async.js b/node_modules/async/lib/async.js deleted file mode 100755 index 01e8afc..0000000 --- a/node_modules/async/lib/async.js +++ /dev/null @@ -1,1123 +0,0 @@ -/*! - * async - * https://github.com/caolan/async - * - * Copyright 2010-2014 Caolan McMahon - * Released under the MIT license - */ -/*jshint onevar: false, indent:4 */ -/*global setImmediate: false, setTimeout: false, console: false */ -(function () { - - var async = {}; - - // global on the server, window in the browser - var root, previous_async; - - root = this; - if (root != null) { - previous_async = root.async; - } - - async.noConflict = function () { - root.async = previous_async; - return async; - }; - - function only_once(fn) { - var called = false; - return function() { - if (called) throw new Error("Callback was already called."); - called = true; - fn.apply(root, arguments); - } - } - - //// cross-browser compatiblity functions //// - - var _toString = Object.prototype.toString; - - var _isArray = Array.isArray || function (obj) { - return _toString.call(obj) === '[object Array]'; - }; - - var _each = function (arr, iterator) { - if (arr.forEach) { - return arr.forEach(iterator); - } - for (var i = 0; i < arr.length; i += 1) { - iterator(arr[i], i, arr); - } - }; - - var _map = function (arr, iterator) { - if (arr.map) { - return arr.map(iterator); - } - var results = []; - _each(arr, function (x, i, a) { - results.push(iterator(x, i, a)); - }); - return results; - }; - - var _reduce = function (arr, iterator, memo) { - if (arr.reduce) { - return arr.reduce(iterator, memo); - } - _each(arr, function (x, i, a) { - memo = iterator(memo, x, i, a); - }); - return memo; - }; - - var _keys = function (obj) { - if (Object.keys) { - return Object.keys(obj); - } - var keys = []; - for (var k in obj) { - if (obj.hasOwnProperty(k)) { - keys.push(k); - } - } - return keys; - }; - - //// exported async module functions //// - - //// nextTick implementation with browser-compatible fallback //// - if (typeof process === 'undefined' || !(process.nextTick)) { - if (typeof setImmediate === 'function') { - async.nextTick = function (fn) { - // not a direct alias for IE10 compatibility - setImmediate(fn); - }; - async.setImmediate = async.nextTick; - } - else { - async.nextTick = function (fn) { - setTimeout(fn, 0); - }; - async.setImmediate = async.nextTick; - } - } - else { - async.nextTick = process.nextTick; - if (typeof setImmediate !== 'undefined') { - async.setImmediate = function (fn) { - // not a direct alias for IE10 compatibility - setImmediate(fn); - }; - } - else { - async.setImmediate = async.nextTick; - } - } - - async.each = function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length) { - return callback(); - } - var completed = 0; - _each(arr, function (x) { - iterator(x, only_once(done) ); - }); - function done(err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed >= arr.length) { - callback(); - } - } - } - }; - async.forEach = async.each; - - async.eachSeries = function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length) { - return callback(); - } - var completed = 0; - var iterate = function () { - iterator(arr[completed], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed >= arr.length) { - callback(); - } - else { - iterate(); - } - } - }); - }; - iterate(); - }; - async.forEachSeries = async.eachSeries; - - async.eachLimit = function (arr, limit, iterator, callback) { - var fn = _eachLimit(limit); - fn.apply(null, [arr, iterator, callback]); - }; - async.forEachLimit = async.eachLimit; - - var _eachLimit = function (limit) { - - return function (arr, iterator, callback) { - callback = callback || function () {}; - if (!arr.length || limit <= 0) { - return callback(); - } - var completed = 0; - var started = 0; - var running = 0; - - (function replenish () { - if (completed >= arr.length) { - return callback(); - } - - while (running < limit && started < arr.length) { - started += 1; - running += 1; - iterator(arr[started - 1], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - running -= 1; - if (completed >= arr.length) { - callback(); - } - else { - replenish(); - } - } - }); - } - })(); - }; - }; - - - var doParallel = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.each].concat(args)); - }; - }; - var doParallelLimit = function(limit, fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [_eachLimit(limit)].concat(args)); - }; - }; - var doSeries = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.eachSeries].concat(args)); - }; - }; - - - var _asyncMap = function (eachfn, arr, iterator, callback) { - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - if (!callback) { - eachfn(arr, function (x, callback) { - iterator(x.value, function (err) { - callback(err); - }); - }); - } else { - var results = []; - eachfn(arr, function (x, callback) { - iterator(x.value, function (err, v) { - results[x.index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - async.map = doParallel(_asyncMap); - async.mapSeries = doSeries(_asyncMap); - async.mapLimit = function (arr, limit, iterator, callback) { - return _mapLimit(limit)(arr, iterator, callback); - }; - - var _mapLimit = function(limit) { - return doParallelLimit(limit, _asyncMap); - }; - - // reduce only has a series version, as doing reduce in parallel won't - // work in many situations. - async.reduce = function (arr, memo, iterator, callback) { - async.eachSeries(arr, function (x, callback) { - iterator(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); - }; - // inject alias - async.inject = async.reduce; - // foldl alias - async.foldl = async.reduce; - - async.reduceRight = function (arr, memo, iterator, callback) { - var reversed = _map(arr, function (x) { - return x; - }).reverse(); - async.reduce(reversed, memo, iterator, callback); - }; - // foldr alias - async.foldr = async.reduceRight; - - var _filter = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.filter = doParallel(_filter); - async.filterSeries = doSeries(_filter); - // select alias - async.select = async.filter; - async.selectSeries = async.filterSeries; - - var _reject = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (!v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.reject = doParallel(_reject); - async.rejectSeries = doSeries(_reject); - - var _detect = function (eachfn, arr, iterator, main_callback) { - eachfn(arr, function (x, callback) { - iterator(x, function (result) { - if (result) { - main_callback(x); - main_callback = function () {}; - } - else { - callback(); - } - }); - }, function (err) { - main_callback(); - }); - }; - async.detect = doParallel(_detect); - async.detectSeries = doSeries(_detect); - - async.some = function (arr, iterator, main_callback) { - async.each(arr, function (x, callback) { - iterator(x, function (v) { - if (v) { - main_callback(true); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(false); - }); - }; - // any alias - async.any = async.some; - - async.every = function (arr, iterator, main_callback) { - async.each(arr, function (x, callback) { - iterator(x, function (v) { - if (!v) { - main_callback(false); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(true); - }); - }; - // all alias - async.all = async.every; - - async.sortBy = function (arr, iterator, callback) { - async.map(arr, function (x, callback) { - iterator(x, function (err, criteria) { - if (err) { - callback(err); - } - else { - callback(null, {value: x, criteria: criteria}); - } - }); - }, function (err, results) { - if (err) { - return callback(err); - } - else { - var fn = function (left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }; - callback(null, _map(results.sort(fn), function (x) { - return x.value; - })); - } - }); - }; - - async.auto = function (tasks, callback) { - callback = callback || function () {}; - var keys = _keys(tasks); - var remainingTasks = keys.length - if (!remainingTasks) { - return callback(); - } - - var results = {}; - - var listeners = []; - var addListener = function (fn) { - listeners.unshift(fn); - }; - var removeListener = function (fn) { - for (var i = 0; i < listeners.length; i += 1) { - if (listeners[i] === fn) { - listeners.splice(i, 1); - return; - } - } - }; - var taskComplete = function () { - remainingTasks-- - _each(listeners.slice(0), function (fn) { - fn(); - }); - }; - - addListener(function () { - if (!remainingTasks) { - var theCallback = callback; - // prevent final callback from calling itself if it errors - callback = function () {}; - - theCallback(null, results); - } - }); - - _each(keys, function (k) { - var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; - var taskCallback = function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - if (err) { - var safeResults = {}; - _each(_keys(results), function(rkey) { - safeResults[rkey] = results[rkey]; - }); - safeResults[k] = args; - callback(err, safeResults); - // stop subsequent errors hitting callback multiple times - callback = function () {}; - } - else { - results[k] = args; - async.setImmediate(taskComplete); - } - }; - var requires = task.slice(0, Math.abs(task.length - 1)) || []; - var ready = function () { - return _reduce(requires, function (a, x) { - return (a && results.hasOwnProperty(x)); - }, true) && !results.hasOwnProperty(k); - }; - if (ready()) { - task[task.length - 1](taskCallback, results); - } - else { - var listener = function () { - if (ready()) { - removeListener(listener); - task[task.length - 1](taskCallback, results); - } - }; - addListener(listener); - } - }); - }; - - async.retry = function(times, task, callback) { - var DEFAULT_TIMES = 5; - var attempts = []; - // Use defaults if times not passed - if (typeof times === 'function') { - callback = task; - task = times; - times = DEFAULT_TIMES; - } - // Make sure times is a number - times = parseInt(times, 10) || DEFAULT_TIMES; - var wrappedTask = function(wrappedCallback, wrappedResults) { - var retryAttempt = function(task, finalAttempt) { - return function(seriesCallback) { - task(function(err, result){ - seriesCallback(!err || finalAttempt, {err: err, result: result}); - }, wrappedResults); - }; - }; - while (times) { - attempts.push(retryAttempt(task, !(times-=1))); - } - async.series(attempts, function(done, data){ - data = data[data.length - 1]; - (wrappedCallback || callback)(data.err, data.result); - }); - } - // If a callback is passed, run this as a controll flow - return callback ? wrappedTask() : wrappedTask - }; - - async.waterfall = function (tasks, callback) { - callback = callback || function () {}; - if (!_isArray(tasks)) { - var err = new Error('First argument to waterfall must be an array of functions'); - return callback(err); - } - if (!tasks.length) { - return callback(); - } - var wrapIterator = function (iterator) { - return function (err) { - if (err) { - callback.apply(null, arguments); - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } - else { - args.push(callback); - } - async.setImmediate(function () { - iterator.apply(null, args); - }); - } - }; - }; - wrapIterator(async.iterator(tasks))(); - }; - - var _parallel = function(eachfn, tasks, callback) { - callback = callback || function () {}; - if (_isArray(tasks)) { - eachfn.map(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - eachfn.each(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.parallel = function (tasks, callback) { - _parallel({ map: async.map, each: async.each }, tasks, callback); - }; - - async.parallelLimit = function(tasks, limit, callback) { - _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); - }; - - async.series = function (tasks, callback) { - callback = callback || function () {}; - if (_isArray(tasks)) { - async.mapSeries(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - async.eachSeries(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.iterator = function (tasks) { - var makeCallback = function (index) { - var fn = function () { - if (tasks.length) { - tasks[index].apply(null, arguments); - } - return fn.next(); - }; - fn.next = function () { - return (index < tasks.length - 1) ? makeCallback(index + 1): null; - }; - return fn; - }; - return makeCallback(0); - }; - - async.apply = function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return fn.apply( - null, args.concat(Array.prototype.slice.call(arguments)) - ); - }; - }; - - var _concat = function (eachfn, arr, fn, callback) { - var r = []; - eachfn(arr, function (x, cb) { - fn(x, function (err, y) { - r = r.concat(y || []); - cb(err); - }); - }, function (err) { - callback(err, r); - }); - }; - async.concat = doParallel(_concat); - async.concatSeries = doSeries(_concat); - - async.whilst = function (test, iterator, callback) { - if (test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.whilst(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.doWhilst = function (iterator, test, callback) { - iterator(function (err) { - if (err) { - return callback(err); - } - var args = Array.prototype.slice.call(arguments, 1); - if (test.apply(null, args)) { - async.doWhilst(iterator, test, callback); - } - else { - callback(); - } - }); - }; - - async.until = function (test, iterator, callback) { - if (!test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.until(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.doUntil = function (iterator, test, callback) { - iterator(function (err) { - if (err) { - return callback(err); - } - var args = Array.prototype.slice.call(arguments, 1); - if (!test.apply(null, args)) { - async.doUntil(iterator, test, callback); - } - else { - callback(); - } - }); - }; - - async.queue = function (worker, concurrency) { - if (concurrency === undefined) { - concurrency = 1; - } - function _insert(q, data, pos, callback) { - if (!q.started){ - q.started = true; - } - if (!_isArray(data)) { - data = [data]; - } - if(data.length == 0) { - // call drain immediately if there are no tasks - return async.setImmediate(function() { - if (q.drain) { - q.drain(); - } - }); - } - _each(data, function(task) { - var item = { - data: task, - callback: typeof callback === 'function' ? callback : null - }; - - if (pos) { - q.tasks.unshift(item); - } else { - q.tasks.push(item); - } - - if (q.saturated && q.tasks.length === q.concurrency) { - q.saturated(); - } - async.setImmediate(q.process); - }); - } - - var workers = 0; - var q = { - tasks: [], - concurrency: concurrency, - saturated: null, - empty: null, - drain: null, - started: false, - paused: false, - push: function (data, callback) { - _insert(q, data, false, callback); - }, - kill: function () { - q.drain = null; - q.tasks = []; - }, - unshift: function (data, callback) { - _insert(q, data, true, callback); - }, - process: function () { - if (!q.paused && workers < q.concurrency && q.tasks.length) { - var task = q.tasks.shift(); - if (q.empty && q.tasks.length === 0) { - q.empty(); - } - workers += 1; - var next = function () { - workers -= 1; - if (task.callback) { - task.callback.apply(task, arguments); - } - if (q.drain && q.tasks.length + workers === 0) { - q.drain(); - } - q.process(); - }; - var cb = only_once(next); - worker(task.data, cb); - } - }, - length: function () { - return q.tasks.length; - }, - running: function () { - return workers; - }, - idle: function() { - return q.tasks.length + workers === 0; - }, - pause: function () { - if (q.paused === true) { return; } - q.paused = true; - q.process(); - }, - resume: function () { - if (q.paused === false) { return; } - q.paused = false; - q.process(); - } - }; - return q; - }; - - async.priorityQueue = function (worker, concurrency) { - - function _compareTasks(a, b){ - return a.priority - b.priority; - }; - - function _binarySearch(sequence, item, compare) { - var beg = -1, - end = sequence.length - 1; - while (beg < end) { - var mid = beg + ((end - beg + 1) >>> 1); - if (compare(item, sequence[mid]) >= 0) { - beg = mid; - } else { - end = mid - 1; - } - } - return beg; - } - - function _insert(q, data, priority, callback) { - if (!q.started){ - q.started = true; - } - if (!_isArray(data)) { - data = [data]; - } - if(data.length == 0) { - // call drain immediately if there are no tasks - return async.setImmediate(function() { - if (q.drain) { - q.drain(); - } - }); - } - _each(data, function(task) { - var item = { - data: task, - priority: priority, - callback: typeof callback === 'function' ? callback : null - }; - - q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); - - if (q.saturated && q.tasks.length === q.concurrency) { - q.saturated(); - } - async.setImmediate(q.process); - }); - } - - // Start with a normal queue - var q = async.queue(worker, concurrency); - - // Override push to accept second parameter representing priority - q.push = function (data, priority, callback) { - _insert(q, data, priority, callback); - }; - - // Remove unshift function - delete q.unshift; - - return q; - }; - - async.cargo = function (worker, payload) { - var working = false, - tasks = []; - - var cargo = { - tasks: tasks, - payload: payload, - saturated: null, - empty: null, - drain: null, - drained: true, - push: function (data, callback) { - if (!_isArray(data)) { - data = [data]; - } - _each(data, function(task) { - tasks.push({ - data: task, - callback: typeof callback === 'function' ? callback : null - }); - cargo.drained = false; - if (cargo.saturated && tasks.length === payload) { - cargo.saturated(); - } - }); - async.setImmediate(cargo.process); - }, - process: function process() { - if (working) return; - if (tasks.length === 0) { - if(cargo.drain && !cargo.drained) cargo.drain(); - cargo.drained = true; - return; - } - - var ts = typeof payload === 'number' - ? tasks.splice(0, payload) - : tasks.splice(0, tasks.length); - - var ds = _map(ts, function (task) { - return task.data; - }); - - if(cargo.empty) cargo.empty(); - working = true; - worker(ds, function () { - working = false; - - var args = arguments; - _each(ts, function (data) { - if (data.callback) { - data.callback.apply(null, args); - } - }); - - process(); - }); - }, - length: function () { - return tasks.length; - }, - running: function () { - return working; - } - }; - return cargo; - }; - - var _console_fn = function (name) { - return function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - fn.apply(null, args.concat([function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (typeof console !== 'undefined') { - if (err) { - if (console.error) { - console.error(err); - } - } - else if (console[name]) { - _each(args, function (x) { - console[name](x); - }); - } - } - }])); - }; - }; - async.log = _console_fn('log'); - async.dir = _console_fn('dir'); - /*async.info = _console_fn('info'); - async.warn = _console_fn('warn'); - async.error = _console_fn('error');*/ - - async.memoize = function (fn, hasher) { - var memo = {}; - var queues = {}; - hasher = hasher || function (x) { - return x; - }; - var memoized = function () { - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - var key = hasher.apply(null, args); - if (key in memo) { - async.nextTick(function () { - callback.apply(null, memo[key]); - }); - } - else if (key in queues) { - queues[key].push(callback); - } - else { - queues[key] = [callback]; - fn.apply(null, args.concat([function () { - memo[key] = arguments; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, arguments); - } - }])); - } - }; - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; - }; - - async.unmemoize = function (fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; - }; - - async.times = function (count, iterator, callback) { - var counter = []; - for (var i = 0; i < count; i++) { - counter.push(i); - } - return async.map(counter, iterator, callback); - }; - - async.timesSeries = function (count, iterator, callback) { - var counter = []; - for (var i = 0; i < count; i++) { - counter.push(i); - } - return async.mapSeries(counter, iterator, callback); - }; - - async.seq = function (/* functions... */) { - var fns = arguments; - return function () { - var that = this; - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - async.reduce(fns, args, function (newargs, fn, cb) { - fn.apply(that, newargs.concat([function () { - var err = arguments[0]; - var nextargs = Array.prototype.slice.call(arguments, 1); - cb(err, nextargs); - }])) - }, - function (err, results) { - callback.apply(that, [err].concat(results)); - }); - }; - }; - - async.compose = function (/* functions... */) { - return async.seq.apply(null, Array.prototype.reverse.call(arguments)); - }; - - var _applyEach = function (eachfn, fns /*args...*/) { - var go = function () { - var that = this; - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - return eachfn(fns, function (fn, cb) { - fn.apply(that, args.concat([cb])); - }, - callback); - }; - if (arguments.length > 2) { - var args = Array.prototype.slice.call(arguments, 2); - return go.apply(this, args); - } - else { - return go; - } - }; - async.applyEach = doParallel(_applyEach); - async.applyEachSeries = doSeries(_applyEach); - - async.forever = function (fn, callback) { - function next(err) { - if (err) { - if (callback) { - return callback(err); - } - throw err; - } - fn(next); - } - next(); - }; - - // Node.js - if (typeof module !== 'undefined' && module.exports) { - module.exports = async; - } - // AMD / RequireJS - else if (typeof define !== 'undefined' && define.amd) { - define([], function () { - return async; - }); - } - // included directly via - - - - - -
-
-

Node.js Configuration

- Node.js Configuration - > test - - > 1-protected-test.js (source view) -
-
- Search: -
-   -
-
-
-
- -
-
-
-
-
- Filters - - - -
-
- -
- -
/**
- * <p>Unit tests</p>
- *
- * @module test
- */
-
-// Change the configuration directory for testing
-process.env.NODE_CONFIG_DIR = __dirname + '/config';
-
-// Hardcode $NODE_ENV=test for testing
-process.env.NODE_ENV='test';
-
-// Test for multi-instance applications
-process.env.NODE_APP_INSTANCE='3';
-
-// Test for old style environment variable overrides
-process.env.CONFIG_EnvOverride_parm__number__1 = 'overridden from test';
-process.env.CONFIG_EnvOverride_parm2 = 13;
-
-// Test $NODE_CONFIG environment and --NODE_CONFIG command line parameter
-process.env.NODE_CONFIG='{"EnvOverride":{"parm3":"overridden from $NODE_CONFIG","parm4":100}}'
-process.argv.push('--NODE_CONFIG={"EnvOverride":{"parm5":"overridden from --NODE_CONFIG","parm6":101}}');
-
-// Dependencies
-var CONFIG = require('../lib/config');
-var vows = require('vows');
-var assert = require('assert');
-
-// Make a copy of the command line args
-var argvOrg = process.argv;
-
-/**
- * <p>Tests for underlying node-config utilities.  To run type:</p>
- * <pre>npm test</pre>
- * <p>Or, in a project that uses node-config:</p>
- * <pre>npm test config</pre>
- *
- * @class ProtectedTest
- */
-exports.PrivateTest = vows.describe('Protected (hackable) utilities test').addBatch({
-  'Library initialization': {
-    'Library is available': function() {
-      assert.isObject(CONFIG);
-    }
-  },
-
-  '_isObject() tests': {
-    'The function exists': function() {
-      assert.isFunction(CONFIG._isObject);
-    },
-    'Correctly identifies objects': function() {
-   	  assert.isTrue(CONFIG._isObject({A:"b"}));
-    },
-    'Correctly excludes non-objects': function() {
-   	  assert.isFalse(CONFIG._isObject("some string"));
-   	  assert.isFalse(CONFIG._isObject(45));
-   	  assert.isFalse(CONFIG._isObject([2, 3]));
-   	  assert.isFalse(CONFIG._isObject(["a", "b"]));
-   	  assert.isFalse(CONFIG._isObject(null));
-   	  assert.isFalse(CONFIG._isObject(undefined));
-    }
-  },
-
-  '_cloneDeep() tests': {
-    topic: function() {
-      // Return an object for copy tests
-      return {
-        elem0:true,
-        elem1:"Element 1",
-        elem2:2,
-        elem3:[1,2,3],
-        elem4:function(){return "hello";},
-        elem5:{sub1:"sub 1",sub2:2,sub3:[1,2,3]}
-      };
-    },
-    'The function exists': function() {
-      assert.isFunction(CONFIG._cloneDeep);
-    },
-    'Original and copy should test equivalent (deep)': function(orig) {
-      var copy = CONFIG._cloneDeep(orig);
-      assert.deepEqual(copy, orig);
-    },
-    'The objects should be different': function(orig) {
-      var copy = CONFIG._cloneDeep(orig);
-      copy.elem1 = false;
-      assert.notDeepEqual(copy, orig);
-    },
-    'Object clones should be objects': function(orig) {
-      assert.isObject(CONFIG._cloneDeep({a:1, b:2}));
-    },
-    'Array clones should be arrays': function(orig) {
-      assert.isArray(CONFIG._cloneDeep(["a", "b", 3]));
-    },
-    'Arrays should be copied by value, not by reference': function(orig) {
-      var copy = CONFIG._cloneDeep(orig);
-      assert.deepEqual(copy, orig);
-      copy.elem3[0] = 2;
-      // If the copy wasn't deep, elem3 would be the same object
-      assert.notDeepEqual(copy, orig);
-    },
-    'Objects should be copied by value, not by reference': function(orig) {
-      var copy = CONFIG._cloneDeep(orig);
-      copy.elem5.sub2 = 3;
-      assert.notDeepEqual(copy, orig);
-      copy = CONFIG._cloneDeep(orig);
-      copy.elem5.sub3[1] = 3;
-      assert.notDeepEqual(copy, orig);
-    }
-  },
-
-  '_extendDeep() tests': {
-    'The function exists': function() {
-      assert.isFunction(CONFIG._extendDeep);
-    },
-    'Performs normal extend': function() {
-      var orig = {elem1:"val1", elem2:"val2"};
-      var extWith = {elem3:"val3"};
-      var shouldBe = {elem1:"val1", elem2:"val2", elem3:"val3"};
-      assert.deepEqual(CONFIG._extendDeep(orig, extWith), shouldBe);
-    },
-    'Replaces non-objects': function() {
-      var orig = {elem1:"val1", elem2:["val2","val3"],elem3:{sub1:"val4"}};
-      var extWith = {elem1:1,elem2:["val4"],elem3:"val3"};
-      var shouldBe = {elem1:1, elem2:["val4"],elem3:"val3"};
-      assert.deepEqual(CONFIG._extendDeep(orig, extWith), shouldBe);
-    },
-    'Merges objects': function() {
-      var orig = {e1:"val1", elem2:{sub1:"val4",sub2:"val5"}};
-      var extWith = {elem2:{sub2:"val6",sub3:"val7"}};
-      var shouldBe = {e1:"val1", elem2:{sub1:"val4",sub2:"val6",sub3:"val7"}};
-      assert.deepEqual(CONFIG._extendDeep(orig, extWith), shouldBe);
-    },
-    'Correctly types new objects and arrays': function() {
-      var orig = {e1:"val1", e3:["val5"]};
-      var extWith = {e2:{elem1:"val1"}, e3:["val6","val7"]};
-      var shouldBe = {e1:"val1", e2:{elem1:"val1"}, e3:["val6","val7"]};
-      var ext = CONFIG._extendDeep({}, orig, extWith);
-      assert.isObject(ext.e2);
-      assert.isArray(ext.e3);
-    },
-    'Keeps non-merged objects intact': function() {
-      var orig     = {e1:"val1", elem2:{sub1:"val4",sub2:"val5"}};
-      var shouldBe = {e1:"val1", elem2:{sub1:"val4",sub2:"val5"}};
-      var extWith = {elem3:{sub2:"val6",sub3:"val7"}};
-      CONFIG._extendDeep({}, orig, extWith);
-      assert.deepEqual(orig, shouldBe);
-    }
-  },
-
-  '_equalsDeep() tests': {
-    'The function exists': function() {
-      assert.isFunction(CONFIG._equalsDeep);
-    },
-    'Succeeds on two empty objects': function() {
-      assert.isTrue(CONFIG._equalsDeep({}, {}));
-    },
-    'Succeeds on array comparisons': function() {
-      assert.isTrue(CONFIG._equalsDeep([1,'hello',2], [1,'hello',2]));
-    },
-    'Succeeds on the same object': function() {
-      var a = {hello:'world'};
-      assert.isTrue(CONFIG._equalsDeep(a, a));
-    },
-    'Succeeds on a regular object': function() {
-      var a = {value_3: 14, hello:'world', value_1: 29};
-      var b = {value_1: 29, hello:'world', value_3: 14};
-      assert.isTrue(CONFIG._equalsDeep(a, b));
-    },
-    'Succeeds on a deep object': function() {
-      var a = {value_3: 14, hello:'world', value_1: 29, value_4:['now','is','the','time']};
-      var b = {value_1: 29, hello:'world', value_3: 14, value_4:['now','is','the','time']};
-      var c = {creditLimit: 10000, deepValue: a};
-      var d = {deepValue: b, creditLimit:10000};
-      assert.isTrue(CONFIG._equalsDeep(c, d));
-    },
-    'Fails if either object is null': function() {
-      assert.isFalse(CONFIG._equalsDeep({}, null));
-      assert.isFalse(CONFIG._equalsDeep(null, {}));
-      assert.isFalse(CONFIG._equalsDeep(null, null));
-    },
-    'Fails if either object is undefined': function() {
-      var a = {};
-      assert.isFalse(CONFIG._equalsDeep({}));
-      assert.isFalse(CONFIG._equalsDeep(a['noElement'], {}));
-    },
-    'Fails if either object is undefined': function() {
-      var a = {};
-      assert.isFalse(CONFIG._equalsDeep({}));
-      assert.isFalse(CONFIG._equalsDeep(a['noElement'], {}));
-    },
-    'Fails if object1 has more elements': function() {
-      var a = {value_3: 14, hello:'world', value_1: 29, otherElem: 40};
-      var b = {value_1: 29, hello:'world', value_3: 14};
-      assert.isFalse(CONFIG._equalsDeep(a, b));
-    },
-    'Fails if object2 has more elements': function() {
-      var a = {value_1: 29, hello:'world', value_3: 14};
-      var b = {value_3: 14, hello:'world', value_1: 29, otherElem: 40};
-      assert.isFalse(CONFIG._equalsDeep(a, b));
-    },
-    'Fails if any value is different': function() {
-      var a = {value_1: 30, hello:'world', value_3: 14, value_4:['now','is','the','time']};
-      var b = {value_1: 29, hello:'world', value_3: 14, value_4:['now','is','the','time']};
-      assert.isFalse(CONFIG._equalsDeep(a, b));
-      var a = {value_1: 29, hello:'world', value_3: 14, value_4:['now','is','the','time']};
-      var b = {value_1: 29, hello:'world', value_3: 14, value_4:['now','isnt','the','time']};
-      assert.isFalse(CONFIG._equalsDeep(a, b));
-    }
-  },
-
-  '_diffDeep() tests': {
-    'The function exists': function() {
-      assert.isFunction(CONFIG._diffDeep);
-    },
-    'Returns an empty object if no differences': function() {
-      var a = {value_3: 14, hello:'world', value_1: 29};
-      var b = {value_1: 29, hello:'world', value_3: 14};
-      assert.equal(typeof(CONFIG._diffDeep(a,b)), 'object');
-      assert.isTrue(Object.keys(CONFIG._diffDeep(a, b)).length == 0);
-    },
-    'Returns an empty object if no differences (deep)': function() {
-      var a = {value_3: 14, hello:'world', value_1: 29, value_4:[1,'hello',2], deepObj:{a:22,b:{c:45,a:44}}};
-      var b = {value_1: 29, hello:'world', value_3: 14, value_4:[1,'hello',2], deepObj:{a:22,b:{a:44,c:45}}};
-      assert.equal(typeof(CONFIG._diffDeep(a,b)), 'object');
-      assert.isTrue(Object.keys(CONFIG._diffDeep(a, b)).length == 0);
-    },
-    'Returns just the diff values': function() {
-      var a = {value_3: 14, hello:'wurld', value_1: 29, deepObj:{a:22,b:{c:45,a:44}}};
-      var b = {value_1: 29, hello:'world', value_3: 14, deepObj:{a:22,b:{a:44,c:45}}};
-      var diff = CONFIG._diffDeep(a,b);
-      assert.equal(Object.keys(diff).length, 1);
-      assert.equal(diff.hello, 'world');
-    },
-    'Returns just the diff values (deep)': function() {
-      var a = {value_3: 14, hello:'wurld', value_1: 29, value_4:[1,'hello',2], deepObj:{a:22,b:{c:45,a:44}}};
-      var b = {value_1: 29, hello:'wurld', value_3: 14, value_4:[1,'goodbye',2], deepObj:{a:22,b:{a:45,c:44}}};
-      var diff = CONFIG._diffDeep(a,b);
-      assert.equal(Object.keys(diff).length, 2);
-      assert.equal(Object.keys(diff.deepObj).length, 1);
-      assert.equal(Object.keys(diff.deepObj.b).length, 2);
-      assert.equal(diff.deepObj.b.a, 45);
-      assert.equal(diff.deepObj.b.c, 44);
-      assert.deepEqual(diff.value_4, [1, 'goodbye', 2]);
-    }
-  },
-
-  '_stripComments() tests': {
-    // Only testing baseline stripComments functionality.
-	// This implementation handles lots of edge cases that aren't in these tests
-    'The function exists': function() {
-      assert.isFunction(CONFIG._stripComments);
-    },
-    'Leaves a simple string without comments alone': function() {
-   	  var str = "Hello\nWorld";
-   	  assert.equal(CONFIG._stripComments(str), str);
-    },
-    'Strips out line-type comments': function() {
-   	  var str1 = "var a='Hello'; // Comment about the a variable";
-   	  var str2 = "var a='Hello'; ";
-   	  assert.equal(CONFIG._stripComments(str1), str2);
-    },
-    'Strips out block-type comments': function() {
-   	  var str1 = "var a='Hello';/* Block Comment */ var b=24";
-   	  var str2 = "var a='Hello'; var b=24";
-   	  assert.equal(CONFIG._stripComments(str1), str2);
-    },
-    'Strips out multi-line block comments': function() {
-   	  var str1 = "var a='Hello';\n/* Block Comment\n  Line 2 comment\n*/\nvar b=24";
-   	  var str2 = "var a='Hello';\n\nvar b=24";
-   	  assert.equal(CONFIG._stripComments(str1), str2);
-    }
-  },
-
-  '_parseFile() tests': {
-    topic: function() {
-      return CONFIG._parseFile(__dirname + '/config/default.yaml');
-    },
-    'The function exists': function() {
-      assert.isFunction(CONFIG._parseFile);
-    },
-    'An object is returned': function(config) {
-      assert.isObject(config);
-    },
-    'The correct object is returned': function(config) {
-      assert.isObject(config.Customers);
-      assert.isTrue(config.Customers.dbName == 'from_default_yaml');
-      assert.isTrue(config.Customers.dbPort == 5984);
-      assert.isObject(config.AnotherModule);
-      assert.isTrue(config.AnotherModule.parm2 == "value2");
-    }
-  },
-
-  '_loadFileConfigs() tests': {
-    topic: function() {
-      return CONFIG._loadFileConfigs();
-    },
-    'The function exists': function() {
-      assert.isFunction(CONFIG._loadFileConfigs);
-    },
-    'An object is returned': function(configs) {
-      assert.isObject(configs);
-    },
-    'The correct object is returned': function(config) {
-      assert.isObject(config.Customers);
-      assert.isTrue(config.Customers.dbHost == 'base');
-      assert.isTrue(config.Customers.dbName == 'override_from_runtime_json');
-    }
-  },
-
-  '_attachProtoDeep() tests': {
-    topic: function() {
-      // Create an object that contains other objects to see
-      // that the prototype is added to all objects.
-      var watchThis = {
-        subObject: {
-          item1: 23,
-          subSubObject: {
-        	item2: "hello"
-          }
-        }
-      };
-      return CONFIG._attachProtoDeep(watchThis);
-    },
-    'The function exists': function() {
-      assert.isFunction(CONFIG._attachProtoDeep);
-    },
-    'The original object is returned': function(config) {
-      assert.isObject(config);
-      assert.isTrue(config.subObject.item1 === 23);
-      assert.isTrue(config.subObject.subSubObject.item2 === "hello");
-    },
-    'The _cloneDeep method is attached to the object': function(config) {
-      assert.isTrue({a:27}.a == config._cloneDeep({a:27}).a);
-    },
-    'The _cloneDeep method is also attached to sub-objects': function(config) {
-      assert.isTrue({a:27}.a == config.subObject._cloneDeep({a:27}).a);
-      assert.isTrue({a:27}.a == config.subObject.subSubObject._cloneDeep({a:27}).a);
-    },
-    'Prototype methods are not exposed in the object': function(config) {
-      // This test is here because altering object.__proto__ places the method
-      // directly onto the object. That caused problems when iterating over the
-      // object.  This implementation does the same thing, but hides them.
-      assert.isTrue(JSON.stringify(config) == '{"subObject":{"item1":23,"subSubObject":{"item2":"hello"}}}');
-    }
-  },
-
-  '_getCmdLineArg() tests': {
-    topic: function() {
-        // Set process.argv example object
-        var testArgv = [
-            process.argv[0],
-            process.argv[1],
-            '--NODE_ENV=staging'
-        ];
-        process.argv = testArgv;
-        return CONFIG._getCmdLineArg('NODE_ENV');
-    },
-    'The function exists': function() {
-        assert.isFunction(CONFIG._getCmdLineArg);
-    },
-    'NODE_ENV should be staging': function(nodeEnv) {
-        assert.equal(nodeEnv, 'staging');
-    },
-    'Returns false if the argument did not match': function() {
-        assert.isFalse(CONFIG._getCmdLineArg('NODE_CONFIG_DIR'));
-    },
-    'Returns the argument (alternative syntax)': function() {
-        process.argv.push('--NODE_CONFIG_DIR=/etc/nodeConfig');
-        assert.equal(CONFIG._getCmdLineArg('NODE_CONFIG_DIR'), '/etc/nodeConfig');
-    },
-    'Returns always the first matching': function() {
-        process.argv.push('--NODE_ENV=test');
-        assert.equal(CONFIG._getCmdLineArg('NODE_ENV'), 'staging');
-    },
-    'Revert original process aruments': function() {
-        assert.notEqual(process.argv, argvOrg);
-        process.argv = argvOrg;
-        assert.equal(process.argv, argvOrg);
-    }
-  }
-
-});
-
-
-
-
-
- -
-
-
-
-Released on github under the Apache License 2.0 -version 0.4.35 -
-
- - - diff --git a/node_modules/config/doc/2-config-test.js.html b/node_modules/config/doc/2-config-test.js.html deleted file mode 100644 index 65d0236..0000000 --- a/node_modules/config/doc/2-config-test.js.html +++ /dev/null @@ -1,450 +0,0 @@ - - - - - test 2-config-test.js - - - - - - - - - - -
-
-

Node.js Configuration

- Node.js Configuration - > test - - > 2-config-test.js (source view) -
-
- Search: -
-   -
-
-
-
- -
-
-
-
-
- Filters - - - -
-
- -
- -
// Change the configuration directory for testing
-process.env.NODE_CONFIG_DIR = __dirname + '/config';
-
-// Hardcode $NODE_ENV=test for testing
-process.env.NODE_ENV='test';
-
-// Test for multi-instance applications
-process.env.NODE_APP_INSTANCE='3';
-
-// Test for old style environment variable overrides
-process.env.CONFIG_EnvOverride_parm__number__1 = 'overridden from test';
-process.env.CONFIG_EnvOverride_parm2 = 13;
-
-// Test $NODE_CONFIG environment and --NODE_CONFIG command line parameter
-process.env.NODE_CONFIG='{"EnvOverride":{"parm3":"overridden from $NODE_CONFIG","parm4":100}}'
-process.argv.push('--NODE_CONFIG={"EnvOverride":{"parm5":"overridden from --NODE_CONFIG","parm6":101}}');
-
-// Dependencies
-var vows = require('vows');
-    assert = require('assert'),
-    CONFIG = require('../lib/config'),
-    FileSystem = require('fs'),
-    originalWatchedValue = CONFIG.watchThisValue,
-    newWatchedValue = Math.floor(Math.random() * 100000),
-    originalDynamicArray = CONFIG.dynamicArray,
-    newDynamicArray = [Math.floor(Math.random() * 100000), Math.floor(Math.random() * 100000)];
-
-var runtimeJsonFilename = __dirname + '/config/runtime.json';
-var runtimeJsonFilenameBak = runtimeJsonFilename+'.bak';
-
-/**
- * <p>Unit tests for the node-config library.  To run type:</p>
- * <pre>npm test</pre>
- * <p>Or, in a project that uses node-config:</p>
- * <pre>npm test config</pre>
- *
- * @class ConfigTest
- */
-exports.ConfigTest = vows.describe('Test suite for node-config').addBatch({
-  'Library initialization': {
-    'Config library is available': function() {
-      assert.isObject(CONFIG);
-    },
-    'Config extensions are included with the library': function() {
-      assert.isFunction(CONFIG._cloneDeep);
-    }
-  },
-
-  'Configuration file Tests': {
-    topic: function() {
-      return CONFIG;
-    },
-
-    'Loading configurations from a JS module is correct': function() {
-      assert.equal(CONFIG.Customers.dbHost, 'base');
-      assert.equal(CONFIG.TestModule.parm1, 'value1');
-    },
-
-    'Loading configurations from a JSON file is correct': function() {
-      assert.equal(CONFIG.AnotherModule.parm1, 'value1');
-    },
-
-    'Loading configurations from a .yaml YAML file is correct': function() {
-      assert.equal(CONFIG.AnotherModule.parm2, 'value2');
-    },
-
-    'Loading configurations from a .yml YAML file is correct': function() {
-      assert.equal(CONFIG.AnotherModule.parm2yml, 'value2yml');
-    },
-
-    'Loading configurations from a Coffee-Script file is correct': function() {
-      assert.equal(CONFIG.AnotherModule.parm3, 'value3');
-    },
-
-    'Loading configurations from an environment file is correct': function() {
-      assert.equal(CONFIG.Customers.dbPort, '5999');
-    },
-
-    'Loading configurations from the local file is correct': function() {
-      assert.equal(CONFIG.Customers.dbPassword, 'real password');
-    },
-
-    'Loading configurations from the local environment file is correct': function() {
-      assert.equal(CONFIG.Customers.dbPassword2, 'another password');
-      assert.deepEqual(CONFIG.Customers.lang, ['en','de','es']);
-    },
-
-    'Loading prior runtime.json configurations is correct': function() {
-      assert.equal(CONFIG.Customers.dbName, 'override_from_runtime_json');
-    },
-
-    'Multi-instance default.json override is correct': function() {
-      assert.equal(CONFIG.Customers.altDbPort, 4400);
-    },
-
-    'Multi-instance local.yaml override is correct': function() {
-      assert.equal(CONFIG.Customers.altDbPort1, 2209);
-    }
-
-  },
-
-  'Old-Style Configurations from environment variables (deprecated)': {
-    topic: function() {
-      return CONFIG;
-    },
-
-    'Configuration can come from environment variables': function() {
-      assert.equal(CONFIG.EnvOverride.parm2, 13);
-    },
-
-    'Double__underscores escape to single_underscores': function() {
-
-      JSON.stringify(CONFIG, null, 2);
-      assert.equal(CONFIG.EnvOverride.parm_number_1, 'overridden from test');
-    }
-  },
-
-  'Configurations from the $NODE_CONFIG environment variable': {
-    topic: function() {
-      return CONFIG;
-    },
-
-    'Configuration can come from the $NODE_CONFIG environment': function() {
-      assert.equal(CONFIG.EnvOverride.parm3, 'overridden from $NODE_CONFIG');
-    },
-
-    'Type correct configurations from $NODE_CONFIG': function() {
-      assert.equal(CONFIG.EnvOverride.parm4, 100);
-    }
-
-  },
-
-  'Configurations from the --NODE_CONFIG command line': {
-    topic: function() {
-      return CONFIG;
-    },
-
-    'Configuration can come from the --NODE_CONFIG command line argument': function() {
-      assert.equal(CONFIG.EnvOverride.parm5, 'overridden from --NODE_CONFIG');
-    },
-
-    'Type correct configurations from --NODE_CONFIG': function() {
-      assert.equal(CONFIG.EnvOverride.parm6, 101);
-    }
-
-  },
-
- 'Assuring a configuration property can be hidden': {
-    topic: function() {
-      var object = {
-        item1: 23,
-        subObject: {
-      	  item2: "hello"
-        }
-      };
-      return object;
-    },
-
-    'The makeHidden() method is available': function() {
-      assert.isFunction(CONFIG.makeHidden);
-    },
-
-    'The test object (before hiding) is correct': function(object) {
-      assert.isTrue(JSON.stringify(object) == '{"item1":23,"subObject":{"item2":"hello"}}');
-    },
-
-    'The test object (after hiding) is correct': function(object) {
-      CONFIG.makeHidden(object, 'item1');
-      assert.isTrue(JSON.stringify(object) == '{"subObject":{"item2":"hello"}}');
-    },
-
-    'The hidden property is readable, and has not changed': function(object) {
-      assert.isTrue(JSON.stringify(object) == '{"subObject":{"item2":"hello"}}');
-      assert.isTrue(object.item1 == 23);
-    }
-
-  },
-
-  'Assuring a configuration property can be made immutable': {
-    topic: function() {
-
-      CONFIG.makeImmutable(CONFIG.TestModule, 'parm1');
-      CONFIG.TestModule.parm1 = "setToThis";
-      return CONFIG.TestModule.parm1;
-    },
-
-    'The makeImmutable() method is available': function() {
-      assert.isFunction(CONFIG.makeImmutable);
-    },
-
-    'Correctly unable to change an immutable configuration': function(value) {
-      assert.isTrue(value != "setToThis");
-    },
-
-    'Left the original value intact after attempting the change': function(value) {
-      assert.equal(value, "value1");
-    }
-  },
-
-  'Configuration for module developers': {
-    topic: function() {
-
-      // Set some parameters for the test module
-      return CONFIG.setModuleDefaults("TestModule", {
-        parm1: 1000, parm2: 2000, parm3: 3000
-      });
-    },
-
-    'The setModuleDefaults() method is available': function() {
-      assert.isFunction(CONFIG.setModuleDefaults);
-    },
-
-    'The module config is in the CONFIG object': function(moduleConfig) {
-      assert.isTrue(typeof(CONFIG.TestModule) != "undefined");
-      assert.deepEqual(CONFIG.TestModule, moduleConfig);
-    },
-
-    'Local configurations are mixed in': function(moduleConfig) {
-      assert.equal(moduleConfig.parm1, "value1");
-    },
-
-    'Defaults remain intact unless overridden': function(moduleConfig) {
-      assert.equal(moduleConfig.parm2, 2000);
-    }
-
-  },
-
-  'Internal Change Notification Tests': {
-    topic: function() {
-
-      // Attach this topic as a watcher
-      var cb = this.callback;
-      CONFIG.watch(CONFIG, null, function(obj, prop, oldValue, newValue){
-        // Don't process the submodule test - that's for later
-        if (prop == 'parm3') return;
-        if (prop == 'dynamicArray') return;
-        if (prop == 'staticArray') {
-          cb('Watch callback should not have been called for staticArray');
-          return false;
-        }
-
-        cb(null, {obj:obj, prop:prop, oldValue:oldValue, newValue:newValue});
-      });
-
-      // Write the new watched value out to the runtime.json file
-      CONFIG.watchThisValue = newWatchedValue;
-
-      // Test that submodule configurations are persisted
-      CONFIG.TestModule.parm3 = 1234;
-
-      // Write the new array value out to the runtime.json file
-      CONFIG.dynamicArray = newDynamicArray;
-
-      // Test that changing an array d
-      CONFIG.staticArray = [2,1,3];
-    },
-
-    'The watch() method is available': function() {
-      assert.isFunction(CONFIG.watch);
-    },
-
-    'The change handler callback was fired': function(err, obj) {
-      assert.isTrue(true);
-    },
-
-    'And it was called on the correct object': function(err, obj) {
-      assert.isTrue(obj.obj === CONFIG);
-    },
-
-    'And it was called with the correct parameter': function(err, obj) {
-      assert.equal(obj.prop, 'watchThisValue');
-    },
-
-    'And it has the correct prior value': function(err, obj) {
-      assert.equal(obj.oldValue, originalWatchedValue);
-    },
-
-    'And it has the correct new value': function(err, obj) {
-      assert.equal(obj.newValue, newWatchedValue);
-    },
-
-    'And the config value was correctly set': function(err, obj) {
-      assert.equal(CONFIG.watchThisValue, newWatchedValue);
-    },
-
-    'Waiting for the O/S to notify us of changes...': function(err, obj) {
-      // This is just a message for the next test
-      assert.isTrue(true);
-    }
-
-  },
-
-  'Runtime Configuration Changes are Persisted to runtime.json': {
-    topic: function() {
-      // Watch the file for changes
-      var t = this;
-      FileSystem.unwatchFile(runtimeJsonFilename);
-      FileSystem.watchFile(runtimeJsonFilename, {persistent:true}, function(){
-        // This was failing on node v0.6 due to the watch happening before full write,
-        // so adding a small interval so it doesn't fail on older node.js versions
-        setTimeout(function(){
-	        t.callback(null, CONFIG._parseFile(runtimeJsonFilename));
-	      },10);
-
-        FileSystem.createReadStream(runtimeJsonFilename).pipe(FileSystem.createWriteStream(runtimeJsonFilenameBak));
-      });
-    },
-    'The runtime.json file was changed': function(err, runtimeObj) {
-      assert.isTrue(!err);
-    },
-    'Prior configuration values were kept intact': function(err, runtimeObj) {
-      assert.equal(runtimeObj.Customers.dbName, "override_from_runtime_json");
-    },
-    'Changed configuration values were persisted': function(err, runtimeObj) {
-      assert.equal(runtimeObj.watchThisValue, CONFIG.watchThisValue);
-      assert.deepEqual(runtimeObj.dynamicArray, CONFIG.dynamicArray);
-    },
-    'Unchanged configuration values were not persisted': function(err, runtimeObj) {
-      assert.isUndefined(runtimeObj.staticArray);
-    },
-    'Module default values are persisted': function(err, runtimeObj) {
-      assert.equal(runtimeObj.TestModule.parm3, 1234);
-    },
-    'The resetRuntime() method is available': function() {
-      assert.isFunction(CONFIG.resetRuntime);
-    },
-    'Runtime Configuration is empty': function() {
-      CONFIG.resetRuntime(function(err, written, buffer) {
-        FileSystem.readFile(runtimeJsonFilename, function(err, data) {
-            assert.isEqual(data,'{}');
-        });
-      });
-    },
-    teardown: function() {
-      FileSystem.rename(runtimeJsonFilenameBak, runtimeJsonFilename, function(err) {
-        if(err) {
-          console.log('Cant rename file');
-        }
-      });
-    }
-  },
-
-  'Assuring you can get originalConfig': {
-    topic: function() {
-      return CONFIG.getOriginalConfig();
-    },
-    'The getOriginalConfig() method is available': function() {
-      assert.isFunction(CONFIG.getOriginalConfig);
-    }
-  }
-
-});
-
-
-
-
-
- -
-
-
-
-Released on github under the Apache License 2.0 -version 0.4.35 -
-
- - - diff --git a/node_modules/config/doc/Config.html b/node_modules/config/doc/Config.html deleted file mode 100644 index a3d59f4..0000000 --- a/node_modules/config/doc/Config.html +++ /dev/null @@ -1,1768 +0,0 @@ - - - - - config Config - - - - - - - - - - -
-
-

Node.js Configuration

- Node.js Configuration - > config - > Config - -
-
- Search: -
-   -
-
-
-
- -
-
-
-
-
- Filters - - - -
-
- -

- - - - - Class: Config - - - -

- - - - - -
-

Runtime Application Configurations

-

-The config module exports a singleton object representing all runtime -configurations for this application deployment. -

-

-Application configurations are stored in files within the config directory -of your application. The default configuration file is loaded, followed -by files specific to the deployment type (development, testing, staging, -production, etc.). -

-

-For example, with the following config/default.yaml file: -

-
-...
-customer:
-  initialCredit: 500
-  db:
-    name: customer
-    port: 5984
-...
-
-

-The following code loads the customer section into the CONFIG variable: -

-

-var CONFIG = require('config').customer;
-...
-newCustomer.creditLimit = CONFIG.initialCredit;
-database.open(CONFIG.db.name, CONFIG.db.port);
-...
-
-
- - -
- -
- -
-
-

Methods

-
-
-

- _attachProtoDeep

-
- - protected - - - - _attachProtoDeep - ( - - - toObject - - - , - depth - - - ) - - -
- Attach the Config class prototype to all config objects recursively. -

-This allows you to do anything with CONFIG sub-objects as you can do with -the top-level CONFIG object. It's so you can do this: -

-
-var CUST_CONFIG = require('config').Customer;
-CUST_CONFIG.watch(...)
-
-
- -
- -
-
Parameters:
-
- toObject - <object> - - -
-
- depth - <object> - - -
-
- - - - - -
- -
-
-
-
-

- _cloneDeep

-
- - protected - - - object - _cloneDeep - ( - - - copyFrom - - - , - depth - - - ) - - -
- Return a deep copy of the specified object. -This returns a new object with all elements copied from the specified -object. Deep copies are made of objects and arrays so you can do anything -with the returned object without affecting the input object. -
- -
- -
-
Parameters:
-
- copyFrom - <object> - - The original object to copy from -
-
- depth - <integer> - - An optional depth to prevent recursion. Default: 20. -
-
- -
-
Returns: - - object -
-
A new object with the elements copied from the copyFrom object
-
- - - - -
- -
-
-
-
-

- _diffDeep

-
- - protected - - - object - _diffDeep - ( - - - object1 - - - , - object2 - - - , - depth - - - ) - - -
- Returns an object containing all elements that differ between two objects. -

-This method was designed to be used to create the runtime.json file -contents, but can be used to get the diffs between any two Javascript objects. -

-

-It works best when object2 originated by deep copying object1, then -changes were made to object2, and you want an object that would give you -the changes made to object1 which resulted in object2. -

-
- -
- -
-
Parameters:
-
- object1 - <object> - - The base object to compare to -
-
- object2 - <object> - - The object to compare with -
-
- depth - <integer> - - An optional depth to prevent recursion. Default: 20. -
-
- -
-
Returns: - - object -
-
A differential object, which if extended onto object1 would -result in object2.
-
- - - - -
- -
-
-
-
-

- _equalsDeep

-
- - protected - - - boolean - _equalsDeep - ( - - - object1 - - - , - object2 - - - , - depth - - - ) - - -
- Return true if two objects have equal contents. -
- -
- -
-
Parameters:
-
- object1 - <object> - - The object to compare from -
-
- object2 - <object> - - The object to compare with -
-
- depth - <integer> - - An optional depth to prevent recursion. Default: 20. -
-
- -
-
Returns: - - boolean -
-
True if both objects have equivalent contents
-
- - - - -
- -
-
-
-
-

- _extendDeep

-
- - protected - - - object - _extendDeep - ( - - - mergeInto - - - , - mergeFrom... - - - , - depth - - - ) - - -
- Extend an object, and any object it contains. -This does not replace deep objects, but dives into them -replacing individual elements instead. -
- -
- -
-
Parameters:
-
- mergeInto - <object> - - The object to merge into -
-
- mergeFrom... - <object...> - - - Any number of objects to merge from -
-
- depth - <integer> - - An optional depth to prevent recursion. Default: 20. -
-
- -
-
Returns: - - object -
-
The altered mergeInto object is returned
-
- - - - -
- -
-
-
-
-

- _getCmdLineArg

-
- - - - - MIXED - _getCmdLineArg - ( - - - searchFor - - - ) - - -
-

Get Command Line Arguments

-

-This method allows you to retrieve the value of the specified command line argument. -

-

-The argument is case sensitive, and must be of the form '--ARG_NAME=value' -

-
- -
- -
-
Parameters:
-
- searchFor - <STRING> - - The argument name to search for -
-
- -
-
Returns: - - MIXED -
-
FALSE if the argument was not found, the argument value if found
-
- - - - -
- -
-
-
-
-

- _initParam

-
- - - - - Any - _initParam - ( - - - paramName - - - , - [defaultValue] - - - ) - - -
-

Initialize a parameter from the command line or process environment

-

-This method looks for the parameter from the command line in the format ---PARAMETER=VALUE, then from the process environment, then from the -default specified as an argument. -

-
- -
- -
-
Parameters:
-
- paramName - <String> - - Name of the parameter -
-
- [defaultValue] - <Any> - - Default value of the parameter -
-
- -
-
Returns: - - Any -
-
The found value, or default value
-
- - - - -
- -
-
-
-
-

- _isObject

-
- - protected - - - boolean - _isObject - ( - - - arg - - - ) - - -
- Is the specified argument a regular javascript object? -The argument is an object if it's a JS object, but not an array. -
- -
- -
-
Parameters:
-
- arg - <MIXED> - - An argument of any type. -
-
- -
-
Returns: - - boolean -
-
TRUE if the arg is an object, FALSE if not
-
- - - - -
- -
-
-
-
-

- _loadFileConfigs

-
- - protected - - - this - _loadFileConfigs - ( - ) - - -
- Load the individual file configurations. -

-This method builds a map of filename to the configuration object defined -by the file. The search order is: -

-
-default.EXT
-(hostname).EXT
-(deployment).EXT
-(hostname)-(deployment).EXT
-local.EXT
-local-(deployment).EXT
-runtime.json
-
-

-EXT can be yml, yaml, coffee, json, or js signifying the file type. -yaml (and yml) is in YAML format, coffee is a coffee-script, -json is in JSON format, and js is a javascript executable file that is -require()'d with module.exports being the config object. -

-

-hostname is the $HOST environment variable (or --HOST command line parameter) -if set, otherwise the $HOSTNAME environment variable (or --HOSTNAME command -line parameter) if set, otherwise the hostname found from -require('os').hostname(). -

-

-Once a hostname is found, everything from the first period ('.') onwards -is removed. For example, abc.example.com becomes abc -

-

-(deployment) is the deployment type, found in the $NODE_ENV environment -variable or --NODE_ENV command line parameter. Defaults to 'development'. -

-

-The runtime.json file contains configuration changes made at runtime either -manually, or by the application setting a configuration value. -

-

-If the $NODE_APP_INSTANCE environment variable (or --NODE_APP_INSTANCE -command line parameter) is set, then files with this appendage will be loaded. -See the Multiple Applicstion Instances section of the main documentaion page -for more information. -

-
- -
- - -
-
Returns: - - this -
-
The configuration object
-
- - - - -
- -
-
-
-
-

- _loadOldStyleEnv

-
- - protected - - - Object - _loadOldStyleEnv - ( - ) - - -
- Check for the old-style environment variable configurations -
- -
- - -
-
Returns: - - Object -
-
old-style configurations from process.env
-
- - - -
- Deprecated   -
- -
- -
-
-
-
-

- _parseFile

-
- - protected - - - configObject - _parseFile - ( - - - fullFilename - - - ) - - -
- Parse and return the specified configuration file. -If the file exists in the application config directory, it will -parse and return it as a JavaScript object. -The file extension determines the parser to use. -.js = File to run that has a module.exports containing the config object -.json = File is parsed using JSON.parse() -.coffee = File to run that has a module.exports with coffee-script containing the config object -.yaml (or .yml) = Parsed with a YAML parser -If the file doesn't exist, a null will be returned. If the file can't be -parsed, an exception will be thrown. -This method performs synchronous file operations, and should not be called -after synchronous module loading. -
- -
- -
-
Parameters:
-
- fullFilename - <string> - - The full file path and name -
-
- -
-
Returns: - - configObject -
-
The configuration object parsed from the file
-
- - - - -
- -
-
-
-
-

- _persistConfigsOnChange

-
- - protected - - - void - _persistConfigsOnChange - ( - - - object - - - ) - - -
-

-Watch the specified object for a change in properties, and persist changes -to runtime.json when a change is detected. -

-
- -
- -
-
Parameters:
-
- object - <object> - - - The config object to watch -
-
- -
-
Returns: - - void -
-
-
- - - - -
- -
-
-
-
-

- _stripComments

-
- - protected - - - string - _stripComments - ( - - - fileString - - - ) - - -
- Strip all Javascript type comments from the string. -The string is usually a file loaded from the O/S, containing -newlines and javascript type comments. -Thanks to James Padolsey, and all who conributed to this implementation. -http://james.padolsey.com/javascript/javascript-comment-removal-revisted/ -
- -
- -
-
Parameters:
-
- fileString - <string> - - The string to strip comments from -
-
- -
-
Returns: - - string -
-
The string with comments stripped.
-
- - - - -
- -
-
-
-
-

- _stripYamlComments

-
- - protected - - - string - _stripYamlComments - ( - - - fileString - - - ) - - -
- Strip YAML comments from the string -The 2.0 yaml parser doesn't allow comment-only or blank lines. Strip them. -
- -
- -
-
Parameters:
-
- fileString - <string> - - The string to strip comments from -
-
- -
-
Returns: - - string -
-
The string with comments stripped.
-
- - - - -
- -
-
-
-
-

- constructor

-
- - - - - object - constructor - ( - ) - - -
-

Get the configuration object.

-

-The configuration object is a shared singleton object within the application, -attained by calling require('config'). -

-

-Usually you'll specify a CONFIG variable at the top of your .js file -for file/module scope. If you want the root of the object, you can do this: -

-
-var CONFIG = require('config');
-
-

-Sometimes you only care about a specific sub-object within the CONFIG -object. In that case you could do this at the top of your file: -

-
-var CONFIG = require('config').customer;
-or
-var CUSTOMER_CONFIG = require('config').customer;
-
- -
- -
- - -
-
Returns: - - object -
-
CONFIG - The top level configuration object
-
- - - - -
- -
-
-
-
-

- getConfigSources

-
- - - - - Array[Object] - getConfigSources - ( - ) - - -
- Return the sources for the configurations -

-All sources for configurations are stored in an array of objects containing -the source name (usually the filename), the original source (as a string), -and the parsed source as an object. -

-
- -
- - -
-
Returns: - - Array[Object] -
-
configSources - An array of objects containing -name, original, and parsed elements
-
- - - - -
- -
-
-
-
-

- getOriginalConfig

-
- - - - - object - getOriginalConfig - ( - ) - - -
-

Exposing original Config

-

-This method allows get the original config properties. -

-
- -
- - -
-
Returns: - - object -
-
The original config object is returned
-
- - - - -
- -
-
-
-
-

- makeHidden

-
- - - - - object - makeHidden - ( - - - object - - - , - property - - - , - value - - - ) - - -
-

Make a configuration property hidden so it doesn't appear when enumerating -elements of the object.

-

-The property still exists and can be read from and written to, but it won't -show up in for ... in loops, Object.keys(), or JSON.stringify() type methods. -

-

-If the property already exists, it will be made hidden. Otherwise it will -be created as a hidden property with the specified value. -

-

-This method was built for hiding configuration values, but it can be applied -to any javascript object. -

-

Example:

-
-var CONFIG = require('config');
-...
-// Hide the Amazon S3 credentials
-CONFIG.makeHidden(CONFIG.amazonS3, 'access_id');
-CONFIG.makeHidden(CONFIG.amazonS3, 'secret_key');
-
-
- -
- -
-
Parameters:
-
- object - <object> - - - The object to make a hidden property into. -
-
- property - <string> - - - The name of the property to make hidden. -
-
- value - <mixed> - - - (optional) Set the property value to this (otherwise leave alone) -
-
- -
-
Returns: - - object -
-
object - The original object is returned - for chaining.
-
- - - - -
- -
-
-
-
-

- makeImmutable

-
- - - - - object - makeImmutable - ( - - - object - - - , - property - - - , - value - - - ) - - -
-

Make a configuration property immutable (assuring it cannot be changed -from the current value).

-

-This operation cannot be undone. -

-

-This method was built for disabling runtime changes to configuration values, -but it can be applied to any javascript object. -

-

Example:

-
-var CONFIG = require('config').customer;
-...
-// Obtain a DB connection using CONFIG parameters
-database.open(CONFIG.db.name, CONFIG.db.port);
-...
-// Don't allow database changes after connect
-CONFIG.makeImmutable(CONFIG.db, 'name');
-CONFIG.makeImmutable(CONFIG.db, 'port');
-
-
- -
- -
-
Parameters:
-
- object - <object> - - - The object to attach an immutable property into. -
-
- property - <string> - - - The name of the property to make immutable. -
-
- value - <mixed> - - - (optional) Set the property value to this (otherwise leave alone) -
-
- -
-
Returns: - - object -
-
object - The original object is returned - for chaining.
-
- - - - -
- -
-
-
-
-

- resetRuntime

-
- - - - - void - resetRuntime - ( - - - callback - - - ) - - -
-

Reset Runtime Config

-

-This method allows you to reset the runtime.json generated file. -

-
- -
- -
-
Parameters:
-
- callback - <function> - - An optional callback function -
-
- -
-
Returns: - - void -
-
-
- - - - -
- -
-
-
-
-

- safeWriteFile

-
- - - - - void - safeWriteFile - ( - - - filename - - - , - content - - - , - callback - - - ) - - -
-

Safely write a file

-

-This method safely overwrites a file by first writing to a temporary file -and then renaming it. This to ensure no other process reads to file in a -truncated state. -

-
- -
- -
-
Parameters:
-
- filename - <String> - - Filename to write to. -
-
- content - <String> - - Data to write. -
-
- callback - <Function> - - Callback function. -
-
- -
-
Returns: - - void -
-
-
- - - - -
- -
-
-
-
-

- setModuleDefaults

-
- - - - - object - setModuleDefaults - ( - - - moduleName - - - , - defaultProperties - - - ) - - -
-

-Set default configurations for a node.js module. -

-

-This allows module developers to attach their configurations onto the -default configuration object so they can be configured by the consumers -of the module. -

-

Using the function within your module:

-
-var CONFIG = require("config");
-CONFIG.setModuleDefaults("MyModule", {
-  templateName: "t-50",
-  colorScheme: "green"
-});
-
-// Template name may be overridden by application config files -console.log("Template: " + CONFIG.MyModule.templateName); -
-

-The above example results in a "MyModule" element of the configuration -object, containing an object with the specified default values. -

-
- -
- -
-
Parameters:
-
- moduleName - <string> - - - Name of your module. -
-
- defaultProperties - <object> - - - The default module configuration. -
-
- -
-
Returns: - - object -
-
moduleConfig - The module level configuration object.
-
- - - - -
- -
-
-
-
-

- watch

-
- - - - - object - watch - ( - - - object - - - , - property - - - , - handler - - - , - depth - - - ) - - -
-

Monitor a configuration value for runtime changes.

-

-Configuration values can be changed at runtime by the application or by a -manual change to the config/runtime.json file. -This method lets you specify a function to run when a configuration -value changes. -

-

-This was built for monitoring changes to configuration values, -but it can be used for watching changes to any javascript object. -

-

Example:

-
-var CONFIG = require('config').customer;
-...
-// Watch for any changes to the customer configuration
-CONFIG.watch(CONFIG, null, function(object, propertyName, priorValue, newValue) {
- console.log("Customer configuration " + propertyName + " changed from " + priorValue + " to " + newValue);
-});
-
-
- -
- -
-
Parameters:
-
- object - <object> - - - The object to watch. -
-
- property - <string> - - - The property name to watch. Watch all object properties if null. -
-
- handler - <function(object, propertyName, priorValue, newValue)> - - - Handler called when a property change is detected. -The handler is run along with other handlers registered for notification. -If your handler changes the value of the property, that change is applied after all handlers have finished processing the current change. -Then all handlers (including this one) will be called again with the newly changed value. -
-
- depth - <integer> - - (optional) - If watching all object properties or if the specified property is an object, this specifies the depth of the object graph to watch for changes. Default 6. -
-
- -
-
Returns: - - object -
-
object - The original object is returned - for chaining.
-
- - - - -
- -
-
-
-
-

- watchForConfigFileChanges

-
- - - - - void - watchForConfigFileChanges - ( - - - interval - - - ) - - -
- Start or stop runtime.json configuration file watching -

-Node-config automatically monitors and apply changes made to the -config/runtime.json file. This paradigm allows for manual changes to running -application servers, and for multi-node application servers to keep in sync. -

-

-This method allows you to change the polling interval from the default -interval (2.5 seconds), or to turn file watching off. On Linux systems with -inotify, and in node.js versions 0.6 and above, this interval is ignored. -

-

-runtime.json file watching can be disabled by setting the NODE_CONFIG_DISABLE_FILE_WATCH -environment variable or --NODE_CONFIG_DISABLE_FILE_WATCH command line parameter -to "Y" prior to running your application. -

-
- -
- -
-
Parameters:
-
- interval - <Integer> - - - Polling interval in milliseconds. Defaults to 2500. -
-
- -
-
Returns: - - void -
-
-
- - - - -
- -
-
-
-
-
- -
- -
- - -
- -
- -
- -
-
- -
-
-
-Released on github under the Apache License 2.0 -version 0.4.35 -
-
- - - diff --git a/node_modules/config/doc/ConfigTest.html b/node_modules/config/doc/ConfigTest.html deleted file mode 100644 index 6a9077c..0000000 --- a/node_modules/config/doc/ConfigTest.html +++ /dev/null @@ -1,132 +0,0 @@ - - - - - test ConfigTest - - - - - - - - - - -
-
-

Node.js Configuration

- Node.js Configuration - > test - > ConfigTest - -
-
- Search: -
-   -
-
-
-
- -
-
-
-
-
- Filters - - - -
-
- -

- - - - - Class: ConfigTest - - - -

- - - - - -
-

Unit tests for the node-config library. To run type:

-
npm test
-

Or, in a project that uses node-config:

-
npm test config
-
- - -
- -
- -
- -
- -
- - -
- -
- -
- -
-
-
- -
-
-
-
-Released on github under the Apache License 2.0 -version 0.4.35 -
-
- - - diff --git a/node_modules/config/doc/ProtectedTest.html b/node_modules/config/doc/ProtectedTest.html deleted file mode 100644 index 2d886ff..0000000 --- a/node_modules/config/doc/ProtectedTest.html +++ /dev/null @@ -1,132 +0,0 @@ - - - - - test ProtectedTest - - - - - - - - - - -
-
-

Node.js Configuration

- Node.js Configuration - > test - > ProtectedTest - -
-
- Search: -
-   -
-
-
-
- -
-
-
-
-
- Filters - - - -
-
- -

- - - - - Class: ProtectedTest - - - -

- - - - - -
-

Tests for underlying node-config utilities. To run type:

-
npm test
-

Or, in a project that uses node-config:

-
npm test config
-
- - -
- -
- -
- -
- -
- - -
- -
- -
- -
-
-
- -
-
-
-
-Released on github under the Apache License 2.0 -version 0.4.35 -
-
- - - diff --git a/node_modules/config/doc/assets/ac-js b/node_modules/config/doc/assets/ac-js deleted file mode 100755 index 15a6dff..0000000 --- a/node_modules/config/doc/assets/ac-js +++ /dev/null @@ -1,162 +0,0 @@ -(function() { - var Event=YAHOO.util.Event, - Dom=YAHOO.util.Dom, - oACDS, oAutoComp, - show = { - 'private': false, - 'protected': false, - 'deprecated': false - }; - -Event.onAvailable('yui-classopts-form', function() { - //Checkboxes are available.. - var handleClick = function(e) { - var id, checked = false; - if (YAHOO.lang.isString(e)) { - id = e; - } else { - var tar = Event.getTarget(e); - id = tar.id; - } - var el = Dom.get(id); - checked = el.checked; - - var className = id; - if (checked) { - show[id.replace('show_', '')] = true; - Dom.addClass(document.body, className); - YAHOO.util.Cookie.setSub('yuidoc', id, 'checked'); - } else { - show[id.replace('show_', '')] = false; - Dom.removeClass(document.body, className); - YAHOO.util.Cookie.setSub('yuidoc', id, ''); - } - }; - - var checkCookie = function(id) { - var value = YAHOO.util.Cookie.getSub('yuidoc', id), - el = Dom.get(id), checked = (value === 'checked');; - - /* - if (value === 'checked') { - el.checked = true; - } else { - el.checked = false; - } - */ - - el.checked = checked; - return checked; - }; - - var els = ['show_deprecated', 'show_protected', 'show_private'], - reapplyHash = false; - - for (var i = 0; i < els.length; i++) { - Event.on(els[i], 'click', handleClick); - reapplyHash = checkCookie(els[i]) || reapplyHash; - handleClick(els[i]); - } - - // If we dynamically show private/protected/etc items during - // load, we need to reapply anchors so that the search feature - // works correctly for items that are initially hidden. - if (reapplyHash) { - var dl = document.location, hash = dl.hash; - if (hash) { - dl.hash = hash; - } - } - -}); - -//Starting the AutoComplete code - var getResults = function(query) { - var results = []; - if(query && query.length > 0) { - - var q = query.toLowerCase(); - - for (var i=0, len=ALL_YUI_PROPS.length; i -1 ) { - results.push([query, prop]); - } - } - } - } - - return results; - }; - - // Define Custom Event handlers - var myOnDataReturn = function(sType, aArgs) { - var oAutoComp = aArgs[0]; - var query = aArgs[1]; - var aResults = aArgs[2]; - - if(aResults.length == 0) { - if (query.length > 0) { - oAutoComp.setBody("
Not found
"); - } - } - }; - - var myOnItemSelect = function(sType, aArgs) { - var ac = aArgs[0]; - var item = aArgs[2]; - location.href = item[1].url; - }; - - - Event.onAvailable("searchresults", function() { - - // Instantiate JS Function DataSource - oACDS = new YAHOO.widget.DS_JSFunction(getResults); - oACDS.maxCacheEntries = 30; - - // Instantiate AutoComplete - oAutoComp = new YAHOO.widget.AutoComplete('searchinput','searchresults', oACDS); - //oAutoComp.alwaysShowContainer = true; - oAutoComp.queryDelay = 0.2; - oAutoComp.maxResultsDisplayed = 200; - oAutoComp.minQueryLength = 0; - oAutoComp.formatResult = function(oResultItem, query) { - var sMarkup = "" + oResultItem[1].host + ' ' + oResultItem[1].name + ''; - return sMarkup; - }; - - // Subscribe to Custom Events - oAutoComp.dataReturnEvent.subscribe(myOnDataReturn); - oAutoComp.itemSelectEvent.subscribe(myOnItemSelect); - - // Set initial content in the container - oAutoComp.sendQuery(Dom.get("searchinput").value); - - }); - - var validateForm = function() { - return false; - }; - - YAHOO.util.Event.onAvailable('classTab', function() { - var tabs = new YAHOO.widget.TabView('classTab'); - }); - /* - YAHOO.util.Event.onAvailable('codeTree', function() { - var tree1 = new YAHOO.widget.TreeView('codeTree'); - tree1.render(); - }); - */ - -})(); diff --git a/node_modules/config/doc/assets/api-js b/node_modules/config/doc/assets/api-js deleted file mode 100755 index e8132e0..0000000 --- a/node_modules/config/doc/assets/api-js +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright (c) 2008, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version: 2.6.0 -*/ -if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var A=arguments,E=null,C,B,D;for(C=0;C0)?A.dump(D[F],I-1):L);}else{K.push(D[F]);}K.push(J);}if(K.length>1){K.pop();}K.push("]");}else{K.push("{");for(F in D){if(A.hasOwnProperty(D,F)){K.push(F+G);if(A.isObject(D[F])){K.push((I>0)?A.dump(D[F],I-1):L);}else{K.push(D[F]);}K.push(J);}}if(K.length>1){K.pop();}K.push("}");}return K.join("");},substitute:function(S,E,L){var I,H,G,O,P,R,N=[],F,J="dump",M=" ",D="{",Q="}";for(;;){I=S.lastIndexOf(D);if(I<0){break;}H=S.indexOf(Q,I);if(I+1>=H){break;}F=S.substring(I+1,H);O=F;R=null;G=O.indexOf(M);if(G>-1){R=O.substring(G+1);O=O.substring(0,G);}P=E[O];if(L){P=L(O,P,R);}if(A.isObject(P)){if(A.isArray(P)){P=A.dump(P,parseInt(R,10));}else{R=R||"";var K=R.indexOf(J);if(K>-1){R=R.substring(4);}if(P.toString===Object.prototype.toString||K>-1){P=A.dump(P,parseInt(R,10));}else{P=P.toString();}}}else{if(!A.isString(P)&&!A.isNumber(P)){P="~-"+N.length+"-~";N[N.length]=F;}}S=S.substring(0,I)+P+S.substring(H+1);}for(I=N.length-1;I>=0;I=I-1){S=S.replace(new RegExp("~-"+I+"-~"),"{"+N[I]+"}","g");}return S;},trim:function(D){try{return D.replace(/^\s+|\s+$/g,"");}catch(E){return D;}},merge:function(){var G={},E=arguments;for(var F=0,D=E.length;F=this.left&&A.right<=this.right&&A.top>=this.top&&A.bottom<=this.bottom);};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left));};YAHOO.util.Region.prototype.intersect=function(E){var C=Math.max(this.top,E.top);var D=Math.min(this.right,E.right);var A=Math.min(this.bottom,E.bottom);var B=Math.max(this.left,E.left);if(A>=C&&D>=B){return new YAHOO.util.Region(C,D,A,B);}else{return null;}};YAHOO.util.Region.prototype.union=function(E){var C=Math.min(this.top,E.top);var D=Math.max(this.right,E.right);var A=Math.max(this.bottom,E.bottom);var B=Math.min(this.left,E.left);return new YAHOO.util.Region(C,D,A,B);};YAHOO.util.Region.prototype.toString=function(){return("Region {"+"top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+"}");};YAHOO.util.Region.getRegion=function(D){var F=YAHOO.util.Dom.getXY(D);var C=F[1];var E=F[0]+D.offsetWidth;var A=F[1]+D.offsetHeight;var B=F[0];return new YAHOO.util.Region(C,E,A,B);};YAHOO.util.Point=function(A,B){if(YAHOO.lang.isArray(A)){B=A[1];A=A[0];}this.x=this.right=this.left=this[0]=A;this.y=this.top=this.bottom=this[1]=B;};YAHOO.util.Point.prototype=new YAHOO.util.Region();YAHOO.register("dom",YAHOO.util.Dom,{version:"2.6.0",build:"1321"});YAHOO.util.CustomEvent=function(D,B,C,A){this.type=D;this.scope=B||window;this.silent=C;this.signature=A||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}var E="_YUICEOnSubscribe";if(D!==E){this.subscribeEvent=new YAHOO.util.CustomEvent(E,this,true);}this.lastError=null;};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(B,C,A){if(!B){throw new Error("Invalid callback for subscriber to '"+this.type+"'");}if(this.subscribeEvent){this.subscribeEvent.fire(B,C,A);}this.subscribers.push(new YAHOO.util.Subscriber(B,C,A));},unsubscribe:function(D,F){if(!D){return this.unsubscribeAll();}var E=false;for(var B=0,A=this.subscribers.length;B0){B=I[0];}try{G=M.fn.call(L,B,M.obj);}catch(F){this.lastError=F;if(A){throw F;}}}else{try{G=M.fn.call(L,this.type,I,M.obj);}catch(H){this.lastError=H;if(A){throw H;}}}if(false===G){if(!this.silent){}break;}}}return(G!==false);},unsubscribeAll:function(){for(var A=this.subscribers.length-1;A>-1;A--){this._delete(A);}this.subscribers=[];return A;},_delete:function(A){var B=this.subscribers[A];if(B){delete B.fn;delete B.obj;}this.subscribers.splice(A,1);},toString:function(){return"CustomEvent: "+"'"+this.type+"', "+"scope: "+this.scope;}};YAHOO.util.Subscriber=function(B,C,A){this.fn=B;this.obj=YAHOO.lang.isUndefined(C)?null:C;this.override=A;};YAHOO.util.Subscriber.prototype.getScope=function(A){if(this.override){if(this.override===true){return this.obj;}else{return this.override;}}return A;};YAHOO.util.Subscriber.prototype.contains=function(A,B){if(B){return(this.fn==A&&this.obj==B);}else{return(this.fn==A);}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+this.obj+", override: "+(this.override||"no")+" }";};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var H=false;var I=[];var J=[];var G=[];var E=[];var C=0;var F=[];var B=[];var A=0;var D={63232:38,63233:40,63234:37,63235:39,63276:33,63277:34,25:9};var K=YAHOO.env.ua.ie?"focusin":"focus";var L=YAHOO.env.ua.ie?"focusout":"blur";return{POLL_RETRYS:2000,POLL_INTERVAL:20,EL:0,TYPE:1,FN:2,WFN:3,UNLOAD_OBJ:3,ADJ_SCOPE:4,OBJ:5,OVERRIDE:6,CAPTURE:7,lastError:null,isSafari:YAHOO.env.ua.webkit,webkit:YAHOO.env.ua.webkit,isIE:YAHOO.env.ua.ie,_interval:null,_dri:null,DOMReady:false,throwErrors:false,startInterval:function(){if(!this._interval){var M=this;var N=function(){M._tryPreloadAttach();};this._interval=setInterval(N,this.POLL_INTERVAL);}},onAvailable:function(R,O,S,Q,P){var M=(YAHOO.lang.isString(R))?[R]:R;for(var N=0;N-1;Q--){W=(this._removeListener(N[Q],M,V,Y)&&W);}return W;}}if(!V||!V.call){return this.purgeElement(N,false,M);}if("unload"==M){for(Q=J.length-1;Q>-1;Q--){X=J[Q];if(X&&X[0]==N&&X[1]==M&&X[2]==V){J.splice(Q,1);return true;}}return false;}var R=null;var S=arguments[4];if("undefined"===typeof S){S=this._getCacheIndex(N,M,V);}if(S>=0){R=I[S];}if(!N||!R){return false;}if(this.useLegacyEvent(N,M)){var P=this.getLegacyIndex(N,M);var O=E[P];if(O){for(Q=0,T=O.length;Q0&&F.length>0);}var R=[];var T=function(V,W){var U=V;if(W.override){if(W.override===true){U=W.obj;}else{U=W.override;}}W.fn.call(U,W.obj);};var N,M,Q,P,O=[];for(N=0,M=F.length;N-1;N--){Q=F[N];if(!Q||!Q.id){F.splice(N,1);}}this.startInterval();}else{clearInterval(this._interval);this._interval=null;}this.locked=false;},purgeElement:function(Q,R,T){var O=(YAHOO.lang.isString(Q))?this.getEl(Q):Q;var S=this.getListeners(O,T),P,M;if(S){for(P=S.length-1;P>-1;P--){var N=S[P];this._removeListener(O,N.type,N.fn,N.capture);}}if(R&&O&&O.childNodes){for(P=0,M=O.childNodes.length;P-1;O--){N=I[O];if(N){M._removeListener(N[M.EL],N[M.TYPE],N[M.FN],N[M.CAPTURE],O);}}N=null;}G=null;M._simpleRemove(window,"unload",M._unload);},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var M=document.documentElement,N=document.body;if(M&&(M.scrollTop||M.scrollLeft)){return[M.scrollTop,M.scrollLeft];}else{if(N){return[N.scrollTop,N.scrollLeft];}else{return[0,0];}}},regCE:function(){},_simpleAdd:function(){if(window.addEventListener){return function(O,P,N,M){O.addEventListener(P,N,(M));};}else{if(window.attachEvent){return function(O,P,N,M){O.attachEvent("on"+P,N);};}else{return function(){};}}}(),_simpleRemove:function(){if(window.removeEventListener){return function(O,P,N,M){O.removeEventListener(P,N,(M));};}else{if(window.detachEvent){return function(N,O,M){N.detachEvent("on"+O,M);};}else{return function(){};}}}()};}();(function(){var EU=YAHOO.util.Event;EU.on=EU.addListener;EU.onFocus=EU.addFocusListener;EU.onBlur=EU.addBlurListener; -/* DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */ -if(EU.isIE){YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);var n=document.createElement("p");EU._dri=setInterval(function(){try{n.doScroll("left");clearInterval(EU._dri);EU._dri=null;EU._ready();n=null;}catch(ex){}},EU.POLL_INTERVAL);}else{if(EU.webkit&&EU.webkit<525){EU._dri=setInterval(function(){var rs=document.readyState;if("loaded"==rs||"complete"==rs){clearInterval(EU._dri);EU._dri=null;EU._ready();}},EU.POLL_INTERVAL);}else{EU._simpleAdd(document,"DOMContentLoaded",EU._ready);}}EU._simpleAdd(window,"load",EU._load);EU._simpleAdd(window,"unload",EU._unload);EU._tryPreloadAttach();})();}YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(A,C,F,E){this.__yui_events=this.__yui_events||{}; -var D=this.__yui_events[A];if(D){D.subscribe(C,F,E);}else{this.__yui_subscribers=this.__yui_subscribers||{};var B=this.__yui_subscribers;if(!B[A]){B[A]=[];}B[A].push({fn:C,obj:F,override:E});}},unsubscribe:function(C,E,G){this.__yui_events=this.__yui_events||{};var A=this.__yui_events;if(C){var F=A[C];if(F){return F.unsubscribe(E,G);}}else{var B=true;for(var D in A){if(YAHOO.lang.hasOwnProperty(A,D)){B=B&&A[D].unsubscribe(E,G);}}return B;}return false;},unsubscribeAll:function(A){return this.unsubscribe(A);},createEvent:function(G,D){this.__yui_events=this.__yui_events||{};var A=D||{};var I=this.__yui_events;if(I[G]){}else{var H=A.scope||this;var E=(A.silent);var B=new YAHOO.util.CustomEvent(G,H,E,YAHOO.util.CustomEvent.FLAT);I[G]=B;if(A.onSubscribeCallback){B.subscribeEvent.subscribe(A.onSubscribeCallback);}this.__yui_subscribers=this.__yui_subscribers||{};var F=this.__yui_subscribers[G];if(F){for(var C=0;C0){if(!aCache){this._aCache=[];}else{var nCacheLength=aCache.length;if(nCacheLength>0){var oResponse=null;this.fireEvent("cacheRequestEvent",{request:oRequest,callback:oCallback,caller:oCaller});for(var i=nCacheLength-1;i>=0;i--){var oCacheElem=aCache[i];if(this.isCacheHit(oRequest,oCacheElem.request)){oResponse=oCacheElem.response;this.fireEvent("cacheResponseEvent",{request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});if(i=this.maxCacheEntries){aCache.shift();}var oCacheElem={request:oRequest,response:oResponse};aCache[aCache.length]=oCacheElem;this.fireEvent("responseCacheEvent",{request:oRequest,response:oResponse});},flushCache:function(){if(this._aCache){this._aCache=[];this.fireEvent("cacheFlushEvent");}},setInterval:function(nMsec,oRequest,oCallback,oCaller){if(lang.isNumber(nMsec)&&(nMsec>=0)){var oSelf=this;var nId=setInterval(function(){oSelf.makeConnection(oRequest,oCallback,oCaller);},nMsec);this._aIntervals.push(nId);return nId;}else{}},clearInterval:function(nId){var tracker=this._aIntervals||[];for(var i=tracker.length-1;i>-1;i--){if(tracker[i]===nId){tracker.splice(i,1);clearInterval(nId);}}},clearAllIntervals:function(){var tracker=this._aIntervals||[];for(var i=tracker.length-1;i>-1;i--){clearInterval(tracker[i]);}tracker=[];},sendRequest:function(oRequest,oCallback,oCaller){var oCachedResponse=this.getCachedResponse(oRequest,oCallback,oCaller);if(oCachedResponse){DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller);return null;}return this.makeConnection(oRequest,oCallback,oCaller);},makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oRawResponse=this.liveData;this.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);return tId;},handleResponse:function(oRequest,oRawResponse,oCallback,oCaller,tId){this.fireEvent("responseEvent",{tId:tId,request:oRequest,response:oRawResponse,callback:oCallback,caller:oCaller});var xhr=(this.dataType==DS.TYPE_XHR)?true:false;var oParsedResponse=null;var oFullResponse=oRawResponse;if(this.responseType===DS.TYPE_UNKNOWN){var ctype=(oRawResponse&&oRawResponse.getResponseHeader)?oRawResponse.getResponseHeader["Content-Type"]:null;if(ctype){if(ctype.indexOf("text/xml")>-1){this.responseType=DS.TYPE_XML;}else{if(ctype.indexOf("application/json")>-1){this.responseType=DS.TYPE_JSON;}else{if(ctype.indexOf("text/plain")>-1){this.responseType=DS.TYPE_TEXT;}}}}else{if(YAHOO.lang.isArray(oRawResponse)){this.responseType=DS.TYPE_JSARRAY;}else{if(oRawResponse&&oRawResponse.nodeType&&oRawResponse.nodeType==9){this.responseType=DS.TYPE_XML;}else{if(oRawResponse&&oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE;}else{if(YAHOO.lang.isObject(oRawResponse)){this.responseType=DS.TYPE_JSON;}else{if(YAHOO.lang.isString(oRawResponse)){this.responseType=DS.TYPE_TEXT;}}}}}}}switch(this.responseType){case DS.TYPE_JSARRAY:if(xhr&&oRawResponse&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText;}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseArrayData(oRequest,oFullResponse); -break;case DS.TYPE_JSON:if(xhr&&oRawResponse&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText;}try{if(lang.isString(oFullResponse)){if(lang.JSON){oFullResponse=lang.JSON.parse(oFullResponse);}else{if(window.JSON&&JSON.parse){oFullResponse=JSON.parse(oFullResponse);}else{if(oFullResponse.parseJSON){oFullResponse=oFullResponse.parseJSON();}else{while(oFullResponse.length>0&&(oFullResponse.charAt(0)!="{")&&(oFullResponse.charAt(0)!="[")){oFullResponse=oFullResponse.substring(1,oFullResponse.length);}if(oFullResponse.length>0){var objEnd=Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));oFullResponse=oFullResponse.substring(0,objEnd+1);oFullResponse=eval("("+oFullResponse+")");}}}}}}catch(e){}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseJSONData(oRequest,oFullResponse);break;case DS.TYPE_HTMLTABLE:if(xhr&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText;}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseHTMLTableData(oRequest,oFullResponse);break;case DS.TYPE_XML:if(xhr&&oRawResponse.responseXML){oFullResponse=oRawResponse.responseXML;}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseXMLData(oRequest,oFullResponse);break;case DS.TYPE_TEXT:if(xhr&&lang.isString(oRawResponse.responseText)){oFullResponse=oRawResponse.responseText;}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseTextData(oRequest,oFullResponse);break;default:oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseData(oRequest,oFullResponse);break;}oParsedResponse=oParsedResponse||{};if(!oParsedResponse.results){oParsedResponse.results=[];}if(!oParsedResponse.meta){oParsedResponse.meta={};}if(oParsedResponse&&!oParsedResponse.error){oParsedResponse=this.doBeforeCallback(oRequest,oFullResponse,oParsedResponse,oCallback);this.fireEvent("responseParseEvent",{request:oRequest,response:oParsedResponse,callback:oCallback,caller:oCaller});this.addToCache(oRequest,oParsedResponse);}else{oParsedResponse.error=true;this.fireEvent("dataErrorEvent",{request:oRequest,response:oRawResponse,callback:oCallback,caller:oCaller,message:DS.ERROR_DATANULL});}oParsedResponse.tId=tId;DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller);},doBeforeParseData:function(oRequest,oFullResponse,oCallback){return oFullResponse;},doBeforeCallback:function(oRequest,oFullResponse,oParsedResponse,oCallback){return oParsedResponse;},parseData:function(oRequest,oFullResponse){if(lang.isValue(oFullResponse)){var oParsedResponse={results:oFullResponse,meta:{}};return oParsedResponse;}return null;},parseArrayData:function(oRequest,oFullResponse){if(lang.isArray(oFullResponse)){var results=[],i,j,rec,field,data;if(lang.isArray(this.responseSchema.fields)){var fields=this.responseSchema.fields;for(i=fields.length-1;i>=0;--i){if(typeof fields[i]!=="object"){fields[i]={key:fields[i]};}}var parsers={},p;for(i=fields.length-1;i>=0;--i){p=(typeof fields[i].parser==="function"?fields[i].parser:DS.Parser[fields[i].parser+""])||fields[i].converter;if(p){parsers[fields[i].key]=p;}}var arrType=lang.isArray(oFullResponse[0]);for(i=oFullResponse.length-1;i>-1;i--){var oResult={};rec=oFullResponse[i];if(typeof rec==="object"){for(j=fields.length-1;j>-1;j--){field=fields[j];data=arrType?rec[j]:rec[field.key];if(parsers[field.key]){data=parsers[field.key].call(this,data);}if(data===undefined){data=null;}oResult[field.key]=data;}}else{if(lang.isString(rec)){for(j=fields.length-1;j>-1;j--){field=fields[j];data=rec;if(parsers[field.key]){data=parsers[field.key].call(this,data);}if(data===undefined){data=null;}oResult[field.key]=data;}}}results[i]=oResult;}}else{results=oFullResponse;}var oParsedResponse={results:results};return oParsedResponse;}return null;},parseTextData:function(oRequest,oFullResponse){if(lang.isString(oFullResponse)){if(lang.isString(this.responseSchema.recordDelim)&&lang.isString(this.responseSchema.fieldDelim)){var oParsedResponse={results:[]};var recDelim=this.responseSchema.recordDelim;var fieldDelim=this.responseSchema.fieldDelim;if(oFullResponse.length>0){var newLength=oFullResponse.length-recDelim.length;if(oFullResponse.substr(newLength)==recDelim){oFullResponse=oFullResponse.substr(0,newLength);}if(oFullResponse.length>0){var recordsarray=oFullResponse.split(recDelim);for(var i=0,len=recordsarray.length,recIdx=0;i0)){var fielddataarray=recordsarray[i].split(fieldDelim);var oResult={};if(lang.isArray(this.responseSchema.fields)){var fields=this.responseSchema.fields;for(var j=fields.length-1;j>-1;j--){try{var data=fielddataarray[j];if(lang.isString(data)){if(data.charAt(0)=='"'){data=data.substr(1);}if(data.charAt(data.length-1)=='"'){data=data.substr(0,data.length-1);}var field=fields[j];var key=(lang.isValue(field.key))?field.key:field;if(!field.parser&&field.converter){field.parser=field.converter;}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data);}if(data===undefined){data=null;}oResult[key]=data;}else{bError=true;}}catch(e){bError=true;}}}else{oResult=fielddataarray;}if(!bError){oParsedResponse.results[recIdx++]=oResult;}}}}}return oParsedResponse;}}return null;},parseXMLResult:function(result){var oResult={},schema=this.responseSchema;try{for(var m=schema.fields.length-1;m>=0;m--){var field=schema.fields[m];var key=(lang.isValue(field.key))?field.key:field;var data=null;var xmlAttr=result.attributes.getNamedItem(key);if(xmlAttr){data=xmlAttr.value;}else{var xmlNode=result.getElementsByTagName(key);if(xmlNode&&xmlNode.item(0)&&xmlNode.item(0)){data=xmlNode.item(0).firstChild.nodeValue;var item=xmlNode.item(0);data=(item.text)?item.text:(item.textContent)?item.textContent:null; -if(!data){var datapieces=[];for(var j=0,len=item.childNodes.length;j0){data=datapieces.join("");}}}}if(data===null){data="";}if(!field.parser&&field.converter){field.parser=field.converter;}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data);}if(data===undefined){data=null;}oResult[key]=data;}}catch(e){}return oResult;},parseXMLData:function(oRequest,oFullResponse){var bError=false,schema=this.responseSchema,oParsedResponse={meta:{}},xmlList=null,metaNode=schema.metaNode,metaLocators=schema.metaFields||{},i,k,loc,v;try{xmlList=(schema.resultNode)?oFullResponse.getElementsByTagName(schema.resultNode):null;metaNode=metaNode?oFullResponse.getElementsByTagName(metaNode)[0]:oFullResponse;if(metaNode){for(k in metaLocators){if(lang.hasOwnProperty(metaLocators,k)){loc=metaLocators[k];v=metaNode.getElementsByTagName(loc)[0];if(v){v=v.firstChild.nodeValue;}else{v=metaNode.attributes.getNamedItem(loc);if(v){v=v.value;}}if(lang.isValue(v)){oParsedResponse.meta[k]=v;}}}}}catch(e){}if(!xmlList||!lang.isArray(schema.fields)){bError=true;}else{oParsedResponse.results=[];for(i=xmlList.length-1;i>=0;--i){var oResult=this.parseXMLResult(xmlList.item(i));oParsedResponse.results[i]=oResult;}}if(bError){oParsedResponse.error=true;}else{}return oParsedResponse;},parseJSONData:function(oRequest,oFullResponse){var oParsedResponse={results:[],meta:{}};if(lang.isObject(oFullResponse)&&this.responseSchema.resultsList){var schema=this.responseSchema,fields=schema.fields,resultsList=oFullResponse,results=[],metaFields=schema.metaFields||{},fieldParsers=[],fieldPaths=[],simpleFields=[],bError=false,i,len,j,v,key,parser,path;var buildPath=function(needle){var path=null,keys=[],i=0;if(needle){needle=needle.replace(/\[(['"])(.*?)\1\]/g,function(x,$1,$2){keys[i]=$2;return".@"+(i++);}).replace(/\[(\d+)\]/g,function(x,$1){keys[i]=parseInt($1,10)|0;return".@"+(i++);}).replace(/^\./,"");if(!/[^\w\.\$@]/.test(needle)){path=needle.split(".");for(i=path.length-1;i>=0;--i){if(path[i].charAt(0)==="@"){path[i]=keys[parseInt(path[i].substr(1),10)];}}}else{}}return path;};var walkPath=function(path,origin){var v=origin,i=0,len=path.length;for(;i1){fieldPaths[fieldPaths.length]={key:key,path:path};}else{simpleFields[simpleFields.length]={key:key,path:path[0]};}}else{}}for(i=resultsList.length-1;i>=0;--i){var r=resultsList[i],rec={};for(j=simpleFields.length-1;j>=0;--j){rec[simpleFields[j].key]=(r[simpleFields[j].path]!==undefined)?r[simpleFields[j].path]:r[j];}for(j=fieldPaths.length-1;j>=0;--j){rec[fieldPaths[j].key]=walkPath(fieldPaths[j].path,r);}for(j=fieldParsers.length-1;j>=0;--j){var p=fieldParsers[j].key;rec[p]=fieldParsers[j].parser(rec[p]);if(rec[p]===undefined){rec[p]=null;}}results[i]=rec;}}else{results=resultsList;}for(key in metaFields){if(lang.hasOwnProperty(metaFields,key)){path=buildPath(metaFields[key]);if(path){v=walkPath(path,oFullResponse);oParsedResponse.meta[key]=v;}}}}else{oParsedResponse.error=true;}oParsedResponse.results=results;}else{oParsedResponse.error=true;}return oParsedResponse;},parseHTMLTableData:function(oRequest,oFullResponse){var bError=false;var elTable=oFullResponse;var fields=this.responseSchema.fields;var oParsedResponse={results:[]};for(var i=0;i-1;j--){var elRow=elTbody.rows[j];var oResult={};for(var k=fields.length-1;k>-1;k--){var field=fields[k];var key=(lang.isValue(field.key))?field.key:field;var data=elRow.cells[k].innerHTML;if(!field.parser&&field.converter){field.parser=field.converter;}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data);}if(data===undefined){data=null;}oResult[key]=data;}oParsedResponse.results[j]=oResult;}}if(bError){oParsedResponse.error=true;}else{}return oParsedResponse;}};lang.augmentProto(DS,util.EventProvider);util.LocalDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_LOCAL;if(oLiveData){if(YAHOO.lang.isArray(oLiveData)){this.responseType=DS.TYPE_JSARRAY;}else{if(oLiveData.nodeType&&oLiveData.nodeType==9){this.responseType=DS.TYPE_XML;}else{if(oLiveData.nodeName&&(oLiveData.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE;oLiveData=oLiveData.cloneNode(true);}else{if(YAHOO.lang.isString(oLiveData)){this.responseType=DS.TYPE_TEXT;}else{if(YAHOO.lang.isObject(oLiveData)){this.responseType=DS.TYPE_JSON;}}}}}}else{oLiveData=[];this.responseType=DS.TYPE_JSARRAY;}this.constructor.superclass.constructor.call(this,oLiveData,oConfigs);};lang.extend(util.LocalDataSource,DS);lang.augmentObject(util.LocalDataSource,DS);util.FunctionDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_JSFUNCTION;oLiveData=oLiveData||function(){};this.constructor.superclass.constructor.call(this,oLiveData,oConfigs);};lang.extend(util.FunctionDataSource,DS,{makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oRawResponse=this.liveData(oRequest);if(this.responseType===DS.TYPE_UNKNOWN){if(YAHOO.lang.isArray(oRawResponse)){this.responseType=DS.TYPE_JSARRAY;}else{if(oRawResponse&&oRawResponse.nodeType&&oRawResponse.nodeType==9){this.responseType=DS.TYPE_XML; -}else{if(oRawResponse&&oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE;}else{if(YAHOO.lang.isObject(oRawResponse)){this.responseType=DS.TYPE_JSON;}else{if(YAHOO.lang.isString(oRawResponse)){this.responseType=DS.TYPE_TEXT;}}}}}}this.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);return tId;}});lang.augmentObject(util.FunctionDataSource,DS);util.ScriptNodeDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_SCRIPTNODE;oLiveData=oLiveData||"";this.constructor.superclass.constructor.call(this,oLiveData,oConfigs);};lang.extend(util.ScriptNodeDataSource,DS,{getUtility:util.Get,asyncMode:"allowAll",scriptCallbackParam:"callback",generateRequestCallback:function(id){return"&"+this.scriptCallbackParam+"=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]";},makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});if(util.ScriptNodeDataSource._nPending===0){util.ScriptNodeDataSource.callbacks=[];util.ScriptNodeDataSource._nId=0;}var id=util.ScriptNodeDataSource._nId;util.ScriptNodeDataSource._nId++;var oSelf=this;util.ScriptNodeDataSource.callbacks[id]=function(oRawResponse){if((oSelf.asyncMode!=="ignoreStaleResponses")||(id===util.ScriptNodeDataSource.callbacks.length-1)){if(oSelf.responseType===DS.TYPE_UNKNOWN){if(YAHOO.lang.isArray(oRawResponse)){oSelf.responseType=DS.TYPE_JSARRAY;}else{if(oRawResponse.nodeType&&oRawResponse.nodeType==9){oSelf.responseType=DS.TYPE_XML;}else{if(oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){oSelf.responseType=DS.TYPE_HTMLTABLE;}else{if(YAHOO.lang.isObject(oRawResponse)){oSelf.responseType=DS.TYPE_JSON;}else{if(YAHOO.lang.isString(oRawResponse)){oSelf.responseType=DS.TYPE_TEXT;}}}}}}oSelf.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);}else{}delete util.ScriptNodeDataSource.callbacks[id];};util.ScriptNodeDataSource._nPending++;var sUri=this.liveData+oRequest+this.generateRequestCallback(id);this.getUtility.script(sUri,{autopurge:true,onsuccess:util.ScriptNodeDataSource._bumpPendingDown,onfail:util.ScriptNodeDataSource._bumpPendingDown});return tId;}});lang.augmentObject(util.ScriptNodeDataSource,DS);lang.augmentObject(util.ScriptNodeDataSource,{_nId:0,_nPending:0,callbacks:[]});util.XHRDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_XHR;this.connMgr=this.connMgr||util.Connect;oLiveData=oLiveData||"";this.constructor.superclass.constructor.call(this,oLiveData,oConfigs);};lang.extend(util.XHRDataSource,DS,{connMgr:null,connXhrMode:"allowAll",connMethodPost:false,connTimeout:0,makeConnection:function(oRequest,oCallback,oCaller){var oRawResponse=null;var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oSelf=this;var oConnMgr=this.connMgr;var oQueue=this._oQueue;var _xhrSuccess=function(oResponse){if(oResponse&&(this.asyncMode=="ignoreStaleResponses")&&(oResponse.tId!=oQueue.conn.tId)){return null;}else{if(!oResponse){this.fireEvent("dataErrorEvent",{request:oRequest,callback:oCallback,caller:oCaller,message:DS.ERROR_DATANULL});DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);return null;}else{if(this.responseType===DS.TYPE_UNKNOWN){var ctype=(oResponse.getResponseHeader)?oResponse.getResponseHeader["Content-Type"]:null;if(ctype){if(ctype.indexOf("text/xml")>-1){this.responseType=DS.TYPE_XML;}else{if(ctype.indexOf("application/json")>-1){this.responseType=DS.TYPE_JSON;}else{if(ctype.indexOf("text/plain")>-1){this.responseType=DS.TYPE_TEXT;}}}}}this.handleResponse(oRequest,oResponse,oCallback,oCaller,tId);}}};var _xhrFailure=function(oResponse){this.fireEvent("dataErrorEvent",{request:oRequest,callback:oCallback,caller:oCaller,message:DS.ERROR_DATAINVALID});if(lang.isString(this.liveData)&&lang.isString(oRequest)&&(this.liveData.lastIndexOf("?")!==this.liveData.length-1)&&(oRequest.indexOf("?")!==0)){}oResponse=oResponse||{};oResponse.error=true;DS.issueCallback(oCallback,[oRequest,oResponse],true,oCaller);return null;};var _xhrCallback={success:_xhrSuccess,failure:_xhrFailure,scope:this};if(lang.isNumber(this.connTimeout)){_xhrCallback.timeout=this.connTimeout;}if(this.connXhrMode=="cancelStaleRequests"){if(oQueue.conn){if(oConnMgr.abort){oConnMgr.abort(oQueue.conn);oQueue.conn=null;}else{}}}if(oConnMgr&&oConnMgr.asyncRequest){var sLiveData=this.liveData;var isPost=this.connMethodPost;var sMethod=(isPost)?"POST":"GET";var sUri=(isPost||!lang.isValue(oRequest))?sLiveData:sLiveData+oRequest;var sRequest=(isPost)?oRequest:null;if(this.connXhrMode!="queueRequests"){oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,_xhrCallback,sRequest);}else{if(oQueue.conn){var allRequests=oQueue.requests;allRequests.push({request:oRequest,callback:_xhrCallback});if(!oQueue.interval){oQueue.interval=setInterval(function(){if(oConnMgr.isCallInProgress(oQueue.conn)){return ;}else{if(allRequests.length>0){sUri=(isPost||!lang.isValue(allRequests[0].request))?sLiveData:sLiveData+allRequests[0].request;sRequest=(isPost)?allRequests[0].request:null;oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,allRequests[0].callback,sRequest);allRequests.shift();}else{clearInterval(oQueue.interval);oQueue.interval=null;}}},50);}}else{oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,_xhrCallback,sRequest);}}}else{DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);}return tId;}});lang.augmentObject(util.XHRDataSource,DS);util.DataSource=function(oLiveData,oConfigs){oConfigs=oConfigs||{};var dataType=oConfigs.dataType;if(dataType){if(dataType==DS.TYPE_LOCAL){lang.augmentObject(util.DataSource,util.LocalDataSource);return new util.LocalDataSource(oLiveData,oConfigs);}else{if(dataType==DS.TYPE_XHR){lang.augmentObject(util.DataSource,util.XHRDataSource);return new util.XHRDataSource(oLiveData,oConfigs);}else{if(dataType==DS.TYPE_SCRIPTNODE){lang.augmentObject(util.DataSource,util.ScriptNodeDataSource); -return new util.ScriptNodeDataSource(oLiveData,oConfigs);}else{if(dataType==DS.TYPE_JSFUNCTION){lang.augmentObject(util.DataSource,util.FunctionDataSource);return new util.FunctionDataSource(oLiveData,oConfigs);}}}}}if(YAHOO.lang.isString(oLiveData)){lang.augmentObject(util.DataSource,util.XHRDataSource);return new util.XHRDataSource(oLiveData,oConfigs);}else{if(YAHOO.lang.isFunction(oLiveData)){lang.augmentObject(util.DataSource,util.FunctionDataSource);return new util.FunctionDataSource(oLiveData,oConfigs);}else{lang.augmentObject(util.DataSource,util.LocalDataSource);return new util.LocalDataSource(oLiveData,oConfigs);}}};lang.augmentObject(util.DataSource,DS);})();YAHOO.util.Number={format:function(B,F){F=F||{};if(!YAHOO.lang.isNumber(B)){B*=1;}if(YAHOO.lang.isNumber(B)){var D=(B<0);var J=B+"";var G=(F.decimalSeparator)?F.decimalSeparator:".";var H;if(YAHOO.lang.isNumber(F.decimalPlaces)){var I=F.decimalPlaces;var C=Math.pow(10,I);J=Math.round(B*C)/C+"";H=J.lastIndexOf(".");if(I>0){if(H<0){J+=G;H=J.length-1;}else{if(G!=="."){J=J.replace(".",G);}}while((J.length-1-H)-1)?H:J.length;var K=J.substring(H);var A=-1;for(var E=H;E>0;E--){A++;if((A%3===0)&&(E!==H)&&(!D||(E>1))){K=L+K;}K=J.charAt(E-1)+K;}J=K;}J=(F.prefix)?F.prefix+J:J;J=(F.suffix)?J+F.suffix:J;return J;}else{return B;}}};(function(){var A=function(C,E,D){if(typeof D==="undefined"){D=10;}for(;parseInt(C,10)1;D/=10){C=E.toString()+C;}return C.toString();};var B={formats:{a:function(D,C){return C.a[D.getDay()];},A:function(D,C){return C.A[D.getDay()];},b:function(D,C){return C.b[D.getMonth()];},B:function(D,C){return C.B[D.getMonth()];},C:function(C){return A(parseInt(C.getFullYear()/100,10),0);},d:["getDate","0"],e:["getDate"," "],g:function(C){return A(parseInt(B.formats.G(C)%100,10),0);},G:function(E){var F=E.getFullYear();var D=parseInt(B.formats.V(E),10);var C=parseInt(B.formats.W(E),10);if(C>D){F++;}else{if(C===0&&D>=52){F--;}}return F;},H:["getHours","0"],I:function(D){var C=D.getHours()%12;return A(C===0?12:C,0);},j:function(G){var F=new Date(""+G.getFullYear()+"/1/1 GMT");var D=new Date(""+G.getFullYear()+"/"+(G.getMonth()+1)+"/"+G.getDate()+" GMT");var C=D-F;var E=parseInt(C/60000/60/24,10)+1;return A(E,0,100);},k:["getHours"," "],l:function(D){var C=D.getHours()%12;return A(C===0?12:C," ");},m:function(C){return A(C.getMonth()+1,0);},M:["getMinutes","0"],p:function(D,C){return C.p[D.getHours()>=12?1:0];},P:function(D,C){return C.P[D.getHours()>=12?1:0];},s:function(D,C){return parseInt(D.getTime()/1000,10);},S:["getSeconds","0"],u:function(C){var D=C.getDay();return D===0?7:D;},U:function(F){var C=parseInt(B.formats.j(F),10);var E=6-F.getDay();var D=parseInt((C+E)/7,10);return A(D,0);},V:function(F){var E=parseInt(B.formats.W(F),10);var C=(new Date(""+F.getFullYear()+"/1/1")).getDay();var D=E+(C>4||C<=1?0:1);if(D===53&&(new Date(""+F.getFullYear()+"/12/31")).getDay()<4){D=1;}else{if(D===0){D=B.formats.V(new Date(""+(F.getFullYear()-1)+"/12/31"));}}return A(D,0);},w:"getDay",W:function(F){var C=parseInt(B.formats.j(F),10);var E=7-B.formats.u(F);var D=parseInt((C+E)/7,10);return A(D,0,10);},y:function(C){return A(C.getFullYear()%100,0);},Y:"getFullYear",z:function(E){var D=E.getTimezoneOffset();var C=A(parseInt(Math.abs(D/60),10),0);var F=A(Math.abs(D%60),0);return(D>0?"-":"+")+C+F;},Z:function(C){var D=C.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/,"$2").replace(/[a-z ]/g,"");if(D.length>4){D=B.formats.z(C);}return D;},"%":function(C){return"%";}},aggregates:{c:"locale",D:"%m/%d/%y",F:"%Y-%m-%d",h:"%b",n:"\n",r:"locale",R:"%H:%M",t:"\t",T:"%H:%M:%S",x:"locale",X:"locale"},format:function(G,F,D){F=F||{};if(!(G instanceof Date)){return YAHOO.lang.isValue(G)?G:"";}var H=F.format||"%m/%d/%Y";if(H==="YYYY/MM/DD"){H="%Y/%m/%d";}else{if(H==="DD/MM/YYYY"){H="%d/%m/%Y";}else{if(H==="MM/DD/YYYY"){H="%m/%d/%Y";}}}D=D||"en";if(!(D in YAHOO.util.DateLocale)){if(D.replace(/-[a-zA-Z]+$/,"") in YAHOO.util.DateLocale){D=D.replace(/-[a-zA-Z]+$/,"");}else{D="en";}}var J=YAHOO.util.DateLocale[D];var C=function(L,K){var M=B.aggregates[K];return(M==="locale"?J[K]:M);};var E=function(L,K){var M=B.formats[K];if(typeof M==="string"){return G[M]();}else{if(typeof M==="function"){return M.call(G,G,J);}else{if(typeof M==="object"&&typeof M[0]==="string"){return A(G[M[0]](),M[1]);}else{return K;}}}};while(H.match(/%[cDFhnrRtTxX]/)){H=H.replace(/%([cDFhnrRtTxX])/g,C);}var I=H.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g,E);C=E=undefined;return I;}};YAHOO.namespace("YAHOO.util");YAHOO.util.Date=B;YAHOO.util.DateLocale={a:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],A:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],b:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],B:["January","February","March","April","May","June","July","August","September","October","November","December"],c:"%a %d %b %Y %T %Z",p:["AM","PM"],P:["am","pm"],r:"%I:%M:%S %p",x:"%d/%m/%y",X:"%T"};YAHOO.util.DateLocale["en"]=YAHOO.lang.merge(YAHOO.util.DateLocale,{});YAHOO.util.DateLocale["en-US"]=YAHOO.lang.merge(YAHOO.util.DateLocale["en"],{c:"%a %d %b %Y %I:%M:%S %p %Z",x:"%m/%d/%Y",X:"%I:%M:%S %p"});YAHOO.util.DateLocale["en-GB"]=YAHOO.lang.merge(YAHOO.util.DateLocale["en"],{r:"%l:%M:%S %P %Z"});YAHOO.util.DateLocale["en-AU"]=YAHOO.lang.merge(YAHOO.util.DateLocale["en"]);})();YAHOO.register("datasource",YAHOO.util.DataSource,{version:"2.6.0",build:"1321"});/* -Copyright (c) 2008, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version: 2.6.0 -*/ -YAHOO.widget.DS_JSArray=YAHOO.util.LocalDataSource;YAHOO.widget.DS_JSFunction=YAHOO.util.FunctionDataSource;YAHOO.widget.DS_XHR=function(B,A,D){var C=new YAHOO.util.XHRDataSource(B,D);C._aDeprecatedSchema=A;return C;};YAHOO.widget.DS_ScriptNode=function(B,A,D){var C=new YAHOO.util.ScriptNodeDataSource(B,D);C._aDeprecatedSchema=A;return C;};YAHOO.widget.DS_XHR.TYPE_JSON=YAHOO.util.DataSourceBase.TYPE_JSON;YAHOO.widget.DS_XHR.TYPE_XML=YAHOO.util.DataSourceBase.TYPE_XML;YAHOO.widget.DS_XHR.TYPE_FLAT=YAHOO.util.DataSourceBase.TYPE_TEXT;YAHOO.widget.AutoComplete=function(G,B,J,C){if(G&&B&&J){if(J instanceof YAHOO.util.DataSourceBase){this.dataSource=J;}else{return ;}this.key=0;var D=J.responseSchema;if(J._aDeprecatedSchema){var K=J._aDeprecatedSchema;if(YAHOO.lang.isArray(K)){if((J.responseType===YAHOO.util.DataSourceBase.TYPE_JSON)||(J.responseType===YAHOO.util.DataSourceBase.TYPE_UNKNOWN)){D.resultsList=K[0];this.key=K[1];D.fields=(K.length<3)?null:K.slice(1);}else{if(J.responseType===YAHOO.util.DataSourceBase.TYPE_XML){D.resultNode=K[0];this.key=K[1];D.fields=K.slice(1);}else{if(J.responseType===YAHOO.util.DataSourceBase.TYPE_TEXT){D.recordDelim=K[0];D.fieldDelim=K[1];}}}J.responseSchema=D;}}if(YAHOO.util.Dom.inDocument(G)){if(YAHOO.lang.isString(G)){this._sName="instance"+YAHOO.widget.AutoComplete._nIndex+" "+G;this._elTextbox=document.getElementById(G);}else{this._sName=(G.id)?"instance"+YAHOO.widget.AutoComplete._nIndex+" "+G.id:"instance"+YAHOO.widget.AutoComplete._nIndex;this._elTextbox=G;}YAHOO.util.Dom.addClass(this._elTextbox,"yui-ac-input");}else{return ;}if(YAHOO.util.Dom.inDocument(B)){if(YAHOO.lang.isString(B)){this._elContainer=document.getElementById(B);}else{this._elContainer=B;}if(this._elContainer.style.display=="none"){}var E=this._elContainer.parentNode;var A=E.tagName.toLowerCase();if(A=="div"){YAHOO.util.Dom.addClass(E,"yui-ac");}else{}}else{return ;}if(this.dataSource.dataType===YAHOO.util.DataSourceBase.TYPE_LOCAL){this.applyLocalFilter=true;}if(C&&(C.constructor==Object)){for(var I in C){if(I){this[I]=C[I];}}}this._initContainerEl();this._initProps();this._initListEl();this._initContainerHelperEls();var H=this;var F=this._elTextbox;YAHOO.util.Event.addListener(F,"keyup",H._onTextboxKeyUp,H);YAHOO.util.Event.addListener(F,"keydown",H._onTextboxKeyDown,H);YAHOO.util.Event.addListener(F,"focus",H._onTextboxFocus,H);YAHOO.util.Event.addListener(F,"blur",H._onTextboxBlur,H);YAHOO.util.Event.addListener(B,"mouseover",H._onContainerMouseover,H);YAHOO.util.Event.addListener(B,"mouseout",H._onContainerMouseout,H);YAHOO.util.Event.addListener(B,"click",H._onContainerClick,H);YAHOO.util.Event.addListener(B,"scroll",H._onContainerScroll,H);YAHOO.util.Event.addListener(B,"resize",H._onContainerResize,H);YAHOO.util.Event.addListener(F,"keypress",H._onTextboxKeyPress,H);YAHOO.util.Event.addListener(window,"unload",H._onWindowUnload,H);this.textboxFocusEvent=new YAHOO.util.CustomEvent("textboxFocus",this);this.textboxKeyEvent=new YAHOO.util.CustomEvent("textboxKey",this);this.dataRequestEvent=new YAHOO.util.CustomEvent("dataRequest",this);this.dataReturnEvent=new YAHOO.util.CustomEvent("dataReturn",this);this.dataErrorEvent=new YAHOO.util.CustomEvent("dataError",this);this.containerPopulateEvent=new YAHOO.util.CustomEvent("containerPopulate",this);this.containerExpandEvent=new YAHOO.util.CustomEvent("containerExpand",this);this.typeAheadEvent=new YAHOO.util.CustomEvent("typeAhead",this);this.itemMouseOverEvent=new YAHOO.util.CustomEvent("itemMouseOver",this);this.itemMouseOutEvent=new YAHOO.util.CustomEvent("itemMouseOut",this);this.itemArrowToEvent=new YAHOO.util.CustomEvent("itemArrowTo",this);this.itemArrowFromEvent=new YAHOO.util.CustomEvent("itemArrowFrom",this);this.itemSelectEvent=new YAHOO.util.CustomEvent("itemSelect",this);this.unmatchedItemSelectEvent=new YAHOO.util.CustomEvent("unmatchedItemSelect",this);this.selectionEnforceEvent=new YAHOO.util.CustomEvent("selectionEnforce",this);this.containerCollapseEvent=new YAHOO.util.CustomEvent("containerCollapse",this);this.textboxBlurEvent=new YAHOO.util.CustomEvent("textboxBlur",this);this.textboxChangeEvent=new YAHOO.util.CustomEvent("textboxChange",this);F.setAttribute("autocomplete","off");YAHOO.widget.AutoComplete._nIndex++;}else{}};YAHOO.widget.AutoComplete.prototype.dataSource=null;YAHOO.widget.AutoComplete.prototype.applyLocalFilter=null;YAHOO.widget.AutoComplete.prototype.queryMatchCase=false;YAHOO.widget.AutoComplete.prototype.queryMatchContains=false;YAHOO.widget.AutoComplete.prototype.queryMatchSubset=false;YAHOO.widget.AutoComplete.prototype.minQueryLength=1;YAHOO.widget.AutoComplete.prototype.maxResultsDisplayed=10;YAHOO.widget.AutoComplete.prototype.queryDelay=0.2;YAHOO.widget.AutoComplete.prototype.typeAheadDelay=0.5;YAHOO.widget.AutoComplete.prototype.queryInterval=500;YAHOO.widget.AutoComplete.prototype.highlightClassName="yui-ac-highlight";YAHOO.widget.AutoComplete.prototype.prehighlightClassName=null;YAHOO.widget.AutoComplete.prototype.delimChar=null;YAHOO.widget.AutoComplete.prototype.autoHighlight=true;YAHOO.widget.AutoComplete.prototype.typeAhead=false;YAHOO.widget.AutoComplete.prototype.animHoriz=false;YAHOO.widget.AutoComplete.prototype.animVert=true;YAHOO.widget.AutoComplete.prototype.animSpeed=0.3;YAHOO.widget.AutoComplete.prototype.forceSelection=false;YAHOO.widget.AutoComplete.prototype.allowBrowserAutocomplete=true;YAHOO.widget.AutoComplete.prototype.alwaysShowContainer=false;YAHOO.widget.AutoComplete.prototype.useIFrame=false;YAHOO.widget.AutoComplete.prototype.useShadow=false;YAHOO.widget.AutoComplete.prototype.suppressInputUpdate=false;YAHOO.widget.AutoComplete.prototype.resultTypeList=true;YAHOO.widget.AutoComplete.prototype.queryQuestionMark=true;YAHOO.widget.AutoComplete.prototype.toString=function(){return"AutoComplete "+this._sName;};YAHOO.widget.AutoComplete.prototype.getInputEl=function(){return this._elTextbox;};YAHOO.widget.AutoComplete.prototype.getContainerEl=function(){return this._elContainer; -};YAHOO.widget.AutoComplete.prototype.isFocused=function(){return(this._bFocused===null)?false:this._bFocused;};YAHOO.widget.AutoComplete.prototype.isContainerOpen=function(){return this._bContainerOpen;};YAHOO.widget.AutoComplete.prototype.getListEl=function(){return this._elList;};YAHOO.widget.AutoComplete.prototype.getListItemMatch=function(A){if(A._sResultMatch){return A._sResultMatch;}else{return null;}};YAHOO.widget.AutoComplete.prototype.getListItemData=function(A){if(A._oResultData){return A._oResultData;}else{return null;}};YAHOO.widget.AutoComplete.prototype.getListItemIndex=function(A){if(YAHOO.lang.isNumber(A._nItemIndex)){return A._nItemIndex;}else{return null;}};YAHOO.widget.AutoComplete.prototype.setHeader=function(B){if(this._elHeader){var A=this._elHeader;if(B){A.innerHTML=B;A.style.display="block";}else{A.innerHTML="";A.style.display="none";}}};YAHOO.widget.AutoComplete.prototype.setFooter=function(B){if(this._elFooter){var A=this._elFooter;if(B){A.innerHTML=B;A.style.display="block";}else{A.innerHTML="";A.style.display="none";}}};YAHOO.widget.AutoComplete.prototype.setBody=function(A){if(this._elBody){var B=this._elBody;YAHOO.util.Event.purgeElement(B,true);if(A){B.innerHTML=A;B.style.display="block";}else{B.innerHTML="";B.style.display="none";}this._elList=null;}};YAHOO.widget.AutoComplete.prototype.generateRequest=function(B){var A=this.dataSource.dataType;if(A===YAHOO.util.DataSourceBase.TYPE_XHR){if(!this.dataSource.connMethodPost){B=(this.queryQuestionMark?"?":"")+(this.dataSource.scriptQueryParam||"query")+"="+B+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"");}else{B=(this.dataSource.scriptQueryParam||"query")+"="+B+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"");}}else{if(A===YAHOO.util.DataSourceBase.TYPE_SCRIPTNODE){B="&"+(this.dataSource.scriptQueryParam||"query")+"="+B+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"");}}return B;};YAHOO.widget.AutoComplete.prototype.sendQuery=function(B){var A=(this.delimChar)?this._elTextbox.value+B:B;this._sendQuery(A);};YAHOO.widget.AutoComplete.prototype.collapseContainer=function(){this._toggleContainer(false);};YAHOO.widget.AutoComplete.prototype.getSubsetMatches=function(E){var D,C,A;for(var B=E.length;B>=this.minQueryLength;B--){A=this.generateRequest(E.substr(0,B));this.dataRequestEvent.fire(this,D,A);C=this.dataSource.getCachedResponse(A);if(C){return this.filterResults.apply(this.dataSource,[E,C,C,{scope:this}]);}}return null;};YAHOO.widget.AutoComplete.prototype.preparseRawResponse=function(C,B,A){var D=((this.responseStripAfter!=="")&&(B.indexOf))?B.indexOf(this.responseStripAfter):-1;if(D!=-1){B=B.substring(0,D);}return B;};YAHOO.widget.AutoComplete.prototype.filterResults=function(J,L,P,K){if(J&&J!==""){P=YAHOO.widget.AutoComplete._cloneObject(P);var H=K.scope,O=this,B=P.results,M=[],D=false,I=(O.queryMatchCase||H.queryMatchCase),A=(O.queryMatchContains||H.queryMatchContains);for(var C=B.length-1;C>=0;C--){var F=B[C];var E=null;if(YAHOO.lang.isString(F)){E=F;}else{if(YAHOO.lang.isArray(F)){E=F[0];}else{if(this.responseSchema.fields){var N=this.responseSchema.fields[0].key||this.responseSchema.fields[0];E=F[N];}else{if(this.key){E=F[this.key];}}}}if(YAHOO.lang.isString(E)){var G=(I)?E.indexOf(decodeURIComponent(J)):E.toLowerCase().indexOf(decodeURIComponent(J).toLowerCase());if((!A&&(G===0))||(A&&(G>-1))){M.unshift(F);}}}P.results=M;}else{}return P;};YAHOO.widget.AutoComplete.prototype.handleResponse=function(C,A,B){if((this instanceof YAHOO.widget.AutoComplete)&&this._sName){this._populateList(C,A,B);}};YAHOO.widget.AutoComplete.prototype.doBeforeLoadData=function(C,A,B){return true;};YAHOO.widget.AutoComplete.prototype.formatResult=function(B,D,A){var C=(A)?A:"";return C;};YAHOO.widget.AutoComplete.prototype.doBeforeExpandContainer=function(D,A,C,B){return true;};YAHOO.widget.AutoComplete.prototype.destroy=function(){var B=this.toString();var A=this._elTextbox;var D=this._elContainer;this.textboxFocusEvent.unsubscribeAll();this.textboxKeyEvent.unsubscribeAll();this.dataRequestEvent.unsubscribeAll();this.dataReturnEvent.unsubscribeAll();this.dataErrorEvent.unsubscribeAll();this.containerPopulateEvent.unsubscribeAll();this.containerExpandEvent.unsubscribeAll();this.typeAheadEvent.unsubscribeAll();this.itemMouseOverEvent.unsubscribeAll();this.itemMouseOutEvent.unsubscribeAll();this.itemArrowToEvent.unsubscribeAll();this.itemArrowFromEvent.unsubscribeAll();this.itemSelectEvent.unsubscribeAll();this.unmatchedItemSelectEvent.unsubscribeAll();this.selectionEnforceEvent.unsubscribeAll();this.containerCollapseEvent.unsubscribeAll();this.textboxBlurEvent.unsubscribeAll();this.textboxChangeEvent.unsubscribeAll();YAHOO.util.Event.purgeElement(A,true);YAHOO.util.Event.purgeElement(D,true);D.innerHTML="";for(var C in this){if(YAHOO.lang.hasOwnProperty(this,C)){this[C]=null;}}};YAHOO.widget.AutoComplete.prototype.textboxFocusEvent=null;YAHOO.widget.AutoComplete.prototype.textboxKeyEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestEvent=null;YAHOO.widget.AutoComplete.prototype.dataReturnEvent=null;YAHOO.widget.AutoComplete.prototype.dataErrorEvent=null;YAHOO.widget.AutoComplete.prototype.containerPopulateEvent=null;YAHOO.widget.AutoComplete.prototype.containerExpandEvent=null;YAHOO.widget.AutoComplete.prototype.typeAheadEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowToEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowFromEvent=null;YAHOO.widget.AutoComplete.prototype.itemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.unmatchedItemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.selectionEnforceEvent=null;YAHOO.widget.AutoComplete.prototype.containerCollapseEvent=null;YAHOO.widget.AutoComplete.prototype.textboxBlurEvent=null;YAHOO.widget.AutoComplete.prototype.textboxChangeEvent=null;YAHOO.widget.AutoComplete._nIndex=0; -YAHOO.widget.AutoComplete.prototype._sName=null;YAHOO.widget.AutoComplete.prototype._elTextbox=null;YAHOO.widget.AutoComplete.prototype._elContainer=null;YAHOO.widget.AutoComplete.prototype._elContent=null;YAHOO.widget.AutoComplete.prototype._elHeader=null;YAHOO.widget.AutoComplete.prototype._elBody=null;YAHOO.widget.AutoComplete.prototype._elFooter=null;YAHOO.widget.AutoComplete.prototype._elShadow=null;YAHOO.widget.AutoComplete.prototype._elIFrame=null;YAHOO.widget.AutoComplete.prototype._bFocused=null;YAHOO.widget.AutoComplete.prototype._oAnim=null;YAHOO.widget.AutoComplete.prototype._bContainerOpen=false;YAHOO.widget.AutoComplete.prototype._bOverContainer=false;YAHOO.widget.AutoComplete.prototype._elList=null;YAHOO.widget.AutoComplete.prototype._nDisplayedItems=0;YAHOO.widget.AutoComplete.prototype._sCurQuery=null;YAHOO.widget.AutoComplete.prototype._sPastSelections="";YAHOO.widget.AutoComplete.prototype._sInitInputValue=null;YAHOO.widget.AutoComplete.prototype._elCurListItem=null;YAHOO.widget.AutoComplete.prototype._bItemSelected=false;YAHOO.widget.AutoComplete.prototype._nKeyCode=null;YAHOO.widget.AutoComplete.prototype._nDelayID=-1;YAHOO.widget.AutoComplete.prototype._nTypeAheadDelayID=-1;YAHOO.widget.AutoComplete.prototype._iFrameSrc="javascript:false;";YAHOO.widget.AutoComplete.prototype._queryInterval=null;YAHOO.widget.AutoComplete.prototype._sLastTextboxValue=null;YAHOO.widget.AutoComplete.prototype._initProps=function(){var B=this.minQueryLength;if(!YAHOO.lang.isNumber(B)){this.minQueryLength=1;}var E=this.maxResultsDisplayed;if(!YAHOO.lang.isNumber(E)||(E<1)){this.maxResultsDisplayed=10;}var F=this.queryDelay;if(!YAHOO.lang.isNumber(F)||(F<0)){this.queryDelay=0.2;}var C=this.typeAheadDelay;if(!YAHOO.lang.isNumber(C)||(C<0)){this.typeAheadDelay=0.2;}var A=this.delimChar;if(YAHOO.lang.isString(A)&&(A.length>0)){this.delimChar=[A];}else{if(!YAHOO.lang.isArray(A)){this.delimChar=null;}}var D=this.animSpeed;if((this.animHoriz||this.animVert)&&YAHOO.util.Anim){if(!YAHOO.lang.isNumber(D)||(D<0)){this.animSpeed=0.3;}if(!this._oAnim){this._oAnim=new YAHOO.util.Anim(this._elContent,{},this.animSpeed);}else{this._oAnim.duration=this.animSpeed;}}if(this.forceSelection&&A){}};YAHOO.widget.AutoComplete.prototype._initContainerHelperEls=function(){if(this.useShadow&&!this._elShadow){var A=document.createElement("div");A.className="yui-ac-shadow";A.style.width=0;A.style.height=0;this._elShadow=this._elContainer.appendChild(A);}if(this.useIFrame&&!this._elIFrame){var B=document.createElement("iframe");B.src=this._iFrameSrc;B.frameBorder=0;B.scrolling="no";B.style.position="absolute";B.style.width=0;B.style.height=0;B.tabIndex=-1;B.style.padding=0;this._elIFrame=this._elContainer.appendChild(B);}};YAHOO.widget.AutoComplete.prototype._initContainerEl=function(){YAHOO.util.Dom.addClass(this._elContainer,"yui-ac-container");if(!this._elContent){var C=document.createElement("div");C.className="yui-ac-content";C.style.display="none";this._elContent=this._elContainer.appendChild(C);var B=document.createElement("div");B.className="yui-ac-hd";B.style.display="none";this._elHeader=this._elContent.appendChild(B);var D=document.createElement("div");D.className="yui-ac-bd";this._elBody=this._elContent.appendChild(D);var A=document.createElement("div");A.className="yui-ac-ft";A.style.display="none";this._elFooter=this._elContent.appendChild(A);}else{}};YAHOO.widget.AutoComplete.prototype._initListEl=function(){var C=this.maxResultsDisplayed;var A=this._elList||document.createElement("ul");var B;while(A.childNodes.length=18&&A<=20)||(A==27)||(A>=33&&A<=35)||(A>=36&&A<=40)||(A>=44&&A<=45)||(A==229)){return true;}return false;};YAHOO.widget.AutoComplete.prototype._sendQuery=function(G){if(this.minQueryLength<0){this._toggleContainer(false);return ;}var I=(this.delimChar)?this.delimChar:null;if(I){var B=-1;for(var F=I.length-1;F>=0;F--){var D=G.lastIndexOf(I[F]);if(D>B){B=D;}}if(I[F]==" "){for(var E=I.length-1;E>=0;E--){if(G[B-1]==I[E]){B--;break;}}}if(B>-1){var H=B+1;while(G.charAt(H)==" "){H+=1;}this._sPastSelections=G.substring(0,H);G=G.substr(H);}else{this._sPastSelections="";}}if((G&&(G.length0)){if(this._nDelayID!=-1){clearTimeout(this._nDelayID);}this._toggleContainer(false);return ;}G=encodeURIComponent(G);this._nDelayID=-1;if(this.dataSource.queryMatchSubset||this.queryMatchSubset){var A=this.getSubsetMatches(G);if(A){this.handleResponse(G,A,{query:G});return ;}}if(this.responseStripAfter){this.dataSource.doBeforeParseData=this.preparseRawResponse;}if(this.applyLocalFilter){this.dataSource.doBeforeCallback=this.filterResults;}var C=this.generateRequest(G);this.dataRequestEvent.fire(this,G,C);this.dataSource.sendRequest(C,{success:this.handleResponse,failure:this.handleResponse,scope:this,argument:{query:G}});};YAHOO.widget.AutoComplete.prototype._populateList=function(K,F,C){if(this._nTypeAheadDelayID!=-1){clearTimeout(this._nTypeAheadDelayID);}K=(C&&C.query)?C.query:K;var H=this.doBeforeLoadData(K,F,C);if(H&&!F.error){this.dataReturnEvent.fire(this,K,F.results);if(this._bFocused||(this._bFocused===null)){var M=decodeURIComponent(K); -this._sCurQuery=M;this._bItemSelected=false;var R=F.results,A=Math.min(R.length,this.maxResultsDisplayed),J=(this.dataSource.responseSchema.fields)?(this.dataSource.responseSchema.fields[0].key||this.dataSource.responseSchema.fields[0]):0;if(A>0){if(!this._elList||(this._elList.childNodes.length=0;Q--){var P=I[Q],E=R[Q];if(this.resultTypeList){var B=[];B[0]=(YAHOO.lang.isString(E))?E:E[J]||E[this.key];var L=this.dataSource.responseSchema.fields;if(YAHOO.lang.isArray(L)&&(L.length>1)){for(var N=1,S=L.length;N=A;O--){G=I[O];G.style.display="none";}}this._nDisplayedItems=A;this.containerPopulateEvent.fire(this,K,R);if(this.autoHighlight){var D=this._elList.firstChild;this._toggleHighlight(D,"to");this.itemArrowToEvent.fire(this,D);this._typeAhead(D,K);}else{this._toggleHighlight(this._elCurListItem,"from");}H=this.doBeforeExpandContainer(this._elTextbox,this._elContainer,K,R);this._toggleContainer(H);}else{this._toggleContainer(false);}return ;}}else{this.dataErrorEvent.fire(this,K);}};YAHOO.widget.AutoComplete.prototype._clearSelection=function(){var C=this._elTextbox.value;var B=(this.delimChar)?this.delimChar[0]:null;var A=(B)?C.lastIndexOf(B,C.length-2):-1;if(A>-1){this._elTextbox.value=C.substring(0,A);}else{this._elTextbox.value="";}this._sPastSelections=this._elTextbox.value;this.selectionEnforceEvent.fire(this);};YAHOO.widget.AutoComplete.prototype._textMatchesOption=function(){var A=null;for(var B=this._nDisplayedItems-1;B>=0;B--){var C=this._elList.childNodes[B];var D=(""+C._sResultMatch).toLowerCase();if(D==this._sCurQuery.toLowerCase()){A=C;break;}}return(A);};YAHOO.widget.AutoComplete.prototype._typeAhead=function(B,D){if(!this.typeAhead||(this._nKeyCode==8)){return ;}var A=this,C=this._elTextbox;if(C.setSelectionRange||C.createTextRange){this._nTypeAheadDelayID=setTimeout(function(){var F=C.value.length;A._updateValue(B);var G=C.value.length;A._selectText(C,F,G);var E=C.value.substr(F,G);A.typeAheadEvent.fire(A,D,E);},(this.typeAheadDelay*1000));}};YAHOO.widget.AutoComplete.prototype._selectText=function(D,A,B){if(D.setSelectionRange){D.setSelectionRange(A,B);}else{if(D.createTextRange){var C=D.createTextRange();C.moveStart("character",A);C.moveEnd("character",B-D.value.length);C.select();}else{D.select();}}};YAHOO.widget.AutoComplete.prototype._toggleContainerHelpers=function(D){var E=this._elContent.offsetWidth+"px";var B=this._elContent.offsetHeight+"px";if(this.useIFrame&&this._elIFrame){var C=this._elIFrame;if(D){C.style.width=E;C.style.height=B;C.style.padding="";}else{C.style.width=0;C.style.height=0;C.style.padding=0;}}if(this.useShadow&&this._elShadow){var A=this._elShadow;if(D){A.style.width=E;A.style.height=B;}else{A.style.width=0;A.style.height=0;}}};YAHOO.widget.AutoComplete.prototype._toggleContainer=function(I){var D=this._elContainer;if(this.alwaysShowContainer&&this._bContainerOpen){return ;}if(!I){this._toggleHighlight(this._elCurListItem,"from");this._nDisplayedItems=0;this._sCurQuery=null;if(!this._bContainerOpen){this._elContent.style.display="none";return ;}}var A=this._oAnim;if(A&&A.getEl()&&(this.animHoriz||this.animVert)){if(A.isAnimated()){A.stop(true);}var G=this._elContent.cloneNode(true);D.appendChild(G);G.style.top="-9000px";G.style.width="";G.style.height="";G.style.display="";var F=G.offsetWidth;var C=G.offsetHeight;var B=(this.animHoriz)?0:F;var E=(this.animVert)?0:C;A.attributes=(I)?{width:{to:F},height:{to:C}}:{width:{to:B},height:{to:E}};if(I&&!this._bContainerOpen){this._elContent.style.width=B+"px";this._elContent.style.height=E+"px";}else{this._elContent.style.width=F+"px";this._elContent.style.height=C+"px";}D.removeChild(G);G=null;var H=this;var J=function(){A.onComplete.unsubscribeAll();if(I){H._toggleContainerHelpers(true);H._bContainerOpen=I;H.containerExpandEvent.fire(H);}else{H._elContent.style.display="none";H._bContainerOpen=I;H.containerCollapseEvent.fire(H);}};this._toggleContainerHelpers(false);this._elContent.style.display="";A.onComplete.subscribe(J);A.animate();}else{if(I){this._elContent.style.display="";this._toggleContainerHelpers(true);this._bContainerOpen=I;this.containerExpandEvent.fire(this);}else{this._toggleContainerHelpers(false);this._elContent.style.display="none";this._bContainerOpen=I;this.containerCollapseEvent.fire(this);}}};YAHOO.widget.AutoComplete.prototype._toggleHighlight=function(A,C){if(A){var B=this.highlightClassName;if(this._elCurListItem){YAHOO.util.Dom.removeClass(this._elCurListItem,B);this._elCurListItem=null;}if((C=="to")&&B){YAHOO.util.Dom.addClass(A,B);this._elCurListItem=A;}}};YAHOO.widget.AutoComplete.prototype._togglePrehighlight=function(B,C){if(B==this._elCurListItem){return ;}var A=this.prehighlightClassName;if((C=="mouseover")&&A){YAHOO.util.Dom.addClass(B,A);}else{YAHOO.util.Dom.removeClass(B,A);}};YAHOO.widget.AutoComplete.prototype._updateValue=function(C){if(!this.suppressInputUpdate){var F=this._elTextbox;var E=(this.delimChar)?(this.delimChar[0]||this.delimChar):null;var B=C._sResultMatch;var D="";if(E){D=this._sPastSelections;D+=B+E;if(E!=" "){D+=" ";}}else{D=B;}F.value=D;if(F.type=="textarea"){F.scrollTop=F.scrollHeight;}var A=F.value.length;this._selectText(F,A,A);this._elCurListItem=C;}};YAHOO.widget.AutoComplete.prototype._selectItem=function(A){this._bItemSelected=true;this._updateValue(A);this._sPastSelections=this._elTextbox.value;this._clearInterval();this.itemSelectEvent.fire(this,A,A._oResultData);this._toggleContainer(false);};YAHOO.widget.AutoComplete.prototype._jumpSelection=function(){if(this._elCurListItem){this._selectItem(this._elCurListItem); -}else{this._toggleContainer(false);}};YAHOO.widget.AutoComplete.prototype._moveSelection=function(G){if(this._bContainerOpen){var F=this._elCurListItem;var E=-1;if(F){E=F._nItemIndex;}var C=(G==40)?(E+1):(E-1);if(C<-2||C>=this._nDisplayedItems){return ;}if(F){this._toggleHighlight(F,"from");this.itemArrowFromEvent.fire(this,F);}if(C==-1){if(this.delimChar){this._elTextbox.value=this._sPastSelections+this._sCurQuery;}else{this._elTextbox.value=this._sCurQuery;}return ;}if(C==-2){this._toggleContainer(false);return ;}var D=this._elList.childNodes[C];var A=this._elContent;var B=((YAHOO.util.Dom.getStyle(A,"overflow")=="auto")||(YAHOO.util.Dom.getStyle(A,"overflowY")=="auto"));if(B&&(C>-1)&&(C(A.scrollTop+A.offsetHeight)){A.scrollTop=(D.offsetTop+D.offsetHeight)-A.offsetHeight;}else{if((D.offsetTop+D.offsetHeight)(A.scrollTop+A.offsetHeight)){this._elContent.scrollTop=(D.offsetTop+D.offsetHeight)-A.offsetHeight;}}}}this._toggleHighlight(D,"to");this.itemArrowToEvent.fire(this,D);if(this.typeAhead){this._updateValue(D);}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseover=function(A,C){var D=YAHOO.util.Event.getTarget(A);var B=D.nodeName.toLowerCase();while(D&&(B!="table")){switch(B){case"body":return ;case"li":if(C.prehighlightClassName){C._togglePrehighlight(D,"mouseover");}else{C._toggleHighlight(D,"to");}C.itemMouseOverEvent.fire(C,D);break;case"div":if(YAHOO.util.Dom.hasClass(D,"yui-ac-container")){C._bOverContainer=true;return ;}break;default:break;}D=D.parentNode;if(D){B=D.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseout=function(A,C){var D=YAHOO.util.Event.getTarget(A);var B=D.nodeName.toLowerCase();while(D&&(B!="table")){switch(B){case"body":return ;case"li":if(C.prehighlightClassName){C._togglePrehighlight(D,"mouseout");}else{C._toggleHighlight(D,"from");}C.itemMouseOutEvent.fire(C,D);break;case"ul":C._toggleHighlight(C._elCurListItem,"to");break;case"div":if(YAHOO.util.Dom.hasClass(D,"yui-ac-container")){C._bOverContainer=false;return ;}break;default:break;}D=D.parentNode;if(D){B=D.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerClick=function(A,C){var D=YAHOO.util.Event.getTarget(A);var B=D.nodeName.toLowerCase();while(D&&(B!="table")){switch(B){case"body":return ;case"li":C._toggleHighlight(D,"to");C._selectItem(D);return ;default:break;}D=D.parentNode;if(D){B=D.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerScroll=function(A,B){B._elTextbox.focus();};YAHOO.widget.AutoComplete.prototype._onContainerResize=function(A,B){B._toggleContainerHelpers(B._bContainerOpen);};YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown=function(A,B){var C=A.keyCode;if(B._nTypeAheadDelayID!=-1){clearTimeout(B._nTypeAheadDelayID);}switch(C){case 9:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(B._elCurListItem){if(B.delimChar&&(B._nKeyCode!=C)){if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);}}B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;case 13:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(B._elCurListItem){if(B._nKeyCode!=C){if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);}}B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;case 27:B._toggleContainer(false);return ;case 39:B._jumpSelection();break;case 38:if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);B._moveSelection(C);}break;case 40:if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);B._moveSelection(C);}break;default:B._bItemSelected=false;B._toggleHighlight(B._elCurListItem,"from");B.textboxKeyEvent.fire(B,C);break;}if(C===18){B._enableIntervalDetection();}B._nKeyCode=C;};YAHOO.widget.AutoComplete.prototype._onTextboxKeyPress=function(A,B){var C=A.keyCode;if(YAHOO.env.ua.opera||(navigator.userAgent.toLowerCase().indexOf("mac")!=-1)&&(YAHOO.env.ua.webkit<420)){switch(C){case 9:if(B._bContainerOpen){if(B.delimChar){YAHOO.util.Event.stopEvent(A);}if(B._elCurListItem){B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;case 13:if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);if(B._elCurListItem){B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;default:break;}}else{if(C==229){B._enableIntervalDetection();}}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyUp=function(A,C){var B=this.value;C._initProps();var D=A.keyCode;if(C._isIgnoreKey(D)){return ;}if(C._nDelayID!=-1){clearTimeout(C._nDelayID);}C._nDelayID=setTimeout(function(){C._sendQuery(B);},(C.queryDelay*1000));};YAHOO.widget.AutoComplete.prototype._onTextboxFocus=function(A,B){if(!B._bFocused){B._elTextbox.setAttribute("autocomplete","off");B._bFocused=true;B._sInitInputValue=B._elTextbox.value;B.textboxFocusEvent.fire(B);}};YAHOO.widget.AutoComplete.prototype._onTextboxBlur=function(A,C){if(!C._bOverContainer||(C._nKeyCode==9)){if(!C._bItemSelected){var B=C._textMatchesOption();if(!C._bContainerOpen||(C._bContainerOpen&&(B===null))){if(C.forceSelection){C._clearSelection();}else{C.unmatchedItemSelectEvent.fire(C,C._sCurQuery);}}else{if(C.forceSelection){C._selectItem(B);}}}if(C._bContainerOpen){C._toggleContainer(false);}C._clearInterval();C._bFocused=false;if(C._sInitInputValue!==C._elTextbox.value){C.textboxChangeEvent.fire(C);}C.textboxBlurEvent.fire(C);}};YAHOO.widget.AutoComplete.prototype._onWindowUnload=function(A,B){if(B&&B._elTextbox&&B.allowBrowserAutocomplete){B._elTextbox.setAttribute("autocomplete","on");}};YAHOO.widget.AutoComplete.prototype.doBeforeSendQuery=function(A){return this.generateRequest(A);};YAHOO.widget.AutoComplete.prototype.getListItems=function(){var C=[],B=this._elList.childNodes;for(var A=B.length-1;A>=0;A--){C[A]=B[A];}return C;};YAHOO.widget.AutoComplete._cloneObject=function(D){if(!YAHOO.lang.isValue(D)){return D; -}var F={};if(YAHOO.lang.isFunction(D)){F=D;}else{if(YAHOO.lang.isArray(D)){var E=[];for(var C=0,B=D.length;C0){for(var B=0,A=D.length;B0){var B=(A===false?function(K){return K;}:decodeURIComponent);if(/[^=]+=[^=;]?(?:; [^=]+=[^=]?)?/.test(I)){var G=I.split(/;\s/g);var H=null;var C=null;var E=null;for(var D=0,F=G.length;D - - - - config config.js - - - - - - - - - - -
-
-

Node.js Configuration

- Node.js Configuration - > config - - > config.js (source view) -
-
- Search: -
-   -
-
-
-
- -
-
-
-
-
- Filters - - - -
-
- -
- -
/*jsl:declare global */
-// config.js (c) 2010-2014 Loren West and other contributors
-// May be freely distributed under the MIT license.
-// For further details and documentation:
-// http://lorenwest.github.com/node-config
-
-// Dependencies
-var Yaml = null,    // External libraries are lazy-loaded
-    VisionmediaYaml = null,  // only if these file types exist.
-    Coffee = null,
-    FileSystem = require('fs');
-
-// Static members
-var DEFAULT_CLONE_DEPTH = 20,
-    FILE_WATCHER_INTERVAL = 2500, // For old style (pre-6.0) file watching
-    CONFIG_DIR, RUNTIME_JSON_FILENAME, NODE_ENV, APP_INSTANCE,
-    DISABLE_FILE_WATCH, PERSIST_ON_CHANGE, HOST, HOSTNAME,
-    originalConfig = null,       // Not including the runtime.json values
-    runtimeJson = {},            // Current runtimeJson extensions
-    runtimeJsonWatcher = null,   // Filesystem watcher for runtime.json
-    configSources = [],          // Configuration sources - array of {name, original, parsed}
-    isQueuedForPersistence = false;
-
-/**
- * <p>Runtime Application Configurations</p>
- *
- * <p>
- * The config module exports a singleton object representing all runtime
- * configurations for this application deployment.
- * </p>
- *
- * <p>
- * Application configurations are stored in files within the config directory
- * of your application.  The default configuration file is loaded, followed
- * by files specific to the deployment type (development, testing, staging,
- * production, etc.).
- * </p>
- *
- * <p>
- * For example, with the following config/default.yaml file:
- * </p>
- *
- * <pre>
- *   ...
- *   customer:
- *     &nbsp;&nbsp;initialCredit: 500
- *     &nbsp;&nbsp;db:
- *       &nbsp;&nbsp;&nbsp;&nbsp;name: customer
- *       &nbsp;&nbsp;&nbsp;&nbsp;port: 5984
- *   ...
- * </pre>
- *
- * <p>
- * The following code loads the customer section into the CONFIG variable:
- * <p>
- *
- * <pre>
- *   var CONFIG = require('config').customer;
- *   ...
- *   newCustomer.creditLimit = CONFIG.initialCredit;
- *   database.open(CONFIG.db.name, CONFIG.db.port);
- *   ...
- * </pre>
- *
- * @module config
- * @class Config
- */
-
-/**
- * <p>Get the configuration object.</p>
- *
- * <p>
- * The configuration object is a shared singleton object within the application,
- * attained by calling require('config').
- * </p>
- *
- * <p>
- * Usually you'll specify a CONFIG variable at the top of your .js file
- * for file/module scope. If you want the root of the object, you can do this:
- * </p>
- * <pre>
- * var CONFIG = require('config');
- * </pre>
- *
- * <p>
- * Sometimes you only care about a specific sub-object within the CONFIG
- * object.  In that case you could do this at the top of your file:
- * </p>
- * <pre>
- * var CONFIG = require('config').customer;
- * or
- * var CUSTOMER_CONFIG = require('config').customer;
- * </pre>
- *
- * <script type="text/javascript">
- *   document.getElementById("showProtected").style.display = "block";
- * </script>
- *
- * @method constructor
- * @return CONFIG {object} - The top level configuration object
- */
-var Config = function() {
-  var t = this;
-
-  // Initialize parameters from command line, environment, or default
-  NODE_ENV = t._initParam('NODE_ENV', 'development');
-  CONFIG_DIR = t._initParam('NODE_CONFIG_DIR', process.cwd() + '/config');
-  if (CONFIG_DIR.indexOf('.') === 0) {
-    CONFIG_DIR = process.cwd() + '/' + CONFIG_DIR;
-  }
-  RUNTIME_JSON_FILENAME = t._initParam('NODE_CONFIG_RUNTIME_JSON', CONFIG_DIR + '/runtime.json');
-  DISABLE_FILE_WATCH = t._initParam('NODE_CONFIG_DISABLE_FILE_WATCH');
-  PERSIST_ON_CHANGE = t._initParam('NODE_CONFIG_PERSIST_ON_CHANGE');
-  APP_INSTANCE = t._initParam('NODE_APP_INSTANCE');
-  HOST = t._initParam('HOST');
-  HOSTNAME = t._initParam('HOSTNAME');
-
-  t._loadFileConfigs();
-  t._persistConfigsOnChange();
-};
-
-/**
- * <p>Monitor a configuration value for runtime changes.</p>
- *
- * <p>
- * Configuration values can be changed at runtime by the application or by a
- * manual change to the config/runtime.json  file.
- * This method lets you specify a function to run when a configuration
- * value changes.
- * </p>
- *
- * <p><i>
- * This was built for monitoring changes to configuration values,
- * but it can be used for watching changes to <u>any</u> javascript object.
- * </i></p>
- *
- * <p>Example:</p>
- * <pre>
- *   var CONFIG = require('config').customer;
- *   ...
- *
- *   // Watch for any changes to the customer configuration
- *   CONFIG.watch(CONFIG, null, function(object, propertyName, priorValue, newValue) {
- *   &nbsp;console.log("Customer configuration " + propertyName + " changed from " + priorValue + " to " + newValue);
- *   });
- * </pre>
- *
- * @method watch
- * @param object {object} - The object to watch.
- * @param property {string} - The property name to watch.  Watch all object properties if null.
- * @param handler {function(object, propertyName, priorValue, newValue)} - Handler called when a property change is detected.
- *   The handler is run along with other handlers registered for notification.
- *   If your handler changes the value of the property, that change is applied after all handlers have finished processing the current change.
- *   Then all handlers (including this one) will be called again with the newly changed value.
- * @param depth {integer} (optional) - If watching all object properties or if the specified property is an object, this specifies the depth of the object graph to watch for changes.  Default 6.
- * @return object {object} - The original object is returned - for chaining.
- */
-Config.prototype.watch = function(object, property, handler, depth) {
-
-  // Initialize
-  var t = this, o = object;
-  var allProperties = property ? [property] : Object.keys(o);
-
-  // Depth detection
-  depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth);
-  if (depth < 0) {
-    return;
-  }
-
-  // Create hidden properties on the object
-  if (!o.__watchers)
-    t.makeHidden(o, '__watchers', {});
-  if (!o.__propertyValues)
-    t.makeHidden(o, '__propertyValues', {});
-
-  // Attach watchers to all requested properties
-  allProperties.forEach(function(prop){
-
-    // Setup the property for watching (first time only)
-    if (typeof(o.__propertyValues[prop]) == 'undefined') {
-
-      // Don't error re-defining the property if immutable
-      var descriptor = Object.getOwnPropertyDescriptor(o, prop);
-      if (descriptor && descriptor.writable === false)
-        return;
-
-      // Copy the value to the hidden field, and add the property to watchers
-      o.__propertyValues[prop] = [o[prop]];
-      o.__watchers[prop] = [];
-
-      // Attach the property watcher
-      Object.defineProperty(o, prop, {
-        enumerable : true,
-
-        get : function(){
-          // If more than 1 item is in the values array,
-          // then we're currently processing watchers.
-          if (o.__propertyValues[prop].length == 1)
-            // Current value
-            return o.__propertyValues[prop][0];
-          else
-            // [0] is prior value, [1] is new value being processed
-            return o.__propertyValues[prop][1];
-        },
-
-        set : function(newValue) {
-
-          // Return early if no change
-          var origValue = o[prop];
-          if (t._equalsDeep(origValue, newValue))
-            return;
-
-          // Remember the new value, and return if we're in another setter
-          o.__propertyValues[prop].push(newValue);
-          if (o.__propertyValues[prop].length > 2)
-            return;
-
-          // Call all watchers for each change requested
-          var numIterations = 0;
-          while (o.__propertyValues[prop].length > 1) {
-
-            // Detect recursion
-            if (++numIterations > 20) {
-              o.__propertyValues[prop] = [origValue];
-              throw new Error('Recursion detected while setting [' + prop + ']');
-            }
-
-            // Call each watcher for the current values
-            var oldValue = o.__propertyValues[prop][0];
-            newValue = o.__propertyValues[prop][1];
-            o.__watchers[prop].forEach(function(watcher) {
-              try {
-                watcher(o, prop, oldValue, newValue);
-              } catch (e) {
-                // Log an error and continue with subsequent watchers
-                console.error("Exception in object watcher for " + prop, e);
-              }
-            });
-
-            // Done processing this value
-            o.__propertyValues[prop].splice(0,1);
-          }
-        }
-      });
-
-    } // Done setting up the property for watching (first time)
-
-    // Add the watcher to the property
-    o.__watchers[prop].push(handler);
-
-    // Recurs if this is an object...
-    if (o[prop] && typeof(o[prop]) == 'object') {
-      Config.prototype.watch(o[prop], null, handler, depth - 1);
-    }
-
-  }); // Done processing each property
-
-  // Return the original object - for chaining
-  return o;
-};
-
-/**
- * <p>
- * Set default configurations for a node.js module.
- * </p>
- *
- * <p>
- * This allows module developers to attach their configurations onto the
- * default configuration object so they can be configured by the consumers
- * of the module.
- * </p>
- *
- * <p>Using the function within your module:</p>
- * <pre>
- *   var CONFIG = require("config");
- *   CONFIG.setModuleDefaults("MyModule", {
- *   &nbsp;&nbsp;templateName: "t-50",
- *   &nbsp;&nbsp;colorScheme: "green"
- *   });
- * <br>
- *   // Template name may be overridden by application config files
- *   console.log("Template: " + CONFIG.MyModule.templateName);
- * </pre>
- *
- * <p>
- * The above example results in a "MyModule" element of the configuration
- * object, containing an object with the specified default values.
- * </p>
- *
- * @method setModuleDefaults
- * @param moduleName {string} - Name of your module.
- * @param defaultProperties {object} - The default module configuration.
- * @return moduleConfig {object} - The module level configuration object.
- */
-Config.prototype.setModuleDefaults = function(moduleName, defaultProperties) {
-
-  // Copy the properties into a new object
-  var t = this,
-      moduleConfig = t._extendDeep({}, defaultProperties);
-
-  // Set module defaults into the first sources element
-  if (configSources.length === 0 || configSources[0].name !== 'Module Defaults') {
-    configSources.splice(0, 0, {
-      name: 'Module Defaults',
-      parsed: {}
-    });
-  }
-  configSources[0].parsed[moduleName] = {};
-  t._extendDeep(configSources[0].parsed[moduleName], defaultProperties);
-
-  // Attach handlers & watchers onto the module config object
-  t._attachProtoDeep(moduleConfig);
-  t._persistConfigsOnChange(moduleConfig);
-
-  // Extend the module config object with values from originalConfig
-  if (originalConfig[moduleName]) {
-    t._extendDeep(moduleConfig, originalConfig[moduleName]);
-  }
-
-  // Save the mixed module config as the original
-  originalConfig[moduleName] = t._cloneDeep(moduleConfig);
-
-  // Extend the module config object with values from runtimeJson
-  if (runtimeJson[moduleName]) {
-    t._extendDeep(moduleConfig, runtimeJson[moduleName]);
-  }
-
-  // Attach the object onto the CONFIG object
-  t[moduleName] = moduleConfig;
-
-  // Return the module config
-  return moduleConfig;
-};
-
-/**
- * <p>Make a configuration property hidden so it doesn't appear when enumerating
- * elements of the object.</p>
- *
- * <p>
- * The property still exists and can be read from and written to, but it won't
- * show up in for ... in loops, Object.keys(), or JSON.stringify() type methods.
- * </p>
- *
- * <p>
- * If the property already exists, it will be made hidden.  Otherwise it will
- * be created as a hidden property with the specified value.
- * </p>
- *
- * <p><i>
- * This method was built for hiding configuration values, but it can be applied
- * to <u>any</u> javascript object.
- * </i></p>
- *
- * <p>Example:</p>
- * <pre>
- *   var CONFIG = require('config');
- *   ...
- *
- *   // Hide the Amazon S3 credentials
- *   CONFIG.makeHidden(CONFIG.amazonS3, 'access_id');
- *   CONFIG.makeHidden(CONFIG.amazonS3, 'secret_key');
- * </pre>
- *
- * @method makeHidden
- * @param object {object} - The object to make a hidden property into.
- * @param property {string} - The name of the property to make hidden.
- * @param value {mixed} - (optional) Set the property value to this (otherwise leave alone)
- * @return object {object} - The original object is returned - for chaining.
- */
-Config.prototype.makeHidden = function(object, property, value) {
-
-  // Use the existing value if the new value isn't specified
-  value = (typeof value == 'undefined') ? object[property] : value;
-
-  // Create the hidden property
-  Object.defineProperty(object, property, {
-    value: value,
-    enumerable : false
-  });
-
-  return object;
-}
-
-/**
- * <p>Make a configuration property immutable (assuring it cannot be changed
- * from the current value).</p>
- *
- * <p>
- * This operation cannot be undone.
- * </p>
- * <p><i>
- *
- * This method was built for disabling runtime changes to configuration values,
- * but it can be applied to <u>any</u> javascript object.
- * </i></p>
- *
- * <p>Example:</p>
- * <pre>
- *   var CONFIG = require('config').customer;
- *   ...
- *
- *   // Obtain a DB connection using CONFIG parameters
- *   database.open(CONFIG.db.name, CONFIG.db.port);
- *   ...
- *
- *   // Don't allow database changes after connect
- *   CONFIG.makeImmutable(CONFIG.db, 'name');
- *   CONFIG.makeImmutable(CONFIG.db, 'port');
- * </pre>
- *
- * @method makeImmutable
- * @param object {object} - The object to attach an immutable property into.
- * @param property {string} - The name of the property to make immutable.
- * @param value {mixed} - (optional) Set the property value to this (otherwise leave alone)
- * @return object {object} - The original object is returned - for chaining.
- */
-Config.prototype.makeImmutable = function(object, property, value) {
-
-  // Use the existing value if a new value isn't specified
-  value = (typeof value == 'undefined') ? object[property] : value;
-
-  // Disable writing, and make sure the property cannot be re-configured.
-  Object.defineProperty(object, property, {
-    value : value,
-    writable : false,
-    configurable: false
-  });
-
-  return object;
-};
-
-/**
- * Start or stop runtime.json configuration file watching
- *
- * <p>
- * Node-config automatically monitors and apply changes made to the
- * config/runtime.json file.  This paradigm allows for manual changes to running
- * application servers, and for multi-node application servers to keep in sync.
- * </p>
- *
- * <p>
- * This method allows you to change the polling interval from the default
- * interval (2.5 seconds), or to turn file watching off.  On Linux systems with
- * inotify, and in node.js versions 0.6 and above, this interval is ignored.
- * </p>
- *
- * <p>
- * runtime.json file watching can be disabled by setting the NODE_CONFIG_DISABLE_FILE_WATCH
- * environment variable or --NODE_CONFIG_DISABLE_FILE_WATCH command line parameter
- * to "Y" prior to running your application.
- * </p>
- *
- * @method watchForConfigFileChanges
- * @param interval {Integer} - Polling interval in milliseconds.  Defaults to 2500.
- */
-Config.prototype.watchForConfigFileChanges = function(interval) {
-
-  // Turn off any prior watching
-  var t = this, watchInterval = (typeof interval === 'undefined' ? FILE_WATCHER_INTERVAL : interval);
-  if (FileSystem.watch) {
-    if (runtimeJsonWatcher) {
-      runtimeJsonWatcher.close();
-      runtimeJsonWatcher = null;
-    }
-  } else {
-    FileSystem.unwatchFile(RUNTIME_JSON_FILENAME);
-  }
-
-  // If interval is zero or file watching is disabled, don't attach a new watcher
-  if (interval === 0 || DISABLE_FILE_WATCH === "Y") {
-    return;
-  }
-
-  // Re-merge the runtime JSON file if we notice a change
-  var onFileChange = function(retry) {
-    FileSystem.readFile(RUNTIME_JSON_FILENAME, 'UTF-8', function(err, fileContent) {
-
-      // Not much to do on error
-      if (err) {
-        console.error("Error loading " + RUNTIME_JSON_FILENAME, err);
-        return;
-      }
-
-      // Parse the file and mix it in to this config object.
-      // This notifies listeners
-      try {
-        var configObject = JSON.parse(t._stripComments(fileContent));
-        t._extendDeep(t, configObject);
-      } catch (e) {
-        console.error("Error parsing " + RUNTIME_JSON_FILENAME, e);
-        // Retry once - could be someone else writing
-        if (!retry) {
-          setTimeout(function(){
-            onFileChange(true);
-          }, 1000);
-        }
-        return;
-      }
-    });
-  };
-
-  // Use the latest version of file watching
-  try {
-    if (FileSystem.watch) {
-      // This is the latest
-      runtimeJsonWatcher = FileSystem.watch(RUNTIME_JSON_FILENAME, {persistent:false}, function(event, filename) {
-
-        // Re-attach watcher on inode change (happens when some editors save a file)
-        // Wait for the O/S rename to complete, then re-watch the file
-        if (event == 'rename') {
-          setTimeout(function(){
-            t.watchForConfigFileChanges();
-            onFileChange();
-          }, 10);
-          return;
-        }
-
-        onFileChange();
-      });
-    }
-    else {
-      // Old style polling - only choice if running pre-6.0
-      FileSystem.watchFile(RUNTIME_JSON_FILENAME, {persistent:false, interval:watchInterval}, function(curr, prev) {
-        if (curr.mtime.getTime() === prev.mtime.getTime()) {return;}
-        onFileChange();
-      });
-    }
-  } catch (e) {
-    // Complain if it exists and we can't watch it
-    if (e.code !== 'ENOENT') {
-      console.error("Error watching for file: " + RUNTIME_JSON_FILENAME, e);
-    }
-  }
-
-};
-
-/**
- * <p>Safely write a file</p>
- *
- * <p>
- * This method safely overwrites a file by first writing to a temporary file
- * and then renaming it. This to ensure no other process reads to file in a
- * truncated state.
- * </p>
- *
- * @method safeWriteFile
- * @param filename {String} Filename to write to.
- * @param content  {String} Data to write.
- * @param callback {Function} Callback function.
- */
-Config.prototype.safeWriteFile = function(filename, data, callback) {
-    var rand = Math.floor(Math.random() * (1 << 30)),
-        tmpFilename = filename + '.tmp-' + rand;
-
-    FileSystem.writeFile(tmpFilename, data, 'utf-8', function (err) {
-        if (err) {
-            return callback(err);
-        }
-
-        FileSystem.rename(tmpFilename, filename, function (err) {
-            callback(err);
-        });
-    });
-}
-
-/**
- * Return the sources for the configurations
- *
- * <p>
- * All sources for configurations are stored in an array of objects containing
- * the source name (usually the filename), the original source (as a string),
- * and the parsed source as an object.
- * </p>
- *
- * @method getConfigSources
- * @return configSources {Array[Object]} - An array of objects containing
- *    name, original, and parsed elements
- */
-Config.prototype.getConfigSources = function() {
-  var t = this;
-  return configSources.slice(0);
-};
-
-/**
- * <p>
- * Watch the specified object for a change in properties, and persist changes
- * to runtime.json when a change is detected.
- * </p>
- *
- * @protected
- * @param object {object} - The config object to watch
- * @method _persistConfigsOnChange
- */
-Config.prototype._persistConfigsOnChange = function(objectToWatch) {
-
-  if (PERSIST_ON_CHANGE === 'N') {
-    return;
-  }
-  // Watch for configuration value changes
-  var t = this;
-  objectToWatch = objectToWatch || t;
-  t.watch(objectToWatch, null, function(){
-
-    // Return early if we're already queued up for persisting
-    if (isQueuedForPersistence)
-      return;
-
-    // Defer persisting until the next tick.  This results in a single
-    // persist across any number of config changes in a single event cycle.
-    isQueuedForPersistence = true;
-    process.nextTick(function(){
-
-      // Persist if necessary
-      var newDiffs = t._diffDeep(originalConfig, t);
-      if (!t._equalsDeep(newDiffs, runtimeJson)) {
-        t.safeWriteFile(RUNTIME_JSON_FILENAME, JSON.stringify(newDiffs, null, 2), function(error){
-          if (error)
-            console.error("Error writing " + RUNTIME_JSON_FILENAME, error);
-        });
-      }
-
-      // Set up for next time
-      isQueuedForPersistence = false;
-    });
-  });
-};
-
-/**
- * Load the individual file configurations.
- *
- * <p>
- * This method builds a map of filename to the configuration object defined
- * by the file.  The search order is:
- * </p>
- *
- * <pre>
- *   default.EXT
- *   (hostname).EXT
- *   (deployment).EXT
- *   (hostname)-(deployment).EXT
- *   local.EXT
- *   local-(deployment).EXT
- *   runtime.json
- * </pre>
- *
- * <p>
- * EXT can be yml, yaml, coffee, json, or js signifying the file type.
- * yaml (and yml) is in YAML format, coffee is a coffee-script,
- * json is in JSON format, and js is a javascript executable file that is
- * require()'d with module.exports being the config object.
- * </p>
- *
- * <p>
- * hostname is the $HOST environment variable (or --HOST command line parameter)
- * if set, otherwise the $HOSTNAME environment variable (or --HOSTNAME command
- * line parameter) if set, otherwise the hostname found from
- * require('os').hostname().
- * </p>
- *
- * <p>
- * Once a hostname is found, everything from the first period ('.') onwards
- * is removed. For example, abc.example.com becomes abc
- * </p>
- *
- * <p>
- * (deployment) is the deployment type, found in the $NODE_ENV environment
- * variable or --NODE_ENV command line parameter.  Defaults to 'development'.
- * </p>
- *
- * <p>
- * The runtime.json file contains configuration changes made at runtime either
- * manually, or by the application setting a configuration value.
- * </p>
- *
- * <p>
- * If the $NODE_APP_INSTANCE environment variable (or --NODE_APP_INSTANCE
- * command line parameter) is set, then files with this appendage will be loaded.
- * See the Multiple Applicstion Instances section of the main documentaion page
- * for more information.
- * </p>
- *
- * @protected
- * @method _loadFileConfigs
- * @return {this} The configuration object
- */
-Config.prototype._loadFileConfigs = function() {
-
-  // Initialize
-  var t = this;
-
-  // Run only once
-  if (originalConfig) {
-    return t;
-  }
-
-  // Determine the host name from the OS module, $HOST, or $HOSTNAME
-  // Remove any . appendages, and default to null if not set
-  try {
-    var hostName = HOST || HOSTNAME;
-
-    if (!hostName) {
-        var OS = require('os');
-        hostName = OS.hostname();
-    }
-  } catch (e) {
-    hostName = '';
-  }
-  hostName = hostName ? hostName.split('.')[0] : null;
-
-  // Read each file in turn
-  var baseNames = ['default', hostName, NODE_ENV, hostName + '-' + NODE_ENV, 'local', 'local-' + NODE_ENV];
-  var extNames = ['js', 'json', 'coffee', 'yaml', 'yml'];
-  baseNames.forEach(function(baseName) {
-    extNames.forEach(function(extName) {
-
-      // Try merging the config object into this object
-      var fullFilename = CONFIG_DIR + '/' + baseName + '.' + extName;
-      var configObj = t._parseFile(fullFilename);
-      if (configObj) {
-        t._extendDeep(t, configObj);
-      }
-
-      // See if the application instance file is available
-      if (APP_INSTANCE) {
-        fullFilename = CONFIG_DIR + '/' + baseName + '-' + APP_INSTANCE + '.' + extName;
-        configObj = t._parseFile(fullFilename);
-        if (configObj) {
-          t._extendDeep(t, configObj);
-        }
-      }
-    });
-  });
-
-  // Override configurations with the old-style environment variables
-  // Warning: This will be deprecated in a future major revision release
-  var oldStyleEnv = t._loadOldStyleEnv();
-  if (JSON.stringify(oldStyleEnv).length > 2) {
-    t._extendDeep(t, oldStyleEnv);
-    configSources.push({
-      name: "Old-Style Environment Variables",
-      parsed: oldStyleEnv,
-    });
-    console.log('\nWarning - old style $CONFIG_* environment configurations found. Convert to $NODE_CONFIG={JSON}')
-  }
-
-  // Override configurations from the $NODE_CONFIG environment variable
-  if (process.env.NODE_CONFIG) {
-    var newStyleEnv = {};
-    try {
-      newStyleEnv = JSON.parse(process.env.NODE_CONFIG);
-    } catch(e) {
-      console.error('The $NODE_CONFIG environment variable is malformed JSON');
-    }
-    t._extendDeep(t, newStyleEnv);
-    configSources.push({
-      name: "$NODE_CONFIG",
-      parsed: newStyleEnv,
-    });
-  }
-
-  // Override configurations from the --NODE_CONFIG command line
-  var cmdLineConfig = t._getCmdLineArg('NODE_CONFIG');
-  if (cmdLineConfig) {
-    try {
-      cmdLineConfig = JSON.parse(cmdLineConfig);
-    } catch(e) {
-      console.error('The --NODE_CONFIG={json} command line argument is malformed JSON');
-    }
-    t._extendDeep(t, cmdLineConfig);
-    configSources.push({
-      name: "--NODE_CONFIG argument",
-      parsed: cmdLineConfig,
-    });
-  }
-
-  // Remember the original configuration (before adding runtimeJson)
-  originalConfig = t._cloneDeep(t);
-
-  // Extend the original config with any prior runtime.json diffs
-  runtimeJson = t._parseFile(RUNTIME_JSON_FILENAME) || {};
-  t._extendDeep(t, runtimeJson);
-
-  // Attach the config.prototype to all sub-objects.
-  t._attachProtoDeep(t);
-
-  // Return the configuration object
-  return t;
-};
-
-/**
- * Check for the old-style environment variable configurations
- *
- * @protected
- * @deprecated
- * @method _loadOldStyleEnv
- * @return {Object} old-style configurations from process.env
- */
-Config.prototype._loadOldStyleEnv = function() {
-  var t = this,
-      envOverride = {};
-
-  for (var varName in process.env) {
-    if (varName.indexOf('CONFIG_') === 0) {
-
-      // Get the string or numeric value
-      var value = process.env[varName],
-          floatVal = parseFloat(value),
-          value = floatVal.toString() === value ? floatVal : value;
-
-      // Convert __ to ` (which you can't have in environment variables)
-      // After splitting, ` are converted to single underscores
-      varName = varName.replace(/__/g,'`');
-      var parts = varName.split('_');
-      parts.splice(0,1); // remove CONFIG
-
-      var curCtxt = envOverride;
-      for (var i = 0, l = parts.length; i < l; i++) {
-        var partName = parts[i].replace(/`/g,'_');
-        if (i == l - 1) {
-          // Final (element) part
-          curCtxt[partName] = value;
-        }
-        else {
-          // Mid (object) part
-          curCtxt[partName] = curCtxt[partName] || {};
-          curCtxt = curCtxt[partName];
-        }
-      }
-    }
-  }
-  return envOverride;
-}
-
-
-/**
- * Parse and return the specified configuration file.
- *
- * If the file exists in the application config directory, it will
- * parse and return it as a JavaScript object.
- *
- * The file extension determines the parser to use.
- *
- * .js = File to run that has a module.exports containing the config object
- * .json = File is parsed using JSON.parse()
- * .coffee = File to run that has a module.exports with coffee-script containing the config object
- * .yaml (or .yml) = Parsed with a YAML parser
- *
- * If the file doesn't exist, a null will be returned.  If the file can't be
- * parsed, an exception will be thrown.
- *
- * This method performs synchronous file operations, and should not be called
- * after synchronous module loading.
- *
- * @protected
- * @method _parseFile
- * @param fullFilename {string} The full file path and name
- * @return {configObject} The configuration object parsed from the file
- */
-Config.prototype._parseFile = function(fullFilename) {
-
-  // Initialize
-  var t = this,
-      extension = fullFilename.substr(fullFilename.lastIndexOf('.') + 1),
-      configObject = null,
-      fileContent = null;
-
-  // Make sure the runtime.json file exists.  This is required for fs.watch().
-  var checkRuntimeJson = function() {
-    if (fullFilename == RUNTIME_JSON_FILENAME) {
-      try {
-        FileSystem.writeFileSync(RUNTIME_JSON_FILENAME, '{}');
-      } catch (e) {
-        // If we cannot write file, clear watch function.
-        t.watchForConfigFileChanges = function () {
-          return;
-        };
-      }
-      return {};
-    }
-    return null;
-  };
-
-  // Return null if the file doesn't exist.
-  // Note that all methods here are the Sync versions.  This is appropriate during
-  // module loading (which is a synchronous operation), but not thereafter.
-  try {
-    var stat = FileSystem.statSync(fullFilename);
-    if (!stat || stat.size < 1) {
-      return checkRuntimeJson();
-    }
-  } catch (e1) {
-    return checkRuntimeJson();
-  }
-
-  // Try loading the file.
-  try {
-    fileContent = FileSystem.readFileSync(fullFilename, 'UTF-8');
-  }
-  catch (e2) {
-    throw new Error('Config file ' + fullFilename + ' cannot be read');
-  }
-
-  // Parse the file based on extension
-  try {
-    if (extension === 'yaml' || extension === 'yml') {
-      if (!Yaml && !VisionmediaYaml) {
-        // Lazy loading
-        try {
-          // Try to load the better js-yaml module
-          Yaml = require('js-yaml');
-        }
-        catch (e) {
-          // If it doesn't exist, load the fallback visionmedia yaml module.
-          VisionmediaYaml = require('yaml');
-        }
-      }
-
-      if (Yaml) {
-        configObject = Yaml.load(t._stripYamlComments(fileContent));
-      }
-      else if (VisionmediaYaml) {
-        // The yaml library doesn't like strings that have newlines but don't
-        // end in a newline: https://github.com/visionmedia/js-yaml/issues/issue/13
-        fileContent += '\n';
-        configObject = VisionmediaYaml.eval(t._stripYamlComments(fileContent));
-      }
-      else {
-        console.error("No YAML parser loaded.  Suggest adding js-yaml dependency to your package.json file.")
-      }
-    }
-    else if (extension == 'json') {
-      // Allow comments in JSON files
-      configObject = JSON.parse(t._stripComments(fileContent));
-    }
-    else if (extension == 'js') {
-      // Use the built-in parser for .js files
-      configObject = require(fullFilename);
-    }
-    else if (extension == 'coffee') {
-      // Lazy load the coffee-script extension
-      Coffee = Coffee || require('coffee-script');
-      // Use the built-in parser for .coffee files with coffee-script
-      configObject = require(fullFilename);
-    }
-  }
-  catch (e3) {
-    throw new Error("Cannot parse config file: '" + fullFilename + "': " + e3);
-  }
-
-  // Keep track of this configuration source if it has anything in it
-  if (JSON.stringify(configObject).length > 2) {
-    configSources.push({
-      name: fullFilename,
-      original: fileContent,
-      parsed: configObject,
-    });
-  }
-
-  return configObject;
-};
-
-/**
- * Attach the Config class prototype to all config objects recursively.
- *
- * <p>
- * This allows you to do anything with CONFIG sub-objects as you can do with
- * the top-level CONFIG object.  It's so you can do this:
- * </p>
- *
- * <pre>
- *   var CUST_CONFIG = require('config').Customer;
- *   CUST_CONFIG.watch(...)
- * </pre>
- *
- * @protected
- * @method _attachProtoDeep
- * @param toObject
- * @param depth
- * @return toObject
- */
-Config.prototype._attachProtoDeep = function(toObject, depth) {
-
-  // Recursion detection
-  var t = this;
-  depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth);
-  if (depth < 0) {
-    return toObject;
-  }
-
-  // Adding Config.prototype methods directly to toObject as hidden properties
-  // because adding to toObject.__proto__ exposes the function in toObject
-  for (var fnName in Config.prototype) {
-    t.makeHidden(toObject, fnName, Config.prototype[fnName]);
-  }
-
-  // Cycle through each element
-  for (var prop in toObject) {
-
-    // Call recursively if an object
-    if (t._isObject(toObject[prop])) {
-      t._attachProtoDeep(toObject[prop], depth - 1);
-    }
-  }
-
-  // Return the original object
-  return toObject;
-
-};
-
-/**
- * Return a deep copy of the specified object.
- *
- * This returns a new object with all elements copied from the specified
- * object.  Deep copies are made of objects and arrays so you can do anything
- * with the returned object without affecting the input object.
- *
- * @protected
- * @method _cloneDeep
- * @param copyFrom {object} The original object to copy from
- * @param depth {integer} An optional depth to prevent recursion.  Default: 20.
- * @return {object} A new object with the elements copied from the copyFrom object
- */
-Config.prototype._cloneDeep = function(obj, depth) {
-
-  // Recursion detection
-  var t = this;
-  depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth);
-  if (depth < 0) {
-    return {};
-  }
-
-  // Create the copy of the correct type
-  var copy = Array.isArray(obj) ? [] : {};
-
-  // Cycle through each element
-  for (var prop in obj) {
-
-    // Call recursively if an object or array
-    if (obj[prop] && typeof obj[prop] == 'object') {
-      copy[prop] = t._cloneDeep(obj[prop], depth - 1);
-    }
-    else {
-      copy[prop] = obj[prop];
-    }
-  }
-
-  // Return the copied object
-  return copy;
-
-};
-
-/**
- * Return true if two objects have equal contents.
- *
- * @protected
- * @method _equalsDeep
- * @param object1 {object} The object to compare from
- * @param object2 {object} The object to compare with
- * @param depth {integer} An optional depth to prevent recursion.  Default: 20.
- * @return {boolean} True if both objects have equivalent contents
- */
-Config.prototype._equalsDeep = function(object1, object2, depth) {
-
-  // Recursion detection
-  var t = this;
-  depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth);
-  if (depth < 0) {
-    return {};
-  }
-
-  // Fast comparisons
-  if (!object1 || !object2) {
-    return false;
-  }
-  if (object1 === object2) {
-    return true;
-  }
-  if (typeof(object1) != 'object' || typeof(object2) != 'object') {
-    return false;
-  }
-
-  // They must have the same keys.  If their length isn't the same
-  // then they're not equal.  If the keys aren't the same, the value
-  // comparisons will fail.
-  if (Object.keys(object1).length != Object.keys(object2).length) {
-    return false;
-  }
-
-  // Compare the values
-  for (var prop in object1) {
-
-    // Call recursively if an object or array
-    if (object1[prop] && typeof(object1[prop]) === 'object') {
-      if (!t._equalsDeep(object1[prop], object2[prop], depth - 1)) {
-        return false;
-      }
-    }
-    else {
-      if (object1[prop] !== object2[prop]) {
-        return false;
-      }
-    }
-  }
-
-  // Test passed.
-  return true;
-};
-
-/**
- * Returns an object containing all elements that differ between two objects.
- * <p>
- * This method was designed to be used to create the runtime.json file
- * contents, but can be used to get the diffs between any two Javascript objects.
- * </p>
- * <p>
- * It works best when object2 originated by deep copying object1, then
- * changes were made to object2, and you want an object that would give you
- * the changes made to object1 which resulted in object2.
- * </p>
- *
- * @protected
- * @method _diffDeep
- * @param object1 {object} The base object to compare to
- * @param object2 {object} The object to compare with
- * @param depth {integer} An optional depth to prevent recursion.  Default: 20.
- * @return {object} A differential object, which if extended onto object1 would
- *                  result in object2.
- */
-Config.prototype._diffDeep = function(object1, object2, depth) {
-
-  // Recursion detection
-  var t = this, diff = {};
-  depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth);
-  if (depth < 0) {
-    return {};
-  }
-
-  // Process each element from object2, adding any element that's different
-  // from object 1.
-  for (var parm in object2) {
-    var value1 = object1[parm];
-    var value2 = object2[parm];
-    if (value1 && value2 && t._isObject(value2)) {
-      if (!(t._equalsDeep(value1, value2))) {
-        diff[parm] = t._diffDeep(value1, value2, depth - 1);
-      }
-    }
-    else if (Array.isArray(value1) && Array.isArray(value2)) {
-      if(!t._equalsDeep(value1, value2)) {
-        diff[parm] = value2;
-      }
-    }
-    else if (value1 !== value2){
-      diff[parm] = value2;
-    }
-  }
-
-  // Return the diff object
-  return diff;
-
-};
-
-/**
- * Extend an object, and any object it contains.
- *
- * This does not replace deep objects, but dives into them
- * replacing individual elements instead.
- *
- * @protected
- * @method _extendDeep
- * @param mergeInto {object} The object to merge into
- * @param mergeFrom... {object...} - Any number of objects to merge from
- * @param depth {integer} An optional depth to prevent recursion.  Default: 20.
- * @return {object} The altered mergeInto object is returned
- */
-Config.prototype._extendDeep = function(mergeInto) {
-
-  // Initialize
-  var t = this;
-  var vargs = Array.prototype.slice.call(arguments, 1);
-  var depth = vargs.pop();
-  if (typeof(depth) != 'number') {
-    vargs.push(depth);
-    depth = DEFAULT_CLONE_DEPTH;
-  }
-
-  // Recursion detection
-  if (depth < 0) {
-    return mergeInto;
-  }
-
-  // Cycle through each object to extend
-  vargs.forEach(function(mergeFrom) {
-
-    // Cycle through each element of the object to merge from
-    for (var prop in mergeFrom) {
-
-      // Extend recursively if both elements are objects
-      if (t._isObject(mergeInto[prop]) && t._isObject(mergeFrom[prop])) {
-        t._extendDeep(mergeInto[prop], mergeFrom[prop], depth - 1);
-      }
-
-      // Copy recursively if the mergeFrom element is an object (or array or fn)
-      else if (mergeFrom[prop] && typeof mergeFrom[prop] == 'object') {
-        mergeInto[prop] = t._cloneDeep(mergeFrom[prop], depth - 1);
-      }
-
-      // Simple assignment otherwise
-      else {
-        mergeInto[prop] = mergeFrom[prop];
-      }
-    }
-  });
-
-  // Chain
-  return mergeInto;
-
-};
-
-/**
- * Strip YAML comments from the string
- *
- * The 2.0 yaml parser doesn't allow comment-only or blank lines.  Strip them.
- *
- * @protected
- * @method _stripYamlComments
- * @param fileString {string} The string to strip comments from
- * @return {string} The string with comments stripped.
- */
-Config.prototype._stripYamlComments = function(fileStr) {
-  // First replace removes comment-only lines
-  // Second replace removes blank lines
-  return fileStr.replace(/^\s*#.*/mg,'').replace(/^\s*[\n|\r]+/mg,'');
-}
-
-/**
- * Strip all Javascript type comments from the string.
- *
- * The string is usually a file loaded from the O/S, containing
- * newlines and javascript type comments.
- *
- * Thanks to James Padolsey, and all who conributed to this implementation.
- * http://james.padolsey.com/javascript/javascript-comment-removal-revisted/
- *
- * @protected
- * @method _stripComments
- * @param fileString {string} The string to strip comments from
- * @return {string} The string with comments stripped.
- */
-Config.prototype._stripComments = function(fileStr) {
-
-  var uid = '_' + +new Date(),
-      primitives = [],
-      primIndex = 0;
-
-  return (
-    fileStr
-
-    /* Remove strings */
-    .replace(/(['"])(\\\1|.)+?\1/g, function(match){
-      primitives[primIndex] = match;
-      return (uid + '') + primIndex++;
-    })
-
-    /* Remove Regexes */
-    .replace(/([^\/])(\/(?!\*|\/)(\\\/|.)+?\/[gim]{0,3})/g, function(match, $1, $2){
-      primitives[primIndex] = $2;
-      return $1 + (uid + '') + primIndex++;
-    })
-
-    /*
-    - Remove single-line comments that contain would-be multi-line delimiters
-        E.g. // Comment /* <--
-    - Remove multi-line comments that contain would be single-line delimiters
-        E.g. /* // <--
-   */
-    .replace(/\/\/.*?\/?\*.+?(?=\n|\r|$)|\/\*[\s\S]*?\/\/[\s\S]*?\*\//g, '')
-
-    /*
-    Remove single and multi-line comments,
-    no consideration of inner-contents
-   */
-    .replace(/\/\/.+?(?=\n|\r|$)|\/\*[\s\S]+?\*\//g, '')
-
-    /*
-    Remove multi-line comments that have a replaced ending (string/regex)
-    Greedy, so no inner strings/regexes will stop it.
-   */
-    .replace(RegExp('\\/\\*[\\s\\S]+' + uid + '\\d+', 'g'), '')
-
-    /* Bring back strings & regexes */
-    .replace(RegExp(uid + '(\\d+)', 'g'), function(match, n){
-      return primitives[n];
-    })
-  );
-
-};
-
-/**
- * Is the specified argument a regular javascript object?
- *
- * The argument is an object if it's a JS object, but not an array.
- *
- * @protected
- * @method _isObject
- * @param arg {MIXED} An argument of any type.
- * @return {boolean} TRUE if the arg is an object, FALSE if not
- */
-Config.prototype._isObject = function(obj) {
-  return (obj !== null) && (typeof obj == 'object') && !(Array.isArray(obj));
-};
-
-/**
- * <p>Exposing original Config</p>
- *
- * <p>
- * This method allows get the original config properties.
- * </p>
- *
- * @method getOriginalConfig
- * @return {object} The original config object is returned
- */
-Config.prototype.getOriginalConfig = function() {
-    return originalConfig;
-}
-
-/**
- * <p>Reset Runtime Config</p>
- *
- * <p>
- * This method allows you to reset the runtime.json generated file.
- * </p>
- *
- * @method resetRuntime
- * @param callback {function} An optional callback function
- */
-Config.prototype.resetRuntime = function(callback) {
-    this.safeWriteFile(RUNTIME_JSON_FILENAME, '{}', function(err, written, buffer) {
-        if(err) {
-            console.log("Cannot write runtime.json file " + err);
-            if (callback && typeof(callback) === 'function') {
-                callback(err);
-            }
-            return;
-        }
-        console.log("Write to runtime.json completed");
-        if (callback && typeof(callback) === 'function') {
-            callback(null, written, buffer);
-        }
-    });
-}
-
-/**
- * <p>Initialize a parameter from the command line or process environment</p>
- *
- * <p>
- * This method looks for the parameter from the command line in the format
- * --PARAMETER=VALUE, then from the process environment, then from the
- * default specified as an argument.
- * </p>
- *
- * @method _initParam
- * @param paramName {String} Name of the parameter
- * @param [defaultValue] {Any} Default value of the parameter
- * @return {Any} The found value, or default value
- */
-Config.prototype._initParam = function (paramName, defaultValue) {
-  var t = this;
-  return t._getCmdLineArg(paramName) || process.env[paramName] || defaultValue;
-}
-
-/**
- * <p>Get Command Line Arguments</p>
- *
- * <p>
- * This method allows you to retrieve the value of the specified command line argument.
- * </p>
- *
- * <p>
- * The argument is case sensitive, and must be of the form '--ARG_NAME=value'
- * </p>
- *
- * @method _getCmdLineArg
- * @param searchFor {STRING} The argument name to search for
- * @return {MIXED} FALSE if the argument was not found, the argument value if found
- */
-Config.prototype._getCmdLineArg = function (searchFor) {
-    var cmdLineArgs = process.argv.slice(2, process.argv.length),
-        argName = '--' + searchFor + '=';
-
-    for (var argvIt = 0; argvIt < cmdLineArgs.length; argvIt++) {
-      if (cmdLineArgs[argvIt].indexOf(argName) === 0) {
-        return cmdLineArgs[argvIt].substr(argName.length);
-      }
-    }
-
-    return false;
-}
-
-// Assure the configuration object is a singleton.
-global.NODE_CONFIG = global.NODE_CONFIG ? global.NODE_CONFIG : new Config();
-
-// The module exports a singleton instance of the Config class so the
-// instance is immediately available on require(), and the prototype methods
-// aren't a part of the object namespace when inspected.
-module.exports = global.NODE_CONFIG;
-
-// Watch for configuration file changes
-global.NODE_CONFIG.watchForConfigFileChanges();
-
-
-
-
-
- -
-
-
-
-Released on github under the Apache License 2.0 -version 0.4.35 -
-
- - - diff --git a/node_modules/config/doc/default.js.html b/node_modules/config/doc/default.js.html deleted file mode 100644 index fe3a4e6..0000000 --- a/node_modules/config/doc/default.js.html +++ /dev/null @@ -1,112 +0,0 @@ - - - - - test default.js - - - - - - - - - - -
-
-

Node.js Configuration

- Node.js Configuration - > test - - > default.js (source view) -
-
- Search: -
-   -
-
-
-
- -
-
-
-
-
- Filters - - - -
-
- -
- -
// Common configuration parameters
-module.exports = {
-  TestModule: {
-    parm1:"value1"
-  },
-  Customers: {
-    dbHost:'base',
-    dbName:'from_default_js'
-  },
-  EnvOverride: {
-    parm_number_1: "from_default_js",
-    parm2: 22
-  }
-};
-
-
-
-
-
- -
-
-
-
-Released on github under the Apache License 2.0 -version 0.4.35 -
-
- - - diff --git a/node_modules/config/doc/index.html b/node_modules/config/doc/index.html deleted file mode 100644 index ba98f38..0000000 --- a/node_modules/config/doc/index.html +++ /dev/null @@ -1,376 +0,0 @@ - - - - - - - - - - - - - - - -
-
-

Node.js Configuration

- Node.js Configuration -
-
- Search: -
-   -
-
-
-
- -
-
-
-
-
- Filters - - - -
-
-

Online Documentation

-
- -

Introduction

-

- Node-config is a configuration system for Node.js application server - deployments. It lets you define a default set of application parameters, - and tune them for different runtime environments (development, qa, - staging, production, etc.). -

-

- Parameters defined by node-config can be monitored and tuned at runtime - without bouncing your production servers. -

- -

Project Guidelines

-
    -
  • Simple - Get started fast
  • -
  • Predictable - Well tested and stable
  • -
  • Flexible - Reasonable defaults & hackable
  • -
  • Powerful - For multi-node enterprise deployment
  • -
  • Lightweight - Small memory and download footprint
  • -
  • Stable - Foundation for module developers
  • -
- -

Getting Started

-

- See the quick-start guide hosted on github -

- -

Configuration Files

-

- Node-config reads configuration files stored in the directory specified by - the NODE_CONFIG_DIR environment variable, which defaults to the config - directory under the process current working directory. Configuration files can be - in JavaScript format, JSON format, COFFEE format, or YAML format - whichever you prefer. -

-

- Configuration files in the config directory are loaded in the following order: -

-
-    default.EXT
-    hostname.EXT
-    deployment.EXT
-    hostname-deployment.EXT
-    local.EXT
-    local-deployment.EXT
-    runtime.json
-  
-

- Where EXT can be .yml, .yaml, .coffee, .json, or .js depending on the format you prefer. - NOTE: If you use .yml, .yaml, or .coffee file extensions, the 'js-yaml' or 'coffee-script' - modules must be available. These external dependencies are not included from - this package. -

-

- hostname is the $HOST environment variable if set, otherwise the $HOSTNAME - environment variable if set, otherwise the hostname found from - require('os').hostname(). Once a hostname is found, everything from the - first period ('.') onwards is removed. For example, abc.example.com becomes abc -

-

- deployment is the deployment type, found in the $NODE_ENV environment - variable. Defaults to 'development'. -

-

- The runtime.json file contains configuration changes made at runtime either - manually, or by the application setting a configuration value. The location is - specified by NODE_CONFIG_RUNTIME_JSON environment variable. By default, it - is a file called runtime.json in NODE_CONFIG_DIR directory. Node-config - monitors this file and loads any new configurations it detects. This file is - loaded after all other configurations, including the $NODE_CONFIG environment - variable and --NODE_CONFIG command line parameter (see below). -

-

- In the running application, each configuration parameter is internally - monitored for changes, and persisted to runtime.json upon change. - This keeps configurations in sync in a mutli-node deployment. If you want to - disable this persistence and sync you can set the environment variable - NODE_CONFIG_PERSIST_ON_CHANGE to "N". This will lead to lower I/O if you - change variables very often in your application. -

- -

File Comments

-

- Javascript-style comments are stripped out of files before parsing, - regardless of the file format type. -

- -

File Formats

-

- JSON files (.json) expose configuration parameters as a JSON object. - Example: -

-
-  /* Customer parameters
-   *
-   * This controls database access and legacy system synchronization
-   */
-  {
-    "Customer": {
-      "dbName": "customers",
-      "dbHost": "localhost",
-      "dbPort": 5984
-      // Database synchronization frequency
-      "syncFrequency": 60
-    }
-  }
-  
-

-

- -

- JavaScript files (.js) expose configuration parameters as module.exports. Example: -

-
-  module.exports = {
-    Customer: {
-      dbName: "customers",
-      dbHost: "localhost",
-      dbPort: 5984,
-      creditLimit: 600 // Default initial credit limit
-    }
-  }
-  
- -

- YAML files (.yaml or .yml) expose configuration parameters in YAML format. Example: -

-
-  Customer:
-      dbName: customers
-      dbHost: localhost
-      dbPort: 5984
-      creditLimit: 600
-  
- -

- Coffee-script files (.coffee) expose configuration parameters in coffee-script format. Example: -

-
-  module.exports =
-    Customer:
-      dbName: "customers"
-      dbHost: "localhost"
-      dbPort: 5984
-      creditLimit: 600
-  
- -

Multiple Instance Configuration

-

- When running multiple instances of your application, you may specify the - $NODE_APP_INSTANCE environment variable prior to running - your app. If set, this variable should contain an identifier for - the specific instance of your app on this server, or within the network. -

-

- Configuration files appended with this identifier will be loaded after - the configuration file without the instance identifier. -

-

- Example: -

-
-    $ export NODE_ENV=staging
-    $ export NODE_APP_INSTANCE=3
-    $ node myApp.js
-  
-

- This instructs node-config to load default-3.json (if present) - immediately after default.json, and staging-3.json after - staging.json. -

-

- All configuration files (except runtime.json) follow this pattern, allowing - your application to specify instance-specific configurations at any level. -

- -

Environment Variable Configurations

-

- If the $NODE_CONFIG environment variable is set, it must be a valid - JSON string containing configuration overrides. These are applied - after configuration files have been loaded. -

-

- For example, setting $NODE_CONFIG={"Customer":{"dbPort":5984}} will set - the CONFIG.Customer.dbPort variable, overriding file configurations. -

- -

Command Line Alternatives to Environment Variables

-

- All environment variables described above may also be supplied on the command - line. -

-

- Example: -

-
-    $ node myApp.js --NODE_ENV=staging --NODE_APP_INSTANCE=3 '--NODE_CONFIG={"Customer":{"dbPort":5984}}'
-  
-

- The format must be two dashes followed by the environment variable name, - an equals sign, and the value (as in the example above). -

- -

Monitoring Changes

-

- One important attribute of node-config is the ability to tune configuration - parameters at runtime. Configuration parameters fall into one of the - following categories: -

-
    -
  • - OK to change - This parameter type can change without - adverse effect. Most parameters fall into this category, where the - parameter value is read every time it's used. -
  • -
  • - Monitored - Some parameters are read infrequently - (usually at the start of the application), and need to be monitored for - change. The CONFIG.watch() function is available to watch these - parameters, and run a function when the value changes. See the - watch method definition for more - information. -
  • -
  • - Not OK to change - Some parameters must be fixed at - runtime and remain stable throughout the lifecycle of the application. - For these parameters, the - makeImmutable method is - offered to guarantee the parameter cannot be changed. -
  • -
- -

Production Deployments

-

- Node-config is designed to run in a multi-node deployment, where many - instances of your application are running on a production server (usually - one per core processor). -

-

- If configuration values change at runtime, these changes are persisted - into the runtime.json file within the config directory. Multi-node - application instances keep in synch by watching for and loading changes - in runtime.json when detected. -

-

- This paradigm does not extend beyond a single machine. -

- -

For Module Developers

-

- Module developers can use node-config to define module specific - configuration parameters, and offer the same runtime tuning and multiple - deployment capability as the local application. -

-

- Node.js modules don't live in the same directory as the application, so - a different mechanism is offered to specify your default configuration. -

-

- The setModuleDefaults - method creates an object (named after the module) within the CONFIG object - containing all module configuration parameters, and their defaults. -

-

- Example: -

-
-    var CONFIG = require("config");
-    CONFIG.setModuleDefaults("MyModule", {
-      templateName: "t-50",
-      colorScheme: "green"
-    });
-  
-

- Users of your module may override your defaults in their config/defaults - file, or any of their deployment-specific configuration files. -

- -

- Online docs built by yui-doc and hosted by github. -

- -
- -
-
-
- -
-
-
-
-Released on github under the Apache License 2.0 -version 0.4.35 -
-
- - - diff --git a/node_modules/config/doc/index.json b/node_modules/config/doc/index.json deleted file mode 100644 index 3b6ce77..0000000 --- a/node_modules/config/doc/index.json +++ /dev/null @@ -1 +0,0 @@ -[{"url": "Config.html#method__attachProtoDeep", "access": "protected", "host": "Config", "type": "method", "name": "_attachProtoDeep"}, {"url": "Config.html#method__cloneDeep", "access": "protected", "host": "Config", "type": "method", "name": "_cloneDeep"}, {"url": "Config.html#method_constructor", "access": "", "host": "Config", "type": "method", "name": "constructor"}, {"url": "Config.html#method__diffDeep", "access": "protected", "host": "Config", "type": "method", "name": "_diffDeep"}, {"url": "Config.html#method__equalsDeep", "access": "protected", "host": "Config", "type": "method", "name": "_equalsDeep"}, {"url": "Config.html#method__extendDeep", "access": "protected", "host": "Config", "type": "method", "name": "_extendDeep"}, {"url": "Config.html#method__getCmdLineArg", "access": "", "host": "Config", "type": "method", "name": "_getCmdLineArg"}, {"url": "Config.html#method_getConfigSources", "access": "", "host": "Config", "type": "method", "name": "getConfigSources"}, {"url": "Config.html#method_getOriginalConfig", "access": "", "host": "Config", "type": "method", "name": "getOriginalConfig"}, {"url": "Config.html#method__initParam", "access": "", "host": "Config", "type": "method", "name": "_initParam"}, {"url": "Config.html#method__isObject", "access": "protected", "host": "Config", "type": "method", "name": "_isObject"}, {"url": "Config.html#method__loadFileConfigs", "access": "protected", "host": "Config", "type": "method", "name": "_loadFileConfigs"}, {"url": "Config.html#method__loadOldStyleEnv", "access": "protected", "host": "Config", "type": "method", "name": "_loadOldStyleEnv"}, {"url": "Config.html#method_makeHidden", "access": "", "host": "Config", "type": "method", "name": "makeHidden"}, {"url": "Config.html#method_makeImmutable", "access": "", "host": "Config", "type": "method", "name": "makeImmutable"}, {"url": "Config.html#method__parseFile", "access": "protected", "host": "Config", "type": "method", "name": "_parseFile"}, {"url": "Config.html#method__persistConfigsOnChange", "access": "protected", "host": "Config", "type": "method", "name": "_persistConfigsOnChange"}, {"url": "Config.html#method_resetRuntime", "access": "", "host": "Config", "type": "method", "name": "resetRuntime"}, {"url": "Config.html#method_safeWriteFile", "access": "", "host": "Config", "type": "method", "name": "safeWriteFile"}, {"url": "Config.html#method_setModuleDefaults", "access": "", "host": "Config", "type": "method", "name": "setModuleDefaults"}, {"url": "Config.html#method__stripComments", "access": "protected", "host": "Config", "type": "method", "name": "_stripComments"}, {"url": "Config.html#method__stripYamlComments", "access": "protected", "host": "Config", "type": "method", "name": "_stripYamlComments"}, {"url": "Config.html#method_watch", "access": "", "host": "Config", "type": "method", "name": "watch"}, {"url": "Config.html#method_watchForConfigFileChanges", "access": "", "host": "Config", "type": "method", "name": "watchForConfigFileChanges"}] \ No newline at end of file diff --git a/node_modules/config/doc/module_config.html b/node_modules/config/doc/module_config.html deleted file mode 100644 index b45147a..0000000 --- a/node_modules/config/doc/module_config.html +++ /dev/null @@ -1,151 +0,0 @@ - - - - - config - - - - - - - - - - -
-
-

Node.js Configuration

- Node.js Configuration - > config - - -
-
- Search: -
-   -
-
-
-
- -
-
-
-
-
- Filters - - - -
-
- - -

Module: config - - - -

-
-

Runtime Application Configurations

-

-The config module exports a singleton object representing all runtime -configurations for this application deployment. -

-

-Application configurations are stored in files within the config directory -of your application. The default configuration file is loaded, followed -by files specific to the deployment type (development, testing, staging, -production, etc.). -

-

-For example, with the following config/default.yaml file: -

-
-...
-customer:
-  initialCredit: 500
-  db:
-    name: customer
-    port: 5984
-...
-
-

-The following code loads the customer section into the CONFIG variable: -

-

-var CONFIG = require('config').customer;
-...
-newCustomer.creditLimit = CONFIG.initialCredit;
-database.open(CONFIG.db.name, CONFIG.db.port);
-...
-
-
- - - -
-
- -

This module contains the following classes:

- -
- -
-
-
- -
-
- -
-
-
- -
-
-
-
-Released on github under the Apache License 2.0 -version 0.4.35 -
-
- - - diff --git a/node_modules/config/doc/module_test.html b/node_modules/config/doc/module_test.html deleted file mode 100644 index f641081..0000000 --- a/node_modules/config/doc/module_test.html +++ /dev/null @@ -1,123 +0,0 @@ - - - - - test - - - - - - - - - - -
-
-

Node.js Configuration

- Node.js Configuration - > test - - -
-
- Search: -
-   -
-
-
-
- -
-
-
-
-
- Filters - - - -
-
- - -

Module: test - - - -

-
-

Unit tests

-
- - - -
-
- -

This module contains the following classes:

- - -
-
- -
-
- -
-
-
- -
-
-
-
-Released on github under the Apache License 2.0 -version 0.4.35 -
-
- - - diff --git a/node_modules/config/doc/raw.json b/node_modules/config/doc/raw.json deleted file mode 100644 index 30aa0b7..0000000 --- a/node_modules/config/doc/raw.json +++ /dev/null @@ -1 +0,0 @@ -{"majorversion": 3, "classmap": {"ConfigTest": {"name": "ConfigTest", "namespace": "", "module": "test", "guessedname": "ConfigTest", "file": "2-config-test.js", "guessedtype": "property", "shortname": "ConfigTest", "description": "

Unit tests for the node-config library. To run type:

\n
npm test
\n

Or, in a project that uses node-config:

\n
npm test config
"}, "Config": {"name": "Config", "namespace": "", "module": "config", "methods": {"_initParam": {"return": {"type": "Any", "description": "The found value, or default value"}, "params": [{"type": "String", "name": "paramName", "description": " Name of the parameter"}, {"type": "Any", "name": "[defaultValue]", "description": " Default value of the parameter"}], "description": "

Initialize a parameter from the command line or process environment

\n

\nThis method looks for the parameter from the command line in the format\n--PARAMETER=VALUE, then from the process environment, then from the\ndefault specified as an argument.\n

", "guessedname": "_initParam", "guessedtype": "function"}, "_diffDeep": {"return": {"type": "object", "description": "A differential object, which if extended onto object1 would\nresult in object2."}, "description": "Returns an object containing all elements that differ between two objects.\n

\nThis method was designed to be used to create the runtime.json file\ncontents, but can be used to get the diffs between any two Javascript objects.\n

\n

\nIt works best when object2 originated by deep copying object1, then\nchanges were made to object2, and you want an object that would give you\nthe changes made to object1 which resulted in object2.\n

", "protected": "", "params": [{"type": "object", "name": "object1", "description": " The base object to compare to"}, {"type": "object", "name": "object2", "description": " The object to compare with"}, {"type": "integer", "name": "depth", "description": " An optional depth to prevent recursion. Default: 20."}], "guessedname": "_diffDeep", "guessedtype": "function"}, "_loadFileConfigs": {"protected": "", "return": {"type": "this", "description": "The configuration object"}, "description": "Load the individual file configurations.\n

\nThis method builds a map of filename to the configuration object defined\nby the file. The search order is:\n

\n
\ndefault.EXT\n(hostname).EXT\n(deployment).EXT\n(hostname)-(deployment).EXT\nlocal.EXT\nlocal-(deployment).EXT\nruntime.json\n
\n

\nEXT can be yml, yaml, coffee, json, or js signifying the file type.\nyaml (and yml) is in YAML format, coffee is a coffee-script,\njson is in JSON format, and js is a javascript executable file that is\nrequire()'d with module.exports being the config object.\n

\n

\nhostname is the $HOST environment variable (or --HOST command line parameter)\nif set, otherwise the $HOSTNAME environment variable (or --HOSTNAME command\nline parameter) if set, otherwise the hostname found from\nrequire('os').hostname().\n

\n

\nOnce a hostname is found, everything from the first period ('.') onwards\nis removed. For example, abc.example.com becomes abc\n

\n

\n(deployment) is the deployment type, found in the $NODE_ENV environment\nvariable or --NODE_ENV command line parameter. Defaults to 'development'.\n

\n

\nThe runtime.json file contains configuration changes made at runtime either\nmanually, or by the application setting a configuration value.\n

\n

\nIf the $NODE_APP_INSTANCE environment variable (or --NODE_APP_INSTANCE\ncommand line parameter) is set, then files with this appendage will be loaded.\nSee the Multiple Applicstion Instances section of the main documentaion page\nfor more information.\n

", "guessedname": "_loadFileConfigs", "guessedtype": "function"}, "watchForConfigFileChanges": {"params": [{"type": "Integer", "name": "interval", "description": " - Polling interval in milliseconds. Defaults to 2500."}], "description": "Start or stop runtime.json configuration file watching\n

\nNode-config automatically monitors and apply changes made to the\nconfig/runtime.json file. This paradigm allows for manual changes to running\napplication servers, and for multi-node application servers to keep in sync.\n

\n

\nThis method allows you to change the polling interval from the default\ninterval (2.5 seconds), or to turn file watching off. On Linux systems with\ninotify, and in node.js versions 0.6 and above, this interval is ignored.\n

\n

\nruntime.json file watching can be disabled by setting the NODE_CONFIG_DISABLE_FILE_WATCH\nenvironment variable or --NODE_CONFIG_DISABLE_FILE_WATCH command line parameter\nto \"Y\" prior to running your application.\n

", "guessedname": "watchForConfigFileChanges", "guessedtype": "function"}, "setModuleDefaults": {"return": {"type": "object", "description": "moduleConfig - The module level configuration object."}, "params": [{"type": "string", "name": "moduleName", "description": " - Name of your module."}, {"type": "object", "name": "defaultProperties", "description": " - The default module configuration."}], "description": "

\nSet default configurations for a node.js module.\n

\n

\nThis allows module developers to attach their configurations onto the\ndefault configuration object so they can be configured by the consumers\nof the module.\n

\n

Using the function within your module:

\n
\nvar CONFIG = require(\"config\");\nCONFIG.setModuleDefaults(\"MyModule\", {\n  templateName: \"t-50\",\n  colorScheme: \"green\"\n});\n
\n// Template name may be overridden by application config files\nconsole.log(\"Template: \" + CONFIG.MyModule.templateName);\n
\n

\nThe above example results in a \"MyModule\" element of the configuration\nobject, containing an object with the specified default values.\n

", "guessedname": "setModuleDefaults", "guessedtype": "function"}, "_isObject": {"return": {"type": "boolean", "description": "TRUE if the arg is an object, FALSE if not"}, "description": "Is the specified argument a regular javascript object?\nThe argument is an object if it's a JS object, but not an array.", "protected": "", "params": [{"type": "MIXED", "name": "arg", "description": " An argument of any type."}], "guessedname": "_isObject", "guessedtype": "function"}, "_getCmdLineArg": {"return": {"type": "MIXED", "description": "FALSE if the argument was not found, the argument value if found"}, "params": [{"type": "STRING", "name": "searchFor", "description": " The argument name to search for"}], "description": "

Get Command Line Arguments

\n

\nThis method allows you to retrieve the value of the specified command line argument.\n

\n

\nThe argument is case sensitive, and must be of the form '--ARG_NAME=value'\n

", "guessedname": "_getCmdLineArg", "guessedtype": "function"}, "_cloneDeep": {"return": {"type": "object", "description": "A new object with the elements copied from the copyFrom object"}, "description": "Return a deep copy of the specified object.\nThis returns a new object with all elements copied from the specified\nobject. Deep copies are made of objects and arrays so you can do anything\nwith the returned object without affecting the input object.", "protected": "", "params": [{"type": "object", "name": "copyFrom", "description": " The original object to copy from"}, {"type": "integer", "name": "depth", "description": " An optional depth to prevent recursion. Default: 20."}], "guessedname": "_cloneDeep", "guessedtype": "function"}, "_loadOldStyleEnv": {"return": {"type": "Object", "description": "old-style configurations from process.env"}, "description": "Check for the old-style environment variable configurations", "deprecated": "", "protected": "", "guessedname": "_loadOldStyleEnv", "guessedtype": "function"}, "getOriginalConfig": {"return": {"type": "object", "description": "The original config object is returned"}, "description": "

Exposing original Config

\n

\nThis method allows get the original config properties.\n

", "guessedname": "getOriginalConfig", "guessedtype": "function"}, "_stripComments": {"return": {"type": "string", "description": "The string with comments stripped."}, "description": "Strip all Javascript type comments from the string.\nThe string is usually a file loaded from the O/S, containing\nnewlines and javascript type comments.\nThanks to James Padolsey, and all who conributed to this implementation.\nhttp://james.padolsey.com/javascript/javascript-comment-removal-revisted/", "protected": "", "params": [{"type": "string", "name": "fileString", "description": " The string to strip comments from"}], "guessedname": "_stripComments", "guessedtype": "function"}, "makeHidden": {"return": {"type": "object", "description": "object - The original object is returned - for chaining."}, "params": [{"type": "object", "name": "object", "description": " - The object to make a hidden property into."}, {"type": "string", "name": "property", "description": " - The name of the property to make hidden."}, {"type": "mixed", "name": "value", "description": " - (optional) Set the property value to this (otherwise leave alone)"}], "description": "

Make a configuration property hidden so it doesn't appear when enumerating\nelements of the object.

\n

\nThe property still exists and can be read from and written to, but it won't\nshow up in for ... in loops, Object.keys(), or JSON.stringify() type methods.\n

\n

\nIf the property already exists, it will be made hidden. Otherwise it will\nbe created as a hidden property with the specified value.\n

\n

\nThis method was built for hiding configuration values, but it can be applied\nto any javascript object.\n

\n

Example:

\n
\nvar CONFIG = require('config');\n...\n// Hide the Amazon S3 credentials\nCONFIG.makeHidden(CONFIG.amazonS3, 'access_id');\nCONFIG.makeHidden(CONFIG.amazonS3, 'secret_key');\n
", "guessedname": "makeHidden", "guessedtype": "function"}, "safeWriteFile": {"params": [{"type": "String", "name": "filename", "description": " Filename to write to."}, {"type": "String", "name": "content", "description": " Data to write."}, {"type": "Function", "name": "callback", "description": " Callback function."}], "description": "

Safely write a file

\n

\nThis method safely overwrites a file by first writing to a temporary file\nand then renaming it. This to ensure no other process reads to file in a\ntruncated state.\n

", "guessedname": "safeWriteFile", "guessedtype": "function"}, "watch": {"return": {"type": "object", "description": "object - The original object is returned - for chaining."}, "params": [{"type": "object", "name": "object", "description": " - The object to watch."}, {"type": "string", "name": "property", "description": " - The property name to watch. Watch all object properties if null."}, {"type": "function(object, propertyName, priorValue, newValue)", "name": "handler", "description": " - Handler called when a property change is detected.\nThe handler is run along with other handlers registered for notification.\nIf your handler changes the value of the property, that change is applied after all handlers have finished processing the current change.\nThen all handlers (including this one) will be called again with the newly changed value."}, {"type": "integer", "name": "depth", "description": " (optional) - If watching all object properties or if the specified property is an object, this specifies the depth of the object graph to watch for changes. Default 6."}], "description": "

Monitor a configuration value for runtime changes.

\n

\nConfiguration values can be changed at runtime by the application or by a\nmanual change to the config/runtime.json file.\nThis method lets you specify a function to run when a configuration\nvalue changes.\n

\n

\nThis was built for monitoring changes to configuration values,\nbut it can be used for watching changes to any javascript object.\n

\n

Example:

\n
\nvar CONFIG = require('config').customer;\n...\n// Watch for any changes to the customer configuration\nCONFIG.watch(CONFIG, null, function(object, propertyName, priorValue, newValue) {\n console.log(\"Customer configuration \" + propertyName + \" changed from \" + priorValue + \" to \" + newValue);\n});\n
", "guessedname": "watch", "guessedtype": "function"}, "_equalsDeep": {"return": {"type": "boolean", "description": "True if both objects have equivalent contents"}, "description": "Return true if two objects have equal contents.", "protected": "", "params": [{"type": "object", "name": "object1", "description": " The object to compare from"}, {"type": "object", "name": "object2", "description": " The object to compare with"}, {"type": "integer", "name": "depth", "description": " An optional depth to prevent recursion. Default: 20."}], "guessedname": "_equalsDeep", "guessedtype": "function"}, "_stripYamlComments": {"return": {"type": "string", "description": "The string with comments stripped."}, "description": "Strip YAML comments from the string\nThe 2.0 yaml parser doesn't allow comment-only or blank lines. Strip them.", "protected": "", "params": [{"type": "string", "name": "fileString", "description": " The string to strip comments from"}], "guessedname": "_stripYamlComments", "guessedtype": "function"}, "makeImmutable": {"return": {"type": "object", "description": "object - The original object is returned - for chaining."}, "params": [{"type": "object", "name": "object", "description": " - The object to attach an immutable property into."}, {"type": "string", "name": "property", "description": " - The name of the property to make immutable."}, {"type": "mixed", "name": "value", "description": " - (optional) Set the property value to this (otherwise leave alone)"}], "description": "

Make a configuration property immutable (assuring it cannot be changed\nfrom the current value).

\n

\nThis operation cannot be undone.\n

\n

\nThis method was built for disabling runtime changes to configuration values,\nbut it can be applied to any javascript object.\n

\n

Example:

\n
\nvar CONFIG = require('config').customer;\n...\n// Obtain a DB connection using CONFIG parameters\ndatabase.open(CONFIG.db.name, CONFIG.db.port);\n...\n// Don't allow database changes after connect\nCONFIG.makeImmutable(CONFIG.db, 'name');\nCONFIG.makeImmutable(CONFIG.db, 'port');\n
", "guessedname": "makeImmutable", "guessedtype": "function"}, "_parseFile": {"return": {"type": "configObject", "description": "The configuration object parsed from the file"}, "description": "Parse and return the specified configuration file.\nIf the file exists in the application config directory, it will\nparse and return it as a JavaScript object.\nThe file extension determines the parser to use.\n.js = File to run that has a module.exports containing the config object\n.json = File is parsed using JSON.parse()\n.coffee = File to run that has a module.exports with coffee-script containing the config object\n.yaml (or .yml) = Parsed with a YAML parser\nIf the file doesn't exist, a null will be returned. If the file can't be\nparsed, an exception will be thrown.\nThis method performs synchronous file operations, and should not be called\nafter synchronous module loading.", "protected": "", "params": [{"type": "string", "name": "fullFilename", "description": " The full file path and name"}], "guessedname": "_parseFile", "guessedtype": "function"}, "_attachProtoDeep": {"return": {"type": "", "description": "toObject"}, "description": "Attach the Config class prototype to all config objects recursively.\n

\nThis allows you to do anything with CONFIG sub-objects as you can do with\nthe top-level CONFIG object. It's so you can do this:\n

\n
\nvar CUST_CONFIG = require('config').Customer;\nCUST_CONFIG.watch(...)\n
", "protected": "", "params": [{"type": "", "name": "toObject", "description": ""}, {"type": "", "name": "depth", "description": ""}], "guessedname": "_attachProtoDeep", "guessedtype": "function"}, "getConfigSources": {"return": {"type": "Array[Object]", "description": "configSources - An array of objects containing\nname, original, and parsed elements"}, "description": "Return the sources for the configurations\n

\nAll sources for configurations are stored in an array of objects containing\nthe source name (usually the filename), the original source (as a string),\nand the parsed source as an object.\n

", "guessedname": "getConfigSources", "guessedtype": "function"}, "_persistConfigsOnChange": {"protected": "", "params": [{"type": "object", "name": "object", "description": " - The config object to watch"}], "description": "

\nWatch the specified object for a change in properties, and persist changes\nto runtime.json when a change is detected.\n

", "guessedname": "_persistConfigsOnChange", "guessedtype": "function"}, "constructor": {"return": {"type": "object", "description": "CONFIG - The top level configuration object"}, "description": "

Get the configuration object.

\n

\nThe configuration object is a shared singleton object within the application,\nattained by calling require('config').\n

\n

\nUsually you'll specify a CONFIG variable at the top of your .js file\nfor file/module scope. If you want the root of the object, you can do this:\n

\n
\nvar CONFIG = require('config');\n
\n

\nSometimes you only care about a specific sub-object within the CONFIG\nobject. In that case you could do this at the top of your file:\n

\n
\nvar CONFIG = require('config').customer;\nor\nvar CUSTOMER_CONFIG = require('config').customer;\n
\n", "guessedname": "Config", "guessedtype": "function"}, "_extendDeep": {"return": {"type": "object", "description": "The altered mergeInto object is returned"}, "description": "Extend an object, and any object it contains.\nThis does not replace deep objects, but dives into them\nreplacing individual elements instead.", "protected": "", "params": [{"type": "object", "name": "mergeInto", "description": " The object to merge into"}, {"type": "object...", "name": "mergeFrom...", "description": " - Any number of objects to merge from"}, {"type": "integer", "name": "depth", "description": " An optional depth to prevent recursion. Default: 20."}], "guessedname": "_extendDeep", "guessedtype": "function"}, "resetRuntime": {"params": [{"type": "function", "name": "callback", "description": " An optional callback function"}], "description": "

Reset Runtime Config

\n

\nThis method allows you to reset the runtime.json generated file.\n

", "guessedname": "resetRuntime", "guessedtype": "function"}}, "file": "config.js", "shortname": "Config", "description": "

Runtime Application Configurations

\n

\nThe config module exports a singleton object representing all runtime\nconfigurations for this application deployment.\n

\n

\nApplication configurations are stored in files within the config directory\nof your application. The default configuration file is loaded, followed\nby files specific to the deployment type (development, testing, staging,\nproduction, etc.).\n

\n

\nFor example, with the following config/default.yaml file:\n

\n
\n...\ncustomer:\n  initialCredit: 500\n  db:\n    name: customer\n    port: 5984\n...\n
\n

\nThe following code loads the customer section into the CONFIG variable:\n

\n

\nvar CONFIG = require('config').customer;\n...\nnewCustomer.creditLimit = CONFIG.initialCredit;\ndatabase.open(CONFIG.db.name, CONFIG.db.port);\n...\n
"}, "ProtectedTest": {"name": "ProtectedTest", "namespace": "", "module": "test", "guessedname": "PrivateTest", "file": "1-protected-test.js", "guessedtype": "property", "shortname": "ProtectedTest", "description": "

Tests for underlying node-config utilities. To run type:

\n
npm test
\n

Or, in a project that uses node-config:

\n
npm test config
"}}, "version": "0.4.35", "modules": {"test": {"description": "

Unit tests

", "submodules": [], "classlist": ["ProtectedTest", "ConfigTest"], "filelist": ["1-protected-test.js", "2-config-test.js", "default.js"], "subdata": {}, "name": "test"}, "config": {"description": "

Runtime Application Configurations

\n

\nThe config module exports a singleton object representing all runtime\nconfigurations for this application deployment.\n

\n

\nApplication configurations are stored in files within the config directory\nof your application. The default configuration file is loaded, followed\nby files specific to the deployment type (development, testing, staging,\nproduction, etc.).\n

\n

\nFor example, with the following config/default.yaml file:\n

\n
\n...\ncustomer:\n  initialCredit: 500\n  db:\n    name: customer\n    port: 5984\n...\n
\n

\nThe following code loads the customer section into the CONFIG variable:\n

\n

\nvar CONFIG = require('config').customer;\n...\nnewCustomer.creditLimit = CONFIG.initialCredit;\ndatabase.open(CONFIG.db.name, CONFIG.db.port);\n...\n
", "submodules": [], "classlist": ["Config"], "filelist": ["config.js"], "subdata": {}, "name": "config"}}, "filemap": {"default.js": {"classlist": [], "name": "default.js", "module": "test"}, "2-config-test.js": {"classlist": ["ConfigTest"], "name": "2-config-test.js", "module": "test"}, "config.js": {"classlist": ["Config"], "name": "config.js", "module": "config"}, "1-protected-test.js": {"classlist": ["ProtectedTest"], "name": "1-protected-test.js", "module": "test"}}} \ No newline at end of file diff --git a/node_modules/config/doc/template/assets/ac-js b/node_modules/config/doc/template/assets/ac-js deleted file mode 100755 index 15a6dff..0000000 --- a/node_modules/config/doc/template/assets/ac-js +++ /dev/null @@ -1,162 +0,0 @@ -(function() { - var Event=YAHOO.util.Event, - Dom=YAHOO.util.Dom, - oACDS, oAutoComp, - show = { - 'private': false, - 'protected': false, - 'deprecated': false - }; - -Event.onAvailable('yui-classopts-form', function() { - //Checkboxes are available.. - var handleClick = function(e) { - var id, checked = false; - if (YAHOO.lang.isString(e)) { - id = e; - } else { - var tar = Event.getTarget(e); - id = tar.id; - } - var el = Dom.get(id); - checked = el.checked; - - var className = id; - if (checked) { - show[id.replace('show_', '')] = true; - Dom.addClass(document.body, className); - YAHOO.util.Cookie.setSub('yuidoc', id, 'checked'); - } else { - show[id.replace('show_', '')] = false; - Dom.removeClass(document.body, className); - YAHOO.util.Cookie.setSub('yuidoc', id, ''); - } - }; - - var checkCookie = function(id) { - var value = YAHOO.util.Cookie.getSub('yuidoc', id), - el = Dom.get(id), checked = (value === 'checked');; - - /* - if (value === 'checked') { - el.checked = true; - } else { - el.checked = false; - } - */ - - el.checked = checked; - return checked; - }; - - var els = ['show_deprecated', 'show_protected', 'show_private'], - reapplyHash = false; - - for (var i = 0; i < els.length; i++) { - Event.on(els[i], 'click', handleClick); - reapplyHash = checkCookie(els[i]) || reapplyHash; - handleClick(els[i]); - } - - // If we dynamically show private/protected/etc items during - // load, we need to reapply anchors so that the search feature - // works correctly for items that are initially hidden. - if (reapplyHash) { - var dl = document.location, hash = dl.hash; - if (hash) { - dl.hash = hash; - } - } - -}); - -//Starting the AutoComplete code - var getResults = function(query) { - var results = []; - if(query && query.length > 0) { - - var q = query.toLowerCase(); - - for (var i=0, len=ALL_YUI_PROPS.length; i -1 ) { - results.push([query, prop]); - } - } - } - } - - return results; - }; - - // Define Custom Event handlers - var myOnDataReturn = function(sType, aArgs) { - var oAutoComp = aArgs[0]; - var query = aArgs[1]; - var aResults = aArgs[2]; - - if(aResults.length == 0) { - if (query.length > 0) { - oAutoComp.setBody("
Not found
"); - } - } - }; - - var myOnItemSelect = function(sType, aArgs) { - var ac = aArgs[0]; - var item = aArgs[2]; - location.href = item[1].url; - }; - - - Event.onAvailable("searchresults", function() { - - // Instantiate JS Function DataSource - oACDS = new YAHOO.widget.DS_JSFunction(getResults); - oACDS.maxCacheEntries = 30; - - // Instantiate AutoComplete - oAutoComp = new YAHOO.widget.AutoComplete('searchinput','searchresults', oACDS); - //oAutoComp.alwaysShowContainer = true; - oAutoComp.queryDelay = 0.2; - oAutoComp.maxResultsDisplayed = 200; - oAutoComp.minQueryLength = 0; - oAutoComp.formatResult = function(oResultItem, query) { - var sMarkup = "" + oResultItem[1].host + ' ' + oResultItem[1].name + ''; - return sMarkup; - }; - - // Subscribe to Custom Events - oAutoComp.dataReturnEvent.subscribe(myOnDataReturn); - oAutoComp.itemSelectEvent.subscribe(myOnItemSelect); - - // Set initial content in the container - oAutoComp.sendQuery(Dom.get("searchinput").value); - - }); - - var validateForm = function() { - return false; - }; - - YAHOO.util.Event.onAvailable('classTab', function() { - var tabs = new YAHOO.widget.TabView('classTab'); - }); - /* - YAHOO.util.Event.onAvailable('codeTree', function() { - var tree1 = new YAHOO.widget.TreeView('codeTree'); - tree1.render(); - }); - */ - -})(); diff --git a/node_modules/config/doc/template/assets/api-js b/node_modules/config/doc/template/assets/api-js deleted file mode 100755 index e8132e0..0000000 --- a/node_modules/config/doc/template/assets/api-js +++ /dev/null @@ -1,42 +0,0 @@ -/* -Copyright (c) 2008, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version: 2.6.0 -*/ -if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var A=arguments,E=null,C,B,D;for(C=0;C0)?A.dump(D[F],I-1):L);}else{K.push(D[F]);}K.push(J);}if(K.length>1){K.pop();}K.push("]");}else{K.push("{");for(F in D){if(A.hasOwnProperty(D,F)){K.push(F+G);if(A.isObject(D[F])){K.push((I>0)?A.dump(D[F],I-1):L);}else{K.push(D[F]);}K.push(J);}}if(K.length>1){K.pop();}K.push("}");}return K.join("");},substitute:function(S,E,L){var I,H,G,O,P,R,N=[],F,J="dump",M=" ",D="{",Q="}";for(;;){I=S.lastIndexOf(D);if(I<0){break;}H=S.indexOf(Q,I);if(I+1>=H){break;}F=S.substring(I+1,H);O=F;R=null;G=O.indexOf(M);if(G>-1){R=O.substring(G+1);O=O.substring(0,G);}P=E[O];if(L){P=L(O,P,R);}if(A.isObject(P)){if(A.isArray(P)){P=A.dump(P,parseInt(R,10));}else{R=R||"";var K=R.indexOf(J);if(K>-1){R=R.substring(4);}if(P.toString===Object.prototype.toString||K>-1){P=A.dump(P,parseInt(R,10));}else{P=P.toString();}}}else{if(!A.isString(P)&&!A.isNumber(P)){P="~-"+N.length+"-~";N[N.length]=F;}}S=S.substring(0,I)+P+S.substring(H+1);}for(I=N.length-1;I>=0;I=I-1){S=S.replace(new RegExp("~-"+I+"-~"),"{"+N[I]+"}","g");}return S;},trim:function(D){try{return D.replace(/^\s+|\s+$/g,"");}catch(E){return D;}},merge:function(){var G={},E=arguments;for(var F=0,D=E.length;F=this.left&&A.right<=this.right&&A.top>=this.top&&A.bottom<=this.bottom);};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left));};YAHOO.util.Region.prototype.intersect=function(E){var C=Math.max(this.top,E.top);var D=Math.min(this.right,E.right);var A=Math.min(this.bottom,E.bottom);var B=Math.max(this.left,E.left);if(A>=C&&D>=B){return new YAHOO.util.Region(C,D,A,B);}else{return null;}};YAHOO.util.Region.prototype.union=function(E){var C=Math.min(this.top,E.top);var D=Math.max(this.right,E.right);var A=Math.max(this.bottom,E.bottom);var B=Math.min(this.left,E.left);return new YAHOO.util.Region(C,D,A,B);};YAHOO.util.Region.prototype.toString=function(){return("Region {"+"top: "+this.top+", right: "+this.right+", bottom: "+this.bottom+", left: "+this.left+"}");};YAHOO.util.Region.getRegion=function(D){var F=YAHOO.util.Dom.getXY(D);var C=F[1];var E=F[0]+D.offsetWidth;var A=F[1]+D.offsetHeight;var B=F[0];return new YAHOO.util.Region(C,E,A,B);};YAHOO.util.Point=function(A,B){if(YAHOO.lang.isArray(A)){B=A[1];A=A[0];}this.x=this.right=this.left=this[0]=A;this.y=this.top=this.bottom=this[1]=B;};YAHOO.util.Point.prototype=new YAHOO.util.Region();YAHOO.register("dom",YAHOO.util.Dom,{version:"2.6.0",build:"1321"});YAHOO.util.CustomEvent=function(D,B,C,A){this.type=D;this.scope=B||window;this.silent=C;this.signature=A||YAHOO.util.CustomEvent.LIST;this.subscribers=[];if(!this.silent){}var E="_YUICEOnSubscribe";if(D!==E){this.subscribeEvent=new YAHOO.util.CustomEvent(E,this,true);}this.lastError=null;};YAHOO.util.CustomEvent.LIST=0;YAHOO.util.CustomEvent.FLAT=1;YAHOO.util.CustomEvent.prototype={subscribe:function(B,C,A){if(!B){throw new Error("Invalid callback for subscriber to '"+this.type+"'");}if(this.subscribeEvent){this.subscribeEvent.fire(B,C,A);}this.subscribers.push(new YAHOO.util.Subscriber(B,C,A));},unsubscribe:function(D,F){if(!D){return this.unsubscribeAll();}var E=false;for(var B=0,A=this.subscribers.length;B0){B=I[0];}try{G=M.fn.call(L,B,M.obj);}catch(F){this.lastError=F;if(A){throw F;}}}else{try{G=M.fn.call(L,this.type,I,M.obj);}catch(H){this.lastError=H;if(A){throw H;}}}if(false===G){if(!this.silent){}break;}}}return(G!==false);},unsubscribeAll:function(){for(var A=this.subscribers.length-1;A>-1;A--){this._delete(A);}this.subscribers=[];return A;},_delete:function(A){var B=this.subscribers[A];if(B){delete B.fn;delete B.obj;}this.subscribers.splice(A,1);},toString:function(){return"CustomEvent: "+"'"+this.type+"', "+"scope: "+this.scope;}};YAHOO.util.Subscriber=function(B,C,A){this.fn=B;this.obj=YAHOO.lang.isUndefined(C)?null:C;this.override=A;};YAHOO.util.Subscriber.prototype.getScope=function(A){if(this.override){if(this.override===true){return this.obj;}else{return this.override;}}return A;};YAHOO.util.Subscriber.prototype.contains=function(A,B){if(B){return(this.fn==A&&this.obj==B);}else{return(this.fn==A);}};YAHOO.util.Subscriber.prototype.toString=function(){return"Subscriber { obj: "+this.obj+", override: "+(this.override||"no")+" }";};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var H=false;var I=[];var J=[];var G=[];var E=[];var C=0;var F=[];var B=[];var A=0;var D={63232:38,63233:40,63234:37,63235:39,63276:33,63277:34,25:9};var K=YAHOO.env.ua.ie?"focusin":"focus";var L=YAHOO.env.ua.ie?"focusout":"blur";return{POLL_RETRYS:2000,POLL_INTERVAL:20,EL:0,TYPE:1,FN:2,WFN:3,UNLOAD_OBJ:3,ADJ_SCOPE:4,OBJ:5,OVERRIDE:6,CAPTURE:7,lastError:null,isSafari:YAHOO.env.ua.webkit,webkit:YAHOO.env.ua.webkit,isIE:YAHOO.env.ua.ie,_interval:null,_dri:null,DOMReady:false,throwErrors:false,startInterval:function(){if(!this._interval){var M=this;var N=function(){M._tryPreloadAttach();};this._interval=setInterval(N,this.POLL_INTERVAL);}},onAvailable:function(R,O,S,Q,P){var M=(YAHOO.lang.isString(R))?[R]:R;for(var N=0;N-1;Q--){W=(this._removeListener(N[Q],M,V,Y)&&W);}return W;}}if(!V||!V.call){return this.purgeElement(N,false,M);}if("unload"==M){for(Q=J.length-1;Q>-1;Q--){X=J[Q];if(X&&X[0]==N&&X[1]==M&&X[2]==V){J.splice(Q,1);return true;}}return false;}var R=null;var S=arguments[4];if("undefined"===typeof S){S=this._getCacheIndex(N,M,V);}if(S>=0){R=I[S];}if(!N||!R){return false;}if(this.useLegacyEvent(N,M)){var P=this.getLegacyIndex(N,M);var O=E[P];if(O){for(Q=0,T=O.length;Q0&&F.length>0);}var R=[];var T=function(V,W){var U=V;if(W.override){if(W.override===true){U=W.obj;}else{U=W.override;}}W.fn.call(U,W.obj);};var N,M,Q,P,O=[];for(N=0,M=F.length;N-1;N--){Q=F[N];if(!Q||!Q.id){F.splice(N,1);}}this.startInterval();}else{clearInterval(this._interval);this._interval=null;}this.locked=false;},purgeElement:function(Q,R,T){var O=(YAHOO.lang.isString(Q))?this.getEl(Q):Q;var S=this.getListeners(O,T),P,M;if(S){for(P=S.length-1;P>-1;P--){var N=S[P];this._removeListener(O,N.type,N.fn,N.capture);}}if(R&&O&&O.childNodes){for(P=0,M=O.childNodes.length;P-1;O--){N=I[O];if(N){M._removeListener(N[M.EL],N[M.TYPE],N[M.FN],N[M.CAPTURE],O);}}N=null;}G=null;M._simpleRemove(window,"unload",M._unload);},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var M=document.documentElement,N=document.body;if(M&&(M.scrollTop||M.scrollLeft)){return[M.scrollTop,M.scrollLeft];}else{if(N){return[N.scrollTop,N.scrollLeft];}else{return[0,0];}}},regCE:function(){},_simpleAdd:function(){if(window.addEventListener){return function(O,P,N,M){O.addEventListener(P,N,(M));};}else{if(window.attachEvent){return function(O,P,N,M){O.attachEvent("on"+P,N);};}else{return function(){};}}}(),_simpleRemove:function(){if(window.removeEventListener){return function(O,P,N,M){O.removeEventListener(P,N,(M));};}else{if(window.detachEvent){return function(N,O,M){N.detachEvent("on"+O,M);};}else{return function(){};}}}()};}();(function(){var EU=YAHOO.util.Event;EU.on=EU.addListener;EU.onFocus=EU.addFocusListener;EU.onBlur=EU.addBlurListener; -/* DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller */ -if(EU.isIE){YAHOO.util.Event.onDOMReady(YAHOO.util.Event._tryPreloadAttach,YAHOO.util.Event,true);var n=document.createElement("p");EU._dri=setInterval(function(){try{n.doScroll("left");clearInterval(EU._dri);EU._dri=null;EU._ready();n=null;}catch(ex){}},EU.POLL_INTERVAL);}else{if(EU.webkit&&EU.webkit<525){EU._dri=setInterval(function(){var rs=document.readyState;if("loaded"==rs||"complete"==rs){clearInterval(EU._dri);EU._dri=null;EU._ready();}},EU.POLL_INTERVAL);}else{EU._simpleAdd(document,"DOMContentLoaded",EU._ready);}}EU._simpleAdd(window,"load",EU._load);EU._simpleAdd(window,"unload",EU._unload);EU._tryPreloadAttach();})();}YAHOO.util.EventProvider=function(){};YAHOO.util.EventProvider.prototype={__yui_events:null,__yui_subscribers:null,subscribe:function(A,C,F,E){this.__yui_events=this.__yui_events||{}; -var D=this.__yui_events[A];if(D){D.subscribe(C,F,E);}else{this.__yui_subscribers=this.__yui_subscribers||{};var B=this.__yui_subscribers;if(!B[A]){B[A]=[];}B[A].push({fn:C,obj:F,override:E});}},unsubscribe:function(C,E,G){this.__yui_events=this.__yui_events||{};var A=this.__yui_events;if(C){var F=A[C];if(F){return F.unsubscribe(E,G);}}else{var B=true;for(var D in A){if(YAHOO.lang.hasOwnProperty(A,D)){B=B&&A[D].unsubscribe(E,G);}}return B;}return false;},unsubscribeAll:function(A){return this.unsubscribe(A);},createEvent:function(G,D){this.__yui_events=this.__yui_events||{};var A=D||{};var I=this.__yui_events;if(I[G]){}else{var H=A.scope||this;var E=(A.silent);var B=new YAHOO.util.CustomEvent(G,H,E,YAHOO.util.CustomEvent.FLAT);I[G]=B;if(A.onSubscribeCallback){B.subscribeEvent.subscribe(A.onSubscribeCallback);}this.__yui_subscribers=this.__yui_subscribers||{};var F=this.__yui_subscribers[G];if(F){for(var C=0;C0){if(!aCache){this._aCache=[];}else{var nCacheLength=aCache.length;if(nCacheLength>0){var oResponse=null;this.fireEvent("cacheRequestEvent",{request:oRequest,callback:oCallback,caller:oCaller});for(var i=nCacheLength-1;i>=0;i--){var oCacheElem=aCache[i];if(this.isCacheHit(oRequest,oCacheElem.request)){oResponse=oCacheElem.response;this.fireEvent("cacheResponseEvent",{request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});if(i=this.maxCacheEntries){aCache.shift();}var oCacheElem={request:oRequest,response:oResponse};aCache[aCache.length]=oCacheElem;this.fireEvent("responseCacheEvent",{request:oRequest,response:oResponse});},flushCache:function(){if(this._aCache){this._aCache=[];this.fireEvent("cacheFlushEvent");}},setInterval:function(nMsec,oRequest,oCallback,oCaller){if(lang.isNumber(nMsec)&&(nMsec>=0)){var oSelf=this;var nId=setInterval(function(){oSelf.makeConnection(oRequest,oCallback,oCaller);},nMsec);this._aIntervals.push(nId);return nId;}else{}},clearInterval:function(nId){var tracker=this._aIntervals||[];for(var i=tracker.length-1;i>-1;i--){if(tracker[i]===nId){tracker.splice(i,1);clearInterval(nId);}}},clearAllIntervals:function(){var tracker=this._aIntervals||[];for(var i=tracker.length-1;i>-1;i--){clearInterval(tracker[i]);}tracker=[];},sendRequest:function(oRequest,oCallback,oCaller){var oCachedResponse=this.getCachedResponse(oRequest,oCallback,oCaller);if(oCachedResponse){DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller);return null;}return this.makeConnection(oRequest,oCallback,oCaller);},makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oRawResponse=this.liveData;this.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);return tId;},handleResponse:function(oRequest,oRawResponse,oCallback,oCaller,tId){this.fireEvent("responseEvent",{tId:tId,request:oRequest,response:oRawResponse,callback:oCallback,caller:oCaller});var xhr=(this.dataType==DS.TYPE_XHR)?true:false;var oParsedResponse=null;var oFullResponse=oRawResponse;if(this.responseType===DS.TYPE_UNKNOWN){var ctype=(oRawResponse&&oRawResponse.getResponseHeader)?oRawResponse.getResponseHeader["Content-Type"]:null;if(ctype){if(ctype.indexOf("text/xml")>-1){this.responseType=DS.TYPE_XML;}else{if(ctype.indexOf("application/json")>-1){this.responseType=DS.TYPE_JSON;}else{if(ctype.indexOf("text/plain")>-1){this.responseType=DS.TYPE_TEXT;}}}}else{if(YAHOO.lang.isArray(oRawResponse)){this.responseType=DS.TYPE_JSARRAY;}else{if(oRawResponse&&oRawResponse.nodeType&&oRawResponse.nodeType==9){this.responseType=DS.TYPE_XML;}else{if(oRawResponse&&oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE;}else{if(YAHOO.lang.isObject(oRawResponse)){this.responseType=DS.TYPE_JSON;}else{if(YAHOO.lang.isString(oRawResponse)){this.responseType=DS.TYPE_TEXT;}}}}}}}switch(this.responseType){case DS.TYPE_JSARRAY:if(xhr&&oRawResponse&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText;}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseArrayData(oRequest,oFullResponse); -break;case DS.TYPE_JSON:if(xhr&&oRawResponse&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText;}try{if(lang.isString(oFullResponse)){if(lang.JSON){oFullResponse=lang.JSON.parse(oFullResponse);}else{if(window.JSON&&JSON.parse){oFullResponse=JSON.parse(oFullResponse);}else{if(oFullResponse.parseJSON){oFullResponse=oFullResponse.parseJSON();}else{while(oFullResponse.length>0&&(oFullResponse.charAt(0)!="{")&&(oFullResponse.charAt(0)!="[")){oFullResponse=oFullResponse.substring(1,oFullResponse.length);}if(oFullResponse.length>0){var objEnd=Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));oFullResponse=oFullResponse.substring(0,objEnd+1);oFullResponse=eval("("+oFullResponse+")");}}}}}}catch(e){}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseJSONData(oRequest,oFullResponse);break;case DS.TYPE_HTMLTABLE:if(xhr&&oRawResponse.responseText){oFullResponse=oRawResponse.responseText;}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseHTMLTableData(oRequest,oFullResponse);break;case DS.TYPE_XML:if(xhr&&oRawResponse.responseXML){oFullResponse=oRawResponse.responseXML;}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseXMLData(oRequest,oFullResponse);break;case DS.TYPE_TEXT:if(xhr&&lang.isString(oRawResponse.responseText)){oFullResponse=oRawResponse.responseText;}oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseTextData(oRequest,oFullResponse);break;default:oFullResponse=this.doBeforeParseData(oRequest,oFullResponse,oCallback);oParsedResponse=this.parseData(oRequest,oFullResponse);break;}oParsedResponse=oParsedResponse||{};if(!oParsedResponse.results){oParsedResponse.results=[];}if(!oParsedResponse.meta){oParsedResponse.meta={};}if(oParsedResponse&&!oParsedResponse.error){oParsedResponse=this.doBeforeCallback(oRequest,oFullResponse,oParsedResponse,oCallback);this.fireEvent("responseParseEvent",{request:oRequest,response:oParsedResponse,callback:oCallback,caller:oCaller});this.addToCache(oRequest,oParsedResponse);}else{oParsedResponse.error=true;this.fireEvent("dataErrorEvent",{request:oRequest,response:oRawResponse,callback:oCallback,caller:oCaller,message:DS.ERROR_DATANULL});}oParsedResponse.tId=tId;DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller);},doBeforeParseData:function(oRequest,oFullResponse,oCallback){return oFullResponse;},doBeforeCallback:function(oRequest,oFullResponse,oParsedResponse,oCallback){return oParsedResponse;},parseData:function(oRequest,oFullResponse){if(lang.isValue(oFullResponse)){var oParsedResponse={results:oFullResponse,meta:{}};return oParsedResponse;}return null;},parseArrayData:function(oRequest,oFullResponse){if(lang.isArray(oFullResponse)){var results=[],i,j,rec,field,data;if(lang.isArray(this.responseSchema.fields)){var fields=this.responseSchema.fields;for(i=fields.length-1;i>=0;--i){if(typeof fields[i]!=="object"){fields[i]={key:fields[i]};}}var parsers={},p;for(i=fields.length-1;i>=0;--i){p=(typeof fields[i].parser==="function"?fields[i].parser:DS.Parser[fields[i].parser+""])||fields[i].converter;if(p){parsers[fields[i].key]=p;}}var arrType=lang.isArray(oFullResponse[0]);for(i=oFullResponse.length-1;i>-1;i--){var oResult={};rec=oFullResponse[i];if(typeof rec==="object"){for(j=fields.length-1;j>-1;j--){field=fields[j];data=arrType?rec[j]:rec[field.key];if(parsers[field.key]){data=parsers[field.key].call(this,data);}if(data===undefined){data=null;}oResult[field.key]=data;}}else{if(lang.isString(rec)){for(j=fields.length-1;j>-1;j--){field=fields[j];data=rec;if(parsers[field.key]){data=parsers[field.key].call(this,data);}if(data===undefined){data=null;}oResult[field.key]=data;}}}results[i]=oResult;}}else{results=oFullResponse;}var oParsedResponse={results:results};return oParsedResponse;}return null;},parseTextData:function(oRequest,oFullResponse){if(lang.isString(oFullResponse)){if(lang.isString(this.responseSchema.recordDelim)&&lang.isString(this.responseSchema.fieldDelim)){var oParsedResponse={results:[]};var recDelim=this.responseSchema.recordDelim;var fieldDelim=this.responseSchema.fieldDelim;if(oFullResponse.length>0){var newLength=oFullResponse.length-recDelim.length;if(oFullResponse.substr(newLength)==recDelim){oFullResponse=oFullResponse.substr(0,newLength);}if(oFullResponse.length>0){var recordsarray=oFullResponse.split(recDelim);for(var i=0,len=recordsarray.length,recIdx=0;i0)){var fielddataarray=recordsarray[i].split(fieldDelim);var oResult={};if(lang.isArray(this.responseSchema.fields)){var fields=this.responseSchema.fields;for(var j=fields.length-1;j>-1;j--){try{var data=fielddataarray[j];if(lang.isString(data)){if(data.charAt(0)=='"'){data=data.substr(1);}if(data.charAt(data.length-1)=='"'){data=data.substr(0,data.length-1);}var field=fields[j];var key=(lang.isValue(field.key))?field.key:field;if(!field.parser&&field.converter){field.parser=field.converter;}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data);}if(data===undefined){data=null;}oResult[key]=data;}else{bError=true;}}catch(e){bError=true;}}}else{oResult=fielddataarray;}if(!bError){oParsedResponse.results[recIdx++]=oResult;}}}}}return oParsedResponse;}}return null;},parseXMLResult:function(result){var oResult={},schema=this.responseSchema;try{for(var m=schema.fields.length-1;m>=0;m--){var field=schema.fields[m];var key=(lang.isValue(field.key))?field.key:field;var data=null;var xmlAttr=result.attributes.getNamedItem(key);if(xmlAttr){data=xmlAttr.value;}else{var xmlNode=result.getElementsByTagName(key);if(xmlNode&&xmlNode.item(0)&&xmlNode.item(0)){data=xmlNode.item(0).firstChild.nodeValue;var item=xmlNode.item(0);data=(item.text)?item.text:(item.textContent)?item.textContent:null; -if(!data){var datapieces=[];for(var j=0,len=item.childNodes.length;j0){data=datapieces.join("");}}}}if(data===null){data="";}if(!field.parser&&field.converter){field.parser=field.converter;}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data);}if(data===undefined){data=null;}oResult[key]=data;}}catch(e){}return oResult;},parseXMLData:function(oRequest,oFullResponse){var bError=false,schema=this.responseSchema,oParsedResponse={meta:{}},xmlList=null,metaNode=schema.metaNode,metaLocators=schema.metaFields||{},i,k,loc,v;try{xmlList=(schema.resultNode)?oFullResponse.getElementsByTagName(schema.resultNode):null;metaNode=metaNode?oFullResponse.getElementsByTagName(metaNode)[0]:oFullResponse;if(metaNode){for(k in metaLocators){if(lang.hasOwnProperty(metaLocators,k)){loc=metaLocators[k];v=metaNode.getElementsByTagName(loc)[0];if(v){v=v.firstChild.nodeValue;}else{v=metaNode.attributes.getNamedItem(loc);if(v){v=v.value;}}if(lang.isValue(v)){oParsedResponse.meta[k]=v;}}}}}catch(e){}if(!xmlList||!lang.isArray(schema.fields)){bError=true;}else{oParsedResponse.results=[];for(i=xmlList.length-1;i>=0;--i){var oResult=this.parseXMLResult(xmlList.item(i));oParsedResponse.results[i]=oResult;}}if(bError){oParsedResponse.error=true;}else{}return oParsedResponse;},parseJSONData:function(oRequest,oFullResponse){var oParsedResponse={results:[],meta:{}};if(lang.isObject(oFullResponse)&&this.responseSchema.resultsList){var schema=this.responseSchema,fields=schema.fields,resultsList=oFullResponse,results=[],metaFields=schema.metaFields||{},fieldParsers=[],fieldPaths=[],simpleFields=[],bError=false,i,len,j,v,key,parser,path;var buildPath=function(needle){var path=null,keys=[],i=0;if(needle){needle=needle.replace(/\[(['"])(.*?)\1\]/g,function(x,$1,$2){keys[i]=$2;return".@"+(i++);}).replace(/\[(\d+)\]/g,function(x,$1){keys[i]=parseInt($1,10)|0;return".@"+(i++);}).replace(/^\./,"");if(!/[^\w\.\$@]/.test(needle)){path=needle.split(".");for(i=path.length-1;i>=0;--i){if(path[i].charAt(0)==="@"){path[i]=keys[parseInt(path[i].substr(1),10)];}}}else{}}return path;};var walkPath=function(path,origin){var v=origin,i=0,len=path.length;for(;i1){fieldPaths[fieldPaths.length]={key:key,path:path};}else{simpleFields[simpleFields.length]={key:key,path:path[0]};}}else{}}for(i=resultsList.length-1;i>=0;--i){var r=resultsList[i],rec={};for(j=simpleFields.length-1;j>=0;--j){rec[simpleFields[j].key]=(r[simpleFields[j].path]!==undefined)?r[simpleFields[j].path]:r[j];}for(j=fieldPaths.length-1;j>=0;--j){rec[fieldPaths[j].key]=walkPath(fieldPaths[j].path,r);}for(j=fieldParsers.length-1;j>=0;--j){var p=fieldParsers[j].key;rec[p]=fieldParsers[j].parser(rec[p]);if(rec[p]===undefined){rec[p]=null;}}results[i]=rec;}}else{results=resultsList;}for(key in metaFields){if(lang.hasOwnProperty(metaFields,key)){path=buildPath(metaFields[key]);if(path){v=walkPath(path,oFullResponse);oParsedResponse.meta[key]=v;}}}}else{oParsedResponse.error=true;}oParsedResponse.results=results;}else{oParsedResponse.error=true;}return oParsedResponse;},parseHTMLTableData:function(oRequest,oFullResponse){var bError=false;var elTable=oFullResponse;var fields=this.responseSchema.fields;var oParsedResponse={results:[]};for(var i=0;i-1;j--){var elRow=elTbody.rows[j];var oResult={};for(var k=fields.length-1;k>-1;k--){var field=fields[k];var key=(lang.isValue(field.key))?field.key:field;var data=elRow.cells[k].innerHTML;if(!field.parser&&field.converter){field.parser=field.converter;}var parser=(typeof field.parser==="function")?field.parser:DS.Parser[field.parser+""];if(parser){data=parser.call(this,data);}if(data===undefined){data=null;}oResult[key]=data;}oParsedResponse.results[j]=oResult;}}if(bError){oParsedResponse.error=true;}else{}return oParsedResponse;}};lang.augmentProto(DS,util.EventProvider);util.LocalDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_LOCAL;if(oLiveData){if(YAHOO.lang.isArray(oLiveData)){this.responseType=DS.TYPE_JSARRAY;}else{if(oLiveData.nodeType&&oLiveData.nodeType==9){this.responseType=DS.TYPE_XML;}else{if(oLiveData.nodeName&&(oLiveData.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE;oLiveData=oLiveData.cloneNode(true);}else{if(YAHOO.lang.isString(oLiveData)){this.responseType=DS.TYPE_TEXT;}else{if(YAHOO.lang.isObject(oLiveData)){this.responseType=DS.TYPE_JSON;}}}}}}else{oLiveData=[];this.responseType=DS.TYPE_JSARRAY;}this.constructor.superclass.constructor.call(this,oLiveData,oConfigs);};lang.extend(util.LocalDataSource,DS);lang.augmentObject(util.LocalDataSource,DS);util.FunctionDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_JSFUNCTION;oLiveData=oLiveData||function(){};this.constructor.superclass.constructor.call(this,oLiveData,oConfigs);};lang.extend(util.FunctionDataSource,DS,{makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oRawResponse=this.liveData(oRequest);if(this.responseType===DS.TYPE_UNKNOWN){if(YAHOO.lang.isArray(oRawResponse)){this.responseType=DS.TYPE_JSARRAY;}else{if(oRawResponse&&oRawResponse.nodeType&&oRawResponse.nodeType==9){this.responseType=DS.TYPE_XML; -}else{if(oRawResponse&&oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){this.responseType=DS.TYPE_HTMLTABLE;}else{if(YAHOO.lang.isObject(oRawResponse)){this.responseType=DS.TYPE_JSON;}else{if(YAHOO.lang.isString(oRawResponse)){this.responseType=DS.TYPE_TEXT;}}}}}}this.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);return tId;}});lang.augmentObject(util.FunctionDataSource,DS);util.ScriptNodeDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_SCRIPTNODE;oLiveData=oLiveData||"";this.constructor.superclass.constructor.call(this,oLiveData,oConfigs);};lang.extend(util.ScriptNodeDataSource,DS,{getUtility:util.Get,asyncMode:"allowAll",scriptCallbackParam:"callback",generateRequestCallback:function(id){return"&"+this.scriptCallbackParam+"=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]";},makeConnection:function(oRequest,oCallback,oCaller){var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});if(util.ScriptNodeDataSource._nPending===0){util.ScriptNodeDataSource.callbacks=[];util.ScriptNodeDataSource._nId=0;}var id=util.ScriptNodeDataSource._nId;util.ScriptNodeDataSource._nId++;var oSelf=this;util.ScriptNodeDataSource.callbacks[id]=function(oRawResponse){if((oSelf.asyncMode!=="ignoreStaleResponses")||(id===util.ScriptNodeDataSource.callbacks.length-1)){if(oSelf.responseType===DS.TYPE_UNKNOWN){if(YAHOO.lang.isArray(oRawResponse)){oSelf.responseType=DS.TYPE_JSARRAY;}else{if(oRawResponse.nodeType&&oRawResponse.nodeType==9){oSelf.responseType=DS.TYPE_XML;}else{if(oRawResponse.nodeName&&(oRawResponse.nodeName.toLowerCase()=="table")){oSelf.responseType=DS.TYPE_HTMLTABLE;}else{if(YAHOO.lang.isObject(oRawResponse)){oSelf.responseType=DS.TYPE_JSON;}else{if(YAHOO.lang.isString(oRawResponse)){oSelf.responseType=DS.TYPE_TEXT;}}}}}}oSelf.handleResponse(oRequest,oRawResponse,oCallback,oCaller,tId);}else{}delete util.ScriptNodeDataSource.callbacks[id];};util.ScriptNodeDataSource._nPending++;var sUri=this.liveData+oRequest+this.generateRequestCallback(id);this.getUtility.script(sUri,{autopurge:true,onsuccess:util.ScriptNodeDataSource._bumpPendingDown,onfail:util.ScriptNodeDataSource._bumpPendingDown});return tId;}});lang.augmentObject(util.ScriptNodeDataSource,DS);lang.augmentObject(util.ScriptNodeDataSource,{_nId:0,_nPending:0,callbacks:[]});util.XHRDataSource=function(oLiveData,oConfigs){this.dataType=DS.TYPE_XHR;this.connMgr=this.connMgr||util.Connect;oLiveData=oLiveData||"";this.constructor.superclass.constructor.call(this,oLiveData,oConfigs);};lang.extend(util.XHRDataSource,DS,{connMgr:null,connXhrMode:"allowAll",connMethodPost:false,connTimeout:0,makeConnection:function(oRequest,oCallback,oCaller){var oRawResponse=null;var tId=DS._nTransactionId++;this.fireEvent("requestEvent",{tId:tId,request:oRequest,callback:oCallback,caller:oCaller});var oSelf=this;var oConnMgr=this.connMgr;var oQueue=this._oQueue;var _xhrSuccess=function(oResponse){if(oResponse&&(this.asyncMode=="ignoreStaleResponses")&&(oResponse.tId!=oQueue.conn.tId)){return null;}else{if(!oResponse){this.fireEvent("dataErrorEvent",{request:oRequest,callback:oCallback,caller:oCaller,message:DS.ERROR_DATANULL});DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);return null;}else{if(this.responseType===DS.TYPE_UNKNOWN){var ctype=(oResponse.getResponseHeader)?oResponse.getResponseHeader["Content-Type"]:null;if(ctype){if(ctype.indexOf("text/xml")>-1){this.responseType=DS.TYPE_XML;}else{if(ctype.indexOf("application/json")>-1){this.responseType=DS.TYPE_JSON;}else{if(ctype.indexOf("text/plain")>-1){this.responseType=DS.TYPE_TEXT;}}}}}this.handleResponse(oRequest,oResponse,oCallback,oCaller,tId);}}};var _xhrFailure=function(oResponse){this.fireEvent("dataErrorEvent",{request:oRequest,callback:oCallback,caller:oCaller,message:DS.ERROR_DATAINVALID});if(lang.isString(this.liveData)&&lang.isString(oRequest)&&(this.liveData.lastIndexOf("?")!==this.liveData.length-1)&&(oRequest.indexOf("?")!==0)){}oResponse=oResponse||{};oResponse.error=true;DS.issueCallback(oCallback,[oRequest,oResponse],true,oCaller);return null;};var _xhrCallback={success:_xhrSuccess,failure:_xhrFailure,scope:this};if(lang.isNumber(this.connTimeout)){_xhrCallback.timeout=this.connTimeout;}if(this.connXhrMode=="cancelStaleRequests"){if(oQueue.conn){if(oConnMgr.abort){oConnMgr.abort(oQueue.conn);oQueue.conn=null;}else{}}}if(oConnMgr&&oConnMgr.asyncRequest){var sLiveData=this.liveData;var isPost=this.connMethodPost;var sMethod=(isPost)?"POST":"GET";var sUri=(isPost||!lang.isValue(oRequest))?sLiveData:sLiveData+oRequest;var sRequest=(isPost)?oRequest:null;if(this.connXhrMode!="queueRequests"){oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,_xhrCallback,sRequest);}else{if(oQueue.conn){var allRequests=oQueue.requests;allRequests.push({request:oRequest,callback:_xhrCallback});if(!oQueue.interval){oQueue.interval=setInterval(function(){if(oConnMgr.isCallInProgress(oQueue.conn)){return ;}else{if(allRequests.length>0){sUri=(isPost||!lang.isValue(allRequests[0].request))?sLiveData:sLiveData+allRequests[0].request;sRequest=(isPost)?allRequests[0].request:null;oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,allRequests[0].callback,sRequest);allRequests.shift();}else{clearInterval(oQueue.interval);oQueue.interval=null;}}},50);}}else{oQueue.conn=oConnMgr.asyncRequest(sMethod,sUri,_xhrCallback,sRequest);}}}else{DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller);}return tId;}});lang.augmentObject(util.XHRDataSource,DS);util.DataSource=function(oLiveData,oConfigs){oConfigs=oConfigs||{};var dataType=oConfigs.dataType;if(dataType){if(dataType==DS.TYPE_LOCAL){lang.augmentObject(util.DataSource,util.LocalDataSource);return new util.LocalDataSource(oLiveData,oConfigs);}else{if(dataType==DS.TYPE_XHR){lang.augmentObject(util.DataSource,util.XHRDataSource);return new util.XHRDataSource(oLiveData,oConfigs);}else{if(dataType==DS.TYPE_SCRIPTNODE){lang.augmentObject(util.DataSource,util.ScriptNodeDataSource); -return new util.ScriptNodeDataSource(oLiveData,oConfigs);}else{if(dataType==DS.TYPE_JSFUNCTION){lang.augmentObject(util.DataSource,util.FunctionDataSource);return new util.FunctionDataSource(oLiveData,oConfigs);}}}}}if(YAHOO.lang.isString(oLiveData)){lang.augmentObject(util.DataSource,util.XHRDataSource);return new util.XHRDataSource(oLiveData,oConfigs);}else{if(YAHOO.lang.isFunction(oLiveData)){lang.augmentObject(util.DataSource,util.FunctionDataSource);return new util.FunctionDataSource(oLiveData,oConfigs);}else{lang.augmentObject(util.DataSource,util.LocalDataSource);return new util.LocalDataSource(oLiveData,oConfigs);}}};lang.augmentObject(util.DataSource,DS);})();YAHOO.util.Number={format:function(B,F){F=F||{};if(!YAHOO.lang.isNumber(B)){B*=1;}if(YAHOO.lang.isNumber(B)){var D=(B<0);var J=B+"";var G=(F.decimalSeparator)?F.decimalSeparator:".";var H;if(YAHOO.lang.isNumber(F.decimalPlaces)){var I=F.decimalPlaces;var C=Math.pow(10,I);J=Math.round(B*C)/C+"";H=J.lastIndexOf(".");if(I>0){if(H<0){J+=G;H=J.length-1;}else{if(G!=="."){J=J.replace(".",G);}}while((J.length-1-H)-1)?H:J.length;var K=J.substring(H);var A=-1;for(var E=H;E>0;E--){A++;if((A%3===0)&&(E!==H)&&(!D||(E>1))){K=L+K;}K=J.charAt(E-1)+K;}J=K;}J=(F.prefix)?F.prefix+J:J;J=(F.suffix)?J+F.suffix:J;return J;}else{return B;}}};(function(){var A=function(C,E,D){if(typeof D==="undefined"){D=10;}for(;parseInt(C,10)1;D/=10){C=E.toString()+C;}return C.toString();};var B={formats:{a:function(D,C){return C.a[D.getDay()];},A:function(D,C){return C.A[D.getDay()];},b:function(D,C){return C.b[D.getMonth()];},B:function(D,C){return C.B[D.getMonth()];},C:function(C){return A(parseInt(C.getFullYear()/100,10),0);},d:["getDate","0"],e:["getDate"," "],g:function(C){return A(parseInt(B.formats.G(C)%100,10),0);},G:function(E){var F=E.getFullYear();var D=parseInt(B.formats.V(E),10);var C=parseInt(B.formats.W(E),10);if(C>D){F++;}else{if(C===0&&D>=52){F--;}}return F;},H:["getHours","0"],I:function(D){var C=D.getHours()%12;return A(C===0?12:C,0);},j:function(G){var F=new Date(""+G.getFullYear()+"/1/1 GMT");var D=new Date(""+G.getFullYear()+"/"+(G.getMonth()+1)+"/"+G.getDate()+" GMT");var C=D-F;var E=parseInt(C/60000/60/24,10)+1;return A(E,0,100);},k:["getHours"," "],l:function(D){var C=D.getHours()%12;return A(C===0?12:C," ");},m:function(C){return A(C.getMonth()+1,0);},M:["getMinutes","0"],p:function(D,C){return C.p[D.getHours()>=12?1:0];},P:function(D,C){return C.P[D.getHours()>=12?1:0];},s:function(D,C){return parseInt(D.getTime()/1000,10);},S:["getSeconds","0"],u:function(C){var D=C.getDay();return D===0?7:D;},U:function(F){var C=parseInt(B.formats.j(F),10);var E=6-F.getDay();var D=parseInt((C+E)/7,10);return A(D,0);},V:function(F){var E=parseInt(B.formats.W(F),10);var C=(new Date(""+F.getFullYear()+"/1/1")).getDay();var D=E+(C>4||C<=1?0:1);if(D===53&&(new Date(""+F.getFullYear()+"/12/31")).getDay()<4){D=1;}else{if(D===0){D=B.formats.V(new Date(""+(F.getFullYear()-1)+"/12/31"));}}return A(D,0);},w:"getDay",W:function(F){var C=parseInt(B.formats.j(F),10);var E=7-B.formats.u(F);var D=parseInt((C+E)/7,10);return A(D,0,10);},y:function(C){return A(C.getFullYear()%100,0);},Y:"getFullYear",z:function(E){var D=E.getTimezoneOffset();var C=A(parseInt(Math.abs(D/60),10),0);var F=A(Math.abs(D%60),0);return(D>0?"-":"+")+C+F;},Z:function(C){var D=C.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/,"$2").replace(/[a-z ]/g,"");if(D.length>4){D=B.formats.z(C);}return D;},"%":function(C){return"%";}},aggregates:{c:"locale",D:"%m/%d/%y",F:"%Y-%m-%d",h:"%b",n:"\n",r:"locale",R:"%H:%M",t:"\t",T:"%H:%M:%S",x:"locale",X:"locale"},format:function(G,F,D){F=F||{};if(!(G instanceof Date)){return YAHOO.lang.isValue(G)?G:"";}var H=F.format||"%m/%d/%Y";if(H==="YYYY/MM/DD"){H="%Y/%m/%d";}else{if(H==="DD/MM/YYYY"){H="%d/%m/%Y";}else{if(H==="MM/DD/YYYY"){H="%m/%d/%Y";}}}D=D||"en";if(!(D in YAHOO.util.DateLocale)){if(D.replace(/-[a-zA-Z]+$/,"") in YAHOO.util.DateLocale){D=D.replace(/-[a-zA-Z]+$/,"");}else{D="en";}}var J=YAHOO.util.DateLocale[D];var C=function(L,K){var M=B.aggregates[K];return(M==="locale"?J[K]:M);};var E=function(L,K){var M=B.formats[K];if(typeof M==="string"){return G[M]();}else{if(typeof M==="function"){return M.call(G,G,J);}else{if(typeof M==="object"&&typeof M[0]==="string"){return A(G[M[0]](),M[1]);}else{return K;}}}};while(H.match(/%[cDFhnrRtTxX]/)){H=H.replace(/%([cDFhnrRtTxX])/g,C);}var I=H.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g,E);C=E=undefined;return I;}};YAHOO.namespace("YAHOO.util");YAHOO.util.Date=B;YAHOO.util.DateLocale={a:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],A:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],b:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],B:["January","February","March","April","May","June","July","August","September","October","November","December"],c:"%a %d %b %Y %T %Z",p:["AM","PM"],P:["am","pm"],r:"%I:%M:%S %p",x:"%d/%m/%y",X:"%T"};YAHOO.util.DateLocale["en"]=YAHOO.lang.merge(YAHOO.util.DateLocale,{});YAHOO.util.DateLocale["en-US"]=YAHOO.lang.merge(YAHOO.util.DateLocale["en"],{c:"%a %d %b %Y %I:%M:%S %p %Z",x:"%m/%d/%Y",X:"%I:%M:%S %p"});YAHOO.util.DateLocale["en-GB"]=YAHOO.lang.merge(YAHOO.util.DateLocale["en"],{r:"%l:%M:%S %P %Z"});YAHOO.util.DateLocale["en-AU"]=YAHOO.lang.merge(YAHOO.util.DateLocale["en"]);})();YAHOO.register("datasource",YAHOO.util.DataSource,{version:"2.6.0",build:"1321"});/* -Copyright (c) 2008, Yahoo! Inc. All rights reserved. -Code licensed under the BSD License: -http://developer.yahoo.net/yui/license.txt -version: 2.6.0 -*/ -YAHOO.widget.DS_JSArray=YAHOO.util.LocalDataSource;YAHOO.widget.DS_JSFunction=YAHOO.util.FunctionDataSource;YAHOO.widget.DS_XHR=function(B,A,D){var C=new YAHOO.util.XHRDataSource(B,D);C._aDeprecatedSchema=A;return C;};YAHOO.widget.DS_ScriptNode=function(B,A,D){var C=new YAHOO.util.ScriptNodeDataSource(B,D);C._aDeprecatedSchema=A;return C;};YAHOO.widget.DS_XHR.TYPE_JSON=YAHOO.util.DataSourceBase.TYPE_JSON;YAHOO.widget.DS_XHR.TYPE_XML=YAHOO.util.DataSourceBase.TYPE_XML;YAHOO.widget.DS_XHR.TYPE_FLAT=YAHOO.util.DataSourceBase.TYPE_TEXT;YAHOO.widget.AutoComplete=function(G,B,J,C){if(G&&B&&J){if(J instanceof YAHOO.util.DataSourceBase){this.dataSource=J;}else{return ;}this.key=0;var D=J.responseSchema;if(J._aDeprecatedSchema){var K=J._aDeprecatedSchema;if(YAHOO.lang.isArray(K)){if((J.responseType===YAHOO.util.DataSourceBase.TYPE_JSON)||(J.responseType===YAHOO.util.DataSourceBase.TYPE_UNKNOWN)){D.resultsList=K[0];this.key=K[1];D.fields=(K.length<3)?null:K.slice(1);}else{if(J.responseType===YAHOO.util.DataSourceBase.TYPE_XML){D.resultNode=K[0];this.key=K[1];D.fields=K.slice(1);}else{if(J.responseType===YAHOO.util.DataSourceBase.TYPE_TEXT){D.recordDelim=K[0];D.fieldDelim=K[1];}}}J.responseSchema=D;}}if(YAHOO.util.Dom.inDocument(G)){if(YAHOO.lang.isString(G)){this._sName="instance"+YAHOO.widget.AutoComplete._nIndex+" "+G;this._elTextbox=document.getElementById(G);}else{this._sName=(G.id)?"instance"+YAHOO.widget.AutoComplete._nIndex+" "+G.id:"instance"+YAHOO.widget.AutoComplete._nIndex;this._elTextbox=G;}YAHOO.util.Dom.addClass(this._elTextbox,"yui-ac-input");}else{return ;}if(YAHOO.util.Dom.inDocument(B)){if(YAHOO.lang.isString(B)){this._elContainer=document.getElementById(B);}else{this._elContainer=B;}if(this._elContainer.style.display=="none"){}var E=this._elContainer.parentNode;var A=E.tagName.toLowerCase();if(A=="div"){YAHOO.util.Dom.addClass(E,"yui-ac");}else{}}else{return ;}if(this.dataSource.dataType===YAHOO.util.DataSourceBase.TYPE_LOCAL){this.applyLocalFilter=true;}if(C&&(C.constructor==Object)){for(var I in C){if(I){this[I]=C[I];}}}this._initContainerEl();this._initProps();this._initListEl();this._initContainerHelperEls();var H=this;var F=this._elTextbox;YAHOO.util.Event.addListener(F,"keyup",H._onTextboxKeyUp,H);YAHOO.util.Event.addListener(F,"keydown",H._onTextboxKeyDown,H);YAHOO.util.Event.addListener(F,"focus",H._onTextboxFocus,H);YAHOO.util.Event.addListener(F,"blur",H._onTextboxBlur,H);YAHOO.util.Event.addListener(B,"mouseover",H._onContainerMouseover,H);YAHOO.util.Event.addListener(B,"mouseout",H._onContainerMouseout,H);YAHOO.util.Event.addListener(B,"click",H._onContainerClick,H);YAHOO.util.Event.addListener(B,"scroll",H._onContainerScroll,H);YAHOO.util.Event.addListener(B,"resize",H._onContainerResize,H);YAHOO.util.Event.addListener(F,"keypress",H._onTextboxKeyPress,H);YAHOO.util.Event.addListener(window,"unload",H._onWindowUnload,H);this.textboxFocusEvent=new YAHOO.util.CustomEvent("textboxFocus",this);this.textboxKeyEvent=new YAHOO.util.CustomEvent("textboxKey",this);this.dataRequestEvent=new YAHOO.util.CustomEvent("dataRequest",this);this.dataReturnEvent=new YAHOO.util.CustomEvent("dataReturn",this);this.dataErrorEvent=new YAHOO.util.CustomEvent("dataError",this);this.containerPopulateEvent=new YAHOO.util.CustomEvent("containerPopulate",this);this.containerExpandEvent=new YAHOO.util.CustomEvent("containerExpand",this);this.typeAheadEvent=new YAHOO.util.CustomEvent("typeAhead",this);this.itemMouseOverEvent=new YAHOO.util.CustomEvent("itemMouseOver",this);this.itemMouseOutEvent=new YAHOO.util.CustomEvent("itemMouseOut",this);this.itemArrowToEvent=new YAHOO.util.CustomEvent("itemArrowTo",this);this.itemArrowFromEvent=new YAHOO.util.CustomEvent("itemArrowFrom",this);this.itemSelectEvent=new YAHOO.util.CustomEvent("itemSelect",this);this.unmatchedItemSelectEvent=new YAHOO.util.CustomEvent("unmatchedItemSelect",this);this.selectionEnforceEvent=new YAHOO.util.CustomEvent("selectionEnforce",this);this.containerCollapseEvent=new YAHOO.util.CustomEvent("containerCollapse",this);this.textboxBlurEvent=new YAHOO.util.CustomEvent("textboxBlur",this);this.textboxChangeEvent=new YAHOO.util.CustomEvent("textboxChange",this);F.setAttribute("autocomplete","off");YAHOO.widget.AutoComplete._nIndex++;}else{}};YAHOO.widget.AutoComplete.prototype.dataSource=null;YAHOO.widget.AutoComplete.prototype.applyLocalFilter=null;YAHOO.widget.AutoComplete.prototype.queryMatchCase=false;YAHOO.widget.AutoComplete.prototype.queryMatchContains=false;YAHOO.widget.AutoComplete.prototype.queryMatchSubset=false;YAHOO.widget.AutoComplete.prototype.minQueryLength=1;YAHOO.widget.AutoComplete.prototype.maxResultsDisplayed=10;YAHOO.widget.AutoComplete.prototype.queryDelay=0.2;YAHOO.widget.AutoComplete.prototype.typeAheadDelay=0.5;YAHOO.widget.AutoComplete.prototype.queryInterval=500;YAHOO.widget.AutoComplete.prototype.highlightClassName="yui-ac-highlight";YAHOO.widget.AutoComplete.prototype.prehighlightClassName=null;YAHOO.widget.AutoComplete.prototype.delimChar=null;YAHOO.widget.AutoComplete.prototype.autoHighlight=true;YAHOO.widget.AutoComplete.prototype.typeAhead=false;YAHOO.widget.AutoComplete.prototype.animHoriz=false;YAHOO.widget.AutoComplete.prototype.animVert=true;YAHOO.widget.AutoComplete.prototype.animSpeed=0.3;YAHOO.widget.AutoComplete.prototype.forceSelection=false;YAHOO.widget.AutoComplete.prototype.allowBrowserAutocomplete=true;YAHOO.widget.AutoComplete.prototype.alwaysShowContainer=false;YAHOO.widget.AutoComplete.prototype.useIFrame=false;YAHOO.widget.AutoComplete.prototype.useShadow=false;YAHOO.widget.AutoComplete.prototype.suppressInputUpdate=false;YAHOO.widget.AutoComplete.prototype.resultTypeList=true;YAHOO.widget.AutoComplete.prototype.queryQuestionMark=true;YAHOO.widget.AutoComplete.prototype.toString=function(){return"AutoComplete "+this._sName;};YAHOO.widget.AutoComplete.prototype.getInputEl=function(){return this._elTextbox;};YAHOO.widget.AutoComplete.prototype.getContainerEl=function(){return this._elContainer; -};YAHOO.widget.AutoComplete.prototype.isFocused=function(){return(this._bFocused===null)?false:this._bFocused;};YAHOO.widget.AutoComplete.prototype.isContainerOpen=function(){return this._bContainerOpen;};YAHOO.widget.AutoComplete.prototype.getListEl=function(){return this._elList;};YAHOO.widget.AutoComplete.prototype.getListItemMatch=function(A){if(A._sResultMatch){return A._sResultMatch;}else{return null;}};YAHOO.widget.AutoComplete.prototype.getListItemData=function(A){if(A._oResultData){return A._oResultData;}else{return null;}};YAHOO.widget.AutoComplete.prototype.getListItemIndex=function(A){if(YAHOO.lang.isNumber(A._nItemIndex)){return A._nItemIndex;}else{return null;}};YAHOO.widget.AutoComplete.prototype.setHeader=function(B){if(this._elHeader){var A=this._elHeader;if(B){A.innerHTML=B;A.style.display="block";}else{A.innerHTML="";A.style.display="none";}}};YAHOO.widget.AutoComplete.prototype.setFooter=function(B){if(this._elFooter){var A=this._elFooter;if(B){A.innerHTML=B;A.style.display="block";}else{A.innerHTML="";A.style.display="none";}}};YAHOO.widget.AutoComplete.prototype.setBody=function(A){if(this._elBody){var B=this._elBody;YAHOO.util.Event.purgeElement(B,true);if(A){B.innerHTML=A;B.style.display="block";}else{B.innerHTML="";B.style.display="none";}this._elList=null;}};YAHOO.widget.AutoComplete.prototype.generateRequest=function(B){var A=this.dataSource.dataType;if(A===YAHOO.util.DataSourceBase.TYPE_XHR){if(!this.dataSource.connMethodPost){B=(this.queryQuestionMark?"?":"")+(this.dataSource.scriptQueryParam||"query")+"="+B+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"");}else{B=(this.dataSource.scriptQueryParam||"query")+"="+B+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"");}}else{if(A===YAHOO.util.DataSourceBase.TYPE_SCRIPTNODE){B="&"+(this.dataSource.scriptQueryParam||"query")+"="+B+(this.dataSource.scriptQueryAppend?("&"+this.dataSource.scriptQueryAppend):"");}}return B;};YAHOO.widget.AutoComplete.prototype.sendQuery=function(B){var A=(this.delimChar)?this._elTextbox.value+B:B;this._sendQuery(A);};YAHOO.widget.AutoComplete.prototype.collapseContainer=function(){this._toggleContainer(false);};YAHOO.widget.AutoComplete.prototype.getSubsetMatches=function(E){var D,C,A;for(var B=E.length;B>=this.minQueryLength;B--){A=this.generateRequest(E.substr(0,B));this.dataRequestEvent.fire(this,D,A);C=this.dataSource.getCachedResponse(A);if(C){return this.filterResults.apply(this.dataSource,[E,C,C,{scope:this}]);}}return null;};YAHOO.widget.AutoComplete.prototype.preparseRawResponse=function(C,B,A){var D=((this.responseStripAfter!=="")&&(B.indexOf))?B.indexOf(this.responseStripAfter):-1;if(D!=-1){B=B.substring(0,D);}return B;};YAHOO.widget.AutoComplete.prototype.filterResults=function(J,L,P,K){if(J&&J!==""){P=YAHOO.widget.AutoComplete._cloneObject(P);var H=K.scope,O=this,B=P.results,M=[],D=false,I=(O.queryMatchCase||H.queryMatchCase),A=(O.queryMatchContains||H.queryMatchContains);for(var C=B.length-1;C>=0;C--){var F=B[C];var E=null;if(YAHOO.lang.isString(F)){E=F;}else{if(YAHOO.lang.isArray(F)){E=F[0];}else{if(this.responseSchema.fields){var N=this.responseSchema.fields[0].key||this.responseSchema.fields[0];E=F[N];}else{if(this.key){E=F[this.key];}}}}if(YAHOO.lang.isString(E)){var G=(I)?E.indexOf(decodeURIComponent(J)):E.toLowerCase().indexOf(decodeURIComponent(J).toLowerCase());if((!A&&(G===0))||(A&&(G>-1))){M.unshift(F);}}}P.results=M;}else{}return P;};YAHOO.widget.AutoComplete.prototype.handleResponse=function(C,A,B){if((this instanceof YAHOO.widget.AutoComplete)&&this._sName){this._populateList(C,A,B);}};YAHOO.widget.AutoComplete.prototype.doBeforeLoadData=function(C,A,B){return true;};YAHOO.widget.AutoComplete.prototype.formatResult=function(B,D,A){var C=(A)?A:"";return C;};YAHOO.widget.AutoComplete.prototype.doBeforeExpandContainer=function(D,A,C,B){return true;};YAHOO.widget.AutoComplete.prototype.destroy=function(){var B=this.toString();var A=this._elTextbox;var D=this._elContainer;this.textboxFocusEvent.unsubscribeAll();this.textboxKeyEvent.unsubscribeAll();this.dataRequestEvent.unsubscribeAll();this.dataReturnEvent.unsubscribeAll();this.dataErrorEvent.unsubscribeAll();this.containerPopulateEvent.unsubscribeAll();this.containerExpandEvent.unsubscribeAll();this.typeAheadEvent.unsubscribeAll();this.itemMouseOverEvent.unsubscribeAll();this.itemMouseOutEvent.unsubscribeAll();this.itemArrowToEvent.unsubscribeAll();this.itemArrowFromEvent.unsubscribeAll();this.itemSelectEvent.unsubscribeAll();this.unmatchedItemSelectEvent.unsubscribeAll();this.selectionEnforceEvent.unsubscribeAll();this.containerCollapseEvent.unsubscribeAll();this.textboxBlurEvent.unsubscribeAll();this.textboxChangeEvent.unsubscribeAll();YAHOO.util.Event.purgeElement(A,true);YAHOO.util.Event.purgeElement(D,true);D.innerHTML="";for(var C in this){if(YAHOO.lang.hasOwnProperty(this,C)){this[C]=null;}}};YAHOO.widget.AutoComplete.prototype.textboxFocusEvent=null;YAHOO.widget.AutoComplete.prototype.textboxKeyEvent=null;YAHOO.widget.AutoComplete.prototype.dataRequestEvent=null;YAHOO.widget.AutoComplete.prototype.dataReturnEvent=null;YAHOO.widget.AutoComplete.prototype.dataErrorEvent=null;YAHOO.widget.AutoComplete.prototype.containerPopulateEvent=null;YAHOO.widget.AutoComplete.prototype.containerExpandEvent=null;YAHOO.widget.AutoComplete.prototype.typeAheadEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOverEvent=null;YAHOO.widget.AutoComplete.prototype.itemMouseOutEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowToEvent=null;YAHOO.widget.AutoComplete.prototype.itemArrowFromEvent=null;YAHOO.widget.AutoComplete.prototype.itemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.unmatchedItemSelectEvent=null;YAHOO.widget.AutoComplete.prototype.selectionEnforceEvent=null;YAHOO.widget.AutoComplete.prototype.containerCollapseEvent=null;YAHOO.widget.AutoComplete.prototype.textboxBlurEvent=null;YAHOO.widget.AutoComplete.prototype.textboxChangeEvent=null;YAHOO.widget.AutoComplete._nIndex=0; -YAHOO.widget.AutoComplete.prototype._sName=null;YAHOO.widget.AutoComplete.prototype._elTextbox=null;YAHOO.widget.AutoComplete.prototype._elContainer=null;YAHOO.widget.AutoComplete.prototype._elContent=null;YAHOO.widget.AutoComplete.prototype._elHeader=null;YAHOO.widget.AutoComplete.prototype._elBody=null;YAHOO.widget.AutoComplete.prototype._elFooter=null;YAHOO.widget.AutoComplete.prototype._elShadow=null;YAHOO.widget.AutoComplete.prototype._elIFrame=null;YAHOO.widget.AutoComplete.prototype._bFocused=null;YAHOO.widget.AutoComplete.prototype._oAnim=null;YAHOO.widget.AutoComplete.prototype._bContainerOpen=false;YAHOO.widget.AutoComplete.prototype._bOverContainer=false;YAHOO.widget.AutoComplete.prototype._elList=null;YAHOO.widget.AutoComplete.prototype._nDisplayedItems=0;YAHOO.widget.AutoComplete.prototype._sCurQuery=null;YAHOO.widget.AutoComplete.prototype._sPastSelections="";YAHOO.widget.AutoComplete.prototype._sInitInputValue=null;YAHOO.widget.AutoComplete.prototype._elCurListItem=null;YAHOO.widget.AutoComplete.prototype._bItemSelected=false;YAHOO.widget.AutoComplete.prototype._nKeyCode=null;YAHOO.widget.AutoComplete.prototype._nDelayID=-1;YAHOO.widget.AutoComplete.prototype._nTypeAheadDelayID=-1;YAHOO.widget.AutoComplete.prototype._iFrameSrc="javascript:false;";YAHOO.widget.AutoComplete.prototype._queryInterval=null;YAHOO.widget.AutoComplete.prototype._sLastTextboxValue=null;YAHOO.widget.AutoComplete.prototype._initProps=function(){var B=this.minQueryLength;if(!YAHOO.lang.isNumber(B)){this.minQueryLength=1;}var E=this.maxResultsDisplayed;if(!YAHOO.lang.isNumber(E)||(E<1)){this.maxResultsDisplayed=10;}var F=this.queryDelay;if(!YAHOO.lang.isNumber(F)||(F<0)){this.queryDelay=0.2;}var C=this.typeAheadDelay;if(!YAHOO.lang.isNumber(C)||(C<0)){this.typeAheadDelay=0.2;}var A=this.delimChar;if(YAHOO.lang.isString(A)&&(A.length>0)){this.delimChar=[A];}else{if(!YAHOO.lang.isArray(A)){this.delimChar=null;}}var D=this.animSpeed;if((this.animHoriz||this.animVert)&&YAHOO.util.Anim){if(!YAHOO.lang.isNumber(D)||(D<0)){this.animSpeed=0.3;}if(!this._oAnim){this._oAnim=new YAHOO.util.Anim(this._elContent,{},this.animSpeed);}else{this._oAnim.duration=this.animSpeed;}}if(this.forceSelection&&A){}};YAHOO.widget.AutoComplete.prototype._initContainerHelperEls=function(){if(this.useShadow&&!this._elShadow){var A=document.createElement("div");A.className="yui-ac-shadow";A.style.width=0;A.style.height=0;this._elShadow=this._elContainer.appendChild(A);}if(this.useIFrame&&!this._elIFrame){var B=document.createElement("iframe");B.src=this._iFrameSrc;B.frameBorder=0;B.scrolling="no";B.style.position="absolute";B.style.width=0;B.style.height=0;B.tabIndex=-1;B.style.padding=0;this._elIFrame=this._elContainer.appendChild(B);}};YAHOO.widget.AutoComplete.prototype._initContainerEl=function(){YAHOO.util.Dom.addClass(this._elContainer,"yui-ac-container");if(!this._elContent){var C=document.createElement("div");C.className="yui-ac-content";C.style.display="none";this._elContent=this._elContainer.appendChild(C);var B=document.createElement("div");B.className="yui-ac-hd";B.style.display="none";this._elHeader=this._elContent.appendChild(B);var D=document.createElement("div");D.className="yui-ac-bd";this._elBody=this._elContent.appendChild(D);var A=document.createElement("div");A.className="yui-ac-ft";A.style.display="none";this._elFooter=this._elContent.appendChild(A);}else{}};YAHOO.widget.AutoComplete.prototype._initListEl=function(){var C=this.maxResultsDisplayed;var A=this._elList||document.createElement("ul");var B;while(A.childNodes.length=18&&A<=20)||(A==27)||(A>=33&&A<=35)||(A>=36&&A<=40)||(A>=44&&A<=45)||(A==229)){return true;}return false;};YAHOO.widget.AutoComplete.prototype._sendQuery=function(G){if(this.minQueryLength<0){this._toggleContainer(false);return ;}var I=(this.delimChar)?this.delimChar:null;if(I){var B=-1;for(var F=I.length-1;F>=0;F--){var D=G.lastIndexOf(I[F]);if(D>B){B=D;}}if(I[F]==" "){for(var E=I.length-1;E>=0;E--){if(G[B-1]==I[E]){B--;break;}}}if(B>-1){var H=B+1;while(G.charAt(H)==" "){H+=1;}this._sPastSelections=G.substring(0,H);G=G.substr(H);}else{this._sPastSelections="";}}if((G&&(G.length0)){if(this._nDelayID!=-1){clearTimeout(this._nDelayID);}this._toggleContainer(false);return ;}G=encodeURIComponent(G);this._nDelayID=-1;if(this.dataSource.queryMatchSubset||this.queryMatchSubset){var A=this.getSubsetMatches(G);if(A){this.handleResponse(G,A,{query:G});return ;}}if(this.responseStripAfter){this.dataSource.doBeforeParseData=this.preparseRawResponse;}if(this.applyLocalFilter){this.dataSource.doBeforeCallback=this.filterResults;}var C=this.generateRequest(G);this.dataRequestEvent.fire(this,G,C);this.dataSource.sendRequest(C,{success:this.handleResponse,failure:this.handleResponse,scope:this,argument:{query:G}});};YAHOO.widget.AutoComplete.prototype._populateList=function(K,F,C){if(this._nTypeAheadDelayID!=-1){clearTimeout(this._nTypeAheadDelayID);}K=(C&&C.query)?C.query:K;var H=this.doBeforeLoadData(K,F,C);if(H&&!F.error){this.dataReturnEvent.fire(this,K,F.results);if(this._bFocused||(this._bFocused===null)){var M=decodeURIComponent(K); -this._sCurQuery=M;this._bItemSelected=false;var R=F.results,A=Math.min(R.length,this.maxResultsDisplayed),J=(this.dataSource.responseSchema.fields)?(this.dataSource.responseSchema.fields[0].key||this.dataSource.responseSchema.fields[0]):0;if(A>0){if(!this._elList||(this._elList.childNodes.length=0;Q--){var P=I[Q],E=R[Q];if(this.resultTypeList){var B=[];B[0]=(YAHOO.lang.isString(E))?E:E[J]||E[this.key];var L=this.dataSource.responseSchema.fields;if(YAHOO.lang.isArray(L)&&(L.length>1)){for(var N=1,S=L.length;N=A;O--){G=I[O];G.style.display="none";}}this._nDisplayedItems=A;this.containerPopulateEvent.fire(this,K,R);if(this.autoHighlight){var D=this._elList.firstChild;this._toggleHighlight(D,"to");this.itemArrowToEvent.fire(this,D);this._typeAhead(D,K);}else{this._toggleHighlight(this._elCurListItem,"from");}H=this.doBeforeExpandContainer(this._elTextbox,this._elContainer,K,R);this._toggleContainer(H);}else{this._toggleContainer(false);}return ;}}else{this.dataErrorEvent.fire(this,K);}};YAHOO.widget.AutoComplete.prototype._clearSelection=function(){var C=this._elTextbox.value;var B=(this.delimChar)?this.delimChar[0]:null;var A=(B)?C.lastIndexOf(B,C.length-2):-1;if(A>-1){this._elTextbox.value=C.substring(0,A);}else{this._elTextbox.value="";}this._sPastSelections=this._elTextbox.value;this.selectionEnforceEvent.fire(this);};YAHOO.widget.AutoComplete.prototype._textMatchesOption=function(){var A=null;for(var B=this._nDisplayedItems-1;B>=0;B--){var C=this._elList.childNodes[B];var D=(""+C._sResultMatch).toLowerCase();if(D==this._sCurQuery.toLowerCase()){A=C;break;}}return(A);};YAHOO.widget.AutoComplete.prototype._typeAhead=function(B,D){if(!this.typeAhead||(this._nKeyCode==8)){return ;}var A=this,C=this._elTextbox;if(C.setSelectionRange||C.createTextRange){this._nTypeAheadDelayID=setTimeout(function(){var F=C.value.length;A._updateValue(B);var G=C.value.length;A._selectText(C,F,G);var E=C.value.substr(F,G);A.typeAheadEvent.fire(A,D,E);},(this.typeAheadDelay*1000));}};YAHOO.widget.AutoComplete.prototype._selectText=function(D,A,B){if(D.setSelectionRange){D.setSelectionRange(A,B);}else{if(D.createTextRange){var C=D.createTextRange();C.moveStart("character",A);C.moveEnd("character",B-D.value.length);C.select();}else{D.select();}}};YAHOO.widget.AutoComplete.prototype._toggleContainerHelpers=function(D){var E=this._elContent.offsetWidth+"px";var B=this._elContent.offsetHeight+"px";if(this.useIFrame&&this._elIFrame){var C=this._elIFrame;if(D){C.style.width=E;C.style.height=B;C.style.padding="";}else{C.style.width=0;C.style.height=0;C.style.padding=0;}}if(this.useShadow&&this._elShadow){var A=this._elShadow;if(D){A.style.width=E;A.style.height=B;}else{A.style.width=0;A.style.height=0;}}};YAHOO.widget.AutoComplete.prototype._toggleContainer=function(I){var D=this._elContainer;if(this.alwaysShowContainer&&this._bContainerOpen){return ;}if(!I){this._toggleHighlight(this._elCurListItem,"from");this._nDisplayedItems=0;this._sCurQuery=null;if(!this._bContainerOpen){this._elContent.style.display="none";return ;}}var A=this._oAnim;if(A&&A.getEl()&&(this.animHoriz||this.animVert)){if(A.isAnimated()){A.stop(true);}var G=this._elContent.cloneNode(true);D.appendChild(G);G.style.top="-9000px";G.style.width="";G.style.height="";G.style.display="";var F=G.offsetWidth;var C=G.offsetHeight;var B=(this.animHoriz)?0:F;var E=(this.animVert)?0:C;A.attributes=(I)?{width:{to:F},height:{to:C}}:{width:{to:B},height:{to:E}};if(I&&!this._bContainerOpen){this._elContent.style.width=B+"px";this._elContent.style.height=E+"px";}else{this._elContent.style.width=F+"px";this._elContent.style.height=C+"px";}D.removeChild(G);G=null;var H=this;var J=function(){A.onComplete.unsubscribeAll();if(I){H._toggleContainerHelpers(true);H._bContainerOpen=I;H.containerExpandEvent.fire(H);}else{H._elContent.style.display="none";H._bContainerOpen=I;H.containerCollapseEvent.fire(H);}};this._toggleContainerHelpers(false);this._elContent.style.display="";A.onComplete.subscribe(J);A.animate();}else{if(I){this._elContent.style.display="";this._toggleContainerHelpers(true);this._bContainerOpen=I;this.containerExpandEvent.fire(this);}else{this._toggleContainerHelpers(false);this._elContent.style.display="none";this._bContainerOpen=I;this.containerCollapseEvent.fire(this);}}};YAHOO.widget.AutoComplete.prototype._toggleHighlight=function(A,C){if(A){var B=this.highlightClassName;if(this._elCurListItem){YAHOO.util.Dom.removeClass(this._elCurListItem,B);this._elCurListItem=null;}if((C=="to")&&B){YAHOO.util.Dom.addClass(A,B);this._elCurListItem=A;}}};YAHOO.widget.AutoComplete.prototype._togglePrehighlight=function(B,C){if(B==this._elCurListItem){return ;}var A=this.prehighlightClassName;if((C=="mouseover")&&A){YAHOO.util.Dom.addClass(B,A);}else{YAHOO.util.Dom.removeClass(B,A);}};YAHOO.widget.AutoComplete.prototype._updateValue=function(C){if(!this.suppressInputUpdate){var F=this._elTextbox;var E=(this.delimChar)?(this.delimChar[0]||this.delimChar):null;var B=C._sResultMatch;var D="";if(E){D=this._sPastSelections;D+=B+E;if(E!=" "){D+=" ";}}else{D=B;}F.value=D;if(F.type=="textarea"){F.scrollTop=F.scrollHeight;}var A=F.value.length;this._selectText(F,A,A);this._elCurListItem=C;}};YAHOO.widget.AutoComplete.prototype._selectItem=function(A){this._bItemSelected=true;this._updateValue(A);this._sPastSelections=this._elTextbox.value;this._clearInterval();this.itemSelectEvent.fire(this,A,A._oResultData);this._toggleContainer(false);};YAHOO.widget.AutoComplete.prototype._jumpSelection=function(){if(this._elCurListItem){this._selectItem(this._elCurListItem); -}else{this._toggleContainer(false);}};YAHOO.widget.AutoComplete.prototype._moveSelection=function(G){if(this._bContainerOpen){var F=this._elCurListItem;var E=-1;if(F){E=F._nItemIndex;}var C=(G==40)?(E+1):(E-1);if(C<-2||C>=this._nDisplayedItems){return ;}if(F){this._toggleHighlight(F,"from");this.itemArrowFromEvent.fire(this,F);}if(C==-1){if(this.delimChar){this._elTextbox.value=this._sPastSelections+this._sCurQuery;}else{this._elTextbox.value=this._sCurQuery;}return ;}if(C==-2){this._toggleContainer(false);return ;}var D=this._elList.childNodes[C];var A=this._elContent;var B=((YAHOO.util.Dom.getStyle(A,"overflow")=="auto")||(YAHOO.util.Dom.getStyle(A,"overflowY")=="auto"));if(B&&(C>-1)&&(C(A.scrollTop+A.offsetHeight)){A.scrollTop=(D.offsetTop+D.offsetHeight)-A.offsetHeight;}else{if((D.offsetTop+D.offsetHeight)(A.scrollTop+A.offsetHeight)){this._elContent.scrollTop=(D.offsetTop+D.offsetHeight)-A.offsetHeight;}}}}this._toggleHighlight(D,"to");this.itemArrowToEvent.fire(this,D);if(this.typeAhead){this._updateValue(D);}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseover=function(A,C){var D=YAHOO.util.Event.getTarget(A);var B=D.nodeName.toLowerCase();while(D&&(B!="table")){switch(B){case"body":return ;case"li":if(C.prehighlightClassName){C._togglePrehighlight(D,"mouseover");}else{C._toggleHighlight(D,"to");}C.itemMouseOverEvent.fire(C,D);break;case"div":if(YAHOO.util.Dom.hasClass(D,"yui-ac-container")){C._bOverContainer=true;return ;}break;default:break;}D=D.parentNode;if(D){B=D.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerMouseout=function(A,C){var D=YAHOO.util.Event.getTarget(A);var B=D.nodeName.toLowerCase();while(D&&(B!="table")){switch(B){case"body":return ;case"li":if(C.prehighlightClassName){C._togglePrehighlight(D,"mouseout");}else{C._toggleHighlight(D,"from");}C.itemMouseOutEvent.fire(C,D);break;case"ul":C._toggleHighlight(C._elCurListItem,"to");break;case"div":if(YAHOO.util.Dom.hasClass(D,"yui-ac-container")){C._bOverContainer=false;return ;}break;default:break;}D=D.parentNode;if(D){B=D.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerClick=function(A,C){var D=YAHOO.util.Event.getTarget(A);var B=D.nodeName.toLowerCase();while(D&&(B!="table")){switch(B){case"body":return ;case"li":C._toggleHighlight(D,"to");C._selectItem(D);return ;default:break;}D=D.parentNode;if(D){B=D.nodeName.toLowerCase();}}};YAHOO.widget.AutoComplete.prototype._onContainerScroll=function(A,B){B._elTextbox.focus();};YAHOO.widget.AutoComplete.prototype._onContainerResize=function(A,B){B._toggleContainerHelpers(B._bContainerOpen);};YAHOO.widget.AutoComplete.prototype._onTextboxKeyDown=function(A,B){var C=A.keyCode;if(B._nTypeAheadDelayID!=-1){clearTimeout(B._nTypeAheadDelayID);}switch(C){case 9:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(B._elCurListItem){if(B.delimChar&&(B._nKeyCode!=C)){if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);}}B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;case 13:if(!YAHOO.env.ua.opera&&(navigator.userAgent.toLowerCase().indexOf("mac")==-1)||(YAHOO.env.ua.webkit>420)){if(B._elCurListItem){if(B._nKeyCode!=C){if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);}}B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;case 27:B._toggleContainer(false);return ;case 39:B._jumpSelection();break;case 38:if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);B._moveSelection(C);}break;case 40:if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);B._moveSelection(C);}break;default:B._bItemSelected=false;B._toggleHighlight(B._elCurListItem,"from");B.textboxKeyEvent.fire(B,C);break;}if(C===18){B._enableIntervalDetection();}B._nKeyCode=C;};YAHOO.widget.AutoComplete.prototype._onTextboxKeyPress=function(A,B){var C=A.keyCode;if(YAHOO.env.ua.opera||(navigator.userAgent.toLowerCase().indexOf("mac")!=-1)&&(YAHOO.env.ua.webkit<420)){switch(C){case 9:if(B._bContainerOpen){if(B.delimChar){YAHOO.util.Event.stopEvent(A);}if(B._elCurListItem){B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;case 13:if(B._bContainerOpen){YAHOO.util.Event.stopEvent(A);if(B._elCurListItem){B._selectItem(B._elCurListItem);}else{B._toggleContainer(false);}}break;default:break;}}else{if(C==229){B._enableIntervalDetection();}}};YAHOO.widget.AutoComplete.prototype._onTextboxKeyUp=function(A,C){var B=this.value;C._initProps();var D=A.keyCode;if(C._isIgnoreKey(D)){return ;}if(C._nDelayID!=-1){clearTimeout(C._nDelayID);}C._nDelayID=setTimeout(function(){C._sendQuery(B);},(C.queryDelay*1000));};YAHOO.widget.AutoComplete.prototype._onTextboxFocus=function(A,B){if(!B._bFocused){B._elTextbox.setAttribute("autocomplete","off");B._bFocused=true;B._sInitInputValue=B._elTextbox.value;B.textboxFocusEvent.fire(B);}};YAHOO.widget.AutoComplete.prototype._onTextboxBlur=function(A,C){if(!C._bOverContainer||(C._nKeyCode==9)){if(!C._bItemSelected){var B=C._textMatchesOption();if(!C._bContainerOpen||(C._bContainerOpen&&(B===null))){if(C.forceSelection){C._clearSelection();}else{C.unmatchedItemSelectEvent.fire(C,C._sCurQuery);}}else{if(C.forceSelection){C._selectItem(B);}}}if(C._bContainerOpen){C._toggleContainer(false);}C._clearInterval();C._bFocused=false;if(C._sInitInputValue!==C._elTextbox.value){C.textboxChangeEvent.fire(C);}C.textboxBlurEvent.fire(C);}};YAHOO.widget.AutoComplete.prototype._onWindowUnload=function(A,B){if(B&&B._elTextbox&&B.allowBrowserAutocomplete){B._elTextbox.setAttribute("autocomplete","on");}};YAHOO.widget.AutoComplete.prototype.doBeforeSendQuery=function(A){return this.generateRequest(A);};YAHOO.widget.AutoComplete.prototype.getListItems=function(){var C=[],B=this._elList.childNodes;for(var A=B.length-1;A>=0;A--){C[A]=B[A];}return C;};YAHOO.widget.AutoComplete._cloneObject=function(D){if(!YAHOO.lang.isValue(D)){return D; -}var F={};if(YAHOO.lang.isFunction(D)){F=D;}else{if(YAHOO.lang.isArray(D)){var E=[];for(var C=0,B=D.length;C0){for(var B=0,A=D.length;B0){var B=(A===false?function(K){return K;}:decodeURIComponent);if(/[^=]+=[^=;]?(?:; [^=]+=[^=]?)?/.test(I)){var G=I.split(/;\s/g);var H=null;var C=null;var E=null;for(var D=0,F=G.length;Dgithub under the Apache License 2.0 -version $version diff --git a/node_modules/config/doc/template/index.tmpl b/node_modules/config/doc/template/index.tmpl deleted file mode 100755 index 0d4f505..0000000 --- a/node_modules/config/doc/template/index.tmpl +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - diff --git a/node_modules/config/doc/template/main.tmpl b/node_modules/config/doc/template/main.tmpl deleted file mode 100755 index 029b9c5..0000000 --- a/node_modules/config/doc/template/main.tmpl +++ /dev/null @@ -1,678 +0,0 @@ -#encoding UTF-8 -#filter EncodeUnicode - - - - - $modulename #if $classname# $classname #end if# #if $filename# $filename #end if# - - - - - - - - - - -
-
-

$projectname

- $projectname - #if $modulename - > $modulename - #if $classname# > $classname #end if# - #if $filename# > $filename (source view) #end if# - #end if -
-
- Search: -
-   -
-
-
-
- -
-
-
-
-
- Filters - - - -
-
- #if $index - #include "doc/template/overview.tmpl" - #end if - - #if $filename -
- - #include raw $filepath_highlighted -
- #else if $classname -

- #if $access#$access#end if# - - #if $static#$static#end if# - #if $final#$final#end if# - Class: $classname - - #if $extends - - extends $extends - #end if - - - #if $uses - - - uses - #set $i=0 - #for $provider in $uses##if $i > 0#, #end if# - - $provider#set $i=$i+1# - - #end for# - - - #end if -

- - - #if $subclasses -
-
Known Subclasses:
-
- #for $subclass in $subclasses - - $subclass - - #end for -
-
- #end if - - #if $deprecated -
Deprecated: $deprecated
- #end if - - #if $see -
See also: $see
- #end if - -
- $description -
- - #if $constructor -
-

Constructor

-
-
- $classname - - ( - #if $constructor.params - #set $i=0 - #set $current="" - - #for $param in $constructor.params# - #if $current != $param.name - #if $i > 0#, #end if# - #set $i = $i + 1 - #set $current = $param.name - $param.name - #end if - #end for - #end if - ) - -
- #if $constructor.params -
-
Parameters:
- #for $param in $constructor.params -
- $param.name - <$param.type> - - $param.description -
- #end for -
- #end if - - #if $constructor.return -
-
Returns:
-
- $constructor.return -
-
- #end if - -
-
-
-
- #end if - -
- #if $properties -
-

Properties

-
- #for $property in $properties -
-

$property.name - - #if $property.access#$property.access #end if##if $property.static#$property.static #end if##if $property.final#$property.final #end if#$property.type -

-
-
- $property.description -
-
- - - #if $property.default -
- Default Value: $property.default -
- #end if - - #if $property.deprecated -
- Deprecated: $property.deprecated -
- #end if - -
-
- #end for -
-
- #end if - - #if $inherited.properties -
- #for $superclassname in $inherited.properties -
-

Properties inherited from $superclassname:

-
- - #set i=0 - #set l=len($inherited.properties[$superclassname])-1 - #for $prop in $inherited.properties[$superclassname]# - - $prop.name#if $i<$l#,#end if# - - #set i=i+1 - #end for# - -
-
- #end for -
- #end if -
- -
- #if $methods -
-

Methods

-
- #for $method in $methods -
-

- $method.name

-
- - #if $method.access# $method.access #end if# - #if $method.static# $method.static #end if# - #if $method.final# $method.final #end if# - $method.return.type - $method.name - ( - #if $method.params - #set $i=0 - #set $current = "" - #for $param in $method.params# - #if $current != $param.name - #if $i > 0#, #end if# - #set $i = $i + 1 - #set $current = $param.name - $param.name - #end if# - #end for# - #end if - ) - - -
- $method.description -
- -
- - #if $method.params -
-
Parameters:
- #for $param in $method.params -
- $param.name - <$param.type> - - $param.description -
- #end for -
- #end if - - #if $method.return.type -
-
Returns: - - $method.return.type -
-
$method.return.description
-
- #end if - - #if $method.chainable -
- Chainable: This method is chainable. -
- #end if - - - #if $method.deprecated -
- Deprecated $method.deprecated -
- #end if - -
- -
-
-
- #end for -
-
- #end if - - #if $inherited.methods -
- #for $superclassname in $inherited.methods -
-

Methods inherited from $superclassname:

-
- - #set i=0 - #set l=len($inherited.methods[$superclassname])-1 - #for $method in $inherited.methods[$superclassname] - - $method.name#if $i<$l#,#end if# - - #set i=i+1 - #end for - -
-
- #end for -
- #end if -
- -
- #if $events -
-

Events

-
- #for $event in $events -
-

- $event.name

-
- - #if $event.access# $event.access #end if# - #if $event.static# $event.static #end if# - #if $event.final# $event.final #end if# - $event.name - - ( - #if $event.params - #set $i=0 - #set $current = "" - #for $param in $event.params# - #if $current != $param.name - #if $i > 0#, #end if# - #set $i = $i + 1 - #set $current = $param.name - $param.name - #end if# - #end for# - #end if - ) - - - -
- $event.description -
- -
- - - #if $event.params -
-
Parameters:
- #for $param in $event.params -
- $param.name - <$param.type> - - $param.description -
- - #end for -
- #end if - - #if $event.bubbles -
- Bubbles: This event bubbles to $event.bubbles. -
- #end if - #if $event.preventable -
- Preventable: This event is preventable by method: $event.preventable. -
- #end if - - #if $event.deprecated -
- Deprecated $event.deprecated -
- #end if -
- -
-
-
- #end for -
-
- #end if - - - #if $inherited.events -
- #for $superclassname in $inherited.events -
-

Events inherited from $superclassname:

-
- - #set i=0 - #set l=len($inherited.methods[$superclassname])-1 - #for $event in $inherited.events[$superclassname] - #set i=i+1 - - $event.name#if $i<$l#,#end if##set i=i+1# - - #end for# - -
-
- #end for -
- #end if -
- -
- #if $configs -
-

Configuration Attributes

-
- #for $config in $configs -
-

$config.name - - #if $config.access#$config.access #end if##if $config.static#$config.static #end if##if $config.writeonce#$config.writeonce #end if##if $config.final#$config.final #end if#$config.type -

-
-
- $config.description -
-
- - #if $config.deprecated -
- Deprecated $config.deprecated -
- #end if - - #if $config.default -
- Default Value: $config.default -
- #end if - -
-
- #end for - -
-
- #end if - - #if $inherited.configs -
- #for $superclassname in $inherited.configs -
-

Configuration attributes inherited from $superclassname:

-
- - #set i=0 - #set l=len($inherited.methods[$superclassname])-1 - #for $config in $inherited.configs[$superclassname] - #set i=i+1 - - $config.name#if $i<$l#,#end if# - - #set i=i+1 - #end for# - -
-
- #end for -
- #end if -
- - #else if $modulename - -

Module: $modulename - - #if $beta - Beta - #end if - - #if $experimental - Experimental - #end if - -

-
- $moduledesc -
- - - #if $requires -
- Requires: $requires -
- #end if - #if $optional -
- Optional: $optional -
- #end if - -
-
- - #if $classnames -

This module contains the following classes:

- -
-
    - #set $counter = 0 - #for $classNames in $classList_raw -
  • $classNames.guessedname
  • - #set $counter = $counter + 1 - #end for -
-
- #end if -
-
- #set count = 0; - #for $info in $submodules - #set count = count + 1 - #end for - #if count != 0 -
-

Submodules:

-
- #for $info in $submodules -
$info
-
$subdata[$info].description
- #end for -
-
- #end if - -
-
- - #end if -
-
-
- -
-
-
-
- #include "doc/template/footer.tmpl" -
-
- -#if $ydn - - -#end if - - -#end filter diff --git a/node_modules/config/doc/template/overview.tmpl b/node_modules/config/doc/template/overview.tmpl deleted file mode 100755 index 35a1502..0000000 --- a/node_modules/config/doc/template/overview.tmpl +++ /dev/null @@ -1,285 +0,0 @@ -

Online Documentation

-
- -

Introduction

-

- Node-config is a configuration system for Node.js application server - deployments. It lets you define a default set of application parameters, - and tune them for different runtime environments (development, qa, - staging, production, etc.). -

-

- Parameters defined by node-config can be monitored and tuned at runtime - without bouncing your production servers. -

- -

Project Guidelines

-
    -
  • Simple - Get started fast
  • -
  • Predictable - Well tested and stable
  • -
  • Flexible - Reasonable defaults & hackable
  • -
  • Powerful - For multi-node enterprise deployment
  • -
  • Lightweight - Small memory and download footprint
  • -
  • Stable - Foundation for module developers
  • -
- -

Getting Started

-

- See the quick-start guide hosted on github -

- -

Configuration Files

-

- Node-config reads configuration files stored in the directory specified by - the NODE_CONFIG_DIR environment variable, which defaults to the config - directory under the process current working directory. Configuration files can be - in JavaScript format, JSON format, COFFEE format, or YAML format - whichever you prefer. -

-

- Configuration files in the config directory are loaded in the following order: -

-
-    default.EXT
-    hostname.EXT
-    deployment.EXT
-    hostname-deployment.EXT
-    local.EXT
-    local-deployment.EXT
-    runtime.json
-  
-

- Where EXT can be .yml, .yaml, .coffee, .json, or .js depending on the format you prefer. - NOTE: If you use .yml, .yaml, or .coffee file extensions, the 'js-yaml' or 'coffee-script' - modules must be available. These external dependencies are not included from - this package. -

-

- hostname is the \$HOST environment variable if set, otherwise the \$HOSTNAME - environment variable if set, otherwise the hostname found from - require('os').hostname(). Once a hostname is found, everything from the - first period ('.') onwards is removed. For example, abc.example.com becomes abc -

-

- deployment is the deployment type, found in the \$NODE_ENV environment - variable. Defaults to 'development'. -

-

- The runtime.json file contains configuration changes made at runtime either - manually, or by the application setting a configuration value. The location is - specified by NODE_CONFIG_RUNTIME_JSON environment variable. By default, it - is a file called runtime.json in NODE_CONFIG_DIR directory. Node-config - monitors this file and loads any new configurations it detects. This file is - loaded after all other configurations, including the \$NODE_CONFIG environment - variable and --NODE_CONFIG command line parameter (see below). -

-

- In the running application, each configuration parameter is internally - monitored for changes, and persisted to runtime.json upon change. - This keeps configurations in sync in a mutli-node deployment. If you want to - disable this persistence and sync you can set the environment variable - NODE_CONFIG_PERSIST_ON_CHANGE to "N". This will lead to lower I/O if you - change variables very often in your application. -

- -

File Comments

-

- Javascript-style comments are stripped out of files before parsing, - regardless of the file format type. -

- -

File Formats

-

- JSON files (.json) expose configuration parameters as a JSON object. - Example: -

-
-  /* Customer parameters
-   *
-   * This controls database access and legacy system synchronization
-   */
-  {
-    "Customer": {
-      "dbName": "customers",
-      "dbHost": "localhost",
-      "dbPort": 5984
-      // Database synchronization frequency
-      "syncFrequency": 60
-    }
-  }
-  
-

-

- -

- JavaScript files (.js) expose configuration parameters as module.exports. Example: -

-
-  module.exports = {
-    Customer: {
-      dbName: "customers",
-      dbHost: "localhost",
-      dbPort: 5984,
-      creditLimit: 600 // Default initial credit limit
-    }
-  }
-  
- -

- YAML files (.yaml or .yml) expose configuration parameters in YAML format. Example: -

-
-  Customer:
-      dbName: customers
-      dbHost: localhost
-      dbPort: 5984
-      creditLimit: 600
-  
- -

- Coffee-script files (.coffee) expose configuration parameters in coffee-script format. Example: -

-
-  module.exports =
-    Customer:
-      dbName: "customers"
-      dbHost: "localhost"
-      dbPort: 5984
-      creditLimit: 600
-  
- -

Multiple Instance Configuration

-

- When running multiple instances of your application, you may specify the - \$NODE_APP_INSTANCE environment variable prior to running - your app. If set, this variable should contain an identifier for - the specific instance of your app on this server, or within the network. -

-

- Configuration files appended with this identifier will be loaded after - the configuration file without the instance identifier. -

-

- Example: -

-
-    $ export NODE_ENV=staging
-    $ export NODE_APP_INSTANCE=3
-    $ node myApp.js
-  
-

- This instructs node-config to load default-3.json (if present) - immediately after default.json, and staging-3.json after - staging.json. -

-

- All configuration files (except runtime.json) follow this pattern, allowing - your application to specify instance-specific configurations at any level. -

- -

Environment Variable Configurations

-

- If the \$NODE_CONFIG environment variable is set, it must be a valid - JSON string containing configuration overrides. These are applied - after configuration files have been loaded. -

-

- For example, setting \$NODE_CONFIG={"Customer":{"dbPort":5984}} will set - the CONFIG.Customer.dbPort variable, overriding file configurations. -

- -

Command Line Alternatives to Environment Variables

-

- All environment variables described above may also be supplied on the command - line. -

-

- Example: -

-
-    $ node myApp.js --NODE_ENV=staging --NODE_APP_INSTANCE=3 '--NODE_CONFIG={"Customer":{"dbPort":5984}}'
-  
-

- The format must be two dashes followed by the environment variable name, - an equals sign, and the value (as in the example above). -

- -

Monitoring Changes

-

- One important attribute of node-config is the ability to tune configuration - parameters at runtime. Configuration parameters fall into one of the - following categories: -

-
    -
  • - OK to change - This parameter type can change without - adverse effect. Most parameters fall into this category, where the - parameter value is read every time it's used. -
  • -
  • - Monitored - Some parameters are read infrequently - (usually at the start of the application), and need to be monitored for - change. The CONFIG.watch() function is available to watch these - parameters, and run a function when the value changes. See the - watch method definition for more - information. -
  • -
  • - Not OK to change - Some parameters must be fixed at - runtime and remain stable throughout the lifecycle of the application. - For these parameters, the - makeImmutable method is - offered to guarantee the parameter cannot be changed. -
  • -
- -

Production Deployments

-

- Node-config is designed to run in a multi-node deployment, where many - instances of your application are running on a production server (usually - one per core processor). -

-

- If configuration values change at runtime, these changes are persisted - into the runtime.json file within the config directory. Multi-node - application instances keep in synch by watching for and loading changes - in runtime.json when detected. -

-

- This paradigm does not extend beyond a single machine. -

- -

For Module Developers

-

- Module developers can use node-config to define module specific - configuration parameters, and offer the same runtime tuning and multiple - deployment capability as the local application. -

-

- Node.js modules don't live in the same directory as the application, so - a different mechanism is offered to specify your default configuration. -

-

- The setModuleDefaults - method creates an object (named after the module) within the CONFIG object - containing all module configuration parameters, and their defaults. -

-

- Example: -

-
-    var CONFIG = require("config");
-    CONFIG.setModuleDefaults("MyModule", {
-      templateName: "t-50",
-      colorScheme: "green"
-    });
-  
-

- Users of your module may override your defaults in their config/defaults - file, or any of their deployment-specific configuration files. -

- -

- Online docs built by yui-doc and hosted by github. -

- -
diff --git a/node_modules/config/lib/config.js b/node_modules/config/lib/config.js deleted file mode 100644 index 6cd2913..0000000 --- a/node_modules/config/lib/config.js +++ /dev/null @@ -1,1410 +0,0 @@ -/*jsl:declare global */ -// config.js (c) 2010-2014 Loren West and other contributors -// May be freely distributed under the MIT license. -// For further details and documentation: -// http://lorenwest.github.com/node-config - -// Dependencies -var Yaml = null, // External libraries are lazy-loaded - VisionmediaYaml = null, // only if these file types exist. - Coffee = null, - FileSystem = require('fs'); - -// Static members -var DEFAULT_CLONE_DEPTH = 20, - FILE_WATCHER_INTERVAL = 2500, // For old style (pre-6.0) file watching - CONFIG_DIR, RUNTIME_JSON_FILENAME, NODE_ENV, APP_INSTANCE, - DISABLE_FILE_WATCH, PERSIST_ON_CHANGE, HOST, HOSTNAME, - originalConfig = null, // Not including the runtime.json values - runtimeJson = {}, // Current runtimeJson extensions - runtimeJsonWatcher = null, // Filesystem watcher for runtime.json - configSources = [], // Configuration sources - array of {name, original, parsed} - isQueuedForPersistence = false; - -/** - *

Runtime Application Configurations

- * - *

- * The config module exports a singleton object representing all runtime - * configurations for this application deployment. - *

- * - *

- * Application configurations are stored in files within the config directory - * of your application. The default configuration file is loaded, followed - * by files specific to the deployment type (development, testing, staging, - * production, etc.). - *

- * - *

- * For example, with the following config/default.yaml file: - *

- * - *
- *   ...
- *   customer:
- *       initialCredit: 500
- *       db:
- *           name: customer
- *           port: 5984
- *   ...
- * 
- * - *

- * The following code loads the customer section into the CONFIG variable: - *

- * - *

- *   var CONFIG = require('config').customer;
- *   ...
- *   newCustomer.creditLimit = CONFIG.initialCredit;
- *   database.open(CONFIG.db.name, CONFIG.db.port);
- *   ...
- * 
- * - * @module config - * @class Config - */ - -/** - *

Get the configuration object.

- * - *

- * The configuration object is a shared singleton object within the application, - * attained by calling require('config'). - *

- * - *

- * Usually you'll specify a CONFIG variable at the top of your .js file - * for file/module scope. If you want the root of the object, you can do this: - *

- *
- * var CONFIG = require('config');
- * 
- * - *

- * Sometimes you only care about a specific sub-object within the CONFIG - * object. In that case you could do this at the top of your file: - *

- *
- * var CONFIG = require('config').customer;
- * or
- * var CUSTOMER_CONFIG = require('config').customer;
- * 
- * - * - * - * @method constructor - * @return CONFIG {object} - The top level configuration object - */ -var Config = function() { - var t = this; - - // Initialize parameters from command line, environment, or default - NODE_ENV = t._initParam('NODE_ENV', 'development'); - CONFIG_DIR = t._initParam('NODE_CONFIG_DIR', process.cwd() + '/config'); - if (CONFIG_DIR.indexOf('.') === 0) { - CONFIG_DIR = process.cwd() + '/' + CONFIG_DIR; - } - RUNTIME_JSON_FILENAME = t._initParam('NODE_CONFIG_RUNTIME_JSON', CONFIG_DIR + '/runtime.json'); - DISABLE_FILE_WATCH = t._initParam('NODE_CONFIG_DISABLE_FILE_WATCH'); - PERSIST_ON_CHANGE = t._initParam('NODE_CONFIG_PERSIST_ON_CHANGE'); - APP_INSTANCE = t._initParam('NODE_APP_INSTANCE'); - HOST = t._initParam('HOST'); - HOSTNAME = t._initParam('HOSTNAME'); - - t._loadFileConfigs(); - t._persistConfigsOnChange(); -}; - -/** - *

Monitor a configuration value for runtime changes.

- * - *

- * Configuration values can be changed at runtime by the application or by a - * manual change to the config/runtime.json file. - * This method lets you specify a function to run when a configuration - * value changes. - *

- * - *

- * This was built for monitoring changes to configuration values, - * but it can be used for watching changes to any javascript object. - *

- * - *

Example:

- *
- *   var CONFIG = require('config').customer;
- *   ...
- *
- *   // Watch for any changes to the customer configuration
- *   CONFIG.watch(CONFIG, null, function(object, propertyName, priorValue, newValue) {
- *    console.log("Customer configuration " + propertyName + " changed from " + priorValue + " to " + newValue);
- *   });
- * 
- * - * @method watch - * @param object {object} - The object to watch. - * @param property {string} - The property name to watch. Watch all object properties if null. - * @param handler {function(object, propertyName, priorValue, newValue)} - Handler called when a property change is detected. - * The handler is run along with other handlers registered for notification. - * If your handler changes the value of the property, that change is applied after all handlers have finished processing the current change. - * Then all handlers (including this one) will be called again with the newly changed value. - * @param depth {integer} (optional) - If watching all object properties or if the specified property is an object, this specifies the depth of the object graph to watch for changes. Default 6. - * @return object {object} - The original object is returned - for chaining. - */ -Config.prototype.watch = function(object, property, handler, depth) { - - // Initialize - var t = this, o = object; - var allProperties = property ? [property] : Object.keys(o); - - // Depth detection - depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth); - if (depth < 0) { - return; - } - - // Create hidden properties on the object - if (!o.__watchers) - t.makeHidden(o, '__watchers', {}); - if (!o.__propertyValues) - t.makeHidden(o, '__propertyValues', {}); - - // Attach watchers to all requested properties - allProperties.forEach(function(prop){ - - // Setup the property for watching (first time only) - if (typeof(o.__propertyValues[prop]) == 'undefined') { - - // Don't error re-defining the property if immutable - var descriptor = Object.getOwnPropertyDescriptor(o, prop); - if (descriptor && descriptor.writable === false) - return; - - // Copy the value to the hidden field, and add the property to watchers - o.__propertyValues[prop] = [o[prop]]; - o.__watchers[prop] = []; - - // Attach the property watcher - Object.defineProperty(o, prop, { - enumerable : true, - - get : function(){ - // If more than 1 item is in the values array, - // then we're currently processing watchers. - if (o.__propertyValues[prop].length == 1) - // Current value - return o.__propertyValues[prop][0]; - else - // [0] is prior value, [1] is new value being processed - return o.__propertyValues[prop][1]; - }, - - set : function(newValue) { - - // Return early if no change - var origValue = o[prop]; - if (t._equalsDeep(origValue, newValue)) - return; - - // Remember the new value, and return if we're in another setter - o.__propertyValues[prop].push(newValue); - if (o.__propertyValues[prop].length > 2) - return; - - // Call all watchers for each change requested - var numIterations = 0; - while (o.__propertyValues[prop].length > 1) { - - // Detect recursion - if (++numIterations > 20) { - o.__propertyValues[prop] = [origValue]; - throw new Error('Recursion detected while setting [' + prop + ']'); - } - - // Call each watcher for the current values - var oldValue = o.__propertyValues[prop][0]; - newValue = o.__propertyValues[prop][1]; - o.__watchers[prop].forEach(function(watcher) { - try { - watcher(o, prop, oldValue, newValue); - } catch (e) { - // Log an error and continue with subsequent watchers - console.error("Exception in object watcher for " + prop, e); - } - }); - - // Done processing this value - o.__propertyValues[prop].splice(0,1); - } - } - }); - - } // Done setting up the property for watching (first time) - - // Add the watcher to the property - o.__watchers[prop].push(handler); - - // Recurs if this is an object... - if (o[prop] && typeof(o[prop]) == 'object') { - Config.prototype.watch(o[prop], null, handler, depth - 1); - } - - }); // Done processing each property - - // Return the original object - for chaining - return o; -}; - -/** - *

- * Set default configurations for a node.js module. - *

- * - *

- * This allows module developers to attach their configurations onto the - * default configuration object so they can be configured by the consumers - * of the module. - *

- * - *

Using the function within your module:

- *
- *   var CONFIG = require("config");
- *   CONFIG.setModuleDefaults("MyModule", {
- *     templateName: "t-50",
- *     colorScheme: "green"
- *   });
- * 
- * // Template name may be overridden by application config files - * console.log("Template: " + CONFIG.MyModule.templateName); - *
- * - *

- * The above example results in a "MyModule" element of the configuration - * object, containing an object with the specified default values. - *

- * - * @method setModuleDefaults - * @param moduleName {string} - Name of your module. - * @param defaultProperties {object} - The default module configuration. - * @return moduleConfig {object} - The module level configuration object. - */ -Config.prototype.setModuleDefaults = function(moduleName, defaultProperties) { - - // Copy the properties into a new object - var t = this, - moduleConfig = t._extendDeep({}, defaultProperties); - - // Set module defaults into the first sources element - if (configSources.length === 0 || configSources[0].name !== 'Module Defaults') { - configSources.splice(0, 0, { - name: 'Module Defaults', - parsed: {} - }); - } - configSources[0].parsed[moduleName] = {}; - t._extendDeep(configSources[0].parsed[moduleName], defaultProperties); - - // Attach handlers & watchers onto the module config object - t._attachProtoDeep(moduleConfig); - t._persistConfigsOnChange(moduleConfig); - - // Extend the module config object with values from originalConfig - if (originalConfig[moduleName]) { - t._extendDeep(moduleConfig, originalConfig[moduleName]); - } - - // Save the mixed module config as the original - originalConfig[moduleName] = t._cloneDeep(moduleConfig); - - // Extend the module config object with values from runtimeJson - if (runtimeJson[moduleName]) { - t._extendDeep(moduleConfig, runtimeJson[moduleName]); - } - - // Attach the object onto the CONFIG object - t[moduleName] = moduleConfig; - - // Return the module config - return moduleConfig; -}; - -/** - *

Make a configuration property hidden so it doesn't appear when enumerating - * elements of the object.

- * - *

- * The property still exists and can be read from and written to, but it won't - * show up in for ... in loops, Object.keys(), or JSON.stringify() type methods. - *

- * - *

- * If the property already exists, it will be made hidden. Otherwise it will - * be created as a hidden property with the specified value. - *

- * - *

- * This method was built for hiding configuration values, but it can be applied - * to any javascript object. - *

- * - *

Example:

- *
- *   var CONFIG = require('config');
- *   ...
- *
- *   // Hide the Amazon S3 credentials
- *   CONFIG.makeHidden(CONFIG.amazonS3, 'access_id');
- *   CONFIG.makeHidden(CONFIG.amazonS3, 'secret_key');
- * 
- * - * @method makeHidden - * @param object {object} - The object to make a hidden property into. - * @param property {string} - The name of the property to make hidden. - * @param value {mixed} - (optional) Set the property value to this (otherwise leave alone) - * @return object {object} - The original object is returned - for chaining. - */ -Config.prototype.makeHidden = function(object, property, value) { - - // Use the existing value if the new value isn't specified - value = (typeof value == 'undefined') ? object[property] : value; - - // Create the hidden property - Object.defineProperty(object, property, { - value: value, - enumerable : false - }); - - return object; -} - -/** - *

Make a configuration property immutable (assuring it cannot be changed - * from the current value).

- * - *

- * This operation cannot be undone. - *

- *

- * - * This method was built for disabling runtime changes to configuration values, - * but it can be applied to any javascript object. - *

- * - *

Example:

- *
- *   var CONFIG = require('config').customer;
- *   ...
- *
- *   // Obtain a DB connection using CONFIG parameters
- *   database.open(CONFIG.db.name, CONFIG.db.port);
- *   ...
- *
- *   // Don't allow database changes after connect
- *   CONFIG.makeImmutable(CONFIG.db, 'name');
- *   CONFIG.makeImmutable(CONFIG.db, 'port');
- * 
- * - * @method makeImmutable - * @param object {object} - The object to attach an immutable property into. - * @param property {string} - The name of the property to make immutable. - * @param value {mixed} - (optional) Set the property value to this (otherwise leave alone) - * @return object {object} - The original object is returned - for chaining. - */ -Config.prototype.makeImmutable = function(object, property, value) { - - // Use the existing value if a new value isn't specified - value = (typeof value == 'undefined') ? object[property] : value; - - // Disable writing, and make sure the property cannot be re-configured. - Object.defineProperty(object, property, { - value : value, - writable : false, - configurable: false - }); - - return object; -}; - -/** - * Start or stop runtime.json configuration file watching - * - *

- * Node-config automatically monitors and apply changes made to the - * config/runtime.json file. This paradigm allows for manual changes to running - * application servers, and for multi-node application servers to keep in sync. - *

- * - *

- * This method allows you to change the polling interval from the default - * interval (2.5 seconds), or to turn file watching off. On Linux systems with - * inotify, and in node.js versions 0.6 and above, this interval is ignored. - *

- * - *

- * runtime.json file watching can be disabled by setting the NODE_CONFIG_DISABLE_FILE_WATCH - * environment variable or --NODE_CONFIG_DISABLE_FILE_WATCH command line parameter - * to "Y" prior to running your application. - *

- * - * @method watchForConfigFileChanges - * @param interval {Integer} - Polling interval in milliseconds. Defaults to 2500. - */ -Config.prototype.watchForConfigFileChanges = function(interval) { - - // Turn off any prior watching - var t = this, watchInterval = (typeof interval === 'undefined' ? FILE_WATCHER_INTERVAL : interval); - if (FileSystem.watch) { - if (runtimeJsonWatcher) { - runtimeJsonWatcher.close(); - runtimeJsonWatcher = null; - } - } else { - FileSystem.unwatchFile(RUNTIME_JSON_FILENAME); - } - - // If interval is zero or file watching is disabled, don't attach a new watcher - if (interval === 0 || DISABLE_FILE_WATCH === "Y") { - return; - } - - // Re-merge the runtime JSON file if we notice a change - var onFileChange = function(retry) { - FileSystem.readFile(RUNTIME_JSON_FILENAME, 'UTF-8', function(err, fileContent) { - - // Not much to do on error - if (err) { - console.error("Error loading " + RUNTIME_JSON_FILENAME, err); - return; - } - - // Parse the file and mix it in to this config object. - // This notifies listeners - try { - var configObject = JSON.parse(t._stripComments(fileContent)); - t._extendDeep(t, configObject); - } catch (e) { - console.error("Error parsing " + RUNTIME_JSON_FILENAME, e); - // Retry once - could be someone else writing - if (!retry) { - setTimeout(function(){ - onFileChange(true); - }, 1000); - } - return; - } - }); - }; - - // Use the latest version of file watching - try { - if (FileSystem.watch) { - // This is the latest - runtimeJsonWatcher = FileSystem.watch(RUNTIME_JSON_FILENAME, {persistent:false}, function(event, filename) { - - // Re-attach watcher on inode change (happens when some editors save a file) - // Wait for the O/S rename to complete, then re-watch the file - if (event == 'rename') { - setTimeout(function(){ - t.watchForConfigFileChanges(); - onFileChange(); - }, 10); - return; - } - - onFileChange(); - }); - } - else { - // Old style polling - only choice if running pre-6.0 - FileSystem.watchFile(RUNTIME_JSON_FILENAME, {persistent:false, interval:watchInterval}, function(curr, prev) { - if (curr.mtime.getTime() === prev.mtime.getTime()) {return;} - onFileChange(); - }); - } - } catch (e) { - // Complain if it exists and we can't watch it - if (e.code !== 'ENOENT') { - console.error("Error watching for file: " + RUNTIME_JSON_FILENAME, e); - } - } - -}; - -/** - *

Safely write a file

- * - *

- * This method safely overwrites a file by first writing to a temporary file - * and then renaming it. This to ensure no other process reads to file in a - * truncated state. - *

- * - * @method safeWriteFile - * @param filename {String} Filename to write to. - * @param content {String} Data to write. - * @param callback {Function} Callback function. - */ -Config.prototype.safeWriteFile = function(filename, data, callback) { - var rand = Math.floor(Math.random() * (1 << 30)), - tmpFilename = filename + '.tmp-' + rand; - - FileSystem.writeFile(tmpFilename, data, 'utf-8', function (err) { - if (err) { - return callback(err); - } - - FileSystem.rename(tmpFilename, filename, function (err) { - callback(err); - }); - }); -} - -/** - * Return the sources for the configurations - * - *

- * All sources for configurations are stored in an array of objects containing - * the source name (usually the filename), the original source (as a string), - * and the parsed source as an object. - *

- * - * @method getConfigSources - * @return configSources {Array[Object]} - An array of objects containing - * name, original, and parsed elements - */ -Config.prototype.getConfigSources = function() { - var t = this; - return configSources.slice(0); -}; - -/** - *

- * Watch the specified object for a change in properties, and persist changes - * to runtime.json when a change is detected. - *

- * - * @protected - * @param object {object} - The config object to watch - * @method _persistConfigsOnChange - */ -Config.prototype._persistConfigsOnChange = function(objectToWatch) { - - if (PERSIST_ON_CHANGE === 'N') { - return; - } - // Watch for configuration value changes - var t = this; - objectToWatch = objectToWatch || t; - t.watch(objectToWatch, null, function(){ - - // Return early if we're already queued up for persisting - if (isQueuedForPersistence) - return; - - // Defer persisting until the next tick. This results in a single - // persist across any number of config changes in a single event cycle. - isQueuedForPersistence = true; - process.nextTick(function(){ - - // Persist if necessary - var newDiffs = t._diffDeep(originalConfig, t); - if (!t._equalsDeep(newDiffs, runtimeJson)) { - t.safeWriteFile(RUNTIME_JSON_FILENAME, JSON.stringify(newDiffs, null, 2), function(error){ - if (error) - console.error("Error writing " + RUNTIME_JSON_FILENAME, error); - }); - } - - // Set up for next time - isQueuedForPersistence = false; - }); - }); -}; - -/** - * Load the individual file configurations. - * - *

- * This method builds a map of filename to the configuration object defined - * by the file. The search order is: - *

- * - *
- *   default.EXT
- *   (hostname).EXT
- *   (deployment).EXT
- *   (hostname)-(deployment).EXT
- *   local.EXT
- *   local-(deployment).EXT
- *   runtime.json
- * 
- * - *

- * EXT can be yml, yaml, coffee, json, or js signifying the file type. - * yaml (and yml) is in YAML format, coffee is a coffee-script, - * json is in JSON format, and js is a javascript executable file that is - * require()'d with module.exports being the config object. - *

- * - *

- * hostname is the $HOST environment variable (or --HOST command line parameter) - * if set, otherwise the $HOSTNAME environment variable (or --HOSTNAME command - * line parameter) if set, otherwise the hostname found from - * require('os').hostname(). - *

- * - *

- * Once a hostname is found, everything from the first period ('.') onwards - * is removed. For example, abc.example.com becomes abc - *

- * - *

- * (deployment) is the deployment type, found in the $NODE_ENV environment - * variable or --NODE_ENV command line parameter. Defaults to 'development'. - *

- * - *

- * The runtime.json file contains configuration changes made at runtime either - * manually, or by the application setting a configuration value. - *

- * - *

- * If the $NODE_APP_INSTANCE environment variable (or --NODE_APP_INSTANCE - * command line parameter) is set, then files with this appendage will be loaded. - * See the Multiple Applicstion Instances section of the main documentaion page - * for more information. - *

- * - * @protected - * @method _loadFileConfigs - * @return {this} The configuration object - */ -Config.prototype._loadFileConfigs = function() { - - // Initialize - var t = this; - - // Run only once - if (originalConfig) { - return t; - } - - // Determine the host name from the OS module, $HOST, or $HOSTNAME - // Remove any . appendages, and default to null if not set - try { - var hostName = HOST || HOSTNAME; - - if (!hostName) { - var OS = require('os'); - hostName = OS.hostname(); - } - } catch (e) { - hostName = ''; - } - hostName = hostName ? hostName.split('.')[0] : null; - - // Read each file in turn - var baseNames = ['default', hostName, NODE_ENV, hostName + '-' + NODE_ENV, 'local', 'local-' + NODE_ENV]; - var extNames = ['js', 'json', 'coffee', 'yaml', 'yml']; - baseNames.forEach(function(baseName) { - extNames.forEach(function(extName) { - - // Try merging the config object into this object - var fullFilename = CONFIG_DIR + '/' + baseName + '.' + extName; - var configObj = t._parseFile(fullFilename); - if (configObj) { - t._extendDeep(t, configObj); - } - - // See if the application instance file is available - if (APP_INSTANCE) { - fullFilename = CONFIG_DIR + '/' + baseName + '-' + APP_INSTANCE + '.' + extName; - configObj = t._parseFile(fullFilename); - if (configObj) { - t._extendDeep(t, configObj); - } - } - }); - }); - - // Override configurations with the old-style environment variables - // Warning: This will be deprecated in a future major revision release - var oldStyleEnv = t._loadOldStyleEnv(); - if (JSON.stringify(oldStyleEnv).length > 2) { - t._extendDeep(t, oldStyleEnv); - configSources.push({ - name: "Old-Style Environment Variables", - parsed: oldStyleEnv, - }); - console.log('\nWarning - old style $CONFIG_* environment configurations found. Convert to $NODE_CONFIG={JSON}') - } - - // Override configurations from the $NODE_CONFIG environment variable - if (process.env.NODE_CONFIG) { - var newStyleEnv = {}; - try { - newStyleEnv = JSON.parse(process.env.NODE_CONFIG); - } catch(e) { - console.error('The $NODE_CONFIG environment variable is malformed JSON'); - } - t._extendDeep(t, newStyleEnv); - configSources.push({ - name: "$NODE_CONFIG", - parsed: newStyleEnv, - }); - } - - // Override configurations from the --NODE_CONFIG command line - var cmdLineConfig = t._getCmdLineArg('NODE_CONFIG'); - if (cmdLineConfig) { - try { - cmdLineConfig = JSON.parse(cmdLineConfig); - } catch(e) { - console.error('The --NODE_CONFIG={json} command line argument is malformed JSON'); - } - t._extendDeep(t, cmdLineConfig); - configSources.push({ - name: "--NODE_CONFIG argument", - parsed: cmdLineConfig, - }); - } - - // Remember the original configuration (before adding runtimeJson) - originalConfig = t._cloneDeep(t); - - // Extend the original config with any prior runtime.json diffs - runtimeJson = t._parseFile(RUNTIME_JSON_FILENAME) || {}; - t._extendDeep(t, runtimeJson); - - // Attach the config.prototype to all sub-objects. - t._attachProtoDeep(t); - - // Return the configuration object - return t; -}; - -/** - * Check for the old-style environment variable configurations - * - * @protected - * @deprecated - * @method _loadOldStyleEnv - * @return {Object} old-style configurations from process.env - */ -Config.prototype._loadOldStyleEnv = function() { - var t = this, - envOverride = {}; - - for (var varName in process.env) { - if (varName.indexOf('CONFIG_') === 0) { - - // Get the string or numeric value - var value = process.env[varName], - floatVal = parseFloat(value), - value = floatVal.toString() === value ? floatVal : value; - - // Convert __ to ` (which you can't have in environment variables) - // After splitting, ` are converted to single underscores - varName = varName.replace(/__/g,'`'); - var parts = varName.split('_'); - parts.splice(0,1); // remove CONFIG - - var curCtxt = envOverride; - for (var i = 0, l = parts.length; i < l; i++) { - var partName = parts[i].replace(/`/g,'_'); - if (i == l - 1) { - // Final (element) part - curCtxt[partName] = value; - } - else { - // Mid (object) part - curCtxt[partName] = curCtxt[partName] || {}; - curCtxt = curCtxt[partName]; - } - } - } - } - return envOverride; -} - - -/** - * Parse and return the specified configuration file. - * - * If the file exists in the application config directory, it will - * parse and return it as a JavaScript object. - * - * The file extension determines the parser to use. - * - * .js = File to run that has a module.exports containing the config object - * .json = File is parsed using JSON.parse() - * .coffee = File to run that has a module.exports with coffee-script containing the config object - * .yaml (or .yml) = Parsed with a YAML parser - * - * If the file doesn't exist, a null will be returned. If the file can't be - * parsed, an exception will be thrown. - * - * This method performs synchronous file operations, and should not be called - * after synchronous module loading. - * - * @protected - * @method _parseFile - * @param fullFilename {string} The full file path and name - * @return {configObject} The configuration object parsed from the file - */ -Config.prototype._parseFile = function(fullFilename) { - - // Initialize - var t = this, - extension = fullFilename.substr(fullFilename.lastIndexOf('.') + 1), - configObject = null, - fileContent = null; - - // Make sure the runtime.json file exists. This is required for fs.watch(). - var checkRuntimeJson = function() { - if (fullFilename == RUNTIME_JSON_FILENAME) { - if (PERSIST_ON_CHANGE === 'N' && DISABLE_FILE_WATCH === 'Y') - return {}; - try { - FileSystem.writeFileSync(RUNTIME_JSON_FILENAME, '{}'); - } catch (e) { - // If we cannot write file, clear watch function. - t.watchForConfigFileChanges = function () { - return; - }; - } - return {}; - } - return null; - }; - - // Return null if the file doesn't exist. - // Note that all methods here are the Sync versions. This is appropriate during - // module loading (which is a synchronous operation), but not thereafter. - try { - var stat = FileSystem.statSync(fullFilename); - if (!stat || stat.size < 1) { - return checkRuntimeJson(); - } - } catch (e1) { - return checkRuntimeJson(); - } - - // Try loading the file. - try { - fileContent = FileSystem.readFileSync(fullFilename, 'UTF-8'); - } - catch (e2) { - throw new Error('Config file ' + fullFilename + ' cannot be read'); - } - - // Parse the file based on extension - try { - if (extension === 'yaml' || extension === 'yml') { - if (!Yaml && !VisionmediaYaml) { - // Lazy loading - try { - // Try to load the better js-yaml module - Yaml = require('js-yaml'); - } - catch (e) { - // If it doesn't exist, load the fallback visionmedia yaml module. - VisionmediaYaml = require('yaml'); - } - } - - if (Yaml) { - configObject = Yaml.load(t._stripYamlComments(fileContent)); - } - else if (VisionmediaYaml) { - // The yaml library doesn't like strings that have newlines but don't - // end in a newline: https://github.com/visionmedia/js-yaml/issues/issue/13 - fileContent += '\n'; - configObject = VisionmediaYaml.eval(t._stripYamlComments(fileContent)); - } - else { - console.error("No YAML parser loaded. Suggest adding js-yaml dependency to your package.json file.") - } - } - else if (extension == 'json') { - // Allow comments in JSON files - configObject = JSON.parse(t._stripComments(fileContent)); - } - else if (extension == 'js') { - // Use the built-in parser for .js files - configObject = require(fullFilename); - } - else if (extension == 'coffee') { - // Lazy load the coffee-script extension - Coffee = Coffee || require('coffee-script'); - // Use the built-in parser for .coffee files with coffee-script - configObject = require(fullFilename); - } - } - catch (e3) { - throw new Error("Cannot parse config file: '" + fullFilename + "': " + e3); - } - - // Keep track of this configuration source if it has anything in it - if (JSON.stringify(configObject).length > 2) { - configSources.push({ - name: fullFilename, - original: fileContent, - parsed: configObject, - }); - } - - return configObject; -}; - -/** - * Attach the Config class prototype to all config objects recursively. - * - *

- * This allows you to do anything with CONFIG sub-objects as you can do with - * the top-level CONFIG object. It's so you can do this: - *

- * - *
- *   var CUST_CONFIG = require('config').Customer;
- *   CUST_CONFIG.watch(...)
- * 
- * - * @protected - * @method _attachProtoDeep - * @param toObject - * @param depth - * @return toObject - */ -Config.prototype._attachProtoDeep = function(toObject, depth) { - - // Recursion detection - var t = this; - depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth); - if (depth < 0) { - return toObject; - } - - // Adding Config.prototype methods directly to toObject as hidden properties - // because adding to toObject.__proto__ exposes the function in toObject - for (var fnName in Config.prototype) { - t.makeHidden(toObject, fnName, Config.prototype[fnName]); - } - - // Cycle through each element - for (var prop in toObject) { - - // Call recursively if an object - if (t._isObject(toObject[prop])) { - t._attachProtoDeep(toObject[prop], depth - 1); - } - } - - // Return the original object - return toObject; - -}; - -/** - * Return a deep copy of the specified object. - * - * This returns a new object with all elements copied from the specified - * object. Deep copies are made of objects and arrays so you can do anything - * with the returned object without affecting the input object. - * - * @protected - * @method _cloneDeep - * @param copyFrom {object} The original object to copy from - * @param depth {integer} An optional depth to prevent recursion. Default: 20. - * @return {object} A new object with the elements copied from the copyFrom object - */ -Config.prototype._cloneDeep = function(obj, depth) { - - // Recursion detection - var t = this; - depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth); - if (depth < 0) { - return {}; - } - - // Create the copy of the correct type - var copy = Array.isArray(obj) ? [] : {}; - - // Cycle through each element - for (var prop in obj) { - - // Call recursively if an object or array - if (obj[prop] && typeof obj[prop] == 'object') { - copy[prop] = t._cloneDeep(obj[prop], depth - 1); - } - else { - copy[prop] = obj[prop]; - } - } - - // Return the copied object - return copy; - -}; - -/** - * Return true if two objects have equal contents. - * - * @protected - * @method _equalsDeep - * @param object1 {object} The object to compare from - * @param object2 {object} The object to compare with - * @param depth {integer} An optional depth to prevent recursion. Default: 20. - * @return {boolean} True if both objects have equivalent contents - */ -Config.prototype._equalsDeep = function(object1, object2, depth) { - - // Recursion detection - var t = this; - depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth); - if (depth < 0) { - return {}; - } - - // Fast comparisons - if (!object1 || !object2) { - return false; - } - if (object1 === object2) { - return true; - } - if (typeof(object1) != 'object' || typeof(object2) != 'object') { - return false; - } - - // They must have the same keys. If their length isn't the same - // then they're not equal. If the keys aren't the same, the value - // comparisons will fail. - if (Object.keys(object1).length != Object.keys(object2).length) { - return false; - } - - // Compare the values - for (var prop in object1) { - - // Call recursively if an object or array - if (object1[prop] && typeof(object1[prop]) === 'object') { - if (!t._equalsDeep(object1[prop], object2[prop], depth - 1)) { - return false; - } - } - else { - if (object1[prop] !== object2[prop]) { - return false; - } - } - } - - // Test passed. - return true; -}; - -/** - * Returns an object containing all elements that differ between two objects. - *

- * This method was designed to be used to create the runtime.json file - * contents, but can be used to get the diffs between any two Javascript objects. - *

- *

- * It works best when object2 originated by deep copying object1, then - * changes were made to object2, and you want an object that would give you - * the changes made to object1 which resulted in object2. - *

- * - * @protected - * @method _diffDeep - * @param object1 {object} The base object to compare to - * @param object2 {object} The object to compare with - * @param depth {integer} An optional depth to prevent recursion. Default: 20. - * @return {object} A differential object, which if extended onto object1 would - * result in object2. - */ -Config.prototype._diffDeep = function(object1, object2, depth) { - - // Recursion detection - var t = this, diff = {}; - depth = (depth === null ? DEFAULT_CLONE_DEPTH : depth); - if (depth < 0) { - return {}; - } - - // Process each element from object2, adding any element that's different - // from object 1. - for (var parm in object2) { - var value1 = object1[parm]; - var value2 = object2[parm]; - if (value1 && value2 && t._isObject(value2)) { - if (!(t._equalsDeep(value1, value2))) { - diff[parm] = t._diffDeep(value1, value2, depth - 1); - } - } - else if (Array.isArray(value1) && Array.isArray(value2)) { - if(!t._equalsDeep(value1, value2)) { - diff[parm] = value2; - } - } - else if (value1 !== value2){ - diff[parm] = value2; - } - } - - // Return the diff object - return diff; - -}; - -/** - * Extend an object, and any object it contains. - * - * This does not replace deep objects, but dives into them - * replacing individual elements instead. - * - * @protected - * @method _extendDeep - * @param mergeInto {object} The object to merge into - * @param mergeFrom... {object...} - Any number of objects to merge from - * @param depth {integer} An optional depth to prevent recursion. Default: 20. - * @return {object} The altered mergeInto object is returned - */ -Config.prototype._extendDeep = function(mergeInto) { - - // Initialize - var t = this; - var vargs = Array.prototype.slice.call(arguments, 1); - var depth = vargs.pop(); - if (typeof(depth) != 'number') { - vargs.push(depth); - depth = DEFAULT_CLONE_DEPTH; - } - - // Recursion detection - if (depth < 0) { - return mergeInto; - } - - // Cycle through each object to extend - vargs.forEach(function(mergeFrom) { - - // Cycle through each element of the object to merge from - for (var prop in mergeFrom) { - - // Extend recursively if both elements are objects - if (t._isObject(mergeInto[prop]) && t._isObject(mergeFrom[prop])) { - t._extendDeep(mergeInto[prop], mergeFrom[prop], depth - 1); - } - - // Copy recursively if the mergeFrom element is an object (or array or fn) - else if (mergeFrom[prop] && typeof mergeFrom[prop] == 'object') { - mergeInto[prop] = t._cloneDeep(mergeFrom[prop], depth - 1); - } - - // Simple assignment otherwise - else { - mergeInto[prop] = mergeFrom[prop]; - } - } - }); - - // Chain - return mergeInto; - -}; - -/** - * Strip YAML comments from the string - * - * The 2.0 yaml parser doesn't allow comment-only or blank lines. Strip them. - * - * @protected - * @method _stripYamlComments - * @param fileString {string} The string to strip comments from - * @return {string} The string with comments stripped. - */ -Config.prototype._stripYamlComments = function(fileStr) { - // First replace removes comment-only lines - // Second replace removes blank lines - return fileStr.replace(/^\s*#.*/mg,'').replace(/^\s*[\n|\r]+/mg,''); -} - -/** - * Strip all Javascript type comments from the string. - * - * The string is usually a file loaded from the O/S, containing - * newlines and javascript type comments. - * - * Thanks to James Padolsey, and all who conributed to this implementation. - * http://james.padolsey.com/javascript/javascript-comment-removal-revisted/ - * - * @protected - * @method _stripComments - * @param fileString {string} The string to strip comments from - * @return {string} The string with comments stripped. - */ -Config.prototype._stripComments = function(fileStr) { - - var uid = '_' + +new Date(), - primitives = [], - primIndex = 0; - - return ( - fileStr - - /* Remove strings */ - .replace(/(['"])(\\\1|.)+?\1/g, function(match){ - primitives[primIndex] = match; - return (uid + '') + primIndex++; - }) - - /* Remove Regexes */ - .replace(/([^\/])(\/(?!\*|\/)(\\\/|.)+?\/[gim]{0,3})/g, function(match, $1, $2){ - primitives[primIndex] = $2; - return $1 + (uid + '') + primIndex++; - }) - - /* - - Remove single-line comments that contain would-be multi-line delimiters - E.g. // Comment /* <-- - - Remove multi-line comments that contain would be single-line delimiters - E.g. /* // <-- - */ - .replace(/\/\/.*?\/?\*.+?(?=\n|\r|$)|\/\*[\s\S]*?\/\/[\s\S]*?\*\//g, '') - - /* - Remove single and multi-line comments, - no consideration of inner-contents - */ - .replace(/\/\/.+?(?=\n|\r|$)|\/\*[\s\S]+?\*\//g, '') - - /* - Remove multi-line comments that have a replaced ending (string/regex) - Greedy, so no inner strings/regexes will stop it. - */ - .replace(RegExp('\\/\\*[\\s\\S]+' + uid + '\\d+', 'g'), '') - - /* Bring back strings & regexes */ - .replace(RegExp(uid + '(\\d+)', 'g'), function(match, n){ - return primitives[n]; - }) - ); - -}; - -/** - * Is the specified argument a regular javascript object? - * - * The argument is an object if it's a JS object, but not an array. - * - * @protected - * @method _isObject - * @param arg {MIXED} An argument of any type. - * @return {boolean} TRUE if the arg is an object, FALSE if not - */ -Config.prototype._isObject = function(obj) { - return (obj !== null) && (typeof obj == 'object') && !(Array.isArray(obj)); -}; - -/** - *

Exposing original Config

- * - *

- * This method allows get the original config properties. - *

- * - * @method getOriginalConfig - * @return {object} The original config object is returned - */ -Config.prototype.getOriginalConfig = function() { - return originalConfig; -} - -/** - *

Reset Runtime Config

- * - *

- * This method allows you to reset the runtime.json generated file. - *

- * - * @method resetRuntime - * @param callback {function} An optional callback function - */ -Config.prototype.resetRuntime = function(callback) { - this.safeWriteFile(RUNTIME_JSON_FILENAME, '{}', function(err, written, buffer) { - if(err) { - console.log("Cannot write runtime.json file " + err); - if (callback && typeof(callback) === 'function') { - callback(err); - } - return; - } - if (callback && typeof(callback) === 'function') { - callback(null, written, buffer); - } - }); -} - -/** - *

Initialize a parameter from the command line or process environment

- * - *

- * This method looks for the parameter from the command line in the format - * --PARAMETER=VALUE, then from the process environment, then from the - * default specified as an argument. - *

- * - * @method _initParam - * @param paramName {String} Name of the parameter - * @param [defaultValue] {Any} Default value of the parameter - * @return {Any} The found value, or default value - */ -Config.prototype._initParam = function (paramName, defaultValue) { - var t = this; - return t._getCmdLineArg(paramName) || process.env[paramName] || defaultValue; -} - -/** - *

Get Command Line Arguments

- * - *

- * This method allows you to retrieve the value of the specified command line argument. - *

- * - *

- * The argument is case sensitive, and must be of the form '--ARG_NAME=value' - *

- * - * @method _getCmdLineArg - * @param searchFor {STRING} The argument name to search for - * @return {MIXED} FALSE if the argument was not found, the argument value if found - */ -Config.prototype._getCmdLineArg = function (searchFor) { - var cmdLineArgs = process.argv.slice(2, process.argv.length), - argName = '--' + searchFor + '='; - - for (var argvIt = 0; argvIt < cmdLineArgs.length; argvIt++) { - if (cmdLineArgs[argvIt].indexOf(argName) === 0) { - return cmdLineArgs[argvIt].substr(argName.length); - } - } - - return false; -} - -// Assure the configuration object is a singleton. -global.NODE_CONFIG = global.NODE_CONFIG ? global.NODE_CONFIG : new Config(); - -// The module exports a singleton instance of the Config class so the -// instance is immediately available on require(), and the prototype methods -// aren't a part of the object namespace when inspected. -module.exports = global.NODE_CONFIG; - -// Watch for configuration file changes -global.NODE_CONFIG.watchForConfigFileChanges(); diff --git a/node_modules/config/package.json b/node_modules/config/package.json deleted file mode 100644 index 726d947..0000000 --- a/node_modules/config/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "config", - "version": "0.4.36", - "main": "./lib/config.js", - "description": "Configuration control for production node deployments", - "author": { - "name": "Loren West", - "email": "open_source@lorenwest.com" - }, - "homepage": "http://lorenwest.github.com/node-config", - "directories": { - "lib": "./lib", - "config": "./config", - "test": "./test" - }, - "licenses": [ - "MIT" - ], - "dependencies": {}, - "devDependencies": { - "js-yaml": "2.1.x", - "coffee-script": ">=1.2.0 <1.7.0", - "vows": ">=0.5.13" - }, - "repository": { - "type": "git", - "url": "http://github.com/lorenwest/node-config.git" - }, - "engines": { - "node": ">0.4.x" - }, - "scripts": { - "test": "./node_modules/vows/bin/vows test/*.js --spec" - }, - "bugs": { - "url": "https://github.com/lorenwest/node-config/issues" - }, - "_id": "config@0.4.36", - "dist": { - "shasum": "02af1237f519c00f1e3aac22f9a034148fc3e786", - "tarball": "http://registry.npmjs.org/config/-/config-0.4.36.tgz" - }, - "_from": "config@0.4.36", - "_npmVersion": "1.3.14", - "_npmUser": { - "name": "lorenwest", - "email": "npm@lorenwest.com" - }, - "maintainers": [ - { - "name": "lorenwest", - "email": "npm@lorenwest.com" - } - ], - "_shasum": "02af1237f519c00f1e3aac22f9a034148fc3e786", - "_resolved": "https://registry.npmjs.org/config/-/config-0.4.36.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/node_modules/config/test/1-protected-test.js b/node_modules/config/test/1-protected-test.js deleted file mode 100644 index e5bb1ac..0000000 --- a/node_modules/config/test/1-protected-test.js +++ /dev/null @@ -1,382 +0,0 @@ -/** - *

Unit tests

- * - * @module test - */ - -// Change the configuration directory for testing -process.env.NODE_CONFIG_DIR = __dirname + '/config'; - -// Hardcode $NODE_ENV=test for testing -process.env.NODE_ENV='test'; - -// Test for multi-instance applications -process.env.NODE_APP_INSTANCE='3'; - -// Test for old style environment variable overrides -process.env.CONFIG_EnvOverride_parm__number__1 = 'overridden from test'; -process.env.CONFIG_EnvOverride_parm2 = 13; - -// Test $NODE_CONFIG environment and --NODE_CONFIG command line parameter -process.env.NODE_CONFIG='{"EnvOverride":{"parm3":"overridden from $NODE_CONFIG","parm4":100}}' -process.argv.push('--NODE_CONFIG={"EnvOverride":{"parm5":"overridden from --NODE_CONFIG","parm6":101}}'); - -// Dependencies -var CONFIG = require('../lib/config'); -var vows = require('vows'); -var assert = require('assert'); - -// Make a copy of the command line args -var argvOrg = process.argv; - -/** - *

Tests for underlying node-config utilities. To run type:

- *
npm test
- *

Or, in a project that uses node-config:

- *
npm test config
- * - * @class ProtectedTest - */ -exports.PrivateTest = vows.describe('Protected (hackable) utilities test').addBatch({ - 'Library initialization': { - 'Library is available': function() { - assert.isObject(CONFIG); - } - }, - - '_isObject() tests': { - 'The function exists': function() { - assert.isFunction(CONFIG._isObject); - }, - 'Correctly identifies objects': function() { - assert.isTrue(CONFIG._isObject({A:"b"})); - }, - 'Correctly excludes non-objects': function() { - assert.isFalse(CONFIG._isObject("some string")); - assert.isFalse(CONFIG._isObject(45)); - assert.isFalse(CONFIG._isObject([2, 3])); - assert.isFalse(CONFIG._isObject(["a", "b"])); - assert.isFalse(CONFIG._isObject(null)); - assert.isFalse(CONFIG._isObject(undefined)); - } - }, - - '_cloneDeep() tests': { - topic: function() { - // Return an object for copy tests - return { - elem0:true, - elem1:"Element 1", - elem2:2, - elem3:[1,2,3], - elem4:function(){return "hello";}, - elem5:{sub1:"sub 1",sub2:2,sub3:[1,2,3]} - }; - }, - 'The function exists': function() { - assert.isFunction(CONFIG._cloneDeep); - }, - 'Original and copy should test equivalent (deep)': function(orig) { - var copy = CONFIG._cloneDeep(orig); - assert.deepEqual(copy, orig); - }, - 'The objects should be different': function(orig) { - var copy = CONFIG._cloneDeep(orig); - copy.elem1 = false; - assert.notDeepEqual(copy, orig); - }, - 'Object clones should be objects': function(orig) { - assert.isObject(CONFIG._cloneDeep({a:1, b:2})); - }, - 'Array clones should be arrays': function(orig) { - assert.isArray(CONFIG._cloneDeep(["a", "b", 3])); - }, - 'Arrays should be copied by value, not by reference': function(orig) { - var copy = CONFIG._cloneDeep(orig); - assert.deepEqual(copy, orig); - copy.elem3[0] = 2; - // If the copy wasn't deep, elem3 would be the same object - assert.notDeepEqual(copy, orig); - }, - 'Objects should be copied by value, not by reference': function(orig) { - var copy = CONFIG._cloneDeep(orig); - copy.elem5.sub2 = 3; - assert.notDeepEqual(copy, orig); - copy = CONFIG._cloneDeep(orig); - copy.elem5.sub3[1] = 3; - assert.notDeepEqual(copy, orig); - } - }, - - '_extendDeep() tests': { - 'The function exists': function() { - assert.isFunction(CONFIG._extendDeep); - }, - 'Performs normal extend': function() { - var orig = {elem1:"val1", elem2:"val2"}; - var extWith = {elem3:"val3"}; - var shouldBe = {elem1:"val1", elem2:"val2", elem3:"val3"}; - assert.deepEqual(CONFIG._extendDeep(orig, extWith), shouldBe); - }, - 'Replaces non-objects': function() { - var orig = {elem1:"val1", elem2:["val2","val3"],elem3:{sub1:"val4"}}; - var extWith = {elem1:1,elem2:["val4"],elem3:"val3"}; - var shouldBe = {elem1:1, elem2:["val4"],elem3:"val3"}; - assert.deepEqual(CONFIG._extendDeep(orig, extWith), shouldBe); - }, - 'Merges objects': function() { - var orig = {e1:"val1", elem2:{sub1:"val4",sub2:"val5"}}; - var extWith = {elem2:{sub2:"val6",sub3:"val7"}}; - var shouldBe = {e1:"val1", elem2:{sub1:"val4",sub2:"val6",sub3:"val7"}}; - assert.deepEqual(CONFIG._extendDeep(orig, extWith), shouldBe); - }, - 'Correctly types new objects and arrays': function() { - var orig = {e1:"val1", e3:["val5"]}; - var extWith = {e2:{elem1:"val1"}, e3:["val6","val7"]}; - var shouldBe = {e1:"val1", e2:{elem1:"val1"}, e3:["val6","val7"]}; - var ext = CONFIG._extendDeep({}, orig, extWith); - assert.isObject(ext.e2); - assert.isArray(ext.e3); - }, - 'Keeps non-merged objects intact': function() { - var orig = {e1:"val1", elem2:{sub1:"val4",sub2:"val5"}}; - var shouldBe = {e1:"val1", elem2:{sub1:"val4",sub2:"val5"}}; - var extWith = {elem3:{sub2:"val6",sub3:"val7"}}; - CONFIG._extendDeep({}, orig, extWith); - assert.deepEqual(orig, shouldBe); - } - }, - - '_equalsDeep() tests': { - 'The function exists': function() { - assert.isFunction(CONFIG._equalsDeep); - }, - 'Succeeds on two empty objects': function() { - assert.isTrue(CONFIG._equalsDeep({}, {})); - }, - 'Succeeds on array comparisons': function() { - assert.isTrue(CONFIG._equalsDeep([1,'hello',2], [1,'hello',2])); - }, - 'Succeeds on the same object': function() { - var a = {hello:'world'}; - assert.isTrue(CONFIG._equalsDeep(a, a)); - }, - 'Succeeds on a regular object': function() { - var a = {value_3: 14, hello:'world', value_1: 29}; - var b = {value_1: 29, hello:'world', value_3: 14}; - assert.isTrue(CONFIG._equalsDeep(a, b)); - }, - 'Succeeds on a deep object': function() { - var a = {value_3: 14, hello:'world', value_1: 29, value_4:['now','is','the','time']}; - var b = {value_1: 29, hello:'world', value_3: 14, value_4:['now','is','the','time']}; - var c = {creditLimit: 10000, deepValue: a}; - var d = {deepValue: b, creditLimit:10000}; - assert.isTrue(CONFIG._equalsDeep(c, d)); - }, - 'Fails if either object is null': function() { - assert.isFalse(CONFIG._equalsDeep({}, null)); - assert.isFalse(CONFIG._equalsDeep(null, {})); - assert.isFalse(CONFIG._equalsDeep(null, null)); - }, - 'Fails if either object is undefined': function() { - var a = {}; - assert.isFalse(CONFIG._equalsDeep({})); - assert.isFalse(CONFIG._equalsDeep(a['noElement'], {})); - }, - 'Fails if either object is undefined': function() { - var a = {}; - assert.isFalse(CONFIG._equalsDeep({})); - assert.isFalse(CONFIG._equalsDeep(a['noElement'], {})); - }, - 'Fails if object1 has more elements': function() { - var a = {value_3: 14, hello:'world', value_1: 29, otherElem: 40}; - var b = {value_1: 29, hello:'world', value_3: 14}; - assert.isFalse(CONFIG._equalsDeep(a, b)); - }, - 'Fails if object2 has more elements': function() { - var a = {value_1: 29, hello:'world', value_3: 14}; - var b = {value_3: 14, hello:'world', value_1: 29, otherElem: 40}; - assert.isFalse(CONFIG._equalsDeep(a, b)); - }, - 'Fails if any value is different': function() { - var a = {value_1: 30, hello:'world', value_3: 14, value_4:['now','is','the','time']}; - var b = {value_1: 29, hello:'world', value_3: 14, value_4:['now','is','the','time']}; - assert.isFalse(CONFIG._equalsDeep(a, b)); - var a = {value_1: 29, hello:'world', value_3: 14, value_4:['now','is','the','time']}; - var b = {value_1: 29, hello:'world', value_3: 14, value_4:['now','isnt','the','time']}; - assert.isFalse(CONFIG._equalsDeep(a, b)); - } - }, - - '_diffDeep() tests': { - 'The function exists': function() { - assert.isFunction(CONFIG._diffDeep); - }, - 'Returns an empty object if no differences': function() { - var a = {value_3: 14, hello:'world', value_1: 29}; - var b = {value_1: 29, hello:'world', value_3: 14}; - assert.equal(typeof(CONFIG._diffDeep(a,b)), 'object'); - assert.isTrue(Object.keys(CONFIG._diffDeep(a, b)).length == 0); - }, - 'Returns an empty object if no differences (deep)': function() { - var a = {value_3: 14, hello:'world', value_1: 29, value_4:[1,'hello',2], deepObj:{a:22,b:{c:45,a:44}}}; - var b = {value_1: 29, hello:'world', value_3: 14, value_4:[1,'hello',2], deepObj:{a:22,b:{a:44,c:45}}}; - assert.equal(typeof(CONFIG._diffDeep(a,b)), 'object'); - assert.isTrue(Object.keys(CONFIG._diffDeep(a, b)).length == 0); - }, - 'Returns just the diff values': function() { - var a = {value_3: 14, hello:'wurld', value_1: 29, deepObj:{a:22,b:{c:45,a:44}}}; - var b = {value_1: 29, hello:'world', value_3: 14, deepObj:{a:22,b:{a:44,c:45}}}; - var diff = CONFIG._diffDeep(a,b); - assert.equal(Object.keys(diff).length, 1); - assert.equal(diff.hello, 'world'); - }, - 'Returns just the diff values (deep)': function() { - var a = {value_3: 14, hello:'wurld', value_1: 29, value_4:[1,'hello',2], deepObj:{a:22,b:{c:45,a:44}}}; - var b = {value_1: 29, hello:'wurld', value_3: 14, value_4:[1,'goodbye',2], deepObj:{a:22,b:{a:45,c:44}}}; - var diff = CONFIG._diffDeep(a,b); - assert.equal(Object.keys(diff).length, 2); - assert.equal(Object.keys(diff.deepObj).length, 1); - assert.equal(Object.keys(diff.deepObj.b).length, 2); - assert.equal(diff.deepObj.b.a, 45); - assert.equal(diff.deepObj.b.c, 44); - assert.deepEqual(diff.value_4, [1, 'goodbye', 2]); - } - }, - - '_stripComments() tests': { - // Only testing baseline stripComments functionality. - // This implementation handles lots of edge cases that aren't in these tests - 'The function exists': function() { - assert.isFunction(CONFIG._stripComments); - }, - 'Leaves a simple string without comments alone': function() { - var str = "Hello\nWorld"; - assert.equal(CONFIG._stripComments(str), str); - }, - 'Strips out line-type comments': function() { - var str1 = "var a='Hello'; // Comment about the a variable"; - var str2 = "var a='Hello'; "; - assert.equal(CONFIG._stripComments(str1), str2); - }, - 'Strips out block-type comments': function() { - var str1 = "var a='Hello';/* Block Comment */ var b=24"; - var str2 = "var a='Hello'; var b=24"; - assert.equal(CONFIG._stripComments(str1), str2); - }, - 'Strips out multi-line block comments': function() { - var str1 = "var a='Hello';\n/* Block Comment\n Line 2 comment\n*/\nvar b=24"; - var str2 = "var a='Hello';\n\nvar b=24"; - assert.equal(CONFIG._stripComments(str1), str2); - } - }, - - '_parseFile() tests': { - topic: function() { - return CONFIG._parseFile(__dirname + '/config/default.yaml'); - }, - 'The function exists': function() { - assert.isFunction(CONFIG._parseFile); - }, - 'An object is returned': function(config) { - assert.isObject(config); - }, - 'The correct object is returned': function(config) { - assert.isObject(config.Customers); - assert.isTrue(config.Customers.dbName == 'from_default_yaml'); - assert.isTrue(config.Customers.dbPort == 5984); - assert.isObject(config.AnotherModule); - assert.isTrue(config.AnotherModule.parm2 == "value2"); - } - }, - - '_loadFileConfigs() tests': { - topic: function() { - return CONFIG._loadFileConfigs(); - }, - 'The function exists': function() { - assert.isFunction(CONFIG._loadFileConfigs); - }, - 'An object is returned': function(configs) { - assert.isObject(configs); - }, - 'The correct object is returned': function(config) { - assert.isObject(config.Customers); - assert.isTrue(config.Customers.dbHost == 'base'); - assert.isTrue(config.Customers.dbName == 'override_from_runtime_json'); - } - }, - - '_attachProtoDeep() tests': { - topic: function() { - // Create an object that contains other objects to see - // that the prototype is added to all objects. - var watchThis = { - subObject: { - item1: 23, - subSubObject: { - item2: "hello" - } - } - }; - return CONFIG._attachProtoDeep(watchThis); - }, - 'The function exists': function() { - assert.isFunction(CONFIG._attachProtoDeep); - }, - 'The original object is returned': function(config) { - assert.isObject(config); - assert.isTrue(config.subObject.item1 === 23); - assert.isTrue(config.subObject.subSubObject.item2 === "hello"); - }, - 'The _cloneDeep method is attached to the object': function(config) { - assert.isTrue({a:27}.a == config._cloneDeep({a:27}).a); - }, - 'The _cloneDeep method is also attached to sub-objects': function(config) { - assert.isTrue({a:27}.a == config.subObject._cloneDeep({a:27}).a); - assert.isTrue({a:27}.a == config.subObject.subSubObject._cloneDeep({a:27}).a); - }, - 'Prototype methods are not exposed in the object': function(config) { - // This test is here because altering object.__proto__ places the method - // directly onto the object. That caused problems when iterating over the - // object. This implementation does the same thing, but hides them. - assert.isTrue(JSON.stringify(config) == '{"subObject":{"item1":23,"subSubObject":{"item2":"hello"}}}'); - } - }, - - '_getCmdLineArg() tests': { - topic: function() { - // Set process.argv example object - var testArgv = [ - process.argv[0], - process.argv[1], - '--NODE_ENV=staging' - ]; - process.argv = testArgv; - return CONFIG._getCmdLineArg('NODE_ENV'); - }, - 'The function exists': function() { - assert.isFunction(CONFIG._getCmdLineArg); - }, - 'NODE_ENV should be staging': function(nodeEnv) { - assert.equal(nodeEnv, 'staging'); - }, - 'Returns false if the argument did not match': function() { - assert.isFalse(CONFIG._getCmdLineArg('NODE_CONFIG_DIR')); - }, - 'Returns the argument (alternative syntax)': function() { - process.argv.push('--NODE_CONFIG_DIR=/etc/nodeConfig'); - assert.equal(CONFIG._getCmdLineArg('NODE_CONFIG_DIR'), '/etc/nodeConfig'); - }, - 'Returns always the first matching': function() { - process.argv.push('--NODE_ENV=test'); - assert.equal(CONFIG._getCmdLineArg('NODE_ENV'), 'staging'); - }, - 'Revert original process aruments': function() { - assert.notEqual(process.argv, argvOrg); - process.argv = argvOrg; - assert.equal(process.argv, argvOrg); - } - } - -}); diff --git a/node_modules/config/test/2-config-test.js b/node_modules/config/test/2-config-test.js deleted file mode 100644 index da8edd0..0000000 --- a/node_modules/config/test/2-config-test.js +++ /dev/null @@ -1,352 +0,0 @@ -// Change the configuration directory for testing -process.env.NODE_CONFIG_DIR = __dirname + '/config'; - -// Hardcode $NODE_ENV=test for testing -process.env.NODE_ENV='test'; - -// Test for multi-instance applications -process.env.NODE_APP_INSTANCE='3'; - -// Test for old style environment variable overrides -process.env.CONFIG_EnvOverride_parm__number__1 = 'overridden from test'; -process.env.CONFIG_EnvOverride_parm2 = 13; - -// Test $NODE_CONFIG environment and --NODE_CONFIG command line parameter -process.env.NODE_CONFIG='{"EnvOverride":{"parm3":"overridden from $NODE_CONFIG","parm4":100}}' -process.argv.push('--NODE_CONFIG={"EnvOverride":{"parm5":"overridden from --NODE_CONFIG","parm6":101}}'); - -// Dependencies -var vows = require('vows'); - assert = require('assert'), - CONFIG = require('../lib/config'), - FileSystem = require('fs'), - originalWatchedValue = CONFIG.watchThisValue, - newWatchedValue = Math.floor(Math.random() * 100000), - originalDynamicArray = CONFIG.dynamicArray, - newDynamicArray = [Math.floor(Math.random() * 100000), Math.floor(Math.random() * 100000)]; - -var runtimeJsonFilename = __dirname + '/config/runtime.json'; -var runtimeJsonFilenameBak = runtimeJsonFilename+'.bak'; - -/** - *

Unit tests for the node-config library. To run type:

- *
npm test
- *

Or, in a project that uses node-config:

- *
npm test config
- * - * @class ConfigTest - */ -exports.ConfigTest = vows.describe('Test suite for node-config').addBatch({ - 'Library initialization': { - 'Config library is available': function() { - assert.isObject(CONFIG); - }, - 'Config extensions are included with the library': function() { - assert.isFunction(CONFIG._cloneDeep); - } - }, - - 'Configuration file Tests': { - topic: function() { - return CONFIG; - }, - - 'Loading configurations from a JS module is correct': function() { - assert.equal(CONFIG.Customers.dbHost, 'base'); - assert.equal(CONFIG.TestModule.parm1, 'value1'); - }, - - 'Loading configurations from a JSON file is correct': function() { - assert.equal(CONFIG.AnotherModule.parm1, 'value1'); - }, - - 'Loading configurations from a .yaml YAML file is correct': function() { - assert.equal(CONFIG.AnotherModule.parm2, 'value2'); - }, - - 'Loading configurations from a .yml YAML file is correct': function() { - assert.equal(CONFIG.AnotherModule.parm2yml, 'value2yml'); - }, - - 'Loading configurations from a Coffee-Script file is correct': function() { - assert.equal(CONFIG.AnotherModule.parm3, 'value3'); - }, - - 'Loading configurations from an environment file is correct': function() { - assert.equal(CONFIG.Customers.dbPort, '5999'); - }, - - 'Loading configurations from the local file is correct': function() { - assert.equal(CONFIG.Customers.dbPassword, 'real password'); - }, - - 'Loading configurations from the local environment file is correct': function() { - assert.equal(CONFIG.Customers.dbPassword2, 'another password'); - assert.deepEqual(CONFIG.Customers.lang, ['en','de','es']); - }, - - 'Loading prior runtime.json configurations is correct': function() { - assert.equal(CONFIG.Customers.dbName, 'override_from_runtime_json'); - }, - - 'Multi-instance default.json override is correct': function() { - assert.equal(CONFIG.Customers.altDbPort, 4400); - }, - - 'Multi-instance local.yaml override is correct': function() { - assert.equal(CONFIG.Customers.altDbPort1, 2209); - } - - }, - - 'Old-Style Configurations from environment variables (deprecated)': { - topic: function() { - return CONFIG; - }, - - 'Configuration can come from environment variables': function() { - assert.equal(CONFIG.EnvOverride.parm2, 13); - }, - - 'Double__underscores escape to single_underscores': function() { - - JSON.stringify(CONFIG, null, 2); - assert.equal(CONFIG.EnvOverride.parm_number_1, 'overridden from test'); - } - }, - - 'Configurations from the $NODE_CONFIG environment variable': { - topic: function() { - return CONFIG; - }, - - 'Configuration can come from the $NODE_CONFIG environment': function() { - assert.equal(CONFIG.EnvOverride.parm3, 'overridden from $NODE_CONFIG'); - }, - - 'Type correct configurations from $NODE_CONFIG': function() { - assert.equal(CONFIG.EnvOverride.parm4, 100); - } - - }, - - 'Configurations from the --NODE_CONFIG command line': { - topic: function() { - return CONFIG; - }, - - 'Configuration can come from the --NODE_CONFIG command line argument': function() { - assert.equal(CONFIG.EnvOverride.parm5, 'overridden from --NODE_CONFIG'); - }, - - 'Type correct configurations from --NODE_CONFIG': function() { - assert.equal(CONFIG.EnvOverride.parm6, 101); - } - - }, - - 'Assuring a configuration property can be hidden': { - topic: function() { - var object = { - item1: 23, - subObject: { - item2: "hello" - } - }; - return object; - }, - - 'The makeHidden() method is available': function() { - assert.isFunction(CONFIG.makeHidden); - }, - - 'The test object (before hiding) is correct': function(object) { - assert.isTrue(JSON.stringify(object) == '{"item1":23,"subObject":{"item2":"hello"}}'); - }, - - 'The test object (after hiding) is correct': function(object) { - CONFIG.makeHidden(object, 'item1'); - assert.isTrue(JSON.stringify(object) == '{"subObject":{"item2":"hello"}}'); - }, - - 'The hidden property is readable, and has not changed': function(object) { - assert.isTrue(JSON.stringify(object) == '{"subObject":{"item2":"hello"}}'); - assert.isTrue(object.item1 == 23); - } - - }, - - 'Assuring a configuration property can be made immutable': { - topic: function() { - - CONFIG.makeImmutable(CONFIG.TestModule, 'parm1'); - CONFIG.TestModule.parm1 = "setToThis"; - return CONFIG.TestModule.parm1; - }, - - 'The makeImmutable() method is available': function() { - assert.isFunction(CONFIG.makeImmutable); - }, - - 'Correctly unable to change an immutable configuration': function(value) { - assert.isTrue(value != "setToThis"); - }, - - 'Left the original value intact after attempting the change': function(value) { - assert.equal(value, "value1"); - } - }, - - 'Configuration for module developers': { - topic: function() { - - // Set some parameters for the test module - return CONFIG.setModuleDefaults("TestModule", { - parm1: 1000, parm2: 2000, parm3: 3000 - }); - }, - - 'The setModuleDefaults() method is available': function() { - assert.isFunction(CONFIG.setModuleDefaults); - }, - - 'The module config is in the CONFIG object': function(moduleConfig) { - assert.isTrue(typeof(CONFIG.TestModule) != "undefined"); - assert.deepEqual(CONFIG.TestModule, moduleConfig); - }, - - 'Local configurations are mixed in': function(moduleConfig) { - assert.equal(moduleConfig.parm1, "value1"); - }, - - 'Defaults remain intact unless overridden': function(moduleConfig) { - assert.equal(moduleConfig.parm2, 2000); - } - - }, - - 'Internal Change Notification Tests': { - topic: function() { - - // Attach this topic as a watcher - var cb = this.callback; - CONFIG.watch(CONFIG, null, function(obj, prop, oldValue, newValue){ - // Don't process the submodule test - that's for later - if (prop == 'parm3') return; - if (prop == 'dynamicArray') return; - if (prop == 'staticArray') { - cb('Watch callback should not have been called for staticArray'); - return false; - } - - cb(null, {obj:obj, prop:prop, oldValue:oldValue, newValue:newValue}); - }); - - // Write the new watched value out to the runtime.json file - CONFIG.watchThisValue = newWatchedValue; - - // Test that submodule configurations are persisted - CONFIG.TestModule.parm3 = 1234; - - // Write the new array value out to the runtime.json file - CONFIG.dynamicArray = newDynamicArray; - - // Test that changing an array d - CONFIG.staticArray = [2,1,3]; - }, - - 'The watch() method is available': function() { - assert.isFunction(CONFIG.watch); - }, - - 'The change handler callback was fired': function(err, obj) { - assert.isTrue(true); - }, - - 'And it was called on the correct object': function(err, obj) { - assert.isTrue(obj.obj === CONFIG); - }, - - 'And it was called with the correct parameter': function(err, obj) { - assert.equal(obj.prop, 'watchThisValue'); - }, - - 'And it has the correct prior value': function(err, obj) { - assert.equal(obj.oldValue, originalWatchedValue); - }, - - 'And it has the correct new value': function(err, obj) { - assert.equal(obj.newValue, newWatchedValue); - }, - - 'And the config value was correctly set': function(err, obj) { - assert.equal(CONFIG.watchThisValue, newWatchedValue); - }, - - 'Waiting for the O/S to notify us of changes...': function(err, obj) { - // This is just a message for the next test - assert.isTrue(true); - } - - }, - - 'Runtime Configuration Changes are Persisted to runtime.json': { - topic: function() { - // Watch the file for changes - var t = this; - FileSystem.unwatchFile(runtimeJsonFilename); - FileSystem.watchFile(runtimeJsonFilename, {persistent:true}, function(){ - // This was failing on node v0.6 due to the watch happening before full write, - // so adding a small interval so it doesn't fail on older node.js versions - setTimeout(function(){ - t.callback(null, CONFIG._parseFile(runtimeJsonFilename)); - },10); - - FileSystem.createReadStream(runtimeJsonFilename).pipe(FileSystem.createWriteStream(runtimeJsonFilenameBak)); - }); - }, - 'The runtime.json file was changed': function(err, runtimeObj) { - assert.isTrue(!err); - }, - 'Prior configuration values were kept intact': function(err, runtimeObj) { - assert.equal(runtimeObj.Customers.dbName, "override_from_runtime_json"); - }, - 'Changed configuration values were persisted': function(err, runtimeObj) { - assert.equal(runtimeObj.watchThisValue, CONFIG.watchThisValue); - assert.deepEqual(runtimeObj.dynamicArray, CONFIG.dynamicArray); - }, - 'Unchanged configuration values were not persisted': function(err, runtimeObj) { - assert.isUndefined(runtimeObj.staticArray); - }, - 'Module default values are persisted': function(err, runtimeObj) { - assert.equal(runtimeObj.TestModule.parm3, 1234); - }, - 'The resetRuntime() method is available': function() { - assert.isFunction(CONFIG.resetRuntime); - }, - 'Runtime Configuration is empty': function() { - CONFIG.resetRuntime(function(err, written, buffer) { - FileSystem.readFile(runtimeJsonFilename, function(err, data) { - assert.isEqual(data,'{}'); - }); - }); - }, - teardown: function() { - FileSystem.rename(runtimeJsonFilenameBak, runtimeJsonFilename, function(err) { - if(err) { - console.log('Cant rename file'); - } - }); - } - }, - - 'Assuring you can get originalConfig': { - topic: function() { - return CONFIG.getOriginalConfig(); - }, - 'The getOriginalConfig() method is available': function() { - assert.isFunction(CONFIG.getOriginalConfig); - } - } - -}); diff --git a/node_modules/config/test/config/default-3.json b/node_modules/config/test/config/default-3.json deleted file mode 100644 index 5ed7026..0000000 --- a/node_modules/config/test/config/default-3.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "Customers": { - "altDbPort": 4400, - "altDbPort1": 4402 - } -} diff --git a/node_modules/config/test/config/default.coffee b/node_modules/config/test/config/default.coffee deleted file mode 100644 index b4ae2ea..0000000 --- a/node_modules/config/test/config/default.coffee +++ /dev/null @@ -1,5 +0,0 @@ -module.exports = - AnotherModule: - parm3: "value3" - Customers: - dbName: "from_default_coffee" diff --git a/node_modules/config/test/config/default.js b/node_modules/config/test/config/default.js deleted file mode 100644 index 642a539..0000000 --- a/node_modules/config/test/config/default.js +++ /dev/null @@ -1,14 +0,0 @@ -// Common configuration parameters -module.exports = { - TestModule: { - parm1:"value1" - }, - Customers: { - dbHost:'base', - dbName:'from_default_js' - }, - EnvOverride: { - parm_number_1: "from_default_js", - parm2: 22 - } -}; diff --git a/node_modules/config/test/config/default.json b/node_modules/config/test/config/default.json deleted file mode 100644 index f0cd3c0..0000000 --- a/node_modules/config/test/config/default.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "Customers": { - "dbName":"from_default_json", - "dbPassword":"password will be overwritten.", - "dbPassword2":"password will be overwritten.", - "lang":["en","es"] - }, - "AnotherModule": { - "parm1":"value1" - }, - "staticArray": [2,1,3] -} diff --git a/node_modules/config/test/config/default.yaml b/node_modules/config/test/config/default.yaml deleted file mode 100644 index daf8599..0000000 --- a/node_modules/config/test/config/default.yaml +++ /dev/null @@ -1,9 +0,0 @@ -# Example of the baseline configuration in YAML - -Customers: - dbPort: 5984 - dbName: from_default_yaml - -AnotherModule: - parm2: value2 - diff --git a/node_modules/config/test/config/default.yml b/node_modules/config/test/config/default.yml deleted file mode 100644 index b1b7b5d..0000000 --- a/node_modules/config/test/config/default.yml +++ /dev/null @@ -1,5 +0,0 @@ -# Example of the baseline configuration in YAML, using .yml extension - -AnotherModule: - parm2yml: value2yml - diff --git a/node_modules/config/test/config/local-3.yml b/node_modules/config/test/config/local-3.yml deleted file mode 100644 index 3a336c6..0000000 --- a/node_modules/config/test/config/local-3.yml +++ /dev/null @@ -1,3 +0,0 @@ - -Customers: - altDbPort1: 2209 diff --git a/node_modules/config/test/config/local-test.json b/node_modules/config/test/config/local-test.json deleted file mode 100644 index c1b18a3..0000000 --- a/node_modules/config/test/config/local-test.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "Customers": { - "dbPassword2":"another password", - "lang":["en","de","es"] - } -} diff --git a/node_modules/config/test/config/local.yaml b/node_modules/config/test/config/local.yaml deleted file mode 100644 index 4e9fe09..0000000 --- a/node_modules/config/test/config/local.yaml +++ /dev/null @@ -1,4 +0,0 @@ - -Customers: - dbPassword: real password - diff --git a/node_modules/config/test/config/runtime.json b/node_modules/config/test/config/runtime.json deleted file mode 100644 index 2546357..0000000 --- a/node_modules/config/test/config/runtime.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "TestModule": { - "parm3": 1234 - }, - "Customers": { - "dbName": "override_from_runtime_json" - }, - "watchThisValue": 10788, - "dynamicArray": [ - 99287, - 72082 - ] -} \ No newline at end of file diff --git a/node_modules/config/test/config/test.yaml b/node_modules/config/test/config/test.yaml deleted file mode 100644 index 960e318..0000000 --- a/node_modules/config/test/config/test.yaml +++ /dev/null @@ -1,4 +0,0 @@ -# This is loaded if $NODE_ENV=test - -Customers: - dbPort: 5999 diff --git a/node_modules/config/tools/gen-docs.sh b/node_modules/config/tools/gen-docs.sh deleted file mode 100755 index 2a214b6..0000000 --- a/node_modules/config/tools/gen-docs.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/bin/sh -# The location of your yuidoc install -yuidoc_home=${yuidoc_home:-../yui/yui-doc} - -# The location of the files to parse. Parses subdirectories, but will fail if -# there are duplicate file names in these directories. You can specify multiple -# source trees: -# parser_in="%HOME/www/yui/src %HOME/www/event/src" -parser_in="lib test" - -# The location to output the parser data. This output is a file containing a -# json string, and copies of the parsed files. -parser_tmp=${parser_tmp:-./tmp} - -# The directory to put the html file outputted by the generator -generator_out=./doc - -# The location of the template files. Any subdirectories here will be copied -# verbatim to the destination directory. -template=./doc/template - -# The version of your project to display within the documentation. -version=`grep version package.json | sed 's/.*: "\(.*\)".*/\1/'` - -# The version of YUI the project is using. This effects the output for -# YUI configuration attributes. This should start with '2' or '3'. -yuiversion=3 - -# The project and URL -project="Node.js Configuration" -project_url="https://github.com/lorenwest/node-config" - -############################################################################## -# add -s to the end of the line to show items marked private - -rm doc/*.html -$yuidoc_home/bin/yuidoc.py \ - $parser_in \ - -p $parser_tmp \ - -o $generator_out \ - -t $template \ - -m "$project" \ - -u "$project_url" \ - -v $version \ - -Y $yuiversion - -rm -rf $parser_tmp - -echo Copying the documentation to ../lorenwest.github.com/node-config/$version -rm -rf ../lorenwest.github.com/node-config/$version -cp -R doc ../lorenwest.github.com/node-config/$version -echo Copying the documentation to ../lorenwest.github.com/node-config/latest -rm -rf ../lorenwest.github.com/node-config/latest -cp -R doc ../lorenwest.github.com/node-config/latest diff --git a/node_modules/mocha/LICENSE b/node_modules/mocha/LICENSE deleted file mode 100644 index ca47f26..0000000 --- a/node_modules/mocha/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -(The MIT License) - -Copyright (c) 2011-2015 TJ Holowaychuk - -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/node_modules/mocha/README.md b/node_modules/mocha/README.md deleted file mode 100644 index 44692d3..0000000 --- a/node_modules/mocha/README.md +++ /dev/null @@ -1,11 +0,0 @@ -[![Build Status](https://api.travis-ci.org/mochajs/mocha.svg?branch=master)](http://travis-ci.org/mochajs/mocha) [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mochajs/mocha?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - - [![Mocha test framework](http://f.cl.ly/items/3l1k0n2A1U3M1I1L210p/Screen%20Shot%202012-02-24%20at%202.21.43%20PM.png)](http://mochajs.org) - - Mocha is a simple, flexible, fun JavaScript test framework for node.js and the browser. For more information view the [documentation](http://mochajs.org). - -## Links - - - [Google Group](http://groups.google.com/group/mochajs) - - [Wiki](https://github.com/mochajs/mocha/wiki) - - Mocha [Extensions and reporters](https://github.com/mochajs/mocha/wiki) diff --git a/node_modules/mocha/bin/_mocha b/node_modules/mocha/bin/_mocha deleted file mode 100755 index 5b3c0c5..0000000 --- a/node_modules/mocha/bin/_mocha +++ /dev/null @@ -1,492 +0,0 @@ -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('commander'), - path = require('path'), - fs = require('fs'), - resolve = path.resolve, - exists = fs.existsSync || path.existsSync, - Mocha = require('../'), - utils = Mocha.utils, - join = path.join, - cwd = process.cwd(), - getOptions = require('./options'), - mocha = new Mocha; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Files. - */ - -var files = []; - -/** - * Globals. - */ - -var globals = []; - -/** - * Requires. - */ - -var requires = []; - -/** - * Images. - */ - -var images = { - fail: __dirname + '/../images/error.png' - , pass: __dirname + '/../images/ok.png' -}; - -// options - -program - .version(JSON.parse(fs.readFileSync(__dirname + '/../package.json', 'utf8')).version) - .usage('[debug] [options] [files]') - .option('-A, --async-only', "force all tests to take a callback (async)") - .option('-c, --colors', 'force enabling of colors') - .option('-C, --no-colors', 'force disabling of colors') - .option('-G, --growl', 'enable growl notification support') - .option('-O, --reporter-options ', 'reporter-specific options') - .option('-R, --reporter ', 'specify the reporter to use', 'spec') - .option('-S, --sort', "sort test files") - .option('-b, --bail', "bail after first test failure") - .option('-d, --debug', "enable node's debugger, synonym for node --debug") - .option('-g, --grep ', 'only run tests matching ') - .option('-f, --fgrep ', 'only run tests containing ') - .option('-gc, --expose-gc', 'expose gc extension') - .option('-i, --invert', 'inverts --grep and --fgrep matches') - .option('-r, --require ', 'require the given module') - .option('-s, --slow ', '"slow" test threshold in milliseconds [75]') - .option('-t, --timeout ', 'set test-case timeout in milliseconds [2000]') - .option('-u, --ui ', 'specify user-interface (bdd|tdd|exports)', 'bdd') - .option('-w, --watch', 'watch files for changes') - .option('--check-leaks', 'check for global variable leaks') - .option('--full-trace', 'display the full stack trace') - .option('--compilers :,...', 'use the given module(s) to compile files', list, []) - .option('--debug-brk', "enable node's debugger breaking on the first line") - .option('--globals ', 'allow the given comma-delimited global [names]', list, []) - .option('--harmony', 'enable all harmony features (except typeof)') - .option('--es_staging', 'enable all staged features') - .option('--harmony-collections', 'enable harmony collections (sets, maps, and weak maps)') - .option('--harmony-generators', 'enable harmony generators') - .option('--harmony-proxies', 'enable harmony proxies') - .option('--harmony_shipping', 'enable all shipped harmony fetaures (iojs)') - .option('--harmony_arrow_functions', 'enable "harmony arrow functions" (iojs)') - .option('--harmony_proxies', 'enable "harmony proxies" (iojs)') - .option('--harmony_classes', 'enable "harmony classes" (iojs)') - .option('--inline-diffs', 'display actual/expected differences inline within each string') - .option('--interfaces', 'display available interfaces') - .option('--no-deprecation', 'silence deprecation warnings') - .option('--no-exit', 'require a clean shutdown of the event loop: mocha will not call process.exit') - .option('--no-timeouts', 'disables timeouts, given implicitly with --debug') - .option('--opts ', 'specify opts path', 'test/mocha.opts') - .option('--prof', 'log statistical profiling information') - .option('--recursive', 'include sub directories') - .option('--reporters', 'display available reporters') - .option('--throw-deprecation', 'throw an exception anytime a deprecated function is used') - .option('--trace', 'trace function calls') - .option('--trace-deprecation', 'show stack traces on deprecations') - .option('--watch-extensions ,...', 'additional extensions to monitor with --watch', list, []) - .option('--delay', 'wait for async suite definition') - -program.name = 'mocha'; - -// init command - -program - .command('init ') - .description('initialize a client-side mocha setup at ') - .action(function(path){ - var mkdir = require('mkdirp'); - mkdir.sync(path); - var css = fs.readFileSync(join(__dirname, '..', 'mocha.css')); - var js = fs.readFileSync(join(__dirname, '..', 'mocha.js')); - var tmpl = fs.readFileSync(join(__dirname, '..', 'lib/template.html')); - fs.writeFileSync(join(path, 'mocha.css'), css); - fs.writeFileSync(join(path, 'mocha.js'), js); - fs.writeFileSync(join(path, 'tests.js'), ''); - fs.writeFileSync(join(path, 'index.html'), tmpl); - process.exit(0); - }); - -// --globals - -program.on('globals', function(val){ - globals = globals.concat(list(val)); -}); - -// --reporters - -program.on('reporters', function(){ - console.log(); - console.log(' dot - dot matrix'); - console.log(' doc - html documentation'); - console.log(' spec - hierarchical spec list'); - console.log(' json - single json object'); - console.log(' progress - progress bar'); - console.log(' list - spec-style listing'); - console.log(' tap - test-anything-protocol'); - console.log(' landing - unicode landing strip'); - console.log(' xunit - xunit reporter'); - console.log(' html-cov - HTML test coverage'); - console.log(' json-cov - JSON test coverage'); - console.log(' min - minimal reporter (great with --watch)'); - console.log(' json-stream - newline delimited json events'); - console.log(' markdown - markdown documentation (github flavour)'); - console.log(' nyan - nyan cat!'); - console.log(); - process.exit(); -}); - -// --interfaces - -program.on('interfaces', function(){ - console.log(''); - console.log(' bdd'); - console.log(' tdd'); - console.log(' qunit'); - console.log(' exports'); - console.log(''); - process.exit(); -}); - -// -r, --require - -module.paths.push(cwd, join(cwd, 'node_modules')); - -program.on('require', function(mod){ - var abs = exists(mod) || exists(mod + '.js'); - if (abs) mod = resolve(mod); - requires.push(mod); -}); - -// load mocha.opts into process.argv - -getOptions(); - -// parse args - -program.parse(process.argv); - -// infinite stack traces - -Error.stackTraceLimit = Infinity; // TODO: config - -// reporter options - -var reporterOptions = {}; -if (program.reporterOptions !== undefined) { - program.reporterOptions.split(",").forEach(function(opt) { - var L = opt.split("="); - if (L.length != 2) { - throw new Error("invalid reporter option '" + opt + "'"); - } - reporterOptions[L[0]] = L[1]; - }); -} - -// reporter - -mocha.reporter(program.reporter, reporterOptions); - -// interface - -mocha.ui(program.ui); - -// load reporter - -try { - Reporter = require('../lib/reporters/' + program.reporter); -} catch (err) { - try { - Reporter = require(program.reporter); - } catch (err) { - throw new Error('reporter "' + program.reporter + '" does not exist'); - } -} - -// --no-colors - -if (!program.colors) mocha.useColors(false); - -// --colors - -if (~process.argv.indexOf('--colors') || - ~process.argv.indexOf('-c')) { - mocha.useColors(true); -} - -// --inline-diffs - -if (program.inlineDiffs) mocha.useInlineDiffs(true); - -// --slow - -if (program.slow) mocha.suite.slow(program.slow); - -// --no-timeouts - -if (!program.timeouts) mocha.enableTimeouts(false); - -// --timeout - -if (program.timeout) mocha.suite.timeout(program.timeout); - -// --bail - -mocha.suite.bail(program.bail); - -// --grep - -if (program.grep) mocha.grep(new RegExp(program.grep)); - -// --fgrep - -if (program.fgrep) mocha.grep(program.fgrep); - -// --invert - -if (program.invert) mocha.invert(); - -// --check-leaks - -if (program.checkLeaks) mocha.checkLeaks(); - -// --stack-trace - -if(program.fullTrace) mocha.fullTrace(); - -// --growl - -if (program.growl) mocha.growl(); - -// --async-only - -if (program.asyncOnly) mocha.asyncOnly(); - -// --delay - -if (program.delay) mocha.delay(); - -// --globals - -mocha.globals(globals); - -// custom compiler support - -var extensions = ['js']; -program.compilers.forEach(function(c) { - var compiler = c.split(':') - , ext = compiler[0] - , mod = compiler[1]; - - if (mod[0] == '.') mod = join(process.cwd(), mod); - require(mod); - extensions.push(ext); - program.watchExtensions.push(ext); -}); - -// requires - -requires.forEach(function(mod) { - require(mod); -}); - -//args - -var args = program.args; - -// default files to test/*.{js,coffee} - -if (!args.length) args.push('test'); - -args.forEach(function(arg){ - files = files.concat(utils.lookupFiles(arg, extensions, program.recursive)); -}); - -// resolve - -files = files.map(function(path){ - return resolve(path); -}); - -if (program.sort) { - files.sort(); -} - -// --watch - -var runner; -if (program.watch) { - console.log(); - hideCursor(); - process.on('SIGINT', function(){ - showCursor(); - console.log('\n'); - process.exit(); - }); - - - var watchFiles = utils.files(cwd, [ 'js' ].concat(program.watchExtensions)); - var runAgain = false; - - function loadAndRun() { - try { - mocha.files = files; - runAgain = false; - runner = mocha.run(function(){ - runner = null; - if (runAgain) { - rerun(); - } - }); - } catch(e) { - console.log(e.stack); - } - } - - function purge() { - watchFiles.forEach(function(file){ - delete require.cache[file]; - }); - } - - loadAndRun(); - - function rerun() { - purge(); - stop() - if (!program.grep) - mocha.grep(null); - mocha.suite = mocha.suite.clone(); - mocha.suite.ctx = new Mocha.Context; - mocha.ui(program.ui); - loadAndRun(); - } - - utils.watch(watchFiles, function(){ - runAgain = true; - if (runner) { - runner.abort(); - } else { - rerun(); - } - }); - - return; -} - -// load - -mocha.files = files; -runner = mocha.run(program.exit ? exit : exitLater); - -function exitLater(code) { - process.on('exit', function() { process.exit(code) }) -} - -function exit(code) { - // flush output for Node.js Windows pipe bug - // https://github.com/joyent/node/issues/6247 is just one bug example - // https://github.com/visionmedia/mocha/issues/333 has a good discussion - function done() { - if (!(draining--)) process.exit(code); - } - - var draining = 0; - var streams = [process.stdout, process.stderr]; - - streams.forEach(function(stream){ - // submit empty write request and wait for completion - draining += 1; - stream.write('', done); - }); - - done(); -} - -process.on('SIGINT', function() { runner.abort(); }) - -// enable growl notifications - -function growl(runner, reporter) { - var notify = require('growl'); - - runner.on('end', function(){ - var stats = reporter.stats; - if (stats.failures) { - var msg = stats.failures + ' of ' + runner.total + ' tests failed'; - notify(msg, { name: 'mocha', title: 'Failed', image: images.fail }); - } else { - notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { - name: 'mocha' - , title: 'Passed' - , image: images.pass - }); - } - }); -} - -/** - * Parse list. - */ - -function list(str) { - return str.split(/ *, */); -} - -/** - * Hide the cursor. - */ - -function hideCursor(){ - process.stdout.write('\u001b[?25l'); -} - -/** - * Show the cursor. - */ - -function showCursor(){ - process.stdout.write('\u001b[?25h'); -} - -/** - * Stop play()ing. - */ - -function stop() { - process.stdout.write('\u001b[2K'); - clearInterval(play.timer); -} - -/** - * Play the given array of strings. - */ - -function play(arr, interval) { - var len = arr.length - , interval = interval || 100 - , i = 0; - - play.timer = setInterval(function(){ - var str = arr[i++ % len]; - process.stdout.write('\u001b[0G' + str); - }, interval); -} diff --git a/node_modules/mocha/bin/mocha b/node_modules/mocha/bin/mocha deleted file mode 100755 index daa8fd9..0000000 --- a/node_modules/mocha/bin/mocha +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env node - -/** - * This tiny wrapper file checks for known node flags and appends them - * when found, before invoking the "real" _mocha(1) executable. - */ - -var spawn = require('child_process').spawn, - path = require('path'), - fs = require('fs'), - args = [path.join(__dirname, '_mocha')], - getOptions = require('./options'); - -// load mocha.opts into process.argv - -getOptions(); - -process.argv.slice(2).forEach(function(arg){ - var flag = arg.split('=')[0]; - - switch (flag) { - case '-d': - args.unshift('--debug'); - args.push('--no-timeouts'); - break; - case 'debug': - case '--debug': - case '--debug-brk': - args.unshift(arg); - args.push('--no-timeouts'); - break; - case '-gc': - case '--expose-gc': - args.unshift('--expose-gc'); - break; - case '--gc-global': - case '--harmony': - case '--es_staging': - case '--harmony-proxies': - case '--harmony-collections': - case '--harmony-generators': - case '--harmony_shipping': - case '--harmony_arrow_functions': - case '--harmony_proxies': - case '--harmony_classes': - case '--no-deprecation': - case '--prof': - case '--throw-deprecation': - case '--trace-deprecation': - case '--allow-natives-syntax': - args.unshift(arg); - break; - default: - if (0 == arg.indexOf('--trace')) args.unshift(arg); - else args.push(arg); - break; - } -}); - -var proc = spawn(process.execPath, args, { stdio: 'inherit' }); -proc.on('exit', function (code, signal) { - process.on('exit', function(){ - if (signal) { - process.kill(process.pid, signal); - } else { - process.exit(code); - } - }); -}); - -// terminate children. -process.on('SIGINT', function () { - proc.kill('SIGINT'); // calls runner.abort() - proc.kill('SIGTERM'); // if that didn't work, we're probably in an infinite loop, so make it die. - process.kill(process.pid, 'SIGINT'); -}); diff --git a/node_modules/mocha/bin/options.js b/node_modules/mocha/bin/options.js deleted file mode 100644 index 3b31798..0000000 --- a/node_modules/mocha/bin/options.js +++ /dev/null @@ -1,36 +0,0 @@ -/** - * Dependencies. - */ - -var fs = require('fs'); - -/** - * Export `getOptions`. - */ - -module.exports = getOptions; - -/** - * Get options. - */ - -function getOptions() { - var optsPath = process.argv.indexOf('--opts') !== -1 - ? process.argv[process.argv.indexOf('--opts') + 1] - : 'test/mocha.opts'; - - try { - var opts = fs.readFileSync(optsPath, 'utf8') - .trim() - .split(/\s+/) - .filter(function(value) { - return value ? true : false; - }); - - process.argv = process.argv - .slice(0, 2) - .concat(opts.concat(process.argv.slice(2))); - } catch (err) { - // ignore - } -} diff --git a/node_modules/mocha/images/error.png b/node_modules/mocha/images/error.png deleted file mode 100644 index a07a1ba..0000000 Binary files a/node_modules/mocha/images/error.png and /dev/null differ diff --git a/node_modules/mocha/images/ok.png b/node_modules/mocha/images/ok.png deleted file mode 100644 index b3623a5..0000000 Binary files a/node_modules/mocha/images/ok.png and /dev/null differ diff --git a/node_modules/mocha/index.js b/node_modules/mocha/index.js deleted file mode 100644 index 169b271..0000000 --- a/node_modules/mocha/index.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = process.env.COV - ? require('./lib-cov/mocha') - : require('./lib/mocha'); diff --git a/node_modules/mocha/lib/browser/debug.js b/node_modules/mocha/lib/browser/debug.js deleted file mode 100644 index 0d939e5..0000000 --- a/node_modules/mocha/lib/browser/debug.js +++ /dev/null @@ -1,4 +0,0 @@ -module.exports = function(type){ - return function(){ - } -}; diff --git a/node_modules/mocha/lib/browser/escape-string-regexp.js b/node_modules/mocha/lib/browser/escape-string-regexp.js deleted file mode 100644 index 21a9566..0000000 --- a/node_modules/mocha/lib/browser/escape-string-regexp.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; - -module.exports = function (str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - - return str.replace(matchOperatorsRe, '\\$&'); -}; diff --git a/node_modules/mocha/lib/browser/events.js b/node_modules/mocha/lib/browser/events.js deleted file mode 100644 index f708260..0000000 --- a/node_modules/mocha/lib/browser/events.js +++ /dev/null @@ -1,177 +0,0 @@ -/** - * Module exports. - */ - -exports.EventEmitter = EventEmitter; - -/** - * Check if `obj` is an array. - */ - -function isArray(obj) { - return '[object Array]' == {}.toString.call(obj); -} - -/** - * Event emitter constructor. - * - * @api public - */ - -function EventEmitter(){}; - -/** - * Adds a listener. - * - * @api public - */ - -EventEmitter.prototype.on = function (name, fn) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = fn; - } else if (isArray(this.$events[name])) { - this.$events[name].push(fn); - } else { - this.$events[name] = [this.$events[name], fn]; - } - - return this; -}; - -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -/** - * Adds a volatile listener. - * - * @api public - */ - -EventEmitter.prototype.once = function (name, fn) { - var self = this; - - function on () { - self.removeListener(name, on); - fn.apply(this, arguments); - }; - - on.listener = fn; - this.on(name, on); - - return this; -}; - -/** - * Removes a listener. - * - * @api public - */ - -EventEmitter.prototype.removeListener = function (name, fn) { - if (this.$events && this.$events[name]) { - var list = this.$events[name]; - - if (isArray(list)) { - var pos = -1; - - for (var i = 0, l = list.length; i < l; i++) { - if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { - pos = i; - break; - } - } - - if (pos < 0) { - return this; - } - - list.splice(pos, 1); - - if (!list.length) { - delete this.$events[name]; - } - } else if (list === fn || (list.listener && list.listener === fn)) { - delete this.$events[name]; - } - } - - return this; -}; - -/** - * Removes all listeners for an event. - * - * @api public - */ - -EventEmitter.prototype.removeAllListeners = function (name) { - if (name === undefined) { - this.$events = {}; - return this; - } - - if (this.$events && this.$events[name]) { - this.$events[name] = null; - } - - return this; -}; - -/** - * Gets all listeners for a certain event. - * - * @api public - */ - -EventEmitter.prototype.listeners = function (name) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = []; - } - - if (!isArray(this.$events[name])) { - this.$events[name] = [this.$events[name]]; - } - - return this.$events[name]; -}; - -/** - * Emits an event. - * - * @api public - */ - -EventEmitter.prototype.emit = function (name) { - if (!this.$events) { - return false; - } - - var handler = this.$events[name]; - - if (!handler) { - return false; - } - - var args = [].slice.call(arguments, 1); - - if ('function' == typeof handler) { - handler.apply(this, args); - } else if (isArray(handler)) { - var listeners = handler.slice(); - - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i].apply(this, args); - } - } else { - return false; - } - - return true; -}; diff --git a/node_modules/mocha/lib/browser/fs.js b/node_modules/mocha/lib/browser/fs.js deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mocha/lib/browser/glob.js b/node_modules/mocha/lib/browser/glob.js deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mocha/lib/browser/path.js b/node_modules/mocha/lib/browser/path.js deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mocha/lib/browser/progress.js b/node_modules/mocha/lib/browser/progress.js deleted file mode 100644 index b30e517..0000000 --- a/node_modules/mocha/lib/browser/progress.js +++ /dev/null @@ -1,125 +0,0 @@ -/** - * Expose `Progress`. - */ - -module.exports = Progress; - -/** - * Initialize a new `Progress` indicator. - */ - -function Progress() { - this.percent = 0; - this.size(0); - this.fontSize(11); - this.font('helvetica, arial, sans-serif'); -} - -/** - * Set progress size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.size = function(n){ - this._size = n; - return this; -}; - -/** - * Set text to `str`. - * - * @param {String} str - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.text = function(str){ - this._text = str; - return this; -}; - -/** - * Set font size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.fontSize = function(n){ - this._fontSize = n; - return this; -}; - -/** - * Set font `family`. - * - * @param {String} family - * @return {Progress} for chaining - */ - -Progress.prototype.font = function(family){ - this._font = family; - return this; -}; - -/** - * Update percentage to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - */ - -Progress.prototype.update = function(n){ - this.percent = n; - return this; -}; - -/** - * Draw on `ctx`. - * - * @param {CanvasRenderingContext2d} ctx - * @return {Progress} for chaining - */ - -Progress.prototype.draw = function(ctx){ - try { - var percent = Math.min(this.percent, 100) - , size = this._size - , half = size / 2 - , x = half - , y = half - , rad = half - 1 - , fontSize = this._fontSize; - - ctx.font = fontSize + 'px ' + this._font; - - var angle = Math.PI * 2 * (percent / 100); - ctx.clearRect(0, 0, size, size); - - // outer circle - ctx.strokeStyle = '#9f9f9f'; - ctx.beginPath(); - ctx.arc(x, y, rad, 0, angle, false); - ctx.stroke(); - - // inner circle - ctx.strokeStyle = '#eee'; - ctx.beginPath(); - ctx.arc(x, y, rad - 1, 0, angle, true); - ctx.stroke(); - - // text - var text = this._text || (percent | 0) + '%' - , w = ctx.measureText(text).width; - - ctx.fillText( - text - , x - w / 2 + 1 - , y + fontSize / 2 - 1); - } catch (ex) {} //don't fail if we can't render progress - return this; -}; diff --git a/node_modules/mocha/lib/browser/tty.js b/node_modules/mocha/lib/browser/tty.js deleted file mode 100644 index eab6388..0000000 --- a/node_modules/mocha/lib/browser/tty.js +++ /dev/null @@ -1,12 +0,0 @@ -exports.isatty = function(){ - return true; -}; - -exports.getWindowSize = function(){ - if ('innerHeight' in global) { - return [global.innerHeight, global.innerWidth]; - } else { - // In a Web Worker, the DOM Window is not available. - return [640, 480]; - } -}; diff --git a/node_modules/mocha/lib/context.js b/node_modules/mocha/lib/context.js deleted file mode 100644 index 3885218..0000000 --- a/node_modules/mocha/lib/context.js +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Expose `Context`. - */ - -module.exports = Context; - -/** - * Initialize a new `Context`. - * - * @api private - */ - -function Context(){} - -/** - * Set or get the context `Runnable` to `runnable`. - * - * @param {Runnable} runnable - * @return {Context} - * @api private - */ - -Context.prototype.runnable = function(runnable){ - if (0 == arguments.length) return this._runnable; - this.test = this._runnable = runnable; - return this; -}; - -/** - * Set test timeout `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.timeout = function(ms){ - if (arguments.length === 0) return this.runnable().timeout(); - this.runnable().timeout(ms); - return this; -}; - -/** - * Set test timeout `enabled`. - * - * @param {Boolean} enabled - * @return {Context} self - * @api private - */ - -Context.prototype.enableTimeouts = function (enabled) { - this.runnable().enableTimeouts(enabled); - return this; -}; - - -/** - * Set test slowness threshold `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.slow = function(ms){ - this.runnable().slow(ms); - return this; -}; - -/** - * Mark a test as skipped. - * - * @return {Context} self - * @api private - */ - -Context.prototype.skip = function(){ - this.runnable().skip(); - return this; -}; - -/** - * Inspect the context void of `._runnable`. - * - * @return {String} - * @api private - */ - -Context.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_runnable' == key) return; - if ('test' == key) return; - return val; - }, 2); -}; diff --git a/node_modules/mocha/lib/hook.js b/node_modules/mocha/lib/hook.js deleted file mode 100644 index c2dc346..0000000 --- a/node_modules/mocha/lib/hook.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Hook`. - */ - -module.exports = Hook; - -/** - * Initialize a new `Hook` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Hook(title, fn) { - Runnable.call(this, title, fn); - this.type = 'hook'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -Hook.prototype.__proto__ = Runnable.prototype; - -/** - * Get or set the test `err`. - * - * @param {Error} err - * @return {Error} - * @api public - */ - -Hook.prototype.error = function(err){ - if (0 == arguments.length) { - var err = this._error; - this._error = null; - return err; - } - - this._error = err; -}; diff --git a/node_modules/mocha/lib/interfaces/bdd.js b/node_modules/mocha/lib/interfaces/bdd.js deleted file mode 100644 index f9f08a3..0000000 --- a/node_modules/mocha/lib/interfaces/bdd.js +++ /dev/null @@ -1,115 +0,0 @@ -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test') - , utils = require('../utils') - , escapeRe = require('escape-string-regexp'); - -/** - * BDD-style interface: - * - * describe('Array', function(){ - * describe('#indexOf()', function(){ - * it('should return -1 when not present', function(){ - * - * }); - * - * it('should return the index when present', function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - var common = require('./common')(suites, context); - - context.before = common.before; - context.after = common.after; - context.beforeEach = common.beforeEach; - context.afterEach = common.afterEach; - context.run = mocha.options.delay && common.runWithSuite(suite); - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.describe = context.context = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.file = file; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Pending describe. - */ - - context.xdescribe = - context.xcontext = - context.describe.skip = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; - - /** - * Exclusive suite. - */ - - context.describe.only = function(title, fn){ - var suite = context.describe(title, fn); - mocha.grep(suite.fullTitle()); - return suite; - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.it = context.specify = function(title, fn){ - var suite = suites[0]; - if (suite.pending) fn = null; - var test = new Test(title, fn); - test.file = file; - suite.addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.it.only = function(title, fn){ - var test = context.it(title, fn); - var reString = '^' + escapeRe(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - return test; - }; - - /** - * Pending test case. - */ - - context.xit = - context.xspecify = - context.it.skip = function(title){ - context.it(title); - }; - - }); -}; diff --git a/node_modules/mocha/lib/interfaces/common.js b/node_modules/mocha/lib/interfaces/common.js deleted file mode 100644 index 1ccd339..0000000 --- a/node_modules/mocha/lib/interfaces/common.js +++ /dev/null @@ -1,58 +0,0 @@ -/** - * Functions common to more than one interface - * @module lib/interfaces/common - */ - -'use strict'; - -module.exports = function (suites, context) { - - return { - /** - * This is only present if flag --delay is passed into Mocha. It triggers - * root suite execution. Returns a function which runs the root suite. - */ - runWithSuite: function runWithSuite(suite) { - return function run() { - suite.run(); - }; - }, - - /** - * Execute before running tests. - */ - before: function (name, fn) { - suites[0].beforeAll(name, fn); - }, - - /** - * Execute after running tests. - */ - after: function (name, fn) { - suites[0].afterAll(name, fn); - }, - - /** - * Execute before each test case. - */ - beforeEach: function (name, fn) { - suites[0].beforeEach(name, fn); - }, - - /** - * Execute after each test case. - */ - afterEach: function (name, fn) { - suites[0].afterEach(name, fn); - }, - - test: { - /** - * Pending test case. - */ - skip: function (title) { - context.test(title); - } - } - } -}; diff --git a/node_modules/mocha/lib/interfaces/exports.js b/node_modules/mocha/lib/interfaces/exports.js deleted file mode 100644 index 95e8a07..0000000 --- a/node_modules/mocha/lib/interfaces/exports.js +++ /dev/null @@ -1,61 +0,0 @@ -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * exports.Array = { - * '#indexOf()': { - * 'should return -1 when the value is not present': function(){ - * - * }, - * - * 'should return the correct index when the value is present': function(){ - * - * } - * } - * }; - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('require', visit); - - function visit(obj, file) { - var suite; - for (var key in obj) { - if ('function' == typeof obj[key]) { - var fn = obj[key]; - switch (key) { - case 'before': - suites[0].beforeAll(fn); - break; - case 'after': - suites[0].afterAll(fn); - break; - case 'beforeEach': - suites[0].beforeEach(fn); - break; - case 'afterEach': - suites[0].afterEach(fn); - break; - default: - var test = new Test(key, fn); - test.file = file; - suites[0].addTest(test); - } - } else { - suite = Suite.create(suites[0], key); - suites.unshift(suite); - visit(obj[key]); - suites.shift(); - } - } - } -}; diff --git a/node_modules/mocha/lib/interfaces/index.js b/node_modules/mocha/lib/interfaces/index.js deleted file mode 100644 index 4f825d1..0000000 --- a/node_modules/mocha/lib/interfaces/index.js +++ /dev/null @@ -1,4 +0,0 @@ -exports.bdd = require('./bdd'); -exports.tdd = require('./tdd'); -exports.qunit = require('./qunit'); -exports.exports = require('./exports'); diff --git a/node_modules/mocha/lib/interfaces/qunit.js b/node_modules/mocha/lib/interfaces/qunit.js deleted file mode 100644 index 6668967..0000000 --- a/node_modules/mocha/lib/interfaces/qunit.js +++ /dev/null @@ -1,94 +0,0 @@ -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test') - , escapeRe = require('escape-string-regexp') - , utils = require('../utils'); - -/** - * QUnit-style interface: - * - * suite('Array'); - * - * test('#length', function(){ - * var arr = [1,2,3]; - * ok(arr.length == 3); - * }); - * - * test('#indexOf()', function(){ - * var arr = [1,2,3]; - * ok(arr.indexOf(1) == 0); - * ok(arr.indexOf(2) == 1); - * ok(arr.indexOf(3) == 2); - * }); - * - * suite('String'); - * - * test('#length', function(){ - * ok('foo'.length == 3); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - var common = require('./common')(suites, context); - - context.before = common.before; - context.after = common.after; - context.beforeEach = common.beforeEach; - context.afterEach = common.afterEach; - context.run = mocha.options.delay && common.runWithSuite(suite); - /** - * Describe a "suite" with the given `title`. - */ - - context.suite = function(title){ - if (suites.length > 1) suites.shift(); - var suite = Suite.create(suites[0], title); - suite.file = file; - suites.unshift(suite); - return suite; - }; - - /** - * Exclusive test-case. - */ - - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - var test = new Test(title, fn); - test.file = file; - suites[0].addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.test.only = function(title, fn){ - var test = context.test(title, fn); - var reString = '^' + escapeRe(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - }; - - context.test.skip = common.test.skip; - - }); -}; diff --git a/node_modules/mocha/lib/interfaces/tdd.js b/node_modules/mocha/lib/interfaces/tdd.js deleted file mode 100644 index 13bc2a3..0000000 --- a/node_modules/mocha/lib/interfaces/tdd.js +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test') - , escapeRe = require('escape-string-regexp') - , utils = require('../utils'); - -/** - * TDD-style interface: - * - * suite('Array', function(){ - * suite('#indexOf()', function(){ - * suiteSetup(function(){ - * - * }); - * - * test('should return -1 when not present', function(){ - * - * }); - * - * test('should return the index when present', function(){ - * - * }); - * - * suiteTeardown(function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - var common = require('./common')(suites, context); - - context.setup = common.beforeEach; - context.teardown = common.afterEach; - context.suiteSetup = common.before; - context.suiteTeardown = common.after; - context.run = mocha.options.delay && common.runWithSuite(suite); - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.suite = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.file = file; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Pending suite. - */ - context.suite.skip = function(title, fn) { - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; - - /** - * Exclusive test-case. - */ - - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - var suite = suites[0]; - if (suite.pending) fn = null; - var test = new Test(title, fn); - test.file = file; - suite.addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.test.only = function(title, fn){ - var test = context.test(title, fn); - var reString = '^' + escapeRe(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - }; - - context.test.skip = common.test.skip; - }); -}; diff --git a/node_modules/mocha/lib/mocha.js b/node_modules/mocha/lib/mocha.js deleted file mode 100644 index 8a11124..0000000 --- a/node_modules/mocha/lib/mocha.js +++ /dev/null @@ -1,446 +0,0 @@ -/*! - * mocha - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var path = require('path') - , escapeRe = require('escape-string-regexp') - , utils = require('./utils'); - -/** - * Expose `Mocha`. - */ - -exports = module.exports = Mocha; - -/** - * To require local UIs and reporters when running in node. - */ - -if (typeof process !== 'undefined' && typeof process.cwd === 'function') { - var join = path.join - , cwd = process.cwd(); - module.paths.push(cwd, join(cwd, 'node_modules')); -} - -/** - * Expose internals. - */ - -exports.utils = utils; -exports.interfaces = require('./interfaces'); -exports.reporters = require('./reporters'); -exports.Runnable = require('./runnable'); -exports.Context = require('./context'); -exports.Runner = require('./runner'); -exports.Suite = require('./suite'); -exports.Hook = require('./hook'); -exports.Test = require('./test'); - -/** - * Return image `name` path. - * - * @param {String} name - * @return {String} - * @api private - */ - -function image(name) { - return __dirname + '/../images/' + name + '.png'; -} - -/** - * Setup mocha with `options`. - * - * Options: - * - * - `ui` name "bdd", "tdd", "exports" etc - * - `reporter` reporter instance, defaults to `mocha.reporters.spec` - * - `globals` array of accepted globals - * - `timeout` timeout in milliseconds - * - `bail` bail on the first test failure - * - `slow` milliseconds to wait before considering a test slow - * - `ignoreLeaks` ignore global leaks - * - `fullTrace` display the full stack-trace on failing - * - `grep` string or regexp to filter tests with - * - * @param {Object} options - * @api public - */ - -function Mocha(options) { - options = options || {}; - this.files = []; - this.options = options; - if (options.grep) this.grep(new RegExp(options.grep)); - if (options.fgrep) this.grep(options.fgrep); - this.suite = new exports.Suite('', new exports.Context); - this.ui(options.ui); - this.bail(options.bail); - this.reporter(options.reporter, options.reporterOptions); - if (null != options.timeout) this.timeout(options.timeout); - this.useColors(options.useColors); - if (options.enableTimeouts !== null) this.enableTimeouts(options.enableTimeouts); - if (options.slow) this.slow(options.slow); - - this.suite.on('pre-require', function (context) { - exports.afterEach = context.afterEach || context.teardown; - exports.after = context.after || context.suiteTeardown; - exports.beforeEach = context.beforeEach || context.setup; - exports.before = context.before || context.suiteSetup; - exports.describe = context.describe || context.suite; - exports.it = context.it || context.test; - exports.setup = context.setup || context.beforeEach; - exports.suiteSetup = context.suiteSetup || context.before; - exports.suiteTeardown = context.suiteTeardown || context.after; - exports.suite = context.suite || context.describe; - exports.teardown = context.teardown || context.afterEach; - exports.test = context.test || context.it; - exports.run = context.run; - }); -} - -/** - * Enable or disable bailing on the first failure. - * - * @param {Boolean} [bail] - * @api public - */ - -Mocha.prototype.bail = function(bail){ - if (0 == arguments.length) bail = true; - this.suite.bail(bail); - return this; -}; - -/** - * Add test `file`. - * - * @param {String} file - * @api public - */ - -Mocha.prototype.addFile = function(file){ - this.files.push(file); - return this; -}; - -/** - * Set reporter to `reporter`, defaults to "spec". - * - * @param {String|Function} reporter name or constructor - * @param {Object} reporterOptions optional options - * @api public - */ -Mocha.prototype.reporter = function(reporter, reporterOptions){ - if ('function' == typeof reporter) { - this._reporter = reporter; - } else { - reporter = reporter || 'spec'; - var _reporter; - try { _reporter = require('./reporters/' + reporter); } catch (err) {} - if (!_reporter) try { _reporter = require(reporter); } catch (err) { - err.message.indexOf('Cannot find module') !== -1 - ? console.warn('"' + reporter + '" reporter not found') - : console.warn('"' + reporter + '" reporter blew up with error:\n' + err.stack); - } - if (!_reporter && reporter === 'teamcity') - console.warn('The Teamcity reporter was moved to a package named ' + - 'mocha-teamcity-reporter ' + - '(https://npmjs.org/package/mocha-teamcity-reporter).'); - if (!_reporter) throw new Error('invalid reporter "' + reporter + '"'); - this._reporter = _reporter; - } - this.options.reporterOptions = reporterOptions; - return this; -}; - -/** - * Set test UI `name`, defaults to "bdd". - * - * @param {String} bdd - * @api public - */ - -Mocha.prototype.ui = function(name){ - name = name || 'bdd'; - this._ui = exports.interfaces[name]; - if (!this._ui) try { this._ui = require(name); } catch (err) {} - if (!this._ui) throw new Error('invalid interface "' + name + '"'); - this._ui = this._ui(this.suite); - return this; -}; - -/** - * Load registered files. - * - * @api private - */ - -Mocha.prototype.loadFiles = function(fn){ - var self = this; - var suite = this.suite; - var pending = this.files.length; - this.files.forEach(function(file){ - file = path.resolve(file); - suite.emit('pre-require', global, file, self); - suite.emit('require', require(file), file, self); - suite.emit('post-require', global, file, self); - --pending || (fn && fn()); - }); -}; - -/** - * Enable growl support. - * - * @api private - */ - -Mocha.prototype._growl = function(runner, reporter) { - var notify = require('growl'); - - runner.on('end', function(){ - var stats = reporter.stats; - if (stats.failures) { - var msg = stats.failures + ' of ' + runner.total + ' tests failed'; - notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); - } else { - notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { - name: 'mocha' - , title: 'Passed' - , image: image('ok') - }); - } - }); -}; - -/** - * Add regexp to grep, if `re` is a string it is escaped. - * - * @param {RegExp|String} re - * @return {Mocha} - * @api public - */ - -Mocha.prototype.grep = function(re){ - this.options.grep = 'string' == typeof re - ? new RegExp(escapeRe(re)) - : re; - return this; -}; - -/** - * Invert `.grep()` matches. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.invert = function(){ - this.options.invert = true; - return this; -}; - -/** - * Ignore global leaks. - * - * @param {Boolean} ignore - * @return {Mocha} - * @api public - */ - -Mocha.prototype.ignoreLeaks = function(ignore){ - this.options.ignoreLeaks = !!ignore; - return this; -}; - -/** - * Enable global leak checking. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.checkLeaks = function(){ - this.options.ignoreLeaks = false; - return this; -}; - -/** - * Display long stack-trace on failing - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.fullTrace = function() { - this.options.fullStackTrace = true; - return this; -}; - -/** - * Enable growl support. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.growl = function(){ - this.options.growl = true; - return this; -}; - -/** - * Ignore `globals` array or string. - * - * @param {Array|String} globals - * @return {Mocha} - * @api public - */ - -Mocha.prototype.globals = function(globals){ - this.options.globals = (this.options.globals || []).concat(globals); - return this; -}; - -/** - * Emit color output. - * - * @param {Boolean} colors - * @return {Mocha} - * @api public - */ - -Mocha.prototype.useColors = function(colors){ - if (colors !== undefined) { - this.options.useColors = colors; - } - return this; -}; - -/** - * Use inline diffs rather than +/-. - * - * @param {Boolean} inlineDiffs - * @return {Mocha} - * @api public - */ - -Mocha.prototype.useInlineDiffs = function(inlineDiffs) { - this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined - ? inlineDiffs - : false; - return this; -}; - -/** - * Set the timeout in milliseconds. - * - * @param {Number} timeout - * @return {Mocha} - * @api public - */ - -Mocha.prototype.timeout = function(timeout){ - this.suite.timeout(timeout); - return this; -}; - -/** - * Set slowness threshold in milliseconds. - * - * @param {Number} slow - * @return {Mocha} - * @api public - */ - -Mocha.prototype.slow = function(slow){ - this.suite.slow(slow); - return this; -}; - -/** - * Enable timeouts. - * - * @param {Boolean} enabled - * @return {Mocha} - * @api public - */ - -Mocha.prototype.enableTimeouts = function(enabled) { - this.suite.enableTimeouts(arguments.length && enabled !== undefined - ? enabled - : true); - return this -}; - -/** - * Makes all tests async (accepting a callback) - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.asyncOnly = function(){ - this.options.asyncOnly = true; - return this; -}; - -/** - * Disable syntax highlighting (in browser). - * @returns {Mocha} - * @api public - */ -Mocha.prototype.noHighlighting = function() { - this.options.noHighlighting = true; - return this; -}; - -/** - * Delay root suite execution. - * @returns {Mocha} - * @api public - */ -Mocha.prototype.delay = function delay() { - this.options.delay = true; - return this; -}; - -/** - * Run tests and invoke `fn()` when complete. - * - * @param {Function} fn - * @return {Runner} - * @api public - */ -Mocha.prototype.run = function(fn){ - if (this.files.length) this.loadFiles(); - var suite = this.suite; - var options = this.options; - options.files = this.files; - var runner = new exports.Runner(suite, options.delay); - var reporter = new this._reporter(runner, options); - runner.ignoreLeaks = false !== options.ignoreLeaks; - runner.fullStackTrace = options.fullStackTrace; - runner.asyncOnly = options.asyncOnly; - if (options.grep) runner.grep(options.grep, options.invert); - if (options.globals) runner.globals(options.globals); - if (options.growl) this._growl(runner, reporter); - if (options.useColors !== undefined) { - exports.reporters.Base.useColors = options.useColors; - } - exports.reporters.Base.inlineDiffs = options.useInlineDiffs; - - function done(failures) { - if (reporter.done) { - reporter.done(failures, fn); - } else fn && fn(failures); - } - - return runner.run(done); -}; diff --git a/node_modules/mocha/lib/ms.js b/node_modules/mocha/lib/ms.js deleted file mode 100644 index ba451fa..0000000 --- a/node_modules/mocha/lib/ms.js +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} options - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options){ - options = options || {}; - if ('string' == typeof val) return parse(val); - return options['long'] ? longFormat(val) : shortFormat(val); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); - if (!match) return; - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 's': - return n * s; - case 'ms': - return n; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function shortFormat(ms) { - if (ms >= d) return Math.round(ms / d) + 'd'; - if (ms >= h) return Math.round(ms / h) + 'h'; - if (ms >= m) return Math.round(ms / m) + 'm'; - if (ms >= s) return Math.round(ms / s) + 's'; - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function longFormat(ms) { - return plural(ms, d, 'day') - || plural(ms, h, 'hour') - || plural(ms, m, 'minute') - || plural(ms, s, 'second') - || ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) return; - if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; - return Math.ceil(ms / n) + ' ' + name + 's'; -} diff --git a/node_modules/mocha/lib/pending.js b/node_modules/mocha/lib/pending.js deleted file mode 100644 index 265ec73..0000000 --- a/node_modules/mocha/lib/pending.js +++ /dev/null @@ -1,16 +0,0 @@ - -/** - * Expose `Pending`. - */ - -module.exports = Pending; - -/** - * Initialize a new `Pending` error with the given message. - * - * @param {String} message - */ - -function Pending(message) { - this.message = message; -} diff --git a/node_modules/mocha/lib/reporters/base.js b/node_modules/mocha/lib/reporters/base.js deleted file mode 100644 index 9b719a8..0000000 --- a/node_modules/mocha/lib/reporters/base.js +++ /dev/null @@ -1,466 +0,0 @@ -/** - * Module dependencies. - */ - -var tty = require('tty') - , diff = require('diff') - , ms = require('../ms') - , utils = require('../utils') - , supportsColor = process.env ? require('supports-color') : null; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Check if both stdio streams are associated with a tty. - */ - -var isatty = tty.isatty(1) && tty.isatty(2); - -/** - * Expose `Base`. - */ - -exports = module.exports = Base; - -/** - * Enable coloring by default, except in the browser interface. - */ - -exports.useColors = process.env - ? (supportsColor || (process.env.MOCHA_COLORS !== undefined)) - : false; - -/** - * Inline diffs instead of +/- - */ - -exports.inlineDiffs = false; - -/** - * Default color map. - */ - -exports.colors = { - 'pass': 90 - , 'fail': 31 - , 'bright pass': 92 - , 'bright fail': 91 - , 'bright yellow': 93 - , 'pending': 36 - , 'suite': 0 - , 'error title': 0 - , 'error message': 31 - , 'error stack': 90 - , 'checkmark': 32 - , 'fast': 90 - , 'medium': 33 - , 'slow': 31 - , 'green': 32 - , 'light': 90 - , 'diff gutter': 90 - , 'diff added': 32 - , 'diff removed': 31 -}; - -/** - * Default symbol map. - */ - -exports.symbols = { - ok: '✓', - err: '✖', - dot: '․' -}; - -// With node.js on Windows: use symbols available in terminal default fonts -if ('win32' == process.platform) { - exports.symbols.ok = '\u221A'; - exports.symbols.err = '\u00D7'; - exports.symbols.dot = '.'; -} - -/** - * Color `str` with the given `type`, - * allowing colors to be disabled, - * as well as user-defined color - * schemes. - * - * @param {String} type - * @param {String} str - * @return {String} - * @api private - */ - -var color = exports.color = function(type, str) { - if (!exports.useColors) return String(str); - return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; -}; - -/** - * Expose term window size, with some - * defaults for when stderr is not a tty. - */ - -exports.window = { - width: isatty - ? process.stdout.getWindowSize - ? process.stdout.getWindowSize(1)[0] - : tty.getWindowSize()[1] - : 75 -}; - -/** - * Expose some basic cursor interactions - * that are common among reporters. - */ - -exports.cursor = { - hide: function(){ - isatty && process.stdout.write('\u001b[?25l'); - }, - - show: function(){ - isatty && process.stdout.write('\u001b[?25h'); - }, - - deleteLine: function(){ - isatty && process.stdout.write('\u001b[2K'); - }, - - beginningOfLine: function(){ - isatty && process.stdout.write('\u001b[0G'); - }, - - CR: function(){ - if (isatty) { - exports.cursor.deleteLine(); - exports.cursor.beginningOfLine(); - } else { - process.stdout.write('\r'); - } - } -}; - -/** - * Outut the given `failures` as a list. - * - * @param {Array} failures - * @api public - */ - -exports.list = function(failures){ - console.log(); - failures.forEach(function(test, i){ - // format - var fmt = color('error title', ' %s) %s:\n') - + color('error message', ' %s') - + color('error stack', '\n%s\n'); - - // msg - var err = test.err - , message = err.message || '' - , stack = err.stack || message - , index = stack.indexOf(message) - , actual = err.actual - , expected = err.expected - , escape = true; - if (index === -1) { - msg = message; - } else { - index += message.length; - msg = stack.slice(0, index); - // remove msg from stack - stack = stack.slice(index + 1); - } - - // uncaught - if (err.uncaught) { - msg = 'Uncaught ' + msg; - } - // explicitly show diff - if (err.showDiff !== false && sameType(actual, expected) - && expected !== undefined) { - - escape = false; - if (!(utils.isString(actual) && utils.isString(expected))) { - err.actual = actual = utils.stringify(actual); - err.expected = expected = utils.stringify(expected); - } - - fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); - var match = message.match(/^([^:]+): expected/); - msg = '\n ' + color('error message', match ? match[1] : msg); - - if (exports.inlineDiffs) { - msg += inlineDiff(err, escape); - } else { - msg += unifiedDiff(err, escape); - } - } - - // indent stack trace - stack = stack.replace(/^/gm, ' '); - - console.log(fmt, (i + 1), test.fullTitle(), msg, stack); - }); -}; - -/** - * Initialize a new `Base` reporter. - * - * All other reporters generally - * inherit from this reporter, providing - * stats such as test duration, number - * of tests passed / failed etc. - * - * @param {Runner} runner - * @api public - */ - -function Base(runner) { - var self = this - , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } - , failures = this.failures = []; - - if (!runner) return; - this.runner = runner; - - runner.stats = stats; - - runner.on('start', function(){ - stats.start = new Date; - }); - - runner.on('suite', function(suite){ - stats.suites = stats.suites || 0; - suite.root || stats.suites++; - }); - - runner.on('test end', function(test){ - stats.tests = stats.tests || 0; - stats.tests++; - }); - - runner.on('pass', function(test){ - stats.passes = stats.passes || 0; - - var medium = test.slow() / 2; - test.speed = test.duration > test.slow() - ? 'slow' - : test.duration > medium - ? 'medium' - : 'fast'; - - stats.passes++; - }); - - runner.on('fail', function(test, err){ - stats.failures = stats.failures || 0; - stats.failures++; - test.err = err; - failures.push(test); - }); - - runner.on('end', function(){ - stats.end = new Date; - stats.duration = new Date - stats.start; - }); - - runner.on('pending', function(){ - stats.pending++; - }); -} - -/** - * Output common epilogue used by many of - * the bundled reporters. - * - * @api public - */ - -Base.prototype.epilogue = function(){ - var stats = this.stats; - var tests; - var fmt; - - console.log(); - - // passes - fmt = color('bright pass', ' ') - + color('green', ' %d passing') - + color('light', ' (%s)'); - - console.log(fmt, - stats.passes || 0, - ms(stats.duration)); - - // pending - if (stats.pending) { - fmt = color('pending', ' ') - + color('pending', ' %d pending'); - - console.log(fmt, stats.pending); - } - - // failures - if (stats.failures) { - fmt = color('fail', ' %d failing'); - - console.log(fmt, stats.failures); - - Base.list(this.failures); - console.log(); - } - - console.log(); -}; - -/** - * Pad the given `str` to `len`. - * - * @param {String} str - * @param {String} len - * @return {String} - * @api private - */ - -function pad(str, len) { - str = String(str); - return Array(len - str.length + 1).join(' ') + str; -} - - -/** - * Returns an inline diff between 2 strings with coloured ANSI output - * - * @param {Error} Error with actual/expected - * @return {String} Diff - * @api private - */ - -function inlineDiff(err, escape) { - var msg = errorDiff(err, 'WordsWithSpace', escape); - - // linenos - var lines = msg.split('\n'); - if (lines.length > 4) { - var width = String(lines.length).length; - msg = lines.map(function(str, i){ - return pad(++i, width) + ' |' + ' ' + str; - }).join('\n'); - } - - // legend - msg = '\n' - + color('diff removed', 'actual') - + ' ' - + color('diff added', 'expected') - + '\n\n' - + msg - + '\n'; - - // indent - msg = msg.replace(/^/gm, ' '); - return msg; -} - -/** - * Returns a unified diff between 2 strings - * - * @param {Error} Error with actual/expected - * @return {String} Diff - * @api private - */ - -function unifiedDiff(err, escape) { - var indent = ' '; - function cleanUp(line) { - if (escape) { - line = escapeInvisibles(line); - } - if (line[0] === '+') return indent + colorLines('diff added', line); - if (line[0] === '-') return indent + colorLines('diff removed', line); - if (line.match(/\@\@/)) return null; - if (line.match(/\\ No newline/)) return null; - else return indent + line; - } - function notBlank(line) { - return line != null; - } - var msg = diff.createPatch('string', err.actual, err.expected); - var lines = msg.split('\n').splice(4); - return '\n ' - + colorLines('diff added', '+ expected') + ' ' - + colorLines('diff removed', '- actual') - + '\n\n' - + lines.map(cleanUp).filter(notBlank).join('\n'); -} - -/** - * Return a character diff for `err`. - * - * @param {Error} err - * @return {String} - * @api private - */ - -function errorDiff(err, type, escape) { - var actual = escape ? escapeInvisibles(err.actual) : err.actual; - var expected = escape ? escapeInvisibles(err.expected) : err.expected; - return diff['diff' + type](actual, expected).map(function(str){ - if (str.added) return colorLines('diff added', str.value); - if (str.removed) return colorLines('diff removed', str.value); - return str.value; - }).join(''); -} - -/** - * Returns a string with all invisible characters in plain text - * - * @param {String} line - * @return {String} - * @api private - */ -function escapeInvisibles(line) { - return line.replace(/\t/g, '') - .replace(/\r/g, '') - .replace(/\n/g, '\n'); -} - -/** - * Color lines for `str`, using the color `name`. - * - * @param {String} name - * @param {String} str - * @return {String} - * @api private - */ - -function colorLines(name, str) { - return str.split('\n').map(function(str){ - return color(name, str); - }).join('\n'); -} - -/** - * Check that a / b have the same type. - * - * @param {Object} a - * @param {Object} b - * @return {Boolean} - * @api private - */ - -function sameType(a, b) { - a = Object.prototype.toString.call(a); - b = Object.prototype.toString.call(b); - return a == b; -} diff --git a/node_modules/mocha/lib/reporters/doc.js b/node_modules/mocha/lib/reporters/doc.js deleted file mode 100644 index d194eb0..0000000 --- a/node_modules/mocha/lib/reporters/doc.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Doc`. - */ - -exports = module.exports = Doc; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Doc(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , indents = 2; - - function indent() { - return Array(indents).join(' '); - } - - runner.on('suite', function(suite){ - if (suite.root) return; - ++indents; - console.log('%s
', indent()); - ++indents; - console.log('%s

%s

', indent(), utils.escape(suite.title)); - console.log('%s
', indent()); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - console.log('%s
', indent()); - --indents; - console.log('%s
', indent()); - --indents; - }); - - runner.on('pass', function(test){ - console.log('%s
%s
', indent(), utils.escape(test.title)); - var code = utils.escape(utils.clean(test.fn.toString())); - console.log('%s
%s
', indent(), code); - }); - - runner.on('fail', function(test, err){ - console.log('%s
%s
', indent(), utils.escape(test.title)); - var code = utils.escape(utils.clean(test.fn.toString())); - console.log('%s
%s
', indent(), code); - console.log('%s
%s
', indent(), utils.escape(err)); - }); -} diff --git a/node_modules/mocha/lib/reporters/dot.js b/node_modules/mocha/lib/reporters/dot.js deleted file mode 100644 index 42a45ee..0000000 --- a/node_modules/mocha/lib/reporters/dot.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = Dot; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Dot(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , n = -1; - - runner.on('start', function(){ - process.stdout.write('\n'); - }); - - runner.on('pending', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('pending', Base.symbols.dot)); - }); - - runner.on('pass', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - if ('slow' == test.speed) { - process.stdout.write(color('bright yellow', Base.symbols.dot)); - } else { - process.stdout.write(color(test.speed, Base.symbols.dot)); - } - }); - - runner.on('fail', function(test, err){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('fail', Base.symbols.dot)); - }); - - runner.on('end', function(){ - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -Dot.prototype.__proto__ = Base.prototype; diff --git a/node_modules/mocha/lib/reporters/html-cov.js b/node_modules/mocha/lib/reporters/html-cov.js deleted file mode 100644 index 74b46ad..0000000 --- a/node_modules/mocha/lib/reporters/html-cov.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Module dependencies. - */ - -var JSONCov = require('./json-cov') - , fs = require('fs'); - -/** - * Expose `HTMLCov`. - */ - -exports = module.exports = HTMLCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTMLCov(runner) { - var jade = require('jade') - , file = __dirname + '/templates/coverage.jade' - , str = fs.readFileSync(file, 'utf8') - , fn = jade.compile(str, { filename: file }) - , self = this; - - JSONCov.call(this, runner, false); - - runner.on('end', function(){ - process.stdout.write(fn({ - cov: self.cov - , coverageClass: coverageClass - })); - }); -} - -/** - * Return coverage class for `n`. - * - * @return {String} - * @api private - */ - -function coverageClass(n) { - if (n >= 75) return 'high'; - if (n >= 50) return 'medium'; - if (n >= 25) return 'low'; - return 'terrible'; -} diff --git a/node_modules/mocha/lib/reporters/html.js b/node_modules/mocha/lib/reporters/html.js deleted file mode 100644 index aec2af0..0000000 --- a/node_modules/mocha/lib/reporters/html.js +++ /dev/null @@ -1,287 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , Progress = require('../browser/progress') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `HTML`. - */ - -exports = module.exports = HTML; - -/** - * Stats template. - */ - -var statsTemplate = ''; - -/** - * Initialize a new `HTML` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTML(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , stat = fragment(statsTemplate) - , items = stat.getElementsByTagName('li') - , passes = items[1].getElementsByTagName('em')[0] - , passesLink = items[1].getElementsByTagName('a')[0] - , failures = items[2].getElementsByTagName('em')[0] - , failuresLink = items[2].getElementsByTagName('a')[0] - , duration = items[3].getElementsByTagName('em')[0] - , canvas = stat.getElementsByTagName('canvas')[0] - , report = fragment('
    ') - , stack = [report] - , progress - , ctx - , root = document.getElementById('mocha'); - - if (canvas.getContext) { - var ratio = window.devicePixelRatio || 1; - canvas.style.width = canvas.width; - canvas.style.height = canvas.height; - canvas.width *= ratio; - canvas.height *= ratio; - ctx = canvas.getContext('2d'); - ctx.scale(ratio, ratio); - progress = new Progress; - } - - if (!root) return error('#mocha div missing, add it to your document'); - - // pass toggle - on(passesLink, 'click', function(){ - unhide(); - var name = /pass/.test(report.className) ? '' : ' pass'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test pass'); - }); - - // failure toggle - on(failuresLink, 'click', function(){ - unhide(); - var name = /fail/.test(report.className) ? '' : ' fail'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test fail'); - }); - - root.appendChild(stat); - root.appendChild(report); - - if (progress) progress.size(40); - - runner.on('suite', function(suite){ - if (suite.root) return; - - // suite - var url = self.suiteURL(suite); - var el = fragment('
  • %s

  • ', url, escape(suite.title)); - - // container - stack[0].appendChild(el); - stack.unshift(document.createElement('ul')); - el.appendChild(stack[0]); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - stack.shift(); - }); - - runner.on('fail', function(test, err){ - if ('hook' == test.type) runner.emit('test end', test); - }); - - runner.on('test end', function(test){ - // TODO: add to stats - var percent = stats.tests / this.total * 100 | 0; - if (progress) progress.update(percent).draw(ctx); - - // update stats - var ms = new Date - stats.start; - text(passes, stats.passes); - text(failures, stats.failures); - text(duration, (ms / 1000).toFixed(2)); - - // test - if ('passed' == test.state) { - var url = self.testURL(test); - var el = fragment('
  • %e%ems

  • ', test.speed, test.title, test.duration, url); - } else if (test.pending) { - var el = fragment('
  • %e

  • ', test.title); - } else { - var el = fragment('
  • %e

  • ', test.title, self.testURL(test)); - var str = test.err.stack || test.err.toString(); - - // FF / Opera do not add the message - if (!~str.indexOf(test.err.message)) { - str = test.err.message + '\n' + str; - } - - // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we - // check for the result of the stringifying. - if ('[object Error]' == str) str = test.err.message; - - // Safari doesn't give you a stack. Let's at least provide a source line. - if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { - str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; - } - - el.appendChild(fragment('
    %e
    ', str)); - } - - // toggle code - // TODO: defer - if (!test.pending) { - var h2 = el.getElementsByTagName('h2')[0]; - - on(h2, 'click', function(){ - pre.style.display = 'none' == pre.style.display - ? 'block' - : 'none'; - }); - - var pre = fragment('
    %e
    ', utils.clean(test.fn.toString())); - el.appendChild(pre); - pre.style.display = 'none'; - } - - // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. - if (stack[0]) stack[0].appendChild(el); - }); -} - -/** - * Makes a URL, preserving querystring ("search") parameters. - * @param {string} s - * @returns {string} your new URL - */ -var makeUrl = function makeUrl(s) { - var search = window.location.search; - - // Remove previous grep query parameter if present - if (search) { - search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?'); - } - - return window.location.pathname + (search ? search + '&' : '?' ) + 'grep=' + encodeURIComponent(s); -}; - -/** - * Provide suite URL - * - * @param {Object} [suite] - */ -HTML.prototype.suiteURL = function(suite){ - return makeUrl(suite.fullTitle()); -}; - -/** - * Provide test URL - * - * @param {Object} [test] - */ - -HTML.prototype.testURL = function(test){ - return makeUrl(test.fullTitle()); -}; - -/** - * Display error `msg`. - */ - -function error(msg) { - document.body.appendChild(fragment('
    %s
    ', msg)); -} - -/** - * Return a DOM fragment from `html`. - */ - -function fragment(html) { - var args = arguments - , div = document.createElement('div') - , i = 1; - - div.innerHTML = html.replace(/%([se])/g, function(_, type){ - switch (type) { - case 's': return String(args[i++]); - case 'e': return escape(args[i++]); - } - }); - - return div.firstChild; -} - -/** - * Check for suites that do not have elements - * with `classname`, and hide them. - */ - -function hideSuitesWithout(classname) { - var suites = document.getElementsByClassName('suite'); - for (var i = 0; i < suites.length; i++) { - var els = suites[i].getElementsByClassName(classname); - if (0 == els.length) suites[i].className += ' hidden'; - } -} - -/** - * Unhide .hidden suites. - */ - -function unhide() { - var els = document.getElementsByClassName('suite hidden'); - for (var i = 0; i < els.length; ++i) { - els[i].className = els[i].className.replace('suite hidden', 'suite'); - } -} - -/** - * Set `el` text to `str`. - */ - -function text(el, str) { - if (el.textContent) { - el.textContent = str; - } else { - el.innerText = str; - } -} - -/** - * Listen on `event` with callback `fn`. - */ - -function on(el, event, fn) { - if (el.addEventListener) { - el.addEventListener(event, fn, false); - } else { - el.attachEvent('on' + event, fn); - } -} diff --git a/node_modules/mocha/lib/reporters/index.js b/node_modules/mocha/lib/reporters/index.js deleted file mode 100644 index 87b76d9..0000000 --- a/node_modules/mocha/lib/reporters/index.js +++ /dev/null @@ -1,17 +0,0 @@ -exports.Base = require('./base'); -exports.Dot = require('./dot'); -exports.Doc = require('./doc'); -exports.TAP = require('./tap'); -exports.JSON = require('./json'); -exports.HTML = require('./html'); -exports.List = require('./list'); -exports.Min = require('./min'); -exports.Spec = require('./spec'); -exports.Nyan = require('./nyan'); -exports.XUnit = require('./xunit'); -exports.Markdown = require('./markdown'); -exports.Progress = require('./progress'); -exports.Landing = require('./landing'); -exports.JSONCov = require('./json-cov'); -exports.HTMLCov = require('./html-cov'); -exports.JSONStream = require('./json-stream'); diff --git a/node_modules/mocha/lib/reporters/json-cov.js b/node_modules/mocha/lib/reporters/json-cov.js deleted file mode 100644 index 309c0ef..0000000 --- a/node_modules/mocha/lib/reporters/json-cov.js +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `JSONCov`. - */ - -exports = module.exports = JSONCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @param {Boolean} output - * @api public - */ - -function JSONCov(runner, output) { - var self = this - , output = 1 == arguments.length ? true : output; - - Base.call(this, runner); - - var tests = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('end', function(){ - var cov = global._$jscoverage || {}; - var result = self.cov = map(cov); - result.stats = self.stats; - result.tests = tests.map(clean); - result.failures = failures.map(clean); - result.passes = passes.map(clean); - if (!output) return; - process.stdout.write(JSON.stringify(result, null, 2 )); - }); -} - -/** - * Map jscoverage data to a JSON structure - * suitable for reporting. - * - * @param {Object} cov - * @return {Object} - * @api private - */ - -function map(cov) { - var ret = { - instrumentation: 'node-jscoverage' - , sloc: 0 - , hits: 0 - , misses: 0 - , coverage: 0 - , files: [] - }; - - for (var filename in cov) { - var data = coverage(filename, cov[filename]); - ret.files.push(data); - ret.hits += data.hits; - ret.misses += data.misses; - ret.sloc += data.sloc; - } - - ret.files.sort(function(a, b) { - return a.filename.localeCompare(b.filename); - }); - - if (ret.sloc > 0) { - ret.coverage = (ret.hits / ret.sloc) * 100; - } - - return ret; -} - -/** - * Map jscoverage data for a single source file - * to a JSON structure suitable for reporting. - * - * @param {String} filename name of the source file - * @param {Object} data jscoverage coverage data - * @return {Object} - * @api private - */ - -function coverage(filename, data) { - var ret = { - filename: filename, - coverage: 0, - hits: 0, - misses: 0, - sloc: 0, - source: {} - }; - - data.source.forEach(function(line, num){ - num++; - - if (data[num] === 0) { - ret.misses++; - ret.sloc++; - } else if (data[num] !== undefined) { - ret.hits++; - ret.sloc++; - } - - ret.source[num] = { - source: line - , coverage: data[num] === undefined - ? '' - : data[num] - }; - }); - - ret.coverage = ret.hits / ret.sloc * 100; - - return ret; -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} diff --git a/node_modules/mocha/lib/reporters/json-stream.js b/node_modules/mocha/lib/reporters/json-stream.js deleted file mode 100644 index f7c05a8..0000000 --- a/node_modules/mocha/lib/reporters/json-stream.js +++ /dev/null @@ -1,62 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total; - - runner.on('start', function(){ - console.log(JSON.stringify(['start', { total: total }])); - }); - - runner.on('pass', function(test){ - console.log(JSON.stringify(['pass', clean(test)])); - }); - - runner.on('fail', function(test, err){ - test = clean(test); - test.err = err.message; - console.log(JSON.stringify(['fail', test])); - }); - - runner.on('end', function(){ - process.stdout.write(JSON.stringify(['end', self.stats])); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} diff --git a/node_modules/mocha/lib/reporters/json.js b/node_modules/mocha/lib/reporters/json.js deleted file mode 100644 index f565506..0000000 --- a/node_modules/mocha/lib/reporters/json.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `JSON`. - */ - -exports = module.exports = JSONReporter; - -/** - * Initialize a new `JSON` reporter. - * - * @param {Runner} runner - * @api public - */ - -function JSONReporter(runner) { - var self = this; - Base.call(this, runner); - - var tests = [] - , pending = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('pending', function(test){ - pending.push(test); - }); - - runner.on('end', function(){ - var obj = { - stats: self.stats, - tests: tests.map(clean), - pending: pending.map(clean), - failures: failures.map(clean), - passes: passes.map(clean) - }; - - runner.testResults = obj; - - process.stdout.write(JSON.stringify(obj, null, 2)); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title, - fullTitle: test.fullTitle(), - duration: test.duration, - err: errorJSON(test.err || {}) - } -} - -/** - * Transform `error` into a JSON object. - * @param {Error} err - * @return {Object} - */ - -function errorJSON(err) { - var res = {}; - Object.getOwnPropertyNames(err).forEach(function(key) { - res[key] = err[key]; - }, err); - return res; -} diff --git a/node_modules/mocha/lib/reporters/landing.js b/node_modules/mocha/lib/reporters/landing.js deleted file mode 100644 index ee004a2..0000000 --- a/node_modules/mocha/lib/reporters/landing.js +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Landing`. - */ - -exports = module.exports = Landing; - -/** - * Airplane color. - */ - -Base.colors.plane = 0; - -/** - * Airplane crash color. - */ - -Base.colors['plane crash'] = 31; - -/** - * Runway color. - */ - -Base.colors.runway = 90; - -/** - * Initialize a new `Landing` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Landing(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , total = runner.total - , stream = process.stdout - , plane = color('plane', '✈') - , crashed = -1 - , n = 0; - - function runway() { - var buf = Array(width).join('-'); - return ' ' + color('runway', buf); - } - - runner.on('start', function(){ - stream.write('\n\n\n '); - cursor.hide(); - }); - - runner.on('test end', function(test){ - // check if the plane crashed - var col = -1 == crashed - ? width * ++n / total | 0 - : crashed; - - // show the crash - if ('failed' == test.state) { - plane = color('plane crash', '✈'); - crashed = col; - } - - // render landing strip - stream.write('\u001b['+(width+1)+'D\u001b[2A'); - stream.write(runway()); - stream.write('\n '); - stream.write(color('runway', Array(col).join('⋅'))); - stream.write(plane) - stream.write(color('runway', Array(width - col).join('⋅') + '\n')); - stream.write(runway()); - stream.write('\u001b[0m'); - }); - - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -Landing.prototype.__proto__ = Base.prototype; diff --git a/node_modules/mocha/lib/reporters/list.js b/node_modules/mocha/lib/reporters/list.js deleted file mode 100644 index f64367a..0000000 --- a/node_modules/mocha/lib/reporters/list.js +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 0; - - runner.on('start', function(){ - console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = color('checkmark', ' -') - + color('pending', ' %s'); - console.log(fmt, test.fullTitle()); - }); - - runner.on('pass', function(test){ - var fmt = color('checkmark', ' '+Base.symbols.dot) - + color('pass', ' %s: ') - + color(test.speed, '%dms'); - cursor.CR(); - console.log(fmt, test.fullTitle(), test.duration); - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -List.prototype.__proto__ = Base.prototype; diff --git a/node_modules/mocha/lib/reporters/markdown.js b/node_modules/mocha/lib/reporters/markdown.js deleted file mode 100644 index e14174c..0000000 --- a/node_modules/mocha/lib/reporters/markdown.js +++ /dev/null @@ -1,100 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Constants - */ - -var SUITE_PREFIX = '$'; - -/** - * Expose `Markdown`. - */ - -exports = module.exports = Markdown; - -/** - * Initialize a new `Markdown` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Markdown(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , level = 0 - , buf = ''; - - function title(str) { - return Array(level).join('#') + ' ' + str; - } - - function indent() { - return Array(level).join(' '); - } - - function mapTOC(suite, obj) { - var ret = obj, - key = SUITE_PREFIX + suite.title; - obj = obj[key] = obj[key] || { suite: suite }; - suite.suites.forEach(function(suite){ - mapTOC(suite, obj); - }); - return ret; - } - - function stringifyTOC(obj, level) { - ++level; - var buf = ''; - var link; - for (var key in obj) { - if ('suite' == key) continue; - if (key !== SUITE_PREFIX) { - link = ' - [' + key.substring(1) + ']'; - link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; - buf += Array(level).join(' ') + link; - } - buf += stringifyTOC(obj[key], level); - } - return buf; - } - - function generateTOC(suite) { - var obj = mapTOC(suite, {}); - return stringifyTOC(obj, 0); - } - - generateTOC(runner.suite); - - runner.on('suite', function(suite){ - ++level; - var slug = utils.slug(suite.fullTitle()); - buf += '' + '\n'; - buf += title(suite.title) + '\n'; - }); - - runner.on('suite end', function(suite){ - --level; - }); - - runner.on('pass', function(test){ - var code = utils.clean(test.fn.toString()); - buf += test.title + '.\n'; - buf += '\n```js\n'; - buf += code + '\n'; - buf += '```\n\n'; - }); - - runner.on('end', function(){ - process.stdout.write('# TOC\n'); - process.stdout.write(generateTOC(runner.suite)); - process.stdout.write(buf); - }); -} diff --git a/node_modules/mocha/lib/reporters/min.js b/node_modules/mocha/lib/reporters/min.js deleted file mode 100644 index ce1a3fe..0000000 --- a/node_modules/mocha/lib/reporters/min.js +++ /dev/null @@ -1,37 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Min`. - */ - -exports = module.exports = Min; - -/** - * Initialize a new `Min` minimal test reporter (best used with --watch). - * - * @param {Runner} runner - * @api public - */ - -function Min(runner) { - Base.call(this, runner); - - runner.on('start', function(){ - // clear screen - process.stdout.write('\u001b[2J'); - // set cursor position - process.stdout.write('\u001b[1;3H'); - }); - - runner.on('end', this.epilogue.bind(this)); -} - -/** - * Inherit from `Base.prototype`. - */ - -Min.prototype.__proto__ = Base.prototype; diff --git a/node_modules/mocha/lib/reporters/nyan.js b/node_modules/mocha/lib/reporters/nyan.js deleted file mode 100644 index 63056b1..0000000 --- a/node_modules/mocha/lib/reporters/nyan.js +++ /dev/null @@ -1,260 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Dot`. - */ - -exports = module.exports = NyanCat; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function NyanCat(runner) { - Base.call(this, runner); - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , rainbowColors = this.rainbowColors = self.generateColors() - , colorIndex = this.colorIndex = 0 - , numerOfLines = this.numberOfLines = 4 - , trajectories = this.trajectories = [[], [], [], []] - , nyanCatWidth = this.nyanCatWidth = 11 - , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) - , scoreboardWidth = this.scoreboardWidth = 5 - , tick = this.tick = 0 - , n = 0; - - runner.on('start', function(){ - Base.cursor.hide(); - self.draw(); - }); - - runner.on('pending', function(test){ - self.draw(); - }); - - runner.on('pass', function(test){ - self.draw(); - }); - - runner.on('fail', function(test, err){ - self.draw(); - }); - - runner.on('end', function(){ - Base.cursor.show(); - for (var i = 0; i < self.numberOfLines; i++) write('\n'); - self.epilogue(); - }); -} - -/** - * Draw the nyan cat - * - * @api private - */ - -NyanCat.prototype.draw = function(){ - this.appendRainbow(); - this.drawScoreboard(); - this.drawRainbow(); - this.drawNyanCat(); - this.tick = !this.tick; -}; - -/** - * Draw the "scoreboard" showing the number - * of passes, failures and pending tests. - * - * @api private - */ - -NyanCat.prototype.drawScoreboard = function(){ - var stats = this.stats; - - function draw(type, n) { - write(' '); - write(Base.color(type, n)); - write('\n'); - } - - draw('green', stats.passes); - draw('fail', stats.failures); - draw('pending', stats.pending); - write('\n'); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Append the rainbow. - * - * @api private - */ - -NyanCat.prototype.appendRainbow = function(){ - var segment = this.tick ? '_' : '-'; - var rainbowified = this.rainbowify(segment); - - for (var index = 0; index < this.numberOfLines; index++) { - var trajectory = this.trajectories[index]; - if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); - trajectory.push(rainbowified); - } -}; - -/** - * Draw the rainbow. - * - * @api private - */ - -NyanCat.prototype.drawRainbow = function(){ - var self = this; - - this.trajectories.forEach(function(line, index) { - write('\u001b[' + self.scoreboardWidth + 'C'); - write(line.join('')); - write('\n'); - }); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Draw the nyan cat - * - * @api private - */ - -NyanCat.prototype.drawNyanCat = function() { - var self = this; - var startWidth = this.scoreboardWidth + this.trajectories[0].length; - var dist = '\u001b[' + startWidth + 'C'; - var padding = ''; - - write(dist); - write('_,------,'); - write('\n'); - - write(dist); - padding = self.tick ? ' ' : ' '; - write('_|' + padding + '/\\_/\\ '); - write('\n'); - - write(dist); - padding = self.tick ? '_' : '__'; - var tail = self.tick ? '~' : '^'; - var face; - write(tail + '|' + padding + this.face() + ' '); - write('\n'); - - write(dist); - padding = self.tick ? ' ' : ' '; - write(padding + '"" "" '); - write('\n'); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Draw nyan cat face. - * - * @return {String} - * @api private - */ - -NyanCat.prototype.face = function() { - var stats = this.stats; - if (stats.failures) { - return '( x .x)'; - } else if (stats.pending) { - return '( o .o)'; - } else if(stats.passes) { - return '( ^ .^)'; - } else { - return '( - .-)'; - } -}; - -/** - * Move cursor up `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorUp = function(n) { - write('\u001b[' + n + 'A'); -}; - -/** - * Move cursor down `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorDown = function(n) { - write('\u001b[' + n + 'B'); -}; - -/** - * Generate rainbow colors. - * - * @return {Array} - * @api private - */ - -NyanCat.prototype.generateColors = function(){ - var colors = []; - - for (var i = 0; i < (6 * 7); i++) { - var pi3 = Math.floor(Math.PI / 3); - var n = (i * (1.0 / 6)); - var r = Math.floor(3 * Math.sin(n) + 3); - var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); - var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); - colors.push(36 * r + 6 * g + b + 16); - } - - return colors; -}; - -/** - * Apply rainbow to the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -NyanCat.prototype.rainbowify = function(str){ - if (!Base.useColors) - return str; - var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; - this.colorIndex += 1; - return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; -}; - -/** - * Stdout helper. - */ - -function write(string) { - process.stdout.write(string); -} - -/** - * Inherit from `Base.prototype`. - */ - -NyanCat.prototype.__proto__ = Base.prototype; diff --git a/node_modules/mocha/lib/reporters/progress.js b/node_modules/mocha/lib/reporters/progress.js deleted file mode 100644 index 2debb94..0000000 --- a/node_modules/mocha/lib/reporters/progress.js +++ /dev/null @@ -1,92 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Progress`. - */ - -exports = module.exports = Progress; - -/** - * General progress bar color. - */ - -Base.colors.progress = 90; - -/** - * Initialize a new `Progress` bar test reporter. - * - * @param {Runner} runner - * @param {Object} options - * @api public - */ - -function Progress(runner, options) { - Base.call(this, runner); - - var self = this - , options = options || {} - , stats = this.stats - , width = Base.window.width * .50 | 0 - , total = runner.total - , complete = 0 - , max = Math.max - , lastN = -1; - - // default chars - options.open = options.open || '['; - options.complete = options.complete || '▬'; - options.incomplete = options.incomplete || Base.symbols.dot; - options.close = options.close || ']'; - options.verbose = false; - - // tests started - runner.on('start', function(){ - console.log(); - cursor.hide(); - }); - - // tests complete - runner.on('test end', function(){ - complete++; - var incomplete = total - complete - , percent = complete / total - , n = width * percent | 0 - , i = width - n; - - if (lastN === n && !options.verbose) { - // Don't re-render the line if it hasn't changed - return; - } - lastN = n; - - cursor.CR(); - process.stdout.write('\u001b[J'); - process.stdout.write(color('progress', ' ' + options.open)); - process.stdout.write(Array(n).join(options.complete)); - process.stdout.write(Array(i).join(options.incomplete)); - process.stdout.write(color('progress', options.close)); - if (options.verbose) { - process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); - } - }); - - // tests are complete, output some stats - // and the failures if any - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -Progress.prototype.__proto__ = Base.prototype; diff --git a/node_modules/mocha/lib/reporters/spec.js b/node_modules/mocha/lib/reporters/spec.js deleted file mode 100644 index 3debffe..0000000 --- a/node_modules/mocha/lib/reporters/spec.js +++ /dev/null @@ -1,82 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Spec`. - */ - -exports = module.exports = Spec; - -/** - * Initialize a new `Spec` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Spec(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , indents = 0 - , n = 0; - - function indent() { - return Array(indents).join(' ') - } - - runner.on('start', function(){ - console.log(); - }); - - runner.on('suite', function(suite){ - ++indents; - console.log(color('suite', '%s%s'), indent(), suite.title); - }); - - runner.on('suite end', function(suite){ - --indents; - if (1 == indents) console.log(); - }); - - runner.on('pending', function(test){ - var fmt = indent() + color('pending', ' - %s'); - console.log(fmt, test.title); - }); - - runner.on('pass', function(test){ - if ('fast' == test.speed) { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s'); - cursor.CR(); - console.log(fmt, test.title); - } else { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s') - + color(test.speed, ' (%dms)'); - cursor.CR(); - console.log(fmt, test.title, test.duration); - } - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -Spec.prototype.__proto__ = Base.prototype; diff --git a/node_modules/mocha/lib/reporters/tap.js b/node_modules/mocha/lib/reporters/tap.js deleted file mode 100644 index 01a92eb..0000000 --- a/node_modules/mocha/lib/reporters/tap.js +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `TAP`. - */ - -exports = module.exports = TAP; - -/** - * Initialize a new `TAP` reporter. - * - * @param {Runner} runner - * @api public - */ - -function TAP(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 1 - , passes = 0 - , failures = 0; - - runner.on('start', function(){ - var total = runner.grepTotal(runner.suite); - console.log('%d..%d', 1, total); - }); - - runner.on('test end', function(){ - ++n; - }); - - runner.on('pending', function(test){ - console.log('ok %d %s # SKIP -', n, title(test)); - }); - - runner.on('pass', function(test){ - passes++; - console.log('ok %d %s', n, title(test)); - }); - - runner.on('fail', function(test, err){ - failures++; - console.log('not ok %d %s', n, title(test)); - if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); - }); - - runner.on('end', function(){ - console.log('# tests ' + (passes + failures)); - console.log('# pass ' + passes); - console.log('# fail ' + failures); - }); -} - -/** - * Return a TAP-safe title of `test` - * - * @param {Object} test - * @return {String} - * @api private - */ - -function title(test) { - return test.fullTitle().replace(/#/g, ''); -} diff --git a/node_modules/mocha/lib/reporters/templates/coverage.jade b/node_modules/mocha/lib/reporters/templates/coverage.jade deleted file mode 100644 index edd59d8..0000000 --- a/node_modules/mocha/lib/reporters/templates/coverage.jade +++ /dev/null @@ -1,51 +0,0 @@ -doctype html -html - head - title Coverage - meta(charset='utf-8') - include script.html - include style.html - body - #coverage - h1#overview Coverage - include menu - - #stats(class=coverageClass(cov.coverage)) - .percentage #{cov.coverage | 0}% - .sloc= cov.sloc - .hits= cov.hits - .misses= cov.misses - - #files - for file in cov.files - .file - h2(id=file.filename)= file.filename - #stats(class=coverageClass(file.coverage)) - .percentage #{file.coverage | 0}% - .sloc= file.sloc - .hits= file.hits - .misses= file.misses - - table#source - thead - tr - th Line - th Hits - th Source - tbody - for line, number in file.source - if line.coverage > 0 - tr.hit - td.line= number - td.hits= line.coverage - td.source= line.source - else if 0 === line.coverage - tr.miss - td.line= number - td.hits 0 - td.source= line.source - else - tr - td.line= number - td.hits - td.source= line.source || ' ' diff --git a/node_modules/mocha/lib/reporters/templates/menu.jade b/node_modules/mocha/lib/reporters/templates/menu.jade deleted file mode 100644 index c682e3f..0000000 --- a/node_modules/mocha/lib/reporters/templates/menu.jade +++ /dev/null @@ -1,13 +0,0 @@ -#menu - li - a(href='#overview') overview - for file in cov.files - li - span.cov(class=coverageClass(file.coverage)) #{file.coverage | 0} - a(href='##{file.filename}') - segments = file.filename.split('/') - basename = segments.pop() - if segments.length - span.dirname= segments.join('/') + '/' - span.basename= basename - a#logo(href='http://mochajs.org/') m diff --git a/node_modules/mocha/lib/reporters/templates/script.html b/node_modules/mocha/lib/reporters/templates/script.html deleted file mode 100644 index 073cf79..0000000 --- a/node_modules/mocha/lib/reporters/templates/script.html +++ /dev/null @@ -1,34 +0,0 @@ - diff --git a/node_modules/mocha/lib/reporters/templates/style.html b/node_modules/mocha/lib/reporters/templates/style.html deleted file mode 100644 index 4c9c37c..0000000 --- a/node_modules/mocha/lib/reporters/templates/style.html +++ /dev/null @@ -1,324 +0,0 @@ - diff --git a/node_modules/mocha/lib/reporters/xunit.js b/node_modules/mocha/lib/reporters/xunit.js deleted file mode 100644 index 77cd347..0000000 --- a/node_modules/mocha/lib/reporters/xunit.js +++ /dev/null @@ -1,149 +0,0 @@ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , fs = require('fs') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `XUnit`. - */ - -exports = module.exports = XUnit; - -/** - * Initialize a new `XUnit` reporter. - * - * @param {Runner} runner - * @api public - */ - -function XUnit(runner, options) { - Base.call(this, runner); - var stats = this.stats - , tests = [] - , self = this; - - if (options.reporterOptions && options.reporterOptions.output) { - if (! fs.createWriteStream) { - throw new Error('file output not supported in browser'); - } - self.fileStream = fs.createWriteStream(options.reporterOptions.output); - } - - runner.on('pending', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - tests.push(test); - }); - - runner.on('fail', function(test){ - tests.push(test); - }); - - runner.on('end', function(){ - self.write(tag('testsuite', { - name: 'Mocha Tests' - , tests: stats.tests - , failures: stats.failures - , errors: stats.failures - , skipped: stats.tests - stats.failures - stats.passes - , timestamp: (new Date).toUTCString() - , time: (stats.duration / 1000) || 0 - }, false)); - - tests.forEach(function(t) { self.test(t); }); - self.write(''); - }); -} - -/** - * Override done to close the stream (if it's a file). - */ -XUnit.prototype.done = function(failures, fn) { - if (this.fileStream) { - this.fileStream.end(function() { - fn(failures); - }); - } else { - fn(failures); - } -}; - -/** - * Inherit from `Base.prototype`. - */ - -XUnit.prototype.__proto__ = Base.prototype; - -/** - * Write out the given line - */ -XUnit.prototype.write = function(line) { - if (this.fileStream) { - this.fileStream.write(line + '\n'); - } else { - console.log(line); - } -}; - -/** - * Output tag for the given `test.` - */ - -XUnit.prototype.test = function(test, ostream) { - var attrs = { - classname: test.parent.fullTitle() - , name: test.title - , time: (test.duration / 1000) || 0 - }; - - if ('failed' == test.state) { - var err = test.err; - this.write(tag('testcase', attrs, false, tag('failure', {}, false, cdata(escape(err.message) + "\n" + err.stack)))); - } else if (test.pending) { - this.write(tag('testcase', attrs, false, tag('skipped', {}, true))); - } else { - this.write(tag('testcase', attrs, true) ); - } -}; - -/** - * HTML tag helper. - */ - -function tag(name, attrs, close, content) { - var end = close ? '/>' : '>' - , pairs = [] - , tag; - - for (var key in attrs) { - pairs.push(key + '="' + escape(attrs[key]) + '"'); - } - - tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; - if (content) tag += content + ''; -} diff --git a/node_modules/mocha/lib/runnable.js b/node_modules/mocha/lib/runnable.js deleted file mode 100644 index 6e4803f..0000000 --- a/node_modules/mocha/lib/runnable.js +++ /dev/null @@ -1,280 +0,0 @@ -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , debug = require('debug')('mocha:runnable') - , Pending = require('./pending') - , milliseconds = require('./ms') - , utils = require('./utils'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Object#toString(). - */ - -var toString = Object.prototype.toString; - -/** - * Expose `Runnable`. - */ - -module.exports = Runnable; - -/** - * Initialize a new `Runnable` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Runnable(title, fn) { - this.title = title; - this.fn = fn; - this.async = fn && fn.length; - this.sync = ! this.async; - this._timeout = 2000; - this._slow = 75; - this._enableTimeouts = true; - this.timedOut = false; - this._trace = new Error('done() called multiple times') -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Runnable.prototype.__proto__ = EventEmitter.prototype; - -/** - * Set & get timeout `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if (ms === 0) this._enableTimeouts = false; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = ms; - if (this.timer) this.resetTimeout(); - return this; -}; - -/** - * Set & get slow `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._slow = ms; - return this; -}; - -/** - * Set and & get timeout `enabled`. - * - * @param {Boolean} enabled - * @return {Runnable|Boolean} enabled or self - * @api private - */ - -Runnable.prototype.enableTimeouts = function(enabled){ - if (arguments.length === 0) return this._enableTimeouts; - debug('enableTimeouts %s', enabled); - this._enableTimeouts = enabled; - return this; -}; - -/** - * Halt and mark as pending. - * - * @api private - */ - -Runnable.prototype.skip = function(){ - throw new Pending(); -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Runnable.prototype.fullTitle = function(){ - return this.parent.fullTitle() + ' ' + this.title; -}; - -/** - * Clear the timeout. - * - * @api private - */ - -Runnable.prototype.clearTimeout = function(){ - clearTimeout(this.timer); -}; - -/** - * Inspect the runnable void of private properties. - * - * @return {String} - * @api private - */ - -Runnable.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_' == key[0]) return; - if ('parent' == key) return '#'; - if ('ctx' == key) return '#'; - return val; - }, 2); -}; - -/** - * Reset the timeout. - * - * @api private - */ - -Runnable.prototype.resetTimeout = function(){ - var self = this; - var ms = this.timeout() || 1e9; - - if (!this._enableTimeouts) return; - this.clearTimeout(); - this.timer = setTimeout(function(){ - if (!self._enableTimeouts) return; - self.callback(new Error('timeout of ' + ms + 'ms exceeded. Ensure the done() callback is being called in this test.')); - self.timedOut = true; - }, ms); -}; - -/** - * Whitelist these globals for this test run - * - * @api private - */ -Runnable.prototype.globals = function(arr){ - var self = this; - this._allowedGlobals = arr; -}; - -/** - * Run the test and invoke `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runnable.prototype.run = function(fn){ - var self = this - , start = new Date - , ctx = this.ctx - , finished - , emitted; - - // Some times the ctx exists but it is not runnable - if (ctx && ctx.runnable) ctx.runnable(this); - - // called multiple times - function multiple(err) { - if (emitted) return; - emitted = true; - self.emit('error', err || new Error('done() called multiple times; stacktrace may be inaccurate')); - } - - // finished - function done(err) { - var ms = self.timeout(); - if (self.timedOut) return; - if (finished) return multiple(err || self._trace); - - // Discard the resolution if this test has already failed asynchronously - if (self.state) return; - - self.clearTimeout(); - self.duration = new Date - start; - finished = true; - if (!err && self.duration > ms && self._enableTimeouts) err = new Error('timeout of ' + ms + 'ms exceeded. Ensure the done() callback is being called in this test.'); - fn(err); - } - - // for .resetTimeout() - this.callback = done; - - // explicit async with `done` argument - if (this.async) { - this.resetTimeout(); - - try { - this.fn.call(ctx, function(err){ - if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); - if (null != err) { - if (Object.prototype.toString.call(err) === '[object Object]') { - return done(new Error('done() invoked with non-Error: ' + JSON.stringify(err))); - } else { - return done(new Error('done() invoked with non-Error: ' + err)); - } - } - done(); - }); - } catch (err) { - done(utils.getError(err)); - } - return; - } - - if (this.asyncOnly) { - return done(new Error('--async-only option in use without declaring `done()`')); - } - - // sync or promise-returning - try { - if (this.pending) { - done(); - } else { - callFn(this.fn); - } - } catch (err) { - done(utils.getError(err)); - } - - function callFn(fn) { - var result = fn.call(ctx); - if (result && typeof result.then === 'function') { - self.resetTimeout(); - result - .then(function() { - done() - }, - function(reason) { - done(reason || new Error('Promise rejected with no or falsy reason')) - }); - } else { - done(); - } - } -}; diff --git a/node_modules/mocha/lib/runner.js b/node_modules/mocha/lib/runner.js deleted file mode 100644 index 3199dc9..0000000 --- a/node_modules/mocha/lib/runner.js +++ /dev/null @@ -1,716 +0,0 @@ -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , debug = require('debug')('mocha:runner') - , Pending = require('./pending') - , Test = require('./test') - , utils = require('./utils') - , filter = utils.filter - , keys = utils.keys - , type = utils.type - , stringify = utils.stringify - , stackFilter = utils.stackTraceFilter(); - -/** - * Non-enumerable globals. - */ - -var globals = [ - 'setTimeout', - 'clearTimeout', - 'setInterval', - 'clearInterval', - 'XMLHttpRequest', - 'Date', - 'setImmediate', - 'clearImmediate' -]; - -/** - * Expose `Runner`. - */ - -module.exports = Runner; - -/** - * Initialize a `Runner` for the given `suite`. - * - * Events: - * - * - `start` execution started - * - `end` execution complete - * - `suite` (suite) test suite execution started - * - `suite end` (suite) all tests (and sub-suites) have finished - * - `test` (test) test execution started - * - `test end` (test) test completed - * - `hook` (hook) hook execution started - * - `hook end` (hook) hook complete - * - `pass` (test) test passed - * - `fail` (test, err) test failed - * - `pending` (test) test pending - * - * @param {Suite} suite Root suite - * @param {boolean} [delay] Whether or not to delay execution of root suite - * until ready. - * @api public - */ - -function Runner(suite, delay) { - var self = this; - this._globals = []; - this._abort = false; - this._delay = delay; - this.suite = suite; - this.total = suite.total(); - this.failures = 0; - this.on('test end', function(test){ self.checkGlobals(test); }); - this.on('hook end', function(hook){ self.checkGlobals(hook); }); - this.grep(/.*/); - this.globals(this.globalProps().concat(extraGlobals())); -} - -/** - * Wrapper for setImmediate, process.nextTick, or browser polyfill. - * - * @param {Function} fn - * @api private - */ - -Runner.immediately = global.setImmediate || process.nextTick; - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Runner.prototype.__proto__ = EventEmitter.prototype; - -/** - * Run tests with full titles matching `re`. Updates runner.total - * with number of tests matched. - * - * @param {RegExp} re - * @param {Boolean} invert - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.grep = function(re, invert){ - debug('grep %s', re); - this._grep = re; - this._invert = invert; - this.total = this.grepTotal(this.suite); - return this; -}; - -/** - * Returns the number of tests matching the grep search for the - * given suite. - * - * @param {Suite} suite - * @return {Number} - * @api public - */ - -Runner.prototype.grepTotal = function(suite) { - var self = this; - var total = 0; - - suite.eachTest(function(test){ - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (match) total++; - }); - - return total; -}; - -/** - * Return a list of global properties. - * - * @return {Array} - * @api private - */ - -Runner.prototype.globalProps = function() { - var props = utils.keys(global); - - // non-enumerables - for (var i = 0; i < globals.length; ++i) { - if (~utils.indexOf(props, globals[i])) continue; - props.push(globals[i]); - } - - return props; -}; - -/** - * Allow the given `arr` of globals. - * - * @param {Array} arr - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.globals = function(arr){ - if (0 == arguments.length) return this._globals; - debug('globals %j', arr); - this._globals = this._globals.concat(arr); - return this; -}; - -/** - * Check for global variable leaks. - * - * @api private - */ - -Runner.prototype.checkGlobals = function(test){ - if (this.ignoreLeaks) return; - var ok = this._globals; - - var globals = this.globalProps(); - var leaks; - - if (test) { - ok = ok.concat(test._allowedGlobals || []); - } - - if(this.prevGlobalsLength == globals.length) return; - this.prevGlobalsLength = globals.length; - - leaks = filterLeaks(ok, globals); - this._globals = this._globals.concat(leaks); - - if (leaks.length > 1) { - this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); - } else if (leaks.length) { - this.fail(test, new Error('global leak detected: ' + leaks[0])); - } -}; - -/** - * Fail the given `test`. - * - * @param {Test} test - * @param {Error} err - * @api private - */ - -Runner.prototype.fail = function(test, err) { - ++this.failures; - test.state = 'failed'; - - if (!(err instanceof Error)) { - err = new Error('the ' + type(err) + ' ' + stringify(err) + ' was thrown, throw an Error :)'); - } - - err.stack = (this.fullStackTrace || !err.stack) - ? err.stack - : stackFilter(err.stack); - - this.emit('fail', test, err); -}; - -/** - * Fail the given `hook` with `err`. - * - * Hook failures work in the following pattern: - * - If bail, then exit - * - Failed `before` hook skips all tests in a suite and subsuites, - * but jumps to corresponding `after` hook - * - Failed `before each` hook skips remaining tests in a - * suite and jumps to corresponding `after each` hook, - * which is run only once - * - Failed `after` hook does not alter - * execution order - * - Failed `after each` hook skips remaining tests in a - * suite and subsuites, but executes other `after each` - * hooks - * - * @param {Hook} hook - * @param {Error} err - * @api private - */ - -Runner.prototype.failHook = function(hook, err){ - this.fail(hook, err); - if (this.suite.bail()) { - this.emit('end'); - } -}; - -/** - * Run hook `name` callbacks and then invoke `fn()`. - * - * @param {String} name - * @param {Function} function - * @api private - */ - -Runner.prototype.hook = function(name, fn){ - var suite = this.suite - , hooks = suite['_' + name] - , self = this - , timer; - - function next(i) { - var hook = hooks[i]; - if (!hook) return fn(); - self.currentRunnable = hook; - - hook.ctx.currentTest = self.test; - - self.emit('hook', hook); - - hook.on('error', function(err){ - self.failHook(hook, err); - }); - - hook.run(function(err){ - hook.removeAllListeners('error'); - var testError = hook.error(); - if (testError) self.fail(self.test, testError); - if (err) { - if (err instanceof Pending) { - suite.pending = true; - } else { - self.failHook(hook, err); - - // stop executing hooks, notify callee of hook err - return fn(err); - } - } - self.emit('hook end', hook); - delete hook.ctx.currentTest; - next(++i); - }); - } - - Runner.immediately(function(){ - next(0); - }); -}; - -/** - * Run hook `name` for the given array of `suites` - * in order, and callback `fn(err, errSuite)`. - * - * @param {String} name - * @param {Array} suites - * @param {Function} fn - * @api private - */ - -Runner.prototype.hooks = function(name, suites, fn){ - var self = this - , orig = this.suite; - - function next(suite) { - self.suite = suite; - - if (!suite) { - self.suite = orig; - return fn(); - } - - self.hook(name, function(err){ - if (err) { - var errSuite = self.suite; - self.suite = orig; - return fn(err, errSuite); - } - - next(suites.pop()); - }); - } - - next(suites.pop()); -}; - -/** - * Run hooks from the top level down. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookUp = function(name, fn){ - var suites = [this.suite].concat(this.parents()).reverse(); - this.hooks(name, suites, fn); -}; - -/** - * Run hooks from the bottom up. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookDown = function(name, fn){ - var suites = [this.suite].concat(this.parents()); - this.hooks(name, suites, fn); -}; - -/** - * Return an array of parent Suites from - * closest to furthest. - * - * @return {Array} - * @api private - */ - -Runner.prototype.parents = function(){ - var suite = this.suite - , suites = []; - while (suite = suite.parent) suites.push(suite); - return suites; -}; - -/** - * Run the current test and callback `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTest = function(fn){ - var test = this.test - , self = this; - - if (this.asyncOnly) test.asyncOnly = true; - - try { - test.on('error', function(err){ - self.fail(test, err); - }); - test.run(fn); - } catch (err) { - fn(err); - } -}; - -/** - * Run tests in the given `suite` and invoke - * the callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTests = function(suite, fn){ - var self = this - , tests = suite.tests.slice() - , test; - - - function hookErr(err, errSuite, after) { - // before/after Each hook for errSuite failed: - var orig = self.suite; - - // for failed 'after each' hook start from errSuite parent, - // otherwise start from errSuite itself - self.suite = after ? errSuite.parent : errSuite; - - if (self.suite) { - // call hookUp afterEach - self.hookUp('afterEach', function(err2, errSuite2) { - self.suite = orig; - // some hooks may fail even now - if (err2) return hookErr(err2, errSuite2, true); - // report error suite - fn(errSuite); - }); - } else { - // there is no need calling other 'after each' hooks - self.suite = orig; - fn(errSuite); - } - } - - function next(err, errSuite) { - // if we bail after first err - if (self.failures && suite._bail) return fn(); - - if (self._abort) return fn(); - - if (err) return hookErr(err, errSuite, true); - - // next test - test = tests.shift(); - - // all done - if (!test) return fn(); - - // grep - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (!match) return next(); - - // pending - if (test.pending) { - self.emit('pending', test); - self.emit('test end', test); - return next(); - } - - // execute test and hook(s) - self.emit('test', self.test = test); - self.hookDown('beforeEach', function(err, errSuite){ - - if (suite.pending) { - self.emit('pending', test); - self.emit('test end', test); - return next(); - } - if (err) return hookErr(err, errSuite, false); - - self.currentRunnable = self.test; - self.runTest(function(err){ - test = self.test; - - if (err) { - if (err instanceof Pending) { - self.emit('pending', test); - } else { - self.fail(test, err); - } - self.emit('test end', test); - - if (err instanceof Pending) { - return next(); - } - - return self.hookUp('afterEach', next); - } - - test.state = 'passed'; - self.emit('pass', test); - self.emit('test end', test); - self.hookUp('afterEach', next); - }); - }); - } - - this.next = next; - next(); -}; - -/** - * Run the given `suite` and invoke the - * callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runSuite = function(suite, fn){ - var total = this.grepTotal(suite) - , self = this - , i = 0; - - debug('run suite %s', suite.fullTitle()); - - if (!total) return fn(); - - this.emit('suite', this.suite = suite); - - function next(errSuite) { - if (errSuite) { - // current suite failed on a hook from errSuite - if (errSuite == suite) { - // if errSuite is current suite - // continue to the next sibling suite - return done(); - } else { - // errSuite is among the parents of current suite - // stop execution of errSuite and all sub-suites - return done(errSuite); - } - } - - if (self._abort) return done(); - - var curr = suite.suites[i++]; - if (!curr) return done(); - self.runSuite(curr, next); - } - - function done(errSuite) { - self.suite = suite; - self.hook('afterAll', function(){ - self.emit('suite end', suite); - fn(errSuite); - }); - } - - this.hook('beforeAll', function(err){ - if (err) return done(); - self.runTests(suite, next); - }); -}; - -/** - * Handle uncaught exceptions. - * - * @param {Error} err - * @api private - */ - -Runner.prototype.uncaught = function(err){ - if (err) { - debug('uncaught exception %s', err !== function () { - return this; - }.call(err) ? err : ( err.message || err )); - } else { - debug('uncaught undefined exception'); - err = utils.undefinedError(); - } - err.uncaught = true; - - var runnable = this.currentRunnable; - if (!runnable) return; - - runnable.clearTimeout(); - - // Ignore errors if complete - if (runnable.state) return; - this.fail(runnable, err); - - // recover from test - if ('test' == runnable.type) { - this.emit('test end', runnable); - this.hookUp('afterEach', this.next); - return; - } - - // bail on hooks - this.emit('end'); -}; - -/** - * Run the root suite and invoke `fn(failures)` - * on completion. - * - * @param {Function} fn - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.run = function(fn){ - var self = this, - rootSuite = this.suite; - - fn = fn || function(){}; - - function uncaught(err){ - self.uncaught(err); - } - - function start() { - self.emit('start'); - self.runSuite(rootSuite, function(){ - debug('finished running'); - self.emit('end'); - }); - } - - debug('start'); - - // callback - this.on('end', function(){ - debug('end'); - process.removeListener('uncaughtException', uncaught); - fn(self.failures); - }); - - // uncaught exception - process.on('uncaughtException', uncaught); - - if (this._delay) { - // for reporters, I guess. - // might be nice to debounce some dots while we wait. - this.emit('waiting', rootSuite); - rootSuite.once('run', start); - } - else { - start(); - } - - return this; -}; - -/** - * Cleanly abort execution - * - * @return {Runner} for chaining - * @api public - */ -Runner.prototype.abort = function(){ - debug('aborting'); - this._abort = true; -}; - -/** - * Filter leaks with the given globals flagged as `ok`. - * - * @param {Array} ok - * @param {Array} globals - * @return {Array} - * @api private - */ - -function filterLeaks(ok, globals) { - return filter(globals, function(key){ - // Firefox and Chrome exposes iframes as index inside the window object - if (/^d+/.test(key)) return false; - - // in firefox - // if runner runs in an iframe, this iframe's window.getInterface method not init at first - // it is assigned in some seconds - if (global.navigator && /^getInterface/.test(key)) return false; - - // an iframe could be approached by window[iframeIndex] - // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak - if (global.navigator && /^\d+/.test(key)) return false; - - // Opera and IE expose global variables for HTML element IDs (issue #243) - if (/^mocha-/.test(key)) return false; - - var matched = filter(ok, function(ok){ - if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); - return key == ok; - }); - return matched.length == 0 && (!global.navigator || 'onerror' !== key); - }); -} - -/** - * Array of globals dependent on the environment. - * - * @return {Array} - * @api private - */ - -function extraGlobals() { - if (typeof(process) === 'object' && - typeof(process.version) === 'string') { - - var nodeVersion = process.version.split('.').reduce(function(a, v) { - return a << 8 | v; - }); - - // 'errno' was renamed to process._errno in v0.9.11. - - if (nodeVersion < 0x00090B) { - return ['errno']; - } - } - - return []; -} diff --git a/node_modules/mocha/lib/suite.js b/node_modules/mocha/lib/suite.js deleted file mode 100644 index edc820e..0000000 --- a/node_modules/mocha/lib/suite.js +++ /dev/null @@ -1,355 +0,0 @@ -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , debug = require('debug')('mocha:suite') - , milliseconds = require('./ms') - , utils = require('./utils') - , Hook = require('./hook'); - -/** - * Expose `Suite`. - */ - -exports = module.exports = Suite; - -/** - * Create a new `Suite` with the given `title` - * and parent `Suite`. When a suite with the - * same title is already present, that suite - * is returned to provide nicer reporter - * and more flexible meta-testing. - * - * @param {Suite} parent - * @param {String} title - * @return {Suite} - * @api public - */ - -exports.create = function(parent, title){ - var suite = new Suite(title, parent.ctx); - suite.parent = parent; - if (parent.pending) suite.pending = true; - title = suite.fullTitle(); - parent.addSuite(suite); - return suite; -}; - -/** - * Initialize a new `Suite` with the given - * `title` and `ctx`. - * - * @param {String} title - * @param {Context} ctx - * @api private - */ - -function Suite(title, parentContext) { - this.title = title; - var context = function() {}; - context.prototype = parentContext; - this.ctx = new context(); - this.suites = []; - this.tests = []; - this.pending = false; - this._beforeEach = []; - this._beforeAll = []; - this._afterEach = []; - this._afterAll = []; - this.root = !title; - this._timeout = 2000; - this._enableTimeouts = true; - this._slow = 75; - this._bail = false; - this.delayed = false; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Suite.prototype.__proto__ = EventEmitter.prototype; - -/** - * Return a clone of this `Suite`. - * - * @return {Suite} - * @api private - */ - -Suite.prototype.clone = function(){ - var suite = new Suite(this.title); - debug('clone'); - suite.ctx = this.ctx; - suite.timeout(this.timeout()); - suite.enableTimeouts(this.enableTimeouts()); - suite.slow(this.slow()); - suite.bail(this.bail()); - return suite; -}; - -/** - * Set timeout `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if (ms.toString() === '0') this._enableTimeouts = false; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = parseInt(ms, 10); - return this; -}; - -/** - * Set timeout `enabled`. - * - * @param {Boolean} enabled - * @return {Suite|Boolean} self or enabled - * @api private - */ - -Suite.prototype.enableTimeouts = function(enabled){ - if (arguments.length === 0) return this._enableTimeouts; - debug('enableTimeouts %s', enabled); - this._enableTimeouts = enabled; - return this; -}; - -/** - * Set slow `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('slow %d', ms); - this._slow = ms; - return this; -}; - -/** - * Sets whether to bail after first error. - * - * @param {Boolean} bail - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.bail = function(bail){ - if (0 == arguments.length) return this._bail; - debug('bail %s', bail); - this._bail = bail; - return this; -}; - -/** - * Run `fn(test[, done])` before running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeAll = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"before all" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeAll.push(hook); - this.emit('beforeAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterAll = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"after all" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterAll.push(hook); - this.emit('afterAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` before each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeEach = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"before each" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeEach.push(hook); - this.emit('beforeEach', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterEach = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"after each" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterEach.push(hook); - this.emit('afterEach', hook); - return this; -}; - -/** - * Add a test `suite`. - * - * @param {Suite} suite - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addSuite = function(suite){ - suite.parent = this; - suite.timeout(this.timeout()); - suite.enableTimeouts(this.enableTimeouts()); - suite.slow(this.slow()); - suite.bail(this.bail()); - this.suites.push(suite); - this.emit('suite', suite); - return this; -}; - -/** - * Add a `test` to this suite. - * - * @param {Test} test - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addTest = function(test){ - test.parent = this; - test.timeout(this.timeout()); - test.enableTimeouts(this.enableTimeouts()); - test.slow(this.slow()); - test.ctx = this.ctx; - this.tests.push(test); - this.emit('test', test); - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Suite.prototype.fullTitle = function(){ - if (this.parent) { - var full = this.parent.fullTitle(); - if (full) return full + ' ' + this.title; - } - return this.title; -}; - -/** - * Return the total number of tests. - * - * @return {Number} - * @api public - */ - -Suite.prototype.total = function(){ - return utils.reduce(this.suites, function(sum, suite){ - return sum + suite.total(); - }, 0) + this.tests.length; -}; - -/** - * Iterates through each suite recursively to find - * all tests. Applies a function in the format - * `fn(test)`. - * - * @param {Function} fn - * @return {Suite} - * @api private - */ - -Suite.prototype.eachTest = function(fn){ - utils.forEach(this.tests, fn); - utils.forEach(this.suites, function(suite){ - suite.eachTest(fn); - }); - return this; -}; - -/** - * This will run the root suite if we happen to be running in delayed mode. - */ -Suite.prototype.run = function run() { - if (this.root) { - this.emit('run'); - } -}; diff --git a/node_modules/mocha/lib/template.html b/node_modules/mocha/lib/template.html deleted file mode 100644 index 0590d4a..0000000 --- a/node_modules/mocha/lib/template.html +++ /dev/null @@ -1,18 +0,0 @@ - - - - Mocha - - - - - -
    - - - - - - diff --git a/node_modules/mocha/lib/test.js b/node_modules/mocha/lib/test.js deleted file mode 100644 index 4a4cf63..0000000 --- a/node_modules/mocha/lib/test.js +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Test`. - */ - -module.exports = Test; - -/** - * Initialize a new `Test` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Test(title, fn) { - Runnable.call(this, title, fn); - this.pending = !fn; - this.type = 'test'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -Test.prototype.__proto__ = Runnable.prototype; diff --git a/node_modules/mocha/lib/utils.js b/node_modules/mocha/lib/utils.js deleted file mode 100644 index 845f84c..0000000 --- a/node_modules/mocha/lib/utils.js +++ /dev/null @@ -1,710 +0,0 @@ -/** - * Module dependencies. - */ - -var fs = require('fs') - , path = require('path') - , basename = path.basename - , exists = fs.existsSync || path.existsSync - , glob = require('glob') - , join = path.join - , debug = require('debug')('mocha:watch'); - -/** - * Ignored directories. - */ - -var ignore = ['node_modules', '.git']; - -/** - * Escape special characters in the given string of html. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -}; - -/** - * Array#forEach (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} scope - * @api private - */ - -exports.forEach = function(arr, fn, scope){ - for (var i = 0, l = arr.length; i < l; i++) - fn.call(scope, arr[i], i); -}; - -/** - * Test if the given obj is type of string - * - * @param {Object} obj - * @returns Boolean - */ - -exports.isString = function(obj) { - return 'string' === typeof obj; -}; - -/** - * Array#map (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} scope - * @api private - */ - -exports.map = function(arr, fn, scope){ - var result = []; - for (var i = 0, l = arr.length; i < l; i++) - result.push(fn.call(scope, arr[i], i, arr)); - return result; -}; - -/** - * Array#indexOf (<=IE8) - * - * @parma {Array} arr - * @param {Object} obj to find index of - * @param {Number} start - * @api private - */ - -exports.indexOf = function(arr, obj, start){ - for (var i = start || 0, l = arr.length; i < l; i++) { - if (arr[i] === obj) - return i; - } - return -1; -}; - -/** - * Array#reduce (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} initial value - * @api private - */ - -exports.reduce = function(arr, fn, val){ - var rval = val; - - for (var i = 0, l = arr.length; i < l; i++) { - rval = fn(rval, arr[i], i, arr); - } - - return rval; -}; - -/** - * Array#filter (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @api private - */ - -exports.filter = function(arr, fn){ - var ret = []; - - for (var i = 0, l = arr.length; i < l; i++) { - var val = arr[i]; - if (fn(val, i, arr)) ret.push(val); - } - - return ret; -}; - -/** - * Object.keys (<=IE8) - * - * @param {Object} obj - * @return {Array} keys - * @api private - */ - -exports.keys = Object.keys || function(obj) { - var keys = [] - , has = Object.prototype.hasOwnProperty; // for `window` on <=IE8 - - for (var key in obj) { - if (has.call(obj, key)) { - keys.push(key); - } - } - - return keys; -}; - -/** - * Watch the given `files` for changes - * and invoke `fn(file)` on modification. - * - * @param {Array} files - * @param {Function} fn - * @api private - */ - -exports.watch = function(files, fn){ - var options = { interval: 100 }; - files.forEach(function(file){ - debug('file %s', file); - fs.watchFile(file, options, function(curr, prev){ - if (prev.mtime < curr.mtime) fn(file); - }); - }); -}; - -/** - * Array.isArray (<=IE8) - * - * @param {Object} obj - * @return {Boolean} - * @api private - */ -var isArray = Array.isArray || function (obj) { - return '[object Array]' == {}.toString.call(obj); -}; - -/** - * @description - * Buffer.prototype.toJSON polyfill - * @type {Function} - */ -if(typeof Buffer !== 'undefined' && Buffer.prototype) { - Buffer.prototype.toJSON = Buffer.prototype.toJSON || function () { - return Array.prototype.slice.call(this, 0); - }; -} - -/** - * Ignored files. - */ - -function ignored(path){ - return !~ignore.indexOf(path); -} - -/** - * Lookup files in the given `dir`. - * - * @return {Array} - * @api private - */ - -exports.files = function(dir, ext, ret){ - ret = ret || []; - ext = ext || ['js']; - - var re = new RegExp('\\.(' + ext.join('|') + ')$'); - - fs.readdirSync(dir) - .filter(ignored) - .forEach(function(path){ - path = join(dir, path); - if (fs.statSync(path).isDirectory()) { - exports.files(path, ext, ret); - } else if (path.match(re)) { - ret.push(path); - } - }); - - return ret; -}; - -/** - * Compute a slug from the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.slug = function(str){ - return str - .toLowerCase() - .replace(/ +/g, '-') - .replace(/[^-\w]/g, ''); -}; - -/** - * Strip the function definition from `str`, - * and re-indent for pre whitespace. - */ - -exports.clean = function(str) { - str = str - .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '') - .replace(/^function *\(.*\)\s*{|\(.*\) *=> *{?/, '') - .replace(/\s+\}$/, ''); - - var spaces = str.match(/^\n?( *)/)[1].length - , tabs = str.match(/^\n?(\t*)/)[1].length - , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm'); - - str = str.replace(re, ''); - - return exports.trim(str); -}; - -/** - * Trim the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.trim = function(str){ - return str.replace(/^\s+|\s+$/g, ''); -}; - -/** - * Parse the given `qs`. - * - * @param {String} qs - * @return {Object} - * @api private - */ - -exports.parseQuery = function(qs){ - return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ - var i = pair.indexOf('=') - , key = pair.slice(0, i) - , val = pair.slice(++i); - - obj[key] = decodeURIComponent(val); - return obj; - }, {}); -}; - -/** - * Highlight the given string of `js`. - * - * @param {String} js - * @return {String} - * @api private - */ - -function highlight(js) { - return js - .replace(//g, '>') - .replace(/\/\/(.*)/gm, '//$1') - .replace(/('.*?')/gm, '$1') - .replace(/(\d+\.\d+)/gm, '$1') - .replace(/(\d+)/gm, '$1') - .replace(/\bnew[ \t]+(\w+)/gm, 'new $1') - .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') -} - -/** - * Highlight the contents of tag `name`. - * - * @param {String} name - * @api private - */ - -exports.highlightTags = function(name) { - var code = document.getElementById('mocha').getElementsByTagName(name); - for (var i = 0, len = code.length; i < len; ++i) { - code[i].innerHTML = highlight(code[i].innerHTML); - } -}; - -/** - * If a value could have properties, and has none, this function is called, which returns - * a string representation of the empty value. - * - * Functions w/ no properties return `'[Function]'` - * Arrays w/ length === 0 return `'[]'` - * Objects w/ no properties return `'{}'` - * All else: return result of `value.toString()` - * - * @param {*} value Value to inspect - * @param {string} [type] The type of the value, if known. - * @returns {string} - */ -var emptyRepresentation = function emptyRepresentation(value, type) { - type = type || exports.type(value); - - switch(type) { - case 'function': - return '[Function]'; - case 'object': - return '{}'; - case 'array': - return '[]'; - default: - return value.toString(); - } -}; - -/** - * Takes some variable and asks `{}.toString()` what it thinks it is. - * @param {*} value Anything - * @example - * type({}) // 'object' - * type([]) // 'array' - * type(1) // 'number' - * type(false) // 'boolean' - * type(Infinity) // 'number' - * type(null) // 'null' - * type(new Date()) // 'date' - * type(/foo/) // 'regexp' - * type('type') // 'string' - * type(global) // 'global' - * @api private - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString - * @returns {string} - */ -exports.type = function type(value) { - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return 'buffer'; - } - return Object.prototype.toString.call(value) - .replace(/^\[.+\s(.+?)\]$/, '$1') - .toLowerCase(); -}; - -/** - * @summary Stringify `value`. - * @description Different behavior depending on type of value. - * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively. - * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes. - * - If `value` is an *empty* object, function, or array, return result of function - * {@link emptyRepresentation}. - * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of - * JSON.stringify(). - * - * @see exports.type - * @param {*} value - * @return {string} - * @api private - */ - -exports.stringify = function(value) { - var type = exports.type(value); - - if (!~exports.indexOf(['object', 'array', 'function'], type)) { - if(type != 'buffer') { - return jsonStringify(value); - } - var json = value.toJSON(); - // Based on the toJSON result - return jsonStringify(json.data && json.type ? json.data : json, 2) - .replace(/,(\n|$)/g, '$1'); - } - - for (var prop in value) { - if (Object.prototype.hasOwnProperty.call(value, prop)) { - return jsonStringify(exports.canonicalize(value), 2).replace(/,(\n|$)/g, '$1'); - } - } - - return emptyRepresentation(value, type); -}; - -/** - * @description - * like JSON.stringify but more sense. - * @param {Object} object - * @param {Number=} spaces - * @param {number=} depth - * @returns {*} - * @private - */ -function jsonStringify(object, spaces, depth) { - if(typeof spaces == 'undefined') return _stringify(object); // primitive types - - depth = depth || 1; - var space = spaces * depth - , str = isArray(object) ? '[' : '{' - , end = isArray(object) ? ']' : '}' - , length = object.length || exports.keys(object).length - , repeat = function(s, n) { return new Array(n).join(s); }; // `.repeat()` polyfill - - function _stringify(val) { - switch (exports.type(val)) { - case 'null': - case 'undefined': - val = '[' + val + ']'; - break; - case 'array': - case 'object': - val = jsonStringify(val, spaces, depth + 1); - break; - case 'boolean': - case 'regexp': - case 'number': - val = val === 0 && (1/val) === -Infinity // `-0` - ? '-0' - : val.toString(); - break; - case 'date': - var sDate = isNaN(val.getTime()) // Invalid date - ? val.toString() - : val.toISOString(); - val = '[Date: ' + sDate + ']'; - break; - case 'buffer': - var json = val.toJSON(); - // Based on the toJSON result - json = json.data && json.type ? json.data : json; - val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']'; - break; - default: - val = (val == '[Function]' || val == '[Circular]') - ? val - : JSON.stringify(val); //string - } - return val; - } - - for(var i in object) { - if(!object.hasOwnProperty(i)) continue; // not my business - --length; - str += '\n ' + repeat(' ', space) - + (isArray(object) ? '' : '"' + i + '": ') // key - + _stringify(object[i]) // value - + (length ? ',' : ''); // comma - } - - return str + (str.length != 1 // [], {} - ? '\n' + repeat(' ', --space) + end - : end); -} - -/** - * Return if obj is a Buffer - * @param {Object} arg - * @return {Boolean} - * @api private - */ -exports.isBuffer = function (arg) { - return typeof Buffer !== 'undefined' && Buffer.isBuffer(arg); -}; - -/** - * @summary Return a new Thing that has the keys in sorted order. Recursive. - * @description If the Thing... - * - has already been seen, return string `'[Circular]'` - * - is `undefined`, return string `'[undefined]'` - * - is `null`, return value `null` - * - is some other primitive, return the value - * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method - * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again. - * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()` - * - * @param {*} value Thing to inspect. May or may not have properties. - * @param {Array} [stack=[]] Stack of seen values - * @return {(Object|Array|Function|string|undefined)} - * @see {@link exports.stringify} - * @api private - */ - -exports.canonicalize = function(value, stack) { - var canonicalizedObj, - type = exports.type(value), - prop, - withStack = function withStack(value, fn) { - stack.push(value); - fn(); - stack.pop(); - }; - - stack = stack || []; - - if (exports.indexOf(stack, value) !== -1) { - return '[Circular]'; - } - - switch(type) { - case 'undefined': - case 'buffer': - case 'null': - canonicalizedObj = value; - break; - case 'array': - withStack(value, function () { - canonicalizedObj = exports.map(value, function (item) { - return exports.canonicalize(item, stack); - }); - }); - break; - case 'function': - for (prop in value) { - canonicalizedObj = {}; - break; - } - if (!canonicalizedObj) { - canonicalizedObj = emptyRepresentation(value, type); - break; - } - /* falls through */ - case 'object': - canonicalizedObj = canonicalizedObj || {}; - withStack(value, function () { - exports.forEach(exports.keys(value).sort(), function (key) { - canonicalizedObj[key] = exports.canonicalize(value[key], stack); - }); - }); - break; - case 'date': - case 'number': - case 'regexp': - case 'boolean': - canonicalizedObj = value; - break; - default: - canonicalizedObj = value.toString(); - } - - return canonicalizedObj; -}; - -/** - * Lookup file names at the given `path`. - */ -exports.lookupFiles = function lookupFiles(path, extensions, recursive) { - var files = []; - var re = new RegExp('\\.(' + extensions.join('|') + ')$'); - - if (!exists(path)) { - if (exists(path + '.js')) { - path += '.js'; - } else { - files = glob.sync(path); - if (!files.length) throw new Error("cannot resolve path (or pattern) '" + path + "'"); - return files; - } - } - - try { - var stat = fs.statSync(path); - if (stat.isFile()) return path; - } - catch (ignored) { - return; - } - - fs.readdirSync(path).forEach(function(file) { - file = join(path, file); - try { - var stat = fs.statSync(file); - if (stat.isDirectory()) { - if (recursive) { - files = files.concat(lookupFiles(file, extensions, recursive)); - } - return; - } - } - catch (ignored) { - return; - } - if (!stat.isFile() || !re.test(file) || basename(file)[0] === '.') return; - files.push(file); - }); - - return files; -}; - -/** - * Generate an undefined error with a message warning the user. - * - * @return {Error} - */ - -exports.undefinedError = function() { - return new Error('Caught undefined error, did you throw without specifying what?'); -}; - -/** - * Generate an undefined error if `err` is not defined. - * - * @param {Error} err - * @return {Error} - */ - -exports.getError = function(err) { - return err || exports.undefinedError(); -}; - - -/** - * @summary - * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`) - * @description - * When invoking this function you get a filter function that get the Error.stack as an input, - * and return a prettify output. - * (i.e: strip Mocha, node_modules, bower and componentJS from stack trace). - * @returns {Function} - */ - -exports.stackTraceFilter = function() { - var slash = '/' - , is = typeof document === 'undefined' - ? { node: true } - : { browser: true } - , cwd = is.node - ? process.cwd() + slash - : location.href.replace(/\/[^\/]*$/, '/'); - - function isNodeModule (line) { - return (~line.indexOf('node_modules')); - } - - function isMochaInternal (line) { - return (~line.indexOf('node_modules' + slash + 'mocha')) || - (~line.indexOf('components' + slash + 'mochajs')) || - (~line.indexOf('components' + slash + 'mocha')); - } - - // node_modules, bower, componentJS - function isBrowserModule(line) { - return (~line.indexOf('node_modules')) || - (~line.indexOf('components')); - } - - function isNodeInternal (line) { - return (~line.indexOf('(timers.js:')) || - (~line.indexOf('(events.js:')) || - (~line.indexOf('(node.js:')) || - (~line.indexOf('(module.js:')) || - (~line.indexOf('GeneratorFunctionPrototype.next (native)')) || - false - } - - return function(stack) { - stack = stack.split('\n'); - - stack = exports.reduce(stack, function(list, line) { - if (is.node && (isNodeModule(line) || - isMochaInternal(line) || - isNodeInternal(line))) - return list; - - if (is.browser && (isBrowserModule(line))) - return list; - - // Clean up cwd(absolute) - list.push(line.replace(cwd, '')); - return list; - }, []); - - return stack.join('\n'); - } -}; \ No newline at end of file diff --git a/node_modules/mocha/mocha.css b/node_modules/mocha/mocha.css deleted file mode 100644 index 42b9798..0000000 --- a/node_modules/mocha/mocha.css +++ /dev/null @@ -1,270 +0,0 @@ -@charset "utf-8"; - -body { - margin:0; -} - -#mocha { - font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; - margin: 60px 50px; -} - -#mocha ul, -#mocha li { - margin: 0; - padding: 0; -} - -#mocha ul { - list-style: none; -} - -#mocha h1, -#mocha h2 { - margin: 0; -} - -#mocha h1 { - margin-top: 15px; - font-size: 1em; - font-weight: 200; -} - -#mocha h1 a { - text-decoration: none; - color: inherit; -} - -#mocha h1 a:hover { - text-decoration: underline; -} - -#mocha .suite .suite h1 { - margin-top: 0; - font-size: .8em; -} - -#mocha .hidden { - display: none; -} - -#mocha h2 { - font-size: 12px; - font-weight: normal; - cursor: pointer; -} - -#mocha .suite { - margin-left: 15px; -} - -#mocha .test { - margin-left: 15px; - overflow: hidden; -} - -#mocha .test.pending:hover h2::after { - content: '(pending)'; - font-family: arial, sans-serif; -} - -#mocha .test.pass.medium .duration { - background: #c09853; -} - -#mocha .test.pass.slow .duration { - background: #b94a48; -} - -#mocha .test.pass::before { - content: '✓'; - font-size: 12px; - display: block; - float: left; - margin-right: 5px; - color: #00d6b2; -} - -#mocha .test.pass .duration { - font-size: 9px; - margin-left: 5px; - padding: 2px 5px; - color: #fff; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - -ms-border-radius: 5px; - -o-border-radius: 5px; - border-radius: 5px; -} - -#mocha .test.pass.fast .duration { - display: none; -} - -#mocha .test.pending { - color: #0b97c4; -} - -#mocha .test.pending::before { - content: '◦'; - color: #0b97c4; -} - -#mocha .test.fail { - color: #c00; -} - -#mocha .test.fail pre { - color: black; -} - -#mocha .test.fail::before { - content: '✖'; - font-size: 12px; - display: block; - float: left; - margin-right: 5px; - color: #c00; -} - -#mocha .test pre.error { - color: #c00; - max-height: 300px; - overflow: auto; -} - -/** - * (1): approximate for browsers not supporting calc - * (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border) - * ^^ seriously - */ -#mocha .test pre { - display: block; - float: left; - clear: left; - font: 12px/1.5 monaco, monospace; - margin: 5px; - padding: 15px; - border: 1px solid #eee; - max-width: 85%; /*(1)*/ - max-width: calc(100% - 42px); /*(2)*/ - word-wrap: break-word; - border-bottom-color: #ddd; - -webkit-border-radius: 3px; - -webkit-box-shadow: 0 1px 3px #eee; - -moz-border-radius: 3px; - -moz-box-shadow: 0 1px 3px #eee; - border-radius: 3px; -} - -#mocha .test h2 { - position: relative; -} - -#mocha .test a.replay { - position: absolute; - top: 3px; - right: 0; - text-decoration: none; - vertical-align: middle; - display: block; - width: 15px; - height: 15px; - line-height: 15px; - text-align: center; - background: #eee; - font-size: 15px; - -moz-border-radius: 15px; - border-radius: 15px; - -webkit-transition: opacity 200ms; - -moz-transition: opacity 200ms; - transition: opacity 200ms; - opacity: 0.3; - color: #888; -} - -#mocha .test:hover a.replay { - opacity: 1; -} - -#mocha-report.pass .test.fail { - display: none; -} - -#mocha-report.fail .test.pass { - display: none; -} - -#mocha-report.pending .test.pass, -#mocha-report.pending .test.fail { - display: none; -} -#mocha-report.pending .test.pass.pending { - display: block; -} - -#mocha-error { - color: #c00; - font-size: 1.5em; - font-weight: 100; - letter-spacing: 1px; -} - -#mocha-stats { - position: fixed; - top: 15px; - right: 10px; - font-size: 12px; - margin: 0; - color: #888; - z-index: 1; -} - -#mocha-stats .progress { - float: right; - padding-top: 0; -} - -#mocha-stats em { - color: black; -} - -#mocha-stats a { - text-decoration: none; - color: inherit; -} - -#mocha-stats a:hover { - border-bottom: 1px solid #eee; -} - -#mocha-stats li { - display: inline-block; - margin: 0 5px; - list-style: none; - padding-top: 11px; -} - -#mocha-stats canvas { - width: 40px; - height: 40px; -} - -#mocha code .comment { color: #ddd; } -#mocha code .init { color: #2f6fad; } -#mocha code .string { color: #5890ad; } -#mocha code .keyword { color: #8a6343; } -#mocha code .number { color: #2f6fad; } - -@media screen and (max-device-width: 480px) { - #mocha { - margin: 60px 0px; - } - - #mocha #stats { - position: absolute; - } -} diff --git a/node_modules/mocha/mocha.js b/node_modules/mocha/mocha.js deleted file mode 100644 index 5ff1385..0000000 --- a/node_modules/mocha/mocha.js +++ /dev/null @@ -1,6564 +0,0 @@ -;(function(){ - -// CommonJS require() - -function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - } - -require.modules = {}; - -require.resolve = function (path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; - -require.register = function (path, fn){ - require.modules[path] = fn; - }; - -require.relative = function (parent) { - return function(p){ - if ('.' != p.charAt(0)) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }; - - -require.register("browser/debug.js", function(module, exports, require){ -module.exports = function(type){ - return function(){ - } -}; - -}); // module: browser/debug.js - -require.register("browser/diff.js", function(module, exports, require){ -/* See LICENSE file for terms of use */ - -/* - * Text diff implementation. - * - * This library supports the following APIS: - * JsDiff.diffChars: Character by character diff - * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace - * JsDiff.diffLines: Line based diff - * - * JsDiff.diffCss: Diff targeted at CSS content - * - * These methods are based on the implementation proposed in - * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 - */ -var JsDiff = (function() { - /*jshint maxparams: 5*/ - function clonePath(path) { - return { newPos: path.newPos, components: path.components.slice(0) }; - } - function removeEmpty(array) { - var ret = []; - for (var i = 0; i < array.length; i++) { - if (array[i]) { - ret.push(array[i]); - } - } - return ret; - } - function escapeHTML(s) { - var n = s; - n = n.replace(/&/g, '&'); - n = n.replace(//g, '>'); - n = n.replace(/"/g, '"'); - - return n; - } - - var Diff = function(ignoreWhitespace) { - this.ignoreWhitespace = ignoreWhitespace; - }; - Diff.prototype = { - diff: function(oldString, newString) { - // Handle the identity case (this is due to unrolling editLength == 0 - if (newString === oldString) { - return [{ value: newString }]; - } - if (!newString) { - return [{ value: oldString, removed: true }]; - } - if (!oldString) { - return [{ value: newString, added: true }]; - } - - newString = this.tokenize(newString); - oldString = this.tokenize(oldString); - - var newLen = newString.length, oldLen = oldString.length; - var maxEditLength = newLen + oldLen; - var bestPath = [{ newPos: -1, components: [] }]; - - // Seed editLength = 0 - var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); - if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { - return bestPath[0].components; - } - - for (var editLength = 1; editLength <= maxEditLength; editLength++) { - for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { - var basePath; - var addPath = bestPath[diagonalPath-1], - removePath = bestPath[diagonalPath+1]; - oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; - if (addPath) { - // No one else is going to attempt to use this value, clear it - bestPath[diagonalPath-1] = undefined; - } - - var canAdd = addPath && addPath.newPos+1 < newLen; - var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; - if (!canAdd && !canRemove) { - bestPath[diagonalPath] = undefined; - continue; - } - - // Select the diagonal that we want to branch from. We select the prior - // path whose position in the new string is the farthest from the origin - // and does not pass the bounds of the diff graph - if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { - basePath = clonePath(removePath); - this.pushComponent(basePath.components, oldString[oldPos], undefined, true); - } else { - basePath = clonePath(addPath); - basePath.newPos++; - this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); - } - - var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); - - if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { - return basePath.components; - } else { - bestPath[diagonalPath] = basePath; - } - } - } - }, - - pushComponent: function(components, value, added, removed) { - var last = components[components.length-1]; - if (last && last.added === added && last.removed === removed) { - // We need to clone here as the component clone operation is just - // as shallow array clone - components[components.length-1] = - {value: this.join(last.value, value), added: added, removed: removed }; - } else { - components.push({value: value, added: added, removed: removed }); - } - }, - extractCommon: function(basePath, newString, oldString, diagonalPath) { - var newLen = newString.length, - oldLen = oldString.length, - newPos = basePath.newPos, - oldPos = newPos - diagonalPath; - while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { - newPos++; - oldPos++; - - this.pushComponent(basePath.components, newString[newPos], undefined, undefined); - } - basePath.newPos = newPos; - return oldPos; - }, - - equals: function(left, right) { - var reWhitespace = /\S/; - if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { - return true; - } else { - return left === right; - } - }, - join: function(left, right) { - return left + right; - }, - tokenize: function(value) { - return value; - } - }; - - var CharDiff = new Diff(); - - var WordDiff = new Diff(true); - var WordWithSpaceDiff = new Diff(); - WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { - return removeEmpty(value.split(/(\s+|\b)/)); - }; - - var CssDiff = new Diff(true); - CssDiff.tokenize = function(value) { - return removeEmpty(value.split(/([{}:;,]|\s+)/)); - }; - - var LineDiff = new Diff(); - LineDiff.tokenize = function(value) { - var retLines = [], - lines = value.split(/^/m); - - for(var i = 0; i < lines.length; i++) { - var line = lines[i], - lastLine = lines[i - 1]; - - // Merge lines that may contain windows new lines - if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') { - retLines[retLines.length - 1] += '\n'; - } else if (line) { - retLines.push(line); - } - } - - return retLines; - }; - - return { - Diff: Diff, - - diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, - diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, - diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); }, - diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, - - diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, - - createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { - var ret = []; - - ret.push('Index: ' + fileName); - ret.push('==================================================================='); - ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader)); - ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader)); - - var diff = LineDiff.diff(oldStr, newStr); - if (!diff[diff.length-1].value) { - diff.pop(); // Remove trailing newline add - } - diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier - - function contextLines(lines) { - return lines.map(function(entry) { return ' ' + entry; }); - } - function eofNL(curRange, i, current) { - var last = diff[diff.length-2], - isLast = i === diff.length-2, - isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed); - - // Figure out if this is the last line for the given file and missing NL - if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { - curRange.push('\\ No newline at end of file'); - } - } - - var oldRangeStart = 0, newRangeStart = 0, curRange = [], - oldLine = 1, newLine = 1; - for (var i = 0; i < diff.length; i++) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, '').split('\n'); - current.lines = lines; - - if (current.added || current.removed) { - if (!oldRangeStart) { - var prev = diff[i-1]; - oldRangeStart = oldLine; - newRangeStart = newLine; - - if (prev) { - curRange = contextLines(prev.lines.slice(-4)); - oldRangeStart -= curRange.length; - newRangeStart -= curRange.length; - } - } - curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; })); - eofNL(curRange, i, current); - - if (current.added) { - newLine += lines.length; - } else { - oldLine += lines.length; - } - } else { - if (oldRangeStart) { - // Close out any changes that have been output (or join overlapping) - if (lines.length <= 8 && i < diff.length-2) { - // Overlapping - curRange.push.apply(curRange, contextLines(lines)); - } else { - // end the range and output - var contextSize = Math.min(lines.length, 4); - ret.push( - '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize) - + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize) - + ' @@'); - ret.push.apply(ret, curRange); - ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); - if (lines.length <= 4) { - eofNL(ret, i, current); - } - - oldRangeStart = 0; newRangeStart = 0; curRange = []; - } - } - oldLine += lines.length; - newLine += lines.length; - } - } - - return ret.join('\n') + '\n'; - }, - - applyPatch: function(oldStr, uniDiff) { - var diffstr = uniDiff.split('\n'); - var diff = []; - var remEOFNL = false, - addEOFNL = false; - - for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) { - if(diffstr[i][0] === '@') { - var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); - diff.unshift({ - start:meh[3], - oldlength:meh[2], - oldlines:[], - newlength:meh[4], - newlines:[] - }); - } else if(diffstr[i][0] === '+') { - diff[0].newlines.push(diffstr[i].substr(1)); - } else if(diffstr[i][0] === '-') { - diff[0].oldlines.push(diffstr[i].substr(1)); - } else if(diffstr[i][0] === ' ') { - diff[0].newlines.push(diffstr[i].substr(1)); - diff[0].oldlines.push(diffstr[i].substr(1)); - } else if(diffstr[i][0] === '\\') { - if (diffstr[i-1][0] === '+') { - remEOFNL = true; - } else if(diffstr[i-1][0] === '-') { - addEOFNL = true; - } - } - } - - var str = oldStr.split('\n'); - for (var i = diff.length - 1; i >= 0; i--) { - var d = diff[i]; - for (var j = 0; j < d.oldlength; j++) { - if(str[d.start-1+j] !== d.oldlines[j]) { - return false; - } - } - Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines)); - } - - if (remEOFNL) { - while (!str[str.length-1]) { - str.pop(); - } - } else if (addEOFNL) { - str.push(''); - } - return str.join('\n'); - }, - - convertChangesToXML: function(changes){ - var ret = []; - for ( var i = 0; i < changes.length; i++) { - var change = changes[i]; - if (change.added) { - ret.push(''); - } else if (change.removed) { - ret.push(''); - } - - ret.push(escapeHTML(change.value)); - - if (change.added) { - ret.push(''); - } else if (change.removed) { - ret.push(''); - } - } - return ret.join(''); - }, - - // See: http://code.google.com/p/google-diff-match-patch/wiki/API - convertChangesToDMP: function(changes){ - var ret = [], change; - for ( var i = 0; i < changes.length; i++) { - change = changes[i]; - ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]); - } - return ret; - } - }; -})(); - -if (typeof module !== 'undefined') { - module.exports = JsDiff; -} - -}); // module: browser/diff.js - -require.register("browser/escape-string-regexp.js", function(module, exports, require){ -'use strict'; - -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; - -module.exports = function (str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - - return str.replace(matchOperatorsRe, '\\$&'); -}; - -}); // module: browser/escape-string-regexp.js - -require.register("browser/events.js", function(module, exports, require){ -/** - * Module exports. - */ - -exports.EventEmitter = EventEmitter; - -/** - * Check if `obj` is an array. - */ - -function isArray(obj) { - return '[object Array]' == {}.toString.call(obj); -} - -/** - * Event emitter constructor. - * - * @api public - */ - -function EventEmitter(){}; - -/** - * Adds a listener. - * - * @api public - */ - -EventEmitter.prototype.on = function (name, fn) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = fn; - } else if (isArray(this.$events[name])) { - this.$events[name].push(fn); - } else { - this.$events[name] = [this.$events[name], fn]; - } - - return this; -}; - -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -/** - * Adds a volatile listener. - * - * @api public - */ - -EventEmitter.prototype.once = function (name, fn) { - var self = this; - - function on () { - self.removeListener(name, on); - fn.apply(this, arguments); - }; - - on.listener = fn; - this.on(name, on); - - return this; -}; - -/** - * Removes a listener. - * - * @api public - */ - -EventEmitter.prototype.removeListener = function (name, fn) { - if (this.$events && this.$events[name]) { - var list = this.$events[name]; - - if (isArray(list)) { - var pos = -1; - - for (var i = 0, l = list.length; i < l; i++) { - if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { - pos = i; - break; - } - } - - if (pos < 0) { - return this; - } - - list.splice(pos, 1); - - if (!list.length) { - delete this.$events[name]; - } - } else if (list === fn || (list.listener && list.listener === fn)) { - delete this.$events[name]; - } - } - - return this; -}; - -/** - * Removes all listeners for an event. - * - * @api public - */ - -EventEmitter.prototype.removeAllListeners = function (name) { - if (name === undefined) { - this.$events = {}; - return this; - } - - if (this.$events && this.$events[name]) { - this.$events[name] = null; - } - - return this; -}; - -/** - * Gets all listeners for a certain event. - * - * @api public - */ - -EventEmitter.prototype.listeners = function (name) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = []; - } - - if (!isArray(this.$events[name])) { - this.$events[name] = [this.$events[name]]; - } - - return this.$events[name]; -}; - -/** - * Emits an event. - * - * @api public - */ - -EventEmitter.prototype.emit = function (name) { - if (!this.$events) { - return false; - } - - var handler = this.$events[name]; - - if (!handler) { - return false; - } - - var args = [].slice.call(arguments, 1); - - if ('function' == typeof handler) { - handler.apply(this, args); - } else if (isArray(handler)) { - var listeners = handler.slice(); - - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i].apply(this, args); - } - } else { - return false; - } - - return true; -}; - -}); // module: browser/events.js - -require.register("browser/fs.js", function(module, exports, require){ - -}); // module: browser/fs.js - -require.register("browser/glob.js", function(module, exports, require){ - -}); // module: browser/glob.js - -require.register("browser/path.js", function(module, exports, require){ - -}); // module: browser/path.js - -require.register("browser/progress.js", function(module, exports, require){ -/** - * Expose `Progress`. - */ - -module.exports = Progress; - -/** - * Initialize a new `Progress` indicator. - */ - -function Progress() { - this.percent = 0; - this.size(0); - this.fontSize(11); - this.font('helvetica, arial, sans-serif'); -} - -/** - * Set progress size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.size = function(n){ - this._size = n; - return this; -}; - -/** - * Set text to `str`. - * - * @param {String} str - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.text = function(str){ - this._text = str; - return this; -}; - -/** - * Set font size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.fontSize = function(n){ - this._fontSize = n; - return this; -}; - -/** - * Set font `family`. - * - * @param {String} family - * @return {Progress} for chaining - */ - -Progress.prototype.font = function(family){ - this._font = family; - return this; -}; - -/** - * Update percentage to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - */ - -Progress.prototype.update = function(n){ - this.percent = n; - return this; -}; - -/** - * Draw on `ctx`. - * - * @param {CanvasRenderingContext2d} ctx - * @return {Progress} for chaining - */ - -Progress.prototype.draw = function(ctx){ - try { - var percent = Math.min(this.percent, 100) - , size = this._size - , half = size / 2 - , x = half - , y = half - , rad = half - 1 - , fontSize = this._fontSize; - - ctx.font = fontSize + 'px ' + this._font; - - var angle = Math.PI * 2 * (percent / 100); - ctx.clearRect(0, 0, size, size); - - // outer circle - ctx.strokeStyle = '#9f9f9f'; - ctx.beginPath(); - ctx.arc(x, y, rad, 0, angle, false); - ctx.stroke(); - - // inner circle - ctx.strokeStyle = '#eee'; - ctx.beginPath(); - ctx.arc(x, y, rad - 1, 0, angle, true); - ctx.stroke(); - - // text - var text = this._text || (percent | 0) + '%' - , w = ctx.measureText(text).width; - - ctx.fillText( - text - , x - w / 2 + 1 - , y + fontSize / 2 - 1); - } catch (ex) {} //don't fail if we can't render progress - return this; -}; - -}); // module: browser/progress.js - -require.register("browser/tty.js", function(module, exports, require){ -exports.isatty = function(){ - return true; -}; - -exports.getWindowSize = function(){ - if ('innerHeight' in global) { - return [global.innerHeight, global.innerWidth]; - } else { - // In a Web Worker, the DOM Window is not available. - return [640, 480]; - } -}; - -}); // module: browser/tty.js - -require.register("context.js", function(module, exports, require){ -/** - * Expose `Context`. - */ - -module.exports = Context; - -/** - * Initialize a new `Context`. - * - * @api private - */ - -function Context(){} - -/** - * Set or get the context `Runnable` to `runnable`. - * - * @param {Runnable} runnable - * @return {Context} - * @api private - */ - -Context.prototype.runnable = function(runnable){ - if (0 == arguments.length) return this._runnable; - this.test = this._runnable = runnable; - return this; -}; - -/** - * Set test timeout `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.timeout = function(ms){ - if (arguments.length === 0) return this.runnable().timeout(); - this.runnable().timeout(ms); - return this; -}; - -/** - * Set test timeout `enabled`. - * - * @param {Boolean} enabled - * @return {Context} self - * @api private - */ - -Context.prototype.enableTimeouts = function (enabled) { - this.runnable().enableTimeouts(enabled); - return this; -}; - - -/** - * Set test slowness threshold `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.slow = function(ms){ - this.runnable().slow(ms); - return this; -}; - -/** - * Mark a test as skipped. - * - * @return {Context} self - * @api private - */ - -Context.prototype.skip = function(){ - this.runnable().skip(); - return this; -}; - -/** - * Inspect the context void of `._runnable`. - * - * @return {String} - * @api private - */ - -Context.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_runnable' == key) return; - if ('test' == key) return; - return val; - }, 2); -}; - -}); // module: context.js - -require.register("hook.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Hook`. - */ - -module.exports = Hook; - -/** - * Initialize a new `Hook` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Hook(title, fn) { - Runnable.call(this, title, fn); - this.type = 'hook'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -function F(){}; -F.prototype = Runnable.prototype; -Hook.prototype = new F; -Hook.prototype.constructor = Hook; - - -/** - * Get or set the test `err`. - * - * @param {Error} err - * @return {Error} - * @api public - */ - -Hook.prototype.error = function(err){ - if (0 == arguments.length) { - var err = this._error; - this._error = null; - return err; - } - - this._error = err; -}; - -}); // module: hook.js - -require.register("interfaces/bdd.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test') - , utils = require('../utils') - , escapeRe = require('browser/escape-string-regexp'); - -/** - * BDD-style interface: - * - * describe('Array', function(){ - * describe('#indexOf()', function(){ - * it('should return -1 when not present', function(){ - * - * }); - * - * it('should return the index when present', function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - var common = require('./common')(suites, context); - - context.before = common.before; - context.after = common.after; - context.beforeEach = common.beforeEach; - context.afterEach = common.afterEach; - context.run = mocha.options.delay && common.runWithSuite(suite); - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.describe = context.context = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.file = file; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Pending describe. - */ - - context.xdescribe = - context.xcontext = - context.describe.skip = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; - - /** - * Exclusive suite. - */ - - context.describe.only = function(title, fn){ - var suite = context.describe(title, fn); - mocha.grep(suite.fullTitle()); - return suite; - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.it = context.specify = function(title, fn){ - var suite = suites[0]; - if (suite.pending) fn = null; - var test = new Test(title, fn); - test.file = file; - suite.addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.it.only = function(title, fn){ - var test = context.it(title, fn); - var reString = '^' + escapeRe(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - return test; - }; - - /** - * Pending test case. - */ - - context.xit = - context.xspecify = - context.it.skip = function(title){ - context.it(title); - }; - - }); -}; - -}); // module: interfaces/bdd.js - -require.register("interfaces/common.js", function(module, exports, require){ -/** - * Functions common to more than one interface - * @module lib/interfaces/common - */ - -'use strict'; - -module.exports = function (suites, context) { - - return { - /** - * This is only present if flag --delay is passed into Mocha. It triggers - * root suite execution. Returns a function which runs the root suite. - */ - runWithSuite: function runWithSuite(suite) { - return function run() { - suite.run(); - }; - }, - - /** - * Execute before running tests. - */ - before: function (name, fn) { - suites[0].beforeAll(name, fn); - }, - - /** - * Execute after running tests. - */ - after: function (name, fn) { - suites[0].afterAll(name, fn); - }, - - /** - * Execute before each test case. - */ - beforeEach: function (name, fn) { - suites[0].beforeEach(name, fn); - }, - - /** - * Execute after each test case. - */ - afterEach: function (name, fn) { - suites[0].afterEach(name, fn); - }, - - test: { - /** - * Pending test case. - */ - skip: function (title) { - context.test(title); - } - } - } -}; - -}); // module: interfaces/common.js - -require.register("interfaces/exports.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * exports.Array = { - * '#indexOf()': { - * 'should return -1 when the value is not present': function(){ - * - * }, - * - * 'should return the correct index when the value is present': function(){ - * - * } - * } - * }; - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('require', visit); - - function visit(obj, file) { - var suite; - for (var key in obj) { - if ('function' == typeof obj[key]) { - var fn = obj[key]; - switch (key) { - case 'before': - suites[0].beforeAll(fn); - break; - case 'after': - suites[0].afterAll(fn); - break; - case 'beforeEach': - suites[0].beforeEach(fn); - break; - case 'afterEach': - suites[0].afterEach(fn); - break; - default: - var test = new Test(key, fn); - test.file = file; - suites[0].addTest(test); - } - } else { - suite = Suite.create(suites[0], key); - suites.unshift(suite); - visit(obj[key]); - suites.shift(); - } - } - } -}; - -}); // module: interfaces/exports.js - -require.register("interfaces/index.js", function(module, exports, require){ -exports.bdd = require('./bdd'); -exports.tdd = require('./tdd'); -exports.qunit = require('./qunit'); -exports.exports = require('./exports'); - -}); // module: interfaces/index.js - -require.register("interfaces/qunit.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test') - , escapeRe = require('browser/escape-string-regexp') - , utils = require('../utils'); - -/** - * QUnit-style interface: - * - * suite('Array'); - * - * test('#length', function(){ - * var arr = [1,2,3]; - * ok(arr.length == 3); - * }); - * - * test('#indexOf()', function(){ - * var arr = [1,2,3]; - * ok(arr.indexOf(1) == 0); - * ok(arr.indexOf(2) == 1); - * ok(arr.indexOf(3) == 2); - * }); - * - * suite('String'); - * - * test('#length', function(){ - * ok('foo'.length == 3); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - var common = require('./common')(suites, context); - - context.before = common.before; - context.after = common.after; - context.beforeEach = common.beforeEach; - context.afterEach = common.afterEach; - context.run = mocha.options.delay && common.runWithSuite(suite); - /** - * Describe a "suite" with the given `title`. - */ - - context.suite = function(title){ - if (suites.length > 1) suites.shift(); - var suite = Suite.create(suites[0], title); - suite.file = file; - suites.unshift(suite); - return suite; - }; - - /** - * Exclusive test-case. - */ - - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - var test = new Test(title, fn); - test.file = file; - suites[0].addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.test.only = function(title, fn){ - var test = context.test(title, fn); - var reString = '^' + escapeRe(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - }; - - context.test.skip = common.test.skip; - - }); -}; - -}); // module: interfaces/qunit.js - -require.register("interfaces/tdd.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test') - , escapeRe = require('browser/escape-string-regexp') - , utils = require('../utils'); - -/** - * TDD-style interface: - * - * suite('Array', function(){ - * suite('#indexOf()', function(){ - * suiteSetup(function(){ - * - * }); - * - * test('should return -1 when not present', function(){ - * - * }); - * - * test('should return the index when present', function(){ - * - * }); - * - * suiteTeardown(function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - var common = require('./common')(suites, context); - - context.setup = common.beforeEach; - context.teardown = common.afterEach; - context.suiteSetup = common.before; - context.suiteTeardown = common.after; - context.run = mocha.options.delay && common.runWithSuite(suite); - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.suite = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.file = file; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Pending suite. - */ - context.suite.skip = function(title, fn) { - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; - - /** - * Exclusive test-case. - */ - - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - var suite = suites[0]; - if (suite.pending) fn = null; - var test = new Test(title, fn); - test.file = file; - suite.addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.test.only = function(title, fn){ - var test = context.test(title, fn); - var reString = '^' + escapeRe(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - }; - - context.test.skip = common.test.skip; - }); -}; - -}); // module: interfaces/tdd.js - -require.register("mocha.js", function(module, exports, require){ -/*! - * mocha - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var path = require('browser/path') - , escapeRe = require('browser/escape-string-regexp') - , utils = require('./utils'); - -/** - * Expose `Mocha`. - */ - -exports = module.exports = Mocha; - -/** - * To require local UIs and reporters when running in node. - */ - -if (typeof process !== 'undefined' && typeof process.cwd === 'function') { - var join = path.join - , cwd = process.cwd(); - module.paths.push(cwd, join(cwd, 'node_modules')); -} - -/** - * Expose internals. - */ - -exports.utils = utils; -exports.interfaces = require('./interfaces'); -exports.reporters = require('./reporters'); -exports.Runnable = require('./runnable'); -exports.Context = require('./context'); -exports.Runner = require('./runner'); -exports.Suite = require('./suite'); -exports.Hook = require('./hook'); -exports.Test = require('./test'); - -/** - * Return image `name` path. - * - * @param {String} name - * @return {String} - * @api private - */ - -function image(name) { - return __dirname + '/../images/' + name + '.png'; -} - -/** - * Setup mocha with `options`. - * - * Options: - * - * - `ui` name "bdd", "tdd", "exports" etc - * - `reporter` reporter instance, defaults to `mocha.reporters.spec` - * - `globals` array of accepted globals - * - `timeout` timeout in milliseconds - * - `bail` bail on the first test failure - * - `slow` milliseconds to wait before considering a test slow - * - `ignoreLeaks` ignore global leaks - * - `fullTrace` display the full stack-trace on failing - * - `grep` string or regexp to filter tests with - * - * @param {Object} options - * @api public - */ - -function Mocha(options) { - options = options || {}; - this.files = []; - this.options = options; - if (options.grep) this.grep(new RegExp(options.grep)); - if (options.fgrep) this.grep(options.fgrep); - this.suite = new exports.Suite('', new exports.Context); - this.ui(options.ui); - this.bail(options.bail); - this.reporter(options.reporter, options.reporterOptions); - if (null != options.timeout) this.timeout(options.timeout); - this.useColors(options.useColors); - if (options.enableTimeouts !== null) this.enableTimeouts(options.enableTimeouts); - if (options.slow) this.slow(options.slow); - - this.suite.on('pre-require', function (context) { - exports.afterEach = context.afterEach || context.teardown; - exports.after = context.after || context.suiteTeardown; - exports.beforeEach = context.beforeEach || context.setup; - exports.before = context.before || context.suiteSetup; - exports.describe = context.describe || context.suite; - exports.it = context.it || context.test; - exports.setup = context.setup || context.beforeEach; - exports.suiteSetup = context.suiteSetup || context.before; - exports.suiteTeardown = context.suiteTeardown || context.after; - exports.suite = context.suite || context.describe; - exports.teardown = context.teardown || context.afterEach; - exports.test = context.test || context.it; - exports.run = context.run; - }); -} - -/** - * Enable or disable bailing on the first failure. - * - * @param {Boolean} [bail] - * @api public - */ - -Mocha.prototype.bail = function(bail){ - if (0 == arguments.length) bail = true; - this.suite.bail(bail); - return this; -}; - -/** - * Add test `file`. - * - * @param {String} file - * @api public - */ - -Mocha.prototype.addFile = function(file){ - this.files.push(file); - return this; -}; - -/** - * Set reporter to `reporter`, defaults to "spec". - * - * @param {String|Function} reporter name or constructor - * @param {Object} reporterOptions optional options - * @api public - */ -Mocha.prototype.reporter = function(reporter, reporterOptions){ - if ('function' == typeof reporter) { - this._reporter = reporter; - } else { - reporter = reporter || 'spec'; - var _reporter; - try { _reporter = require('./reporters/' + reporter); } catch (err) {} - if (!_reporter) try { _reporter = require(reporter); } catch (err) { - err.message.indexOf('Cannot find module') !== -1 - ? console.warn('"' + reporter + '" reporter not found') - : console.warn('"' + reporter + '" reporter blew up with error:\n' + err.stack); - } - if (!_reporter && reporter === 'teamcity') - console.warn('The Teamcity reporter was moved to a package named ' + - 'mocha-teamcity-reporter ' + - '(https://npmjs.org/package/mocha-teamcity-reporter).'); - if (!_reporter) throw new Error('invalid reporter "' + reporter + '"'); - this._reporter = _reporter; - } - this.options.reporterOptions = reporterOptions; - return this; -}; - -/** - * Set test UI `name`, defaults to "bdd". - * - * @param {String} bdd - * @api public - */ - -Mocha.prototype.ui = function(name){ - name = name || 'bdd'; - this._ui = exports.interfaces[name]; - if (!this._ui) try { this._ui = require(name); } catch (err) {} - if (!this._ui) throw new Error('invalid interface "' + name + '"'); - this._ui = this._ui(this.suite); - return this; -}; - -/** - * Load registered files. - * - * @api private - */ - -Mocha.prototype.loadFiles = function(fn){ - var self = this; - var suite = this.suite; - var pending = this.files.length; - this.files.forEach(function(file){ - file = path.resolve(file); - suite.emit('pre-require', global, file, self); - suite.emit('require', require(file), file, self); - suite.emit('post-require', global, file, self); - --pending || (fn && fn()); - }); -}; - -/** - * Enable growl support. - * - * @api private - */ - -Mocha.prototype._growl = function(runner, reporter) { - var notify = require('growl'); - - runner.on('end', function(){ - var stats = reporter.stats; - if (stats.failures) { - var msg = stats.failures + ' of ' + runner.total + ' tests failed'; - notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); - } else { - notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { - name: 'mocha' - , title: 'Passed' - , image: image('ok') - }); - } - }); -}; - -/** - * Add regexp to grep, if `re` is a string it is escaped. - * - * @param {RegExp|String} re - * @return {Mocha} - * @api public - */ - -Mocha.prototype.grep = function(re){ - this.options.grep = 'string' == typeof re - ? new RegExp(escapeRe(re)) - : re; - return this; -}; - -/** - * Invert `.grep()` matches. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.invert = function(){ - this.options.invert = true; - return this; -}; - -/** - * Ignore global leaks. - * - * @param {Boolean} ignore - * @return {Mocha} - * @api public - */ - -Mocha.prototype.ignoreLeaks = function(ignore){ - this.options.ignoreLeaks = !!ignore; - return this; -}; - -/** - * Enable global leak checking. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.checkLeaks = function(){ - this.options.ignoreLeaks = false; - return this; -}; - -/** - * Display long stack-trace on failing - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.fullTrace = function() { - this.options.fullStackTrace = true; - return this; -}; - -/** - * Enable growl support. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.growl = function(){ - this.options.growl = true; - return this; -}; - -/** - * Ignore `globals` array or string. - * - * @param {Array|String} globals - * @return {Mocha} - * @api public - */ - -Mocha.prototype.globals = function(globals){ - this.options.globals = (this.options.globals || []).concat(globals); - return this; -}; - -/** - * Emit color output. - * - * @param {Boolean} colors - * @return {Mocha} - * @api public - */ - -Mocha.prototype.useColors = function(colors){ - if (colors !== undefined) { - this.options.useColors = colors; - } - return this; -}; - -/** - * Use inline diffs rather than +/-. - * - * @param {Boolean} inlineDiffs - * @return {Mocha} - * @api public - */ - -Mocha.prototype.useInlineDiffs = function(inlineDiffs) { - this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined - ? inlineDiffs - : false; - return this; -}; - -/** - * Set the timeout in milliseconds. - * - * @param {Number} timeout - * @return {Mocha} - * @api public - */ - -Mocha.prototype.timeout = function(timeout){ - this.suite.timeout(timeout); - return this; -}; - -/** - * Set slowness threshold in milliseconds. - * - * @param {Number} slow - * @return {Mocha} - * @api public - */ - -Mocha.prototype.slow = function(slow){ - this.suite.slow(slow); - return this; -}; - -/** - * Enable timeouts. - * - * @param {Boolean} enabled - * @return {Mocha} - * @api public - */ - -Mocha.prototype.enableTimeouts = function(enabled) { - this.suite.enableTimeouts(arguments.length && enabled !== undefined - ? enabled - : true); - return this -}; - -/** - * Makes all tests async (accepting a callback) - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.asyncOnly = function(){ - this.options.asyncOnly = true; - return this; -}; - -/** - * Disable syntax highlighting (in browser). - * @returns {Mocha} - * @api public - */ -Mocha.prototype.noHighlighting = function() { - this.options.noHighlighting = true; - return this; -}; - -/** - * Delay root suite execution. - * @returns {Mocha} - * @api public - */ -Mocha.prototype.delay = function delay() { - this.options.delay = true; - return this; -}; - -/** - * Run tests and invoke `fn()` when complete. - * - * @param {Function} fn - * @return {Runner} - * @api public - */ -Mocha.prototype.run = function(fn){ - if (this.files.length) this.loadFiles(); - var suite = this.suite; - var options = this.options; - options.files = this.files; - var runner = new exports.Runner(suite, options.delay); - var reporter = new this._reporter(runner, options); - runner.ignoreLeaks = false !== options.ignoreLeaks; - runner.fullStackTrace = options.fullStackTrace; - runner.asyncOnly = options.asyncOnly; - if (options.grep) runner.grep(options.grep, options.invert); - if (options.globals) runner.globals(options.globals); - if (options.growl) this._growl(runner, reporter); - if (options.useColors !== undefined) { - exports.reporters.Base.useColors = options.useColors; - } - exports.reporters.Base.inlineDiffs = options.useInlineDiffs; - - function done(failures) { - if (reporter.done) { - reporter.done(failures, fn); - } else fn && fn(failures); - } - - return runner.run(done); -}; - -}); // module: mocha.js - -require.register("ms.js", function(module, exports, require){ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} options - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options){ - options = options || {}; - if ('string' == typeof val) return parse(val); - return options['long'] ? longFormat(val) : shortFormat(val); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); - if (!match) return; - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 's': - return n * s; - case 'ms': - return n; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function shortFormat(ms) { - if (ms >= d) return Math.round(ms / d) + 'd'; - if (ms >= h) return Math.round(ms / h) + 'h'; - if (ms >= m) return Math.round(ms / m) + 'm'; - if (ms >= s) return Math.round(ms / s) + 's'; - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function longFormat(ms) { - return plural(ms, d, 'day') - || plural(ms, h, 'hour') - || plural(ms, m, 'minute') - || plural(ms, s, 'second') - || ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) return; - if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; - return Math.ceil(ms / n) + ' ' + name + 's'; -} - -}); // module: ms.js - -require.register("pending.js", function(module, exports, require){ - -/** - * Expose `Pending`. - */ - -module.exports = Pending; - -/** - * Initialize a new `Pending` error with the given message. - * - * @param {String} message - */ - -function Pending(message) { - this.message = message; -} - -}); // module: pending.js - -require.register("reporters/base.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var tty = require('browser/tty') - , diff = require('browser/diff') - , ms = require('../ms') - , utils = require('../utils') - , supportsColor = process.env ? require('supports-color') : null; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Check if both stdio streams are associated with a tty. - */ - -var isatty = tty.isatty(1) && tty.isatty(2); - -/** - * Expose `Base`. - */ - -exports = module.exports = Base; - -/** - * Enable coloring by default, except in the browser interface. - */ - -exports.useColors = process.env - ? (supportsColor || (process.env.MOCHA_COLORS !== undefined)) - : false; - -/** - * Inline diffs instead of +/- - */ - -exports.inlineDiffs = false; - -/** - * Default color map. - */ - -exports.colors = { - 'pass': 90 - , 'fail': 31 - , 'bright pass': 92 - , 'bright fail': 91 - , 'bright yellow': 93 - , 'pending': 36 - , 'suite': 0 - , 'error title': 0 - , 'error message': 31 - , 'error stack': 90 - , 'checkmark': 32 - , 'fast': 90 - , 'medium': 33 - , 'slow': 31 - , 'green': 32 - , 'light': 90 - , 'diff gutter': 90 - , 'diff added': 42 - , 'diff removed': 41 -}; - -/** - * Default symbol map. - */ - -exports.symbols = { - ok: '✓', - err: '✖', - dot: '․' -}; - -// With node.js on Windows: use symbols available in terminal default fonts -if ('win32' == process.platform) { - exports.symbols.ok = '\u221A'; - exports.symbols.err = '\u00D7'; - exports.symbols.dot = '.'; -} - -/** - * Color `str` with the given `type`, - * allowing colors to be disabled, - * as well as user-defined color - * schemes. - * - * @param {String} type - * @param {String} str - * @return {String} - * @api private - */ - -var color = exports.color = function(type, str) { - if (!exports.useColors) return String(str); - return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; -}; - -/** - * Expose term window size, with some - * defaults for when stderr is not a tty. - */ - -exports.window = { - width: isatty - ? process.stdout.getWindowSize - ? process.stdout.getWindowSize(1)[0] - : tty.getWindowSize()[1] - : 75 -}; - -/** - * Expose some basic cursor interactions - * that are common among reporters. - */ - -exports.cursor = { - hide: function(){ - isatty && process.stdout.write('\u001b[?25l'); - }, - - show: function(){ - isatty && process.stdout.write('\u001b[?25h'); - }, - - deleteLine: function(){ - isatty && process.stdout.write('\u001b[2K'); - }, - - beginningOfLine: function(){ - isatty && process.stdout.write('\u001b[0G'); - }, - - CR: function(){ - if (isatty) { - exports.cursor.deleteLine(); - exports.cursor.beginningOfLine(); - } else { - process.stdout.write('\r'); - } - } -}; - -/** - * Outut the given `failures` as a list. - * - * @param {Array} failures - * @api public - */ - -exports.list = function(failures){ - console.log(); - failures.forEach(function(test, i){ - // format - var fmt = color('error title', ' %s) %s:\n') - + color('error message', ' %s') - + color('error stack', '\n%s\n'); - - // msg - var err = test.err - , message = err.message || '' - , stack = err.stack || message - , index = stack.indexOf(message) - , actual = err.actual - , expected = err.expected - , escape = true; - if (index === -1) { - msg = message; - } else { - index += message.length; - msg = stack.slice(0, index); - // remove msg from stack - stack = stack.slice(index + 1); - } - - // uncaught - if (err.uncaught) { - msg = 'Uncaught ' + msg; - } - // explicitly show diff - if (err.showDiff !== false && sameType(actual, expected) - && expected !== undefined) { - - if ('string' !== typeof actual) { - escape = false; - err.actual = actual = utils.stringify(actual); - err.expected = expected = utils.stringify(expected); - } - - fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); - var match = message.match(/^([^:]+): expected/); - msg = '\n ' + color('error message', match ? match[1] : msg); - - if (exports.inlineDiffs) { - msg += inlineDiff(err, escape); - } else { - msg += unifiedDiff(err, escape); - } - } - - // indent stack trace - stack = stack.replace(/^/gm, ' '); - - console.log(fmt, (i + 1), test.fullTitle(), msg, stack); - }); -}; - -/** - * Initialize a new `Base` reporter. - * - * All other reporters generally - * inherit from this reporter, providing - * stats such as test duration, number - * of tests passed / failed etc. - * - * @param {Runner} runner - * @api public - */ - -function Base(runner) { - var self = this - , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } - , failures = this.failures = []; - - if (!runner) return; - this.runner = runner; - - runner.stats = stats; - - runner.on('start', function(){ - stats.start = new Date; - }); - - runner.on('suite', function(suite){ - stats.suites = stats.suites || 0; - suite.root || stats.suites++; - }); - - runner.on('test end', function(test){ - stats.tests = stats.tests || 0; - stats.tests++; - }); - - runner.on('pass', function(test){ - stats.passes = stats.passes || 0; - - var medium = test.slow() / 2; - test.speed = test.duration > test.slow() - ? 'slow' - : test.duration > medium - ? 'medium' - : 'fast'; - - stats.passes++; - }); - - runner.on('fail', function(test, err){ - stats.failures = stats.failures || 0; - stats.failures++; - test.err = err; - failures.push(test); - }); - - runner.on('end', function(){ - stats.end = new Date; - stats.duration = new Date - stats.start; - }); - - runner.on('pending', function(){ - stats.pending++; - }); -} - -/** - * Output common epilogue used by many of - * the bundled reporters. - * - * @api public - */ - -Base.prototype.epilogue = function(){ - var stats = this.stats; - var tests; - var fmt; - - console.log(); - - // passes - fmt = color('bright pass', ' ') - + color('green', ' %d passing') - + color('light', ' (%s)'); - - console.log(fmt, - stats.passes || 0, - ms(stats.duration)); - - // pending - if (stats.pending) { - fmt = color('pending', ' ') - + color('pending', ' %d pending'); - - console.log(fmt, stats.pending); - } - - // failures - if (stats.failures) { - fmt = color('fail', ' %d failing'); - - console.log(fmt, stats.failures); - - Base.list(this.failures); - console.log(); - } - - console.log(); -}; - -/** - * Pad the given `str` to `len`. - * - * @param {String} str - * @param {String} len - * @return {String} - * @api private - */ - -function pad(str, len) { - str = String(str); - return Array(len - str.length + 1).join(' ') + str; -} - - -/** - * Returns an inline diff between 2 strings with coloured ANSI output - * - * @param {Error} Error with actual/expected - * @return {String} Diff - * @api private - */ - -function inlineDiff(err, escape) { - var msg = errorDiff(err, 'WordsWithSpace', escape); - - // linenos - var lines = msg.split('\n'); - if (lines.length > 4) { - var width = String(lines.length).length; - msg = lines.map(function(str, i){ - return pad(++i, width) + ' |' + ' ' + str; - }).join('\n'); - } - - // legend - msg = '\n' - + color('diff removed', 'actual') - + ' ' - + color('diff added', 'expected') - + '\n\n' - + msg - + '\n'; - - // indent - msg = msg.replace(/^/gm, ' '); - return msg; -} - -/** - * Returns a unified diff between 2 strings - * - * @param {Error} Error with actual/expected - * @return {String} Diff - * @api private - */ - -function unifiedDiff(err, escape) { - var indent = ' '; - function cleanUp(line) { - if (escape) { - line = escapeInvisibles(line); - } - if (line[0] === '+') return indent + colorLines('diff added', line); - if (line[0] === '-') return indent + colorLines('diff removed', line); - if (line.match(/\@\@/)) return null; - if (line.match(/\\ No newline/)) return null; - else return indent + line; - } - function notBlank(line) { - return line != null; - } - var msg = diff.createPatch('string', err.actual, err.expected); - var lines = msg.split('\n').splice(4); - return '\n ' - + colorLines('diff added', '+ expected') + ' ' - + colorLines('diff removed', '- actual') - + '\n\n' - + lines.map(cleanUp).filter(notBlank).join('\n'); -} - -/** - * Return a character diff for `err`. - * - * @param {Error} err - * @return {String} - * @api private - */ - -function errorDiff(err, type, escape) { - var actual = escape ? escapeInvisibles(err.actual) : err.actual; - var expected = escape ? escapeInvisibles(err.expected) : err.expected; - return diff['diff' + type](actual, expected).map(function(str){ - if (str.added) return colorLines('diff added', str.value); - if (str.removed) return colorLines('diff removed', str.value); - return str.value; - }).join(''); -} - -/** - * Returns a string with all invisible characters in plain text - * - * @param {String} line - * @return {String} - * @api private - */ -function escapeInvisibles(line) { - return line.replace(/\t/g, '') - .replace(/\r/g, '') - .replace(/\n/g, '\n'); -} - -/** - * Color lines for `str`, using the color `name`. - * - * @param {String} name - * @param {String} str - * @return {String} - * @api private - */ - -function colorLines(name, str) { - return str.split('\n').map(function(str){ - return color(name, str); - }).join('\n'); -} - -/** - * Check that a / b have the same type. - * - * @param {Object} a - * @param {Object} b - * @return {Boolean} - * @api private - */ - -function sameType(a, b) { - a = Object.prototype.toString.call(a); - b = Object.prototype.toString.call(b); - return a == b; -} - -}); // module: reporters/base.js - -require.register("reporters/doc.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Doc`. - */ - -exports = module.exports = Doc; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Doc(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , indents = 2; - - function indent() { - return Array(indents).join(' '); - } - - runner.on('suite', function(suite){ - if (suite.root) return; - ++indents; - console.log('%s
    ', indent()); - ++indents; - console.log('%s

    %s

    ', indent(), utils.escape(suite.title)); - console.log('%s
    ', indent()); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - console.log('%s
    ', indent()); - --indents; - console.log('%s
    ', indent()); - --indents; - }); - - runner.on('pass', function(test){ - console.log('%s
    %s
    ', indent(), utils.escape(test.title)); - var code = utils.escape(utils.clean(test.fn.toString())); - console.log('%s
    %s
    ', indent(), code); - }); - - runner.on('fail', function(test, err){ - console.log('%s
    %s
    ', indent(), utils.escape(test.title)); - var code = utils.escape(utils.clean(test.fn.toString())); - console.log('%s
    %s
    ', indent(), code); - console.log('%s
    %s
    ', indent(), utils.escape(err)); - }); -} - -}); // module: reporters/doc.js - -require.register("reporters/dot.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = Dot; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Dot(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , n = -1; - - runner.on('start', function(){ - process.stdout.write('\n'); - }); - - runner.on('pending', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('pending', Base.symbols.dot)); - }); - - runner.on('pass', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - if ('slow' == test.speed) { - process.stdout.write(color('bright yellow', Base.symbols.dot)); - } else { - process.stdout.write(color(test.speed, Base.symbols.dot)); - } - }); - - runner.on('fail', function(test, err){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('fail', Base.symbols.dot)); - }); - - runner.on('end', function(){ - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Dot.prototype = new F; -Dot.prototype.constructor = Dot; - - -}); // module: reporters/dot.js - -require.register("reporters/html-cov.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var JSONCov = require('./json-cov') - , fs = require('browser/fs'); - -/** - * Expose `HTMLCov`. - */ - -exports = module.exports = HTMLCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTMLCov(runner) { - var jade = require('jade') - , file = __dirname + '/templates/coverage.jade' - , str = fs.readFileSync(file, 'utf8') - , fn = jade.compile(str, { filename: file }) - , self = this; - - JSONCov.call(this, runner, false); - - runner.on('end', function(){ - process.stdout.write(fn({ - cov: self.cov - , coverageClass: coverageClass - })); - }); -} - -/** - * Return coverage class for `n`. - * - * @return {String} - * @api private - */ - -function coverageClass(n) { - if (n >= 75) return 'high'; - if (n >= 50) return 'medium'; - if (n >= 25) return 'low'; - return 'terrible'; -} - -}); // module: reporters/html-cov.js - -require.register("reporters/html.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , Progress = require('../browser/progress') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `HTML`. - */ - -exports = module.exports = HTML; - -/** - * Stats template. - */ - -var statsTemplate = ''; - -/** - * Initialize a new `HTML` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTML(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , stat = fragment(statsTemplate) - , items = stat.getElementsByTagName('li') - , passes = items[1].getElementsByTagName('em')[0] - , passesLink = items[1].getElementsByTagName('a')[0] - , failures = items[2].getElementsByTagName('em')[0] - , failuresLink = items[2].getElementsByTagName('a')[0] - , duration = items[3].getElementsByTagName('em')[0] - , canvas = stat.getElementsByTagName('canvas')[0] - , report = fragment('
      ') - , stack = [report] - , progress - , ctx - , root = document.getElementById('mocha'); - - if (canvas.getContext) { - var ratio = window.devicePixelRatio || 1; - canvas.style.width = canvas.width; - canvas.style.height = canvas.height; - canvas.width *= ratio; - canvas.height *= ratio; - ctx = canvas.getContext('2d'); - ctx.scale(ratio, ratio); - progress = new Progress; - } - - if (!root) return error('#mocha div missing, add it to your document'); - - // pass toggle - on(passesLink, 'click', function(){ - unhide(); - var name = /pass/.test(report.className) ? '' : ' pass'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test pass'); - }); - - // failure toggle - on(failuresLink, 'click', function(){ - unhide(); - var name = /fail/.test(report.className) ? '' : ' fail'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test fail'); - }); - - root.appendChild(stat); - root.appendChild(report); - - if (progress) progress.size(40); - - runner.on('suite', function(suite){ - if (suite.root) return; - - // suite - var url = self.suiteURL(suite); - var el = fragment('
    • %s

    • ', url, escape(suite.title)); - - // container - stack[0].appendChild(el); - stack.unshift(document.createElement('ul')); - el.appendChild(stack[0]); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - stack.shift(); - }); - - runner.on('fail', function(test, err){ - if ('hook' == test.type) runner.emit('test end', test); - }); - - runner.on('test end', function(test){ - // TODO: add to stats - var percent = stats.tests / this.total * 100 | 0; - if (progress) progress.update(percent).draw(ctx); - - // update stats - var ms = new Date - stats.start; - text(passes, stats.passes); - text(failures, stats.failures); - text(duration, (ms / 1000).toFixed(2)); - - // test - if ('passed' == test.state) { - var url = self.testURL(test); - var el = fragment('
    • %e%ems

    • ', test.speed, test.title, test.duration, url); - } else if (test.pending) { - var el = fragment('
    • %e

    • ', test.title); - } else { - var el = fragment('
    • %e

    • ', test.title, self.testURL(test)); - var str = test.err.stack || test.err.toString(); - - // FF / Opera do not add the message - if (!~str.indexOf(test.err.message)) { - str = test.err.message + '\n' + str; - } - - // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we - // check for the result of the stringifying. - if ('[object Error]' == str) str = test.err.message; - - // Safari doesn't give you a stack. Let's at least provide a source line. - if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { - str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; - } - - el.appendChild(fragment('
      %e
      ', str)); - } - - // toggle code - // TODO: defer - if (!test.pending) { - var h2 = el.getElementsByTagName('h2')[0]; - - on(h2, 'click', function(){ - pre.style.display = 'none' == pre.style.display - ? 'block' - : 'none'; - }); - - var pre = fragment('
      %e
      ', utils.clean(test.fn.toString())); - el.appendChild(pre); - pre.style.display = 'none'; - } - - // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. - if (stack[0]) stack[0].appendChild(el); - }); -} - -/** - * Makes a URL, preserving querystring ("search") parameters. - * @param {string} s - * @returns {string} your new URL - */ -var makeUrl = function makeUrl(s) { - var search = window.location.search; - - // Remove previous grep query parameter if present - if (search) { - search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?'); - } - - return window.location.pathname + (search ? search + '&' : '?' ) + 'grep=' + encodeURIComponent(s); -}; - -/** - * Provide suite URL - * - * @param {Object} [suite] - */ -HTML.prototype.suiteURL = function(suite){ - return makeUrl(suite.fullTitle()); -}; - -/** - * Provide test URL - * - * @param {Object} [test] - */ - -HTML.prototype.testURL = function(test){ - return makeUrl(test.fullTitle()); -}; - -/** - * Display error `msg`. - */ - -function error(msg) { - document.body.appendChild(fragment('
      %s
      ', msg)); -} - -/** - * Return a DOM fragment from `html`. - */ - -function fragment(html) { - var args = arguments - , div = document.createElement('div') - , i = 1; - - div.innerHTML = html.replace(/%([se])/g, function(_, type){ - switch (type) { - case 's': return String(args[i++]); - case 'e': return escape(args[i++]); - } - }); - - return div.firstChild; -} - -/** - * Check for suites that do not have elements - * with `classname`, and hide them. - */ - -function hideSuitesWithout(classname) { - var suites = document.getElementsByClassName('suite'); - for (var i = 0; i < suites.length; i++) { - var els = suites[i].getElementsByClassName(classname); - if (0 == els.length) suites[i].className += ' hidden'; - } -} - -/** - * Unhide .hidden suites. - */ - -function unhide() { - var els = document.getElementsByClassName('suite hidden'); - for (var i = 0; i < els.length; ++i) { - els[i].className = els[i].className.replace('suite hidden', 'suite'); - } -} - -/** - * Set `el` text to `str`. - */ - -function text(el, str) { - if (el.textContent) { - el.textContent = str; - } else { - el.innerText = str; - } -} - -/** - * Listen on `event` with callback `fn`. - */ - -function on(el, event, fn) { - if (el.addEventListener) { - el.addEventListener(event, fn, false); - } else { - el.attachEvent('on' + event, fn); - } -} - -}); // module: reporters/html.js - -require.register("reporters/index.js", function(module, exports, require){ -exports.Base = require('./base'); -exports.Dot = require('./dot'); -exports.Doc = require('./doc'); -exports.TAP = require('./tap'); -exports.JSON = require('./json'); -exports.HTML = require('./html'); -exports.List = require('./list'); -exports.Min = require('./min'); -exports.Spec = require('./spec'); -exports.Nyan = require('./nyan'); -exports.XUnit = require('./xunit'); -exports.Markdown = require('./markdown'); -exports.Progress = require('./progress'); -exports.Landing = require('./landing'); -exports.JSONCov = require('./json-cov'); -exports.HTMLCov = require('./html-cov'); -exports.JSONStream = require('./json-stream'); - -}); // module: reporters/index.js - -require.register("reporters/json-cov.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `JSONCov`. - */ - -exports = module.exports = JSONCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @param {Boolean} output - * @api public - */ - -function JSONCov(runner, output) { - var self = this - , output = 1 == arguments.length ? true : output; - - Base.call(this, runner); - - var tests = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('end', function(){ - var cov = global._$jscoverage || {}; - var result = self.cov = map(cov); - result.stats = self.stats; - result.tests = tests.map(clean); - result.failures = failures.map(clean); - result.passes = passes.map(clean); - if (!output) return; - process.stdout.write(JSON.stringify(result, null, 2 )); - }); -} - -/** - * Map jscoverage data to a JSON structure - * suitable for reporting. - * - * @param {Object} cov - * @return {Object} - * @api private - */ - -function map(cov) { - var ret = { - instrumentation: 'node-jscoverage' - , sloc: 0 - , hits: 0 - , misses: 0 - , coverage: 0 - , files: [] - }; - - for (var filename in cov) { - var data = coverage(filename, cov[filename]); - ret.files.push(data); - ret.hits += data.hits; - ret.misses += data.misses; - ret.sloc += data.sloc; - } - - ret.files.sort(function(a, b) { - return a.filename.localeCompare(b.filename); - }); - - if (ret.sloc > 0) { - ret.coverage = (ret.hits / ret.sloc) * 100; - } - - return ret; -} - -/** - * Map jscoverage data for a single source file - * to a JSON structure suitable for reporting. - * - * @param {String} filename name of the source file - * @param {Object} data jscoverage coverage data - * @return {Object} - * @api private - */ - -function coverage(filename, data) { - var ret = { - filename: filename, - coverage: 0, - hits: 0, - misses: 0, - sloc: 0, - source: {} - }; - - data.source.forEach(function(line, num){ - num++; - - if (data[num] === 0) { - ret.misses++; - ret.sloc++; - } else if (data[num] !== undefined) { - ret.hits++; - ret.sloc++; - } - - ret.source[num] = { - source: line - , coverage: data[num] === undefined - ? '' - : data[num] - }; - }); - - ret.coverage = ret.hits / ret.sloc * 100; - - return ret; -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} - -}); // module: reporters/json-cov.js - -require.register("reporters/json-stream.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total; - - runner.on('start', function(){ - console.log(JSON.stringify(['start', { total: total }])); - }); - - runner.on('pass', function(test){ - console.log(JSON.stringify(['pass', clean(test)])); - }); - - runner.on('fail', function(test, err){ - test = clean(test); - test.err = err.message; - console.log(JSON.stringify(['fail', test])); - }); - - runner.on('end', function(){ - process.stdout.write(JSON.stringify(['end', self.stats])); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} - -}); // module: reporters/json-stream.js - -require.register("reporters/json.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `JSON`. - */ - -exports = module.exports = JSONReporter; - -/** - * Initialize a new `JSON` reporter. - * - * @param {Runner} runner - * @api public - */ - -function JSONReporter(runner) { - var self = this; - Base.call(this, runner); - - var tests = [] - , pending = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('pending', function(test){ - pending.push(test); - }); - - runner.on('end', function(){ - var obj = { - stats: self.stats, - tests: tests.map(clean), - pending: pending.map(clean), - failures: failures.map(clean), - passes: passes.map(clean) - }; - - runner.testResults = obj; - - process.stdout.write(JSON.stringify(obj, null, 2)); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title, - fullTitle: test.fullTitle(), - duration: test.duration, - err: errorJSON(test.err || {}) - } -} - -/** - * Transform `error` into a JSON object. - * @param {Error} err - * @return {Object} - */ - -function errorJSON(err) { - var res = {}; - Object.getOwnPropertyNames(err).forEach(function(key) { - res[key] = err[key]; - }, err); - return res; -} - -}); // module: reporters/json.js - -require.register("reporters/landing.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Landing`. - */ - -exports = module.exports = Landing; - -/** - * Airplane color. - */ - -Base.colors.plane = 0; - -/** - * Airplane crash color. - */ - -Base.colors['plane crash'] = 31; - -/** - * Runway color. - */ - -Base.colors.runway = 90; - -/** - * Initialize a new `Landing` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Landing(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , total = runner.total - , stream = process.stdout - , plane = color('plane', '✈') - , crashed = -1 - , n = 0; - - function runway() { - var buf = Array(width).join('-'); - return ' ' + color('runway', buf); - } - - runner.on('start', function(){ - stream.write('\n\n\n '); - cursor.hide(); - }); - - runner.on('test end', function(test){ - // check if the plane crashed - var col = -1 == crashed - ? width * ++n / total | 0 - : crashed; - - // show the crash - if ('failed' == test.state) { - plane = color('plane crash', '✈'); - crashed = col; - } - - // render landing strip - stream.write('\u001b['+(width+1)+'D\u001b[2A'); - stream.write(runway()); - stream.write('\n '); - stream.write(color('runway', Array(col).join('⋅'))); - stream.write(plane) - stream.write(color('runway', Array(width - col).join('⋅') + '\n')); - stream.write(runway()); - stream.write('\u001b[0m'); - }); - - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Landing.prototype = new F; -Landing.prototype.constructor = Landing; - - -}); // module: reporters/landing.js - -require.register("reporters/list.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 0; - - runner.on('start', function(){ - console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = color('checkmark', ' -') - + color('pending', ' %s'); - console.log(fmt, test.fullTitle()); - }); - - runner.on('pass', function(test){ - var fmt = color('checkmark', ' '+Base.symbols.dot) - + color('pass', ' %s: ') - + color(test.speed, '%dms'); - cursor.CR(); - console.log(fmt, test.fullTitle(), test.duration); - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -List.prototype = new F; -List.prototype.constructor = List; - - -}); // module: reporters/list.js - -require.register("reporters/markdown.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Constants - */ - -var SUITE_PREFIX = '$'; - -/** - * Expose `Markdown`. - */ - -exports = module.exports = Markdown; - -/** - * Initialize a new `Markdown` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Markdown(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , level = 0 - , buf = ''; - - function title(str) { - return Array(level).join('#') + ' ' + str; - } - - function indent() { - return Array(level).join(' '); - } - - function mapTOC(suite, obj) { - var ret = obj, - key = SUITE_PREFIX + suite.title; - obj = obj[key] = obj[key] || { suite: suite }; - suite.suites.forEach(function(suite){ - mapTOC(suite, obj); - }); - return ret; - } - - function stringifyTOC(obj, level) { - ++level; - var buf = ''; - var link; - for (var key in obj) { - if ('suite' == key) continue; - if (key !== SUITE_PREFIX) { - link = ' - [' + key.substring(1) + ']'; - link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; - buf += Array(level).join(' ') + link; - } - buf += stringifyTOC(obj[key], level); - } - return buf; - } - - function generateTOC(suite) { - var obj = mapTOC(suite, {}); - return stringifyTOC(obj, 0); - } - - generateTOC(runner.suite); - - runner.on('suite', function(suite){ - ++level; - var slug = utils.slug(suite.fullTitle()); - buf += '' + '\n'; - buf += title(suite.title) + '\n'; - }); - - runner.on('suite end', function(suite){ - --level; - }); - - runner.on('pass', function(test){ - var code = utils.clean(test.fn.toString()); - buf += test.title + '.\n'; - buf += '\n```js\n'; - buf += code + '\n'; - buf += '```\n\n'; - }); - - runner.on('end', function(){ - process.stdout.write('# TOC\n'); - process.stdout.write(generateTOC(runner.suite)); - process.stdout.write(buf); - }); -} - -}); // module: reporters/markdown.js - -require.register("reporters/min.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Min`. - */ - -exports = module.exports = Min; - -/** - * Initialize a new `Min` minimal test reporter (best used with --watch). - * - * @param {Runner} runner - * @api public - */ - -function Min(runner) { - Base.call(this, runner); - - runner.on('start', function(){ - // clear screen - process.stdout.write('\u001b[2J'); - // set cursor position - process.stdout.write('\u001b[1;3H'); - }); - - runner.on('end', this.epilogue.bind(this)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Min.prototype = new F; -Min.prototype.constructor = Min; - - -}); // module: reporters/min.js - -require.register("reporters/nyan.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Dot`. - */ - -exports = module.exports = NyanCat; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function NyanCat(runner) { - Base.call(this, runner); - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , rainbowColors = this.rainbowColors = self.generateColors() - , colorIndex = this.colorIndex = 0 - , numerOfLines = this.numberOfLines = 4 - , trajectories = this.trajectories = [[], [], [], []] - , nyanCatWidth = this.nyanCatWidth = 11 - , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) - , scoreboardWidth = this.scoreboardWidth = 5 - , tick = this.tick = 0 - , n = 0; - - runner.on('start', function(){ - Base.cursor.hide(); - self.draw(); - }); - - runner.on('pending', function(test){ - self.draw(); - }); - - runner.on('pass', function(test){ - self.draw(); - }); - - runner.on('fail', function(test, err){ - self.draw(); - }); - - runner.on('end', function(){ - Base.cursor.show(); - for (var i = 0; i < self.numberOfLines; i++) write('\n'); - self.epilogue(); - }); -} - -/** - * Draw the nyan cat - * - * @api private - */ - -NyanCat.prototype.draw = function(){ - this.appendRainbow(); - this.drawScoreboard(); - this.drawRainbow(); - this.drawNyanCat(); - this.tick = !this.tick; -}; - -/** - * Draw the "scoreboard" showing the number - * of passes, failures and pending tests. - * - * @api private - */ - -NyanCat.prototype.drawScoreboard = function(){ - var stats = this.stats; - - function draw(type, n) { - write(' '); - write(Base.color(type, n)); - write('\n'); - } - - draw('green', stats.passes); - draw('fail', stats.failures); - draw('pending', stats.pending); - write('\n'); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Append the rainbow. - * - * @api private - */ - -NyanCat.prototype.appendRainbow = function(){ - var segment = this.tick ? '_' : '-'; - var rainbowified = this.rainbowify(segment); - - for (var index = 0; index < this.numberOfLines; index++) { - var trajectory = this.trajectories[index]; - if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); - trajectory.push(rainbowified); - } -}; - -/** - * Draw the rainbow. - * - * @api private - */ - -NyanCat.prototype.drawRainbow = function(){ - var self = this; - - this.trajectories.forEach(function(line, index) { - write('\u001b[' + self.scoreboardWidth + 'C'); - write(line.join('')); - write('\n'); - }); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Draw the nyan cat - * - * @api private - */ - -NyanCat.prototype.drawNyanCat = function() { - var self = this; - var startWidth = this.scoreboardWidth + this.trajectories[0].length; - var dist = '\u001b[' + startWidth + 'C'; - var padding = ''; - - write(dist); - write('_,------,'); - write('\n'); - - write(dist); - padding = self.tick ? ' ' : ' '; - write('_|' + padding + '/\\_/\\ '); - write('\n'); - - write(dist); - padding = self.tick ? '_' : '__'; - var tail = self.tick ? '~' : '^'; - var face; - write(tail + '|' + padding + this.face() + ' '); - write('\n'); - - write(dist); - padding = self.tick ? ' ' : ' '; - write(padding + '"" "" '); - write('\n'); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Draw nyan cat face. - * - * @return {String} - * @api private - */ - -NyanCat.prototype.face = function() { - var stats = this.stats; - if (stats.failures) { - return '( x .x)'; - } else if (stats.pending) { - return '( o .o)'; - } else if(stats.passes) { - return '( ^ .^)'; - } else { - return '( - .-)'; - } -}; - -/** - * Move cursor up `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorUp = function(n) { - write('\u001b[' + n + 'A'); -}; - -/** - * Move cursor down `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorDown = function(n) { - write('\u001b[' + n + 'B'); -}; - -/** - * Generate rainbow colors. - * - * @return {Array} - * @api private - */ - -NyanCat.prototype.generateColors = function(){ - var colors = []; - - for (var i = 0; i < (6 * 7); i++) { - var pi3 = Math.floor(Math.PI / 3); - var n = (i * (1.0 / 6)); - var r = Math.floor(3 * Math.sin(n) + 3); - var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); - var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); - colors.push(36 * r + 6 * g + b + 16); - } - - return colors; -}; - -/** - * Apply rainbow to the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -NyanCat.prototype.rainbowify = function(str){ - if (!Base.useColors) - return str; - var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; - this.colorIndex += 1; - return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; -}; - -/** - * Stdout helper. - */ - -function write(string) { - process.stdout.write(string); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -NyanCat.prototype = new F; -NyanCat.prototype.constructor = NyanCat; - - -}); // module: reporters/nyan.js - -require.register("reporters/progress.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Progress`. - */ - -exports = module.exports = Progress; - -/** - * General progress bar color. - */ - -Base.colors.progress = 90; - -/** - * Initialize a new `Progress` bar test reporter. - * - * @param {Runner} runner - * @param {Object} options - * @api public - */ - -function Progress(runner, options) { - Base.call(this, runner); - - var self = this - , options = options || {} - , stats = this.stats - , width = Base.window.width * .50 | 0 - , total = runner.total - , complete = 0 - , max = Math.max - , lastN = -1; - - // default chars - options.open = options.open || '['; - options.complete = options.complete || '▬'; - options.incomplete = options.incomplete || Base.symbols.dot; - options.close = options.close || ']'; - options.verbose = false; - - // tests started - runner.on('start', function(){ - console.log(); - cursor.hide(); - }); - - // tests complete - runner.on('test end', function(){ - complete++; - var incomplete = total - complete - , percent = complete / total - , n = width * percent | 0 - , i = width - n; - - if (lastN === n && !options.verbose) { - // Don't re-render the line if it hasn't changed - return; - } - lastN = n; - - cursor.CR(); - process.stdout.write('\u001b[J'); - process.stdout.write(color('progress', ' ' + options.open)); - process.stdout.write(Array(n).join(options.complete)); - process.stdout.write(Array(i).join(options.incomplete)); - process.stdout.write(color('progress', options.close)); - if (options.verbose) { - process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); - } - }); - - // tests are complete, output some stats - // and the failures if any - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Progress.prototype = new F; -Progress.prototype.constructor = Progress; - - -}); // module: reporters/progress.js - -require.register("reporters/spec.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Spec`. - */ - -exports = module.exports = Spec; - -/** - * Initialize a new `Spec` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Spec(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , indents = 0 - , n = 0; - - function indent() { - return Array(indents).join(' ') - } - - runner.on('start', function(){ - console.log(); - }); - - runner.on('suite', function(suite){ - ++indents; - console.log(color('suite', '%s%s'), indent(), suite.title); - }); - - runner.on('suite end', function(suite){ - --indents; - if (1 == indents) console.log(); - }); - - runner.on('pending', function(test){ - var fmt = indent() + color('pending', ' - %s'); - console.log(fmt, test.title); - }); - - runner.on('pass', function(test){ - if ('fast' == test.speed) { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s'); - cursor.CR(); - console.log(fmt, test.title); - } else { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s') - + color(test.speed, ' (%dms)'); - cursor.CR(); - console.log(fmt, test.title, test.duration); - } - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Spec.prototype = new F; -Spec.prototype.constructor = Spec; - - -}); // module: reporters/spec.js - -require.register("reporters/tap.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `TAP`. - */ - -exports = module.exports = TAP; - -/** - * Initialize a new `TAP` reporter. - * - * @param {Runner} runner - * @api public - */ - -function TAP(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 1 - , passes = 0 - , failures = 0; - - runner.on('start', function(){ - var total = runner.grepTotal(runner.suite); - console.log('%d..%d', 1, total); - }); - - runner.on('test end', function(){ - ++n; - }); - - runner.on('pending', function(test){ - console.log('ok %d %s # SKIP -', n, title(test)); - }); - - runner.on('pass', function(test){ - passes++; - console.log('ok %d %s', n, title(test)); - }); - - runner.on('fail', function(test, err){ - failures++; - console.log('not ok %d %s', n, title(test)); - if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); - }); - - runner.on('end', function(){ - console.log('# tests ' + (passes + failures)); - console.log('# pass ' + passes); - console.log('# fail ' + failures); - }); -} - -/** - * Return a TAP-safe title of `test` - * - * @param {Object} test - * @return {String} - * @api private - */ - -function title(test) { - return test.fullTitle().replace(/#/g, ''); -} - -}); // module: reporters/tap.js - -require.register("reporters/xunit.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , fs = require('browser/fs') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `XUnit`. - */ - -exports = module.exports = XUnit; - -/** - * Initialize a new `XUnit` reporter. - * - * @param {Runner} runner - * @api public - */ - -function XUnit(runner, options) { - Base.call(this, runner); - var stats = this.stats - , tests = [] - , self = this; - - if (options.reporterOptions && options.reporterOptions.output) { - if (! fs.createWriteStream) { - throw new Error('file output not supported in browser'); - } - self.fileStream = fs.createWriteStream(options.reporterOptions.output); - } - - runner.on('pending', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - tests.push(test); - }); - - runner.on('fail', function(test){ - tests.push(test); - }); - - runner.on('end', function(){ - self.write(tag('testsuite', { - name: 'Mocha Tests' - , tests: stats.tests - , failures: stats.failures - , errors: stats.failures - , skipped: stats.tests - stats.failures - stats.passes - , timestamp: (new Date).toUTCString() - , time: (stats.duration / 1000) || 0 - }, false)); - - tests.forEach(function(t) { self.test(t); }); - self.write(''); - }); -} - -/** - * Override done to close the stream (if it's a file). - */ -XUnit.prototype.done = function(failures, fn) { - if (this.fileStream) { - this.fileStream.end(function() { - fn(failures); - }); - } else { - fn(failures); - } -}; - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -XUnit.prototype = new F; -XUnit.prototype.constructor = XUnit; - - -/** - * Write out the given line - */ -XUnit.prototype.write = function(line) { - if (this.fileStream) { - this.fileStream.write(line + '\n'); - } else { - console.log(line); - } -}; - -/** - * Output tag for the given `test.` - */ - -XUnit.prototype.test = function(test, ostream) { - var attrs = { - classname: test.parent.fullTitle() - , name: test.title - , time: (test.duration / 1000) || 0 - }; - - if ('failed' == test.state) { - var err = test.err; - this.write(tag('testcase', attrs, false, tag('failure', {}, false, cdata(escape(err.message) + "\n" + err.stack)))); - } else if (test.pending) { - this.write(tag('testcase', attrs, false, tag('skipped', {}, true))); - } else { - this.write(tag('testcase', attrs, true) ); - } -}; - -/** - * HTML tag helper. - */ - -function tag(name, attrs, close, content) { - var end = close ? '/>' : '>' - , pairs = [] - , tag; - - for (var key in attrs) { - pairs.push(key + '="' + escape(attrs[key]) + '"'); - } - - tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; - if (content) tag += content + ''; -} - -}); // module: reporters/xunit.js - -require.register("runnable.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runnable') - , Pending = require('./pending') - , milliseconds = require('./ms') - , utils = require('./utils'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Object#toString(). - */ - -var toString = Object.prototype.toString; - -/** - * Expose `Runnable`. - */ - -module.exports = Runnable; - -/** - * Initialize a new `Runnable` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Runnable(title, fn) { - this.title = title; - this.fn = fn; - this.async = fn && fn.length; - this.sync = ! this.async; - this._timeout = 2000; - this._slow = 75; - this._enableTimeouts = true; - this.timedOut = false; - this._trace = new Error('done() called multiple times') -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Runnable.prototype = new F; -Runnable.prototype.constructor = Runnable; - - -/** - * Set & get timeout `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if (ms === 0) this._enableTimeouts = false; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = ms; - if (this.timer) this.resetTimeout(); - return this; -}; - -/** - * Set & get slow `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._slow = ms; - return this; -}; - -/** - * Set and & get timeout `enabled`. - * - * @param {Boolean} enabled - * @return {Runnable|Boolean} enabled or self - * @api private - */ - -Runnable.prototype.enableTimeouts = function(enabled){ - if (arguments.length === 0) return this._enableTimeouts; - debug('enableTimeouts %s', enabled); - this._enableTimeouts = enabled; - return this; -}; - -/** - * Halt and mark as pending. - * - * @api private - */ - -Runnable.prototype.skip = function(){ - throw new Pending(); -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Runnable.prototype.fullTitle = function(){ - return this.parent.fullTitle() + ' ' + this.title; -}; - -/** - * Clear the timeout. - * - * @api private - */ - -Runnable.prototype.clearTimeout = function(){ - clearTimeout(this.timer); -}; - -/** - * Inspect the runnable void of private properties. - * - * @return {String} - * @api private - */ - -Runnable.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_' == key[0]) return; - if ('parent' == key) return '#'; - if ('ctx' == key) return '#'; - return val; - }, 2); -}; - -/** - * Reset the timeout. - * - * @api private - */ - -Runnable.prototype.resetTimeout = function(){ - var self = this; - var ms = this.timeout() || 1e9; - - if (!this._enableTimeouts) return; - this.clearTimeout(); - this.timer = setTimeout(function(){ - if (!self._enableTimeouts) return; - self.callback(new Error('timeout of ' + ms + 'ms exceeded. Ensure the done() callback is being called in this test.')); - self.timedOut = true; - }, ms); -}; - -/** - * Whitelist these globals for this test run - * - * @api private - */ -Runnable.prototype.globals = function(arr){ - var self = this; - this._allowedGlobals = arr; -}; - -/** - * Run the test and invoke `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runnable.prototype.run = function(fn){ - var self = this - , start = new Date - , ctx = this.ctx - , finished - , emitted; - - // Some times the ctx exists but it is not runnable - if (ctx && ctx.runnable) ctx.runnable(this); - - // called multiple times - function multiple(err) { - if (emitted) return; - emitted = true; - self.emit('error', err || new Error('done() called multiple times; stacktrace may be inaccurate')); - } - - // finished - function done(err) { - var ms = self.timeout(); - if (self.timedOut) return; - if (finished) return multiple(err || self._trace); - - // Discard the resolution if this test has already failed asynchronously - if (self.state) return; - - self.clearTimeout(); - self.duration = new Date - start; - finished = true; - if (!err && self.duration > ms && self._enableTimeouts) err = new Error('timeout of ' + ms + 'ms exceeded. Ensure the done() callback is being called in this test.'); - fn(err); - } - - // for .resetTimeout() - this.callback = done; - - // explicit async with `done` argument - if (this.async) { - this.resetTimeout(); - - try { - this.fn.call(ctx, function(err){ - if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); - if (null != err) { - if (Object.prototype.toString.call(err) === '[object Object]') { - return done(new Error('done() invoked with non-Error: ' + JSON.stringify(err))); - } else { - return done(new Error('done() invoked with non-Error: ' + err)); - } - } - done(); - }); - } catch (err) { - done(utils.getError(err)); - } - return; - } - - if (this.asyncOnly) { - return done(new Error('--async-only option in use without declaring `done()`')); - } - - // sync or promise-returning - try { - if (this.pending) { - done(); - } else { - callFn(this.fn); - } - } catch (err) { - done(utils.getError(err)); - } - - function callFn(fn) { - var result = fn.call(ctx); - if (result && typeof result.then === 'function') { - self.resetTimeout(); - result - .then(function() { - done() - }, - function(reason) { - done(reason || new Error('Promise rejected with no or falsy reason')) - }); - } else { - done(); - } - } -}; - -}); // module: runnable.js - -require.register("runner.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runner') - , Pending = require('./pending') - , Test = require('./test') - , utils = require('./utils') - , filter = utils.filter - , keys = utils.keys - , type = utils.type - , stringify = utils.stringify - , stackFilter = utils.stackTraceFilter(); - -/** - * Non-enumerable globals. - */ - -var globals = [ - 'setTimeout', - 'clearTimeout', - 'setInterval', - 'clearInterval', - 'XMLHttpRequest', - 'Date', - 'setImmediate', - 'clearImmediate' -]; - -/** - * Expose `Runner`. - */ - -module.exports = Runner; - -/** - * Initialize a `Runner` for the given `suite`. - * - * Events: - * - * - `start` execution started - * - `end` execution complete - * - `suite` (suite) test suite execution started - * - `suite end` (suite) all tests (and sub-suites) have finished - * - `test` (test) test execution started - * - `test end` (test) test completed - * - `hook` (hook) hook execution started - * - `hook end` (hook) hook complete - * - `pass` (test) test passed - * - `fail` (test, err) test failed - * - `pending` (test) test pending - * - * @param {Suite} suite Root suite - * @param {boolean} [delay] Whether or not to delay execution of root suite - * until ready. - * @api public - */ - -function Runner(suite, delay) { - var self = this; - this._globals = []; - this._abort = false; - this._delay = delay; - this.suite = suite; - this.total = suite.total(); - this.failures = 0; - this.on('test end', function(test){ self.checkGlobals(test); }); - this.on('hook end', function(hook){ self.checkGlobals(hook); }); - this.grep(/.*/); - this.globals(this.globalProps().concat(extraGlobals())); -} - -/** - * Wrapper for setImmediate, process.nextTick, or browser polyfill. - * - * @param {Function} fn - * @api private - */ - -Runner.immediately = global.setImmediate || process.nextTick; - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Runner.prototype = new F; -Runner.prototype.constructor = Runner; - - -/** - * Run tests with full titles matching `re`. Updates runner.total - * with number of tests matched. - * - * @param {RegExp} re - * @param {Boolean} invert - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.grep = function(re, invert){ - debug('grep %s', re); - this._grep = re; - this._invert = invert; - this.total = this.grepTotal(this.suite); - return this; -}; - -/** - * Returns the number of tests matching the grep search for the - * given suite. - * - * @param {Suite} suite - * @return {Number} - * @api public - */ - -Runner.prototype.grepTotal = function(suite) { - var self = this; - var total = 0; - - suite.eachTest(function(test){ - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (match) total++; - }); - - return total; -}; - -/** - * Return a list of global properties. - * - * @return {Array} - * @api private - */ - -Runner.prototype.globalProps = function() { - var props = utils.keys(global); - - // non-enumerables - for (var i = 0; i < globals.length; ++i) { - if (~utils.indexOf(props, globals[i])) continue; - props.push(globals[i]); - } - - return props; -}; - -/** - * Allow the given `arr` of globals. - * - * @param {Array} arr - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.globals = function(arr){ - if (0 == arguments.length) return this._globals; - debug('globals %j', arr); - this._globals = this._globals.concat(arr); - return this; -}; - -/** - * Check for global variable leaks. - * - * @api private - */ - -Runner.prototype.checkGlobals = function(test){ - if (this.ignoreLeaks) return; - var ok = this._globals; - - var globals = this.globalProps(); - var leaks; - - if (test) { - ok = ok.concat(test._allowedGlobals || []); - } - - if(this.prevGlobalsLength == globals.length) return; - this.prevGlobalsLength = globals.length; - - leaks = filterLeaks(ok, globals); - this._globals = this._globals.concat(leaks); - - if (leaks.length > 1) { - this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); - } else if (leaks.length) { - this.fail(test, new Error('global leak detected: ' + leaks[0])); - } -}; - -/** - * Fail the given `test`. - * - * @param {Test} test - * @param {Error} err - * @api private - */ - -Runner.prototype.fail = function(test, err) { - ++this.failures; - test.state = 'failed'; - - if (!(err instanceof Error)) { - err = new Error('the ' + type(err) + ' ' + stringify(err) + ' was thrown, throw an Error :)'); - } - - err.stack = (this.fullStackTrace || !err.stack) - ? err.stack - : stackFilter(err.stack); - - this.emit('fail', test, err); -}; - -/** - * Fail the given `hook` with `err`. - * - * Hook failures work in the following pattern: - * - If bail, then exit - * - Failed `before` hook skips all tests in a suite and subsuites, - * but jumps to corresponding `after` hook - * - Failed `before each` hook skips remaining tests in a - * suite and jumps to corresponding `after each` hook, - * which is run only once - * - Failed `after` hook does not alter - * execution order - * - Failed `after each` hook skips remaining tests in a - * suite and subsuites, but executes other `after each` - * hooks - * - * @param {Hook} hook - * @param {Error} err - * @api private - */ - -Runner.prototype.failHook = function(hook, err){ - this.fail(hook, err); - if (this.suite.bail()) { - this.emit('end'); - } -}; - -/** - * Run hook `name` callbacks and then invoke `fn()`. - * - * @param {String} name - * @param {Function} function - * @api private - */ - -Runner.prototype.hook = function(name, fn){ - var suite = this.suite - , hooks = suite['_' + name] - , self = this - , timer; - - function next(i) { - var hook = hooks[i]; - if (!hook) return fn(); - self.currentRunnable = hook; - - hook.ctx.currentTest = self.test; - - self.emit('hook', hook); - - hook.on('error', function(err){ - self.failHook(hook, err); - }); - - hook.run(function(err){ - hook.removeAllListeners('error'); - var testError = hook.error(); - if (testError) self.fail(self.test, testError); - if (err) { - if (err instanceof Pending) { - suite.pending = true; - } else { - self.failHook(hook, err); - - // stop executing hooks, notify callee of hook err - return fn(err); - } - } - self.emit('hook end', hook); - delete hook.ctx.currentTest; - next(++i); - }); - } - - Runner.immediately(function(){ - next(0); - }); -}; - -/** - * Run hook `name` for the given array of `suites` - * in order, and callback `fn(err, errSuite)`. - * - * @param {String} name - * @param {Array} suites - * @param {Function} fn - * @api private - */ - -Runner.prototype.hooks = function(name, suites, fn){ - var self = this - , orig = this.suite; - - function next(suite) { - self.suite = suite; - - if (!suite) { - self.suite = orig; - return fn(); - } - - self.hook(name, function(err){ - if (err) { - var errSuite = self.suite; - self.suite = orig; - return fn(err, errSuite); - } - - next(suites.pop()); - }); - } - - next(suites.pop()); -}; - -/** - * Run hooks from the top level down. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookUp = function(name, fn){ - var suites = [this.suite].concat(this.parents()).reverse(); - this.hooks(name, suites, fn); -}; - -/** - * Run hooks from the bottom up. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookDown = function(name, fn){ - var suites = [this.suite].concat(this.parents()); - this.hooks(name, suites, fn); -}; - -/** - * Return an array of parent Suites from - * closest to furthest. - * - * @return {Array} - * @api private - */ - -Runner.prototype.parents = function(){ - var suite = this.suite - , suites = []; - while (suite = suite.parent) suites.push(suite); - return suites; -}; - -/** - * Run the current test and callback `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTest = function(fn){ - var test = this.test - , self = this; - - if (this.asyncOnly) test.asyncOnly = true; - - try { - test.on('error', function(err){ - self.fail(test, err); - }); - test.run(fn); - } catch (err) { - fn(err); - } -}; - -/** - * Run tests in the given `suite` and invoke - * the callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTests = function(suite, fn){ - var self = this - , tests = suite.tests.slice() - , test; - - - function hookErr(err, errSuite, after) { - // before/after Each hook for errSuite failed: - var orig = self.suite; - - // for failed 'after each' hook start from errSuite parent, - // otherwise start from errSuite itself - self.suite = after ? errSuite.parent : errSuite; - - if (self.suite) { - // call hookUp afterEach - self.hookUp('afterEach', function(err2, errSuite2) { - self.suite = orig; - // some hooks may fail even now - if (err2) return hookErr(err2, errSuite2, true); - // report error suite - fn(errSuite); - }); - } else { - // there is no need calling other 'after each' hooks - self.suite = orig; - fn(errSuite); - } - } - - function next(err, errSuite) { - // if we bail after first err - if (self.failures && suite._bail) return fn(); - - if (self._abort) return fn(); - - if (err) return hookErr(err, errSuite, true); - - // next test - test = tests.shift(); - - // all done - if (!test) return fn(); - - // grep - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (!match) return next(); - - // pending - if (test.pending) { - self.emit('pending', test); - self.emit('test end', test); - return next(); - } - - // execute test and hook(s) - self.emit('test', self.test = test); - self.hookDown('beforeEach', function(err, errSuite){ - - if (suite.pending) { - self.emit('pending', test); - self.emit('test end', test); - return next(); - } - if (err) return hookErr(err, errSuite, false); - - self.currentRunnable = self.test; - self.runTest(function(err){ - test = self.test; - - if (err) { - if (err instanceof Pending) { - self.emit('pending', test); - } else { - self.fail(test, err); - } - self.emit('test end', test); - - if (err instanceof Pending) { - return next(); - } - - return self.hookUp('afterEach', next); - } - - test.state = 'passed'; - self.emit('pass', test); - self.emit('test end', test); - self.hookUp('afterEach', next); - }); - }); - } - - this.next = next; - next(); -}; - -/** - * Run the given `suite` and invoke the - * callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runSuite = function(suite, fn){ - var total = this.grepTotal(suite) - , self = this - , i = 0; - - debug('run suite %s', suite.fullTitle()); - - if (!total) return fn(); - - this.emit('suite', this.suite = suite); - - function next(errSuite) { - if (errSuite) { - // current suite failed on a hook from errSuite - if (errSuite == suite) { - // if errSuite is current suite - // continue to the next sibling suite - return done(); - } else { - // errSuite is among the parents of current suite - // stop execution of errSuite and all sub-suites - return done(errSuite); - } - } - - if (self._abort) return done(); - - var curr = suite.suites[i++]; - if (!curr) return done(); - self.runSuite(curr, next); - } - - function done(errSuite) { - self.suite = suite; - self.hook('afterAll', function(){ - self.emit('suite end', suite); - fn(errSuite); - }); - } - - this.hook('beforeAll', function(err){ - if (err) return done(); - self.runTests(suite, next); - }); -}; - -/** - * Handle uncaught exceptions. - * - * @param {Error} err - * @api private - */ - -Runner.prototype.uncaught = function(err){ - if (err) { - debug('uncaught exception %s', err !== function () { - return this; - }.call(err) ? err : ( err.message || err )); - } else { - debug('uncaught undefined exception'); - err = utils.undefinedError(); - } - err.uncaught = true; - - var runnable = this.currentRunnable; - if (!runnable) return; - - runnable.clearTimeout(); - - // Ignore errors if complete - if (runnable.state) return; - this.fail(runnable, err); - - // recover from test - if ('test' == runnable.type) { - this.emit('test end', runnable); - this.hookUp('afterEach', this.next); - return; - } - - // bail on hooks - this.emit('end'); -}; - -/** - * Run the root suite and invoke `fn(failures)` - * on completion. - * - * @param {Function} fn - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.run = function(fn){ - var self = this, - rootSuite = this.suite; - - fn = fn || function(){}; - - function uncaught(err){ - self.uncaught(err); - } - - function start() { - self.emit('start'); - self.runSuite(rootSuite, function(){ - debug('finished running'); - self.emit('end'); - }); - } - - debug('start'); - - // callback - this.on('end', function(){ - debug('end'); - process.removeListener('uncaughtException', uncaught); - fn(self.failures); - }); - - // uncaught exception - process.on('uncaughtException', uncaught); - - if (this._delay) { - // for reporters, I guess. - // might be nice to debounce some dots while we wait. - this.emit('waiting', rootSuite); - rootSuite.once('run', start); - } - else { - start(); - } - - return this; -}; - -/** - * Cleanly abort execution - * - * @return {Runner} for chaining - * @api public - */ -Runner.prototype.abort = function(){ - debug('aborting'); - this._abort = true; -}; - -/** - * Filter leaks with the given globals flagged as `ok`. - * - * @param {Array} ok - * @param {Array} globals - * @return {Array} - * @api private - */ - -function filterLeaks(ok, globals) { - return filter(globals, function(key){ - // Firefox and Chrome exposes iframes as index inside the window object - if (/^d+/.test(key)) return false; - - // in firefox - // if runner runs in an iframe, this iframe's window.getInterface method not init at first - // it is assigned in some seconds - if (global.navigator && /^getInterface/.test(key)) return false; - - // an iframe could be approached by window[iframeIndex] - // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak - if (global.navigator && /^\d+/.test(key)) return false; - - // Opera and IE expose global variables for HTML element IDs (issue #243) - if (/^mocha-/.test(key)) return false; - - var matched = filter(ok, function(ok){ - if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); - return key == ok; - }); - return matched.length == 0 && (!global.navigator || 'onerror' !== key); - }); -} - -/** - * Array of globals dependent on the environment. - * - * @return {Array} - * @api private - */ - -function extraGlobals() { - if (typeof(process) === 'object' && - typeof(process.version) === 'string') { - - var nodeVersion = process.version.split('.').reduce(function(a, v) { - return a << 8 | v; - }); - - // 'errno' was renamed to process._errno in v0.9.11. - - if (nodeVersion < 0x00090B) { - return ['errno']; - } - } - - return []; -} - -}); // module: runner.js - -require.register("suite.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:suite') - , milliseconds = require('./ms') - , utils = require('./utils') - , Hook = require('./hook'); - -/** - * Expose `Suite`. - */ - -exports = module.exports = Suite; - -/** - * Create a new `Suite` with the given `title` - * and parent `Suite`. When a suite with the - * same title is already present, that suite - * is returned to provide nicer reporter - * and more flexible meta-testing. - * - * @param {Suite} parent - * @param {String} title - * @return {Suite} - * @api public - */ - -exports.create = function(parent, title){ - var suite = new Suite(title, parent.ctx); - suite.parent = parent; - if (parent.pending) suite.pending = true; - title = suite.fullTitle(); - parent.addSuite(suite); - return suite; -}; - -/** - * Initialize a new `Suite` with the given - * `title` and `ctx`. - * - * @param {String} title - * @param {Context} ctx - * @api private - */ - -function Suite(title, parentContext) { - this.title = title; - var context = function() {}; - context.prototype = parentContext; - this.ctx = new context(); - this.suites = []; - this.tests = []; - this.pending = false; - this._beforeEach = []; - this._beforeAll = []; - this._afterEach = []; - this._afterAll = []; - this.root = !title; - this._timeout = 2000; - this._enableTimeouts = true; - this._slow = 75; - this._bail = false; - this.delayed = false; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Suite.prototype = new F; -Suite.prototype.constructor = Suite; - - -/** - * Return a clone of this `Suite`. - * - * @return {Suite} - * @api private - */ - -Suite.prototype.clone = function(){ - var suite = new Suite(this.title); - debug('clone'); - suite.ctx = this.ctx; - suite.timeout(this.timeout()); - suite.enableTimeouts(this.enableTimeouts()); - suite.slow(this.slow()); - suite.bail(this.bail()); - return suite; -}; - -/** - * Set timeout `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if (ms.toString() === '0') this._enableTimeouts = false; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = parseInt(ms, 10); - return this; -}; - -/** - * Set timeout `enabled`. - * - * @param {Boolean} enabled - * @return {Suite|Boolean} self or enabled - * @api private - */ - -Suite.prototype.enableTimeouts = function(enabled){ - if (arguments.length === 0) return this._enableTimeouts; - debug('enableTimeouts %s', enabled); - this._enableTimeouts = enabled; - return this; -}; - -/** - * Set slow `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('slow %d', ms); - this._slow = ms; - return this; -}; - -/** - * Sets whether to bail after first error. - * - * @param {Boolean} bail - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.bail = function(bail){ - if (0 == arguments.length) return this._bail; - debug('bail %s', bail); - this._bail = bail; - return this; -}; - -/** - * Run `fn(test[, done])` before running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeAll = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"before all" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeAll.push(hook); - this.emit('beforeAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterAll = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"after all" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterAll.push(hook); - this.emit('afterAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` before each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeEach = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"before each" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeEach.push(hook); - this.emit('beforeEach', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterEach = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"after each" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterEach.push(hook); - this.emit('afterEach', hook); - return this; -}; - -/** - * Add a test `suite`. - * - * @param {Suite} suite - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addSuite = function(suite){ - suite.parent = this; - suite.timeout(this.timeout()); - suite.enableTimeouts(this.enableTimeouts()); - suite.slow(this.slow()); - suite.bail(this.bail()); - this.suites.push(suite); - this.emit('suite', suite); - return this; -}; - -/** - * Add a `test` to this suite. - * - * @param {Test} test - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addTest = function(test){ - test.parent = this; - test.timeout(this.timeout()); - test.enableTimeouts(this.enableTimeouts()); - test.slow(this.slow()); - test.ctx = this.ctx; - this.tests.push(test); - this.emit('test', test); - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Suite.prototype.fullTitle = function(){ - if (this.parent) { - var full = this.parent.fullTitle(); - if (full) return full + ' ' + this.title; - } - return this.title; -}; - -/** - * Return the total number of tests. - * - * @return {Number} - * @api public - */ - -Suite.prototype.total = function(){ - return utils.reduce(this.suites, function(sum, suite){ - return sum + suite.total(); - }, 0) + this.tests.length; -}; - -/** - * Iterates through each suite recursively to find - * all tests. Applies a function in the format - * `fn(test)`. - * - * @param {Function} fn - * @return {Suite} - * @api private - */ - -Suite.prototype.eachTest = function(fn){ - utils.forEach(this.tests, fn); - utils.forEach(this.suites, function(suite){ - suite.eachTest(fn); - }); - return this; -}; - -/** - * This will run the root suite if we happen to be running in delayed mode. - */ -Suite.prototype.run = function run() { - if (this.root) { - this.emit('run'); - } -}; - -}); // module: suite.js - -require.register("test.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Test`. - */ - -module.exports = Test; - -/** - * Initialize a new `Test` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Test(title, fn) { - Runnable.call(this, title, fn); - this.pending = !fn; - this.type = 'test'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -function F(){}; -F.prototype = Runnable.prototype; -Test.prototype = new F; -Test.prototype.constructor = Test; - - -}); // module: test.js - -require.register("utils.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var fs = require('browser/fs') - , path = require('browser/path') - , basename = path.basename - , exists = fs.existsSync || path.existsSync - , glob = require('browser/glob') - , join = path.join - , debug = require('browser/debug')('mocha:watch'); - -/** - * Ignored directories. - */ - -var ignore = ['node_modules', '.git']; - -/** - * Escape special characters in the given string of html. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -}; - -/** - * Array#forEach (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} scope - * @api private - */ - -exports.forEach = function(arr, fn, scope){ - for (var i = 0, l = arr.length; i < l; i++) - fn.call(scope, arr[i], i); -}; - -/** - * Array#map (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} scope - * @api private - */ - -exports.map = function(arr, fn, scope){ - var result = []; - for (var i = 0, l = arr.length; i < l; i++) - result.push(fn.call(scope, arr[i], i, arr)); - return result; -}; - -/** - * Array#indexOf (<=IE8) - * - * @parma {Array} arr - * @param {Object} obj to find index of - * @param {Number} start - * @api private - */ - -exports.indexOf = function(arr, obj, start){ - for (var i = start || 0, l = arr.length; i < l; i++) { - if (arr[i] === obj) - return i; - } - return -1; -}; - -/** - * Array#reduce (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} initial value - * @api private - */ - -exports.reduce = function(arr, fn, val){ - var rval = val; - - for (var i = 0, l = arr.length; i < l; i++) { - rval = fn(rval, arr[i], i, arr); - } - - return rval; -}; - -/** - * Array#filter (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @api private - */ - -exports.filter = function(arr, fn){ - var ret = []; - - for (var i = 0, l = arr.length; i < l; i++) { - var val = arr[i]; - if (fn(val, i, arr)) ret.push(val); - } - - return ret; -}; - -/** - * Object.keys (<=IE8) - * - * @param {Object} obj - * @return {Array} keys - * @api private - */ - -exports.keys = Object.keys || function(obj) { - var keys = [] - , has = Object.prototype.hasOwnProperty; // for `window` on <=IE8 - - for (var key in obj) { - if (has.call(obj, key)) { - keys.push(key); - } - } - - return keys; -}; - -/** - * Watch the given `files` for changes - * and invoke `fn(file)` on modification. - * - * @param {Array} files - * @param {Function} fn - * @api private - */ - -exports.watch = function(files, fn){ - var options = { interval: 100 }; - files.forEach(function(file){ - debug('file %s', file); - fs.watchFile(file, options, function(curr, prev){ - if (prev.mtime < curr.mtime) fn(file); - }); - }); -}; - -/** - * Array.isArray (<=IE8) - * - * @param {Object} obj - * @return {Boolean} - * @api private - */ -var isArray = Array.isArray || function (obj) { - return '[object Array]' == {}.toString.call(obj); -}; - -/** - * @description - * Buffer.prototype.toJSON polyfill - * @type {Function} - */ -if(typeof Buffer !== 'undefined' && Buffer.prototype) { - Buffer.prototype.toJSON = Buffer.prototype.toJSON || function () { - return Array.prototype.slice.call(this, 0); - }; -} - -/** - * Ignored files. - */ - -function ignored(path){ - return !~ignore.indexOf(path); -} - -/** - * Lookup files in the given `dir`. - * - * @return {Array} - * @api private - */ - -exports.files = function(dir, ext, ret){ - ret = ret || []; - ext = ext || ['js']; - - var re = new RegExp('\\.(' + ext.join('|') + ')$'); - - fs.readdirSync(dir) - .filter(ignored) - .forEach(function(path){ - path = join(dir, path); - if (fs.statSync(path).isDirectory()) { - exports.files(path, ext, ret); - } else if (path.match(re)) { - ret.push(path); - } - }); - - return ret; -}; - -/** - * Compute a slug from the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.slug = function(str){ - return str - .toLowerCase() - .replace(/ +/g, '-') - .replace(/[^-\w]/g, ''); -}; - -/** - * Strip the function definition from `str`, - * and re-indent for pre whitespace. - */ - -exports.clean = function(str) { - str = str - .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '') - .replace(/^function *\(.*\)\s*{|\(.*\) *=> *{?/, '') - .replace(/\s+\}$/, ''); - - var spaces = str.match(/^\n?( *)/)[1].length - , tabs = str.match(/^\n?(\t*)/)[1].length - , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm'); - - str = str.replace(re, ''); - - return exports.trim(str); -}; - -/** - * Trim the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.trim = function(str){ - return str.replace(/^\s+|\s+$/g, ''); -}; - -/** - * Parse the given `qs`. - * - * @param {String} qs - * @return {Object} - * @api private - */ - -exports.parseQuery = function(qs){ - return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ - var i = pair.indexOf('=') - , key = pair.slice(0, i) - , val = pair.slice(++i); - - obj[key] = decodeURIComponent(val); - return obj; - }, {}); -}; - -/** - * Highlight the given string of `js`. - * - * @param {String} js - * @return {String} - * @api private - */ - -function highlight(js) { - return js - .replace(//g, '>') - .replace(/\/\/(.*)/gm, '//$1') - .replace(/('.*?')/gm, '$1') - .replace(/(\d+\.\d+)/gm, '$1') - .replace(/(\d+)/gm, '$1') - .replace(/\bnew[ \t]+(\w+)/gm, 'new $1') - .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') -} - -/** - * Highlight the contents of tag `name`. - * - * @param {String} name - * @api private - */ - -exports.highlightTags = function(name) { - var code = document.getElementById('mocha').getElementsByTagName(name); - for (var i = 0, len = code.length; i < len; ++i) { - code[i].innerHTML = highlight(code[i].innerHTML); - } -}; - -/** - * If a value could have properties, and has none, this function is called, which returns - * a string representation of the empty value. - * - * Functions w/ no properties return `'[Function]'` - * Arrays w/ length === 0 return `'[]'` - * Objects w/ no properties return `'{}'` - * All else: return result of `value.toString()` - * - * @param {*} value Value to inspect - * @param {string} [type] The type of the value, if known. - * @returns {string} - */ -var emptyRepresentation = function emptyRepresentation(value, type) { - type = type || exports.type(value); - - switch(type) { - case 'function': - return '[Function]'; - case 'object': - return '{}'; - case 'array': - return '[]'; - default: - return value.toString(); - } -}; - -/** - * Takes some variable and asks `{}.toString()` what it thinks it is. - * @param {*} value Anything - * @example - * type({}) // 'object' - * type([]) // 'array' - * type(1) // 'number' - * type(false) // 'boolean' - * type(Infinity) // 'number' - * type(null) // 'null' - * type(new Date()) // 'date' - * type(/foo/) // 'regexp' - * type('type') // 'string' - * type(global) // 'global' - * @api private - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString - * @returns {string} - */ -exports.type = function type(value) { - if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return 'buffer'; - } - return Object.prototype.toString.call(value) - .replace(/^\[.+\s(.+?)\]$/, '$1') - .toLowerCase(); -}; - -/** - * @summary Stringify `value`. - * @description Different behavior depending on type of value. - * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively. - * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes. - * - If `value` is an *empty* object, function, or array, return result of function - * {@link emptyRepresentation}. - * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of - * JSON.stringify(). - * - * @see exports.type - * @param {*} value - * @return {string} - * @api private - */ - -exports.stringify = function(value) { - var type = exports.type(value); - - if (!~exports.indexOf(['object', 'array', 'function'], type)) { - if(type != 'buffer') { - return jsonStringify(value); - } - var json = value.toJSON(); - // Based on the toJSON result - return jsonStringify(json.data && json.type ? json.data : json, 2) - .replace(/,(\n|$)/g, '$1'); - } - - for (var prop in value) { - if (Object.prototype.hasOwnProperty.call(value, prop)) { - return jsonStringify(exports.canonicalize(value), 2).replace(/,(\n|$)/g, '$1'); - } - } - - return emptyRepresentation(value, type); -}; - -/** - * @description - * like JSON.stringify but more sense. - * @param {Object} object - * @param {Number=} spaces - * @param {number=} depth - * @returns {*} - * @private - */ -function jsonStringify(object, spaces, depth) { - if(typeof spaces == 'undefined') return _stringify(object); // primitive types - - depth = depth || 1; - var space = spaces * depth - , str = isArray(object) ? '[' : '{' - , end = isArray(object) ? ']' : '}' - , length = object.length || exports.keys(object).length - , repeat = function(s, n) { return new Array(n).join(s); }; // `.repeat()` polyfill - - function _stringify(val) { - switch (exports.type(val)) { - case 'null': - case 'undefined': - val = '[' + val + ']'; - break; - case 'array': - case 'object': - val = jsonStringify(val, spaces, depth + 1); - break; - case 'boolean': - case 'regexp': - case 'number': - val = val === 0 && (1/val) === -Infinity // `-0` - ? '-0' - : val.toString(); - break; - case 'date': - val = '[Date: ' + val.toISOString() + ']'; - break; - case 'buffer': - var json = val.toJSON(); - // Based on the toJSON result - json = json.data && json.type ? json.data : json; - val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']'; - break; - default: - val = (val == '[Function]' || val == '[Circular]') - ? val - : '"' + val + '"'; //string - } - return val; - } - - for(var i in object) { - if(!object.hasOwnProperty(i)) continue; // not my business - --length; - str += '\n ' + repeat(' ', space) - + (isArray(object) ? '' : '"' + i + '": ') // key - + _stringify(object[i]) // value - + (length ? ',' : ''); // comma - } - - return str + (str.length != 1 // [], {} - ? '\n' + repeat(' ', --space) + end - : end); -} - -/** - * Return if obj is a Buffer - * @param {Object} arg - * @return {Boolean} - * @api private - */ -exports.isBuffer = function (arg) { - return typeof Buffer !== 'undefined' && Buffer.isBuffer(arg); -}; - -/** - * @summary Return a new Thing that has the keys in sorted order. Recursive. - * @description If the Thing... - * - has already been seen, return string `'[Circular]'` - * - is `undefined`, return string `'[undefined]'` - * - is `null`, return value `null` - * - is some other primitive, return the value - * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method - * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again. - * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()` - * - * @param {*} value Thing to inspect. May or may not have properties. - * @param {Array} [stack=[]] Stack of seen values - * @return {(Object|Array|Function|string|undefined)} - * @see {@link exports.stringify} - * @api private - */ - -exports.canonicalize = function(value, stack) { - var canonicalizedObj, - type = exports.type(value), - prop, - withStack = function withStack(value, fn) { - stack.push(value); - fn(); - stack.pop(); - }; - - stack = stack || []; - - if (exports.indexOf(stack, value) !== -1) { - return '[Circular]'; - } - - switch(type) { - case 'undefined': - case 'buffer': - case 'null': - canonicalizedObj = value; - break; - case 'array': - withStack(value, function () { - canonicalizedObj = exports.map(value, function (item) { - return exports.canonicalize(item, stack); - }); - }); - break; - case 'function': - for (prop in value) { - canonicalizedObj = {}; - break; - } - if (!canonicalizedObj) { - canonicalizedObj = emptyRepresentation(value, type); - break; - } - /* falls through */ - case 'object': - canonicalizedObj = canonicalizedObj || {}; - withStack(value, function () { - exports.forEach(exports.keys(value).sort(), function (key) { - canonicalizedObj[key] = exports.canonicalize(value[key], stack); - }); - }); - break; - case 'date': - case 'number': - case 'regexp': - case 'boolean': - canonicalizedObj = value; - break; - default: - canonicalizedObj = value.toString(); - } - - return canonicalizedObj; -}; - -/** - * Lookup file names at the given `path`. - */ -exports.lookupFiles = function lookupFiles(path, extensions, recursive) { - var files = []; - var re = new RegExp('\\.(' + extensions.join('|') + ')$'); - - if (!exists(path)) { - if (exists(path + '.js')) { - path += '.js'; - } else { - files = glob.sync(path); - if (!files.length) throw new Error("cannot resolve path (or pattern) '" + path + "'"); - return files; - } - } - - try { - var stat = fs.statSync(path); - if (stat.isFile()) return path; - } - catch (ignored) { - return; - } - - fs.readdirSync(path).forEach(function(file) { - file = join(path, file); - try { - var stat = fs.statSync(file); - if (stat.isDirectory()) { - if (recursive) { - files = files.concat(lookupFiles(file, extensions, recursive)); - } - return; - } - } - catch (ignored) { - return; - } - if (!stat.isFile() || !re.test(file) || basename(file)[0] === '.') return; - files.push(file); - }); - - return files; -}; - -/** - * Generate an undefined error with a message warning the user. - * - * @return {Error} - */ - -exports.undefinedError = function() { - return new Error('Caught undefined error, did you throw without specifying what?'); -}; - -/** - * Generate an undefined error if `err` is not defined. - * - * @param {Error} err - * @return {Error} - */ - -exports.getError = function(err) { - return err || exports.undefinedError(); -}; - - -/** - * @summary - * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`) - * @description - * When invoking this function you get a filter function that get the Error.stack as an input, - * and return a prettify output. - * (i.e: strip Mocha, node_modules, bower and componentJS from stack trace). - * @returns {Function} - */ - -exports.stackTraceFilter = function() { - var slash = '/' - , is = typeof document === 'undefined' - ? { node: true } - : { browser: true } - , cwd = is.node - ? process.cwd() + slash - : location.href.replace(/\/[^\/]*$/, '/'); - - function isNodeModule (line) { - return (~line.indexOf('node_modules')); - } - - function isMochaInternal (line) { - return (~line.indexOf('node_modules' + slash + 'mocha')) || - (~line.indexOf('components' + slash + 'mochajs')) || - (~line.indexOf('components' + slash + 'mocha')); - } - - // node_modules, bower, componentJS - function isBrowserModule(line) { - return (~line.indexOf('node_modules')) || - (~line.indexOf('components')); - } - - function isNodeInternal (line) { - return (~line.indexOf('(timers.js:')) || - (~line.indexOf('(events.js:')) || - (~line.indexOf('(node.js:')) || - (~line.indexOf('(module.js:')) || - (~line.indexOf('GeneratorFunctionPrototype.next (native)')) || - false - } - - return function(stack) { - stack = stack.split('\n'); - - stack = exports.reduce(stack, function(list, line) { - if (is.node && (isNodeModule(line) || - isMochaInternal(line) || - isNodeInternal(line))) - return list; - - if (is.browser && (isBrowserModule(line))) - return list; - - // Clean up cwd(absolute) - list.push(line.replace(cwd, '')); - return list; - }, []); - - return stack.join('\n'); - } -}; -}); // module: utils.js -// The global object is "self" in Web Workers. -var global = (function() { return this; })(); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date; -var setTimeout = global.setTimeout; -var setInterval = global.setInterval; -var clearTimeout = global.clearTimeout; -var clearInterval = global.clearInterval; - -/** - * Node shims. - * - * These are meant only to allow - * mocha.js to run untouched, not - * to allow running node code in - * the browser. - */ - -var process = {}; -process.exit = function(status){}; -process.stdout = {}; - -var uncaughtExceptionHandlers = []; - -var originalOnerrorHandler = global.onerror; - -/** - * Remove uncaughtException listener. - * Revert to original onerror handler if previously defined. - */ - -process.removeListener = function(e, fn){ - if ('uncaughtException' == e) { - if (originalOnerrorHandler) { - global.onerror = originalOnerrorHandler; - } else { - global.onerror = function() {}; - } - var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn); - if (i != -1) { uncaughtExceptionHandlers.splice(i, 1); } - } -}; - -/** - * Implements uncaughtException listener. - */ - -process.on = function(e, fn){ - if ('uncaughtException' == e) { - global.onerror = function(err, url, line){ - fn(new Error(err + ' (' + url + ':' + line + ')')); - return true; - }; - uncaughtExceptionHandlers.push(fn); - } -}; - -/** - * Expose mocha. - */ - -var Mocha = global.Mocha = require('mocha'), - mocha = global.mocha = new Mocha({ reporter: 'html' }); - -// The BDD UI is registered by default, but no UI will be functional in the -// browser without an explicit call to the overridden `mocha.ui` (see below). -// Ensure that this default UI does not expose its methods to the global scope. -mocha.suite.removeAllListeners('pre-require'); - -var immediateQueue = [] - , immediateTimeout; - -function timeslice() { - var immediateStart = new Date().getTime(); - while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) { - immediateQueue.shift()(); - } - if (immediateQueue.length) { - immediateTimeout = setTimeout(timeslice, 0); - } else { - immediateTimeout = null; - } -} - -/** - * High-performance override of Runner.immediately. - */ - -Mocha.Runner.immediately = function(callback) { - immediateQueue.push(callback); - if (!immediateTimeout) { - immediateTimeout = setTimeout(timeslice, 0); - } -}; - -/** - * Function to allow assertion libraries to throw errors directly into mocha. - * This is useful when running tests in a browser because window.onerror will - * only receive the 'message' attribute of the Error. - */ -mocha.throwError = function(err) { - Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) { - fn(err); - }); - throw err; -}; - -/** - * Override ui to ensure that the ui functions are initialized. - * Normally this would happen in Mocha.prototype.loadFiles. - */ - -mocha.ui = function(ui){ - Mocha.prototype.ui.call(this, ui); - this.suite.emit('pre-require', global, null, this); - return this; -}; - -/** - * Setup mocha with the given setting options. - */ - -mocha.setup = function(opts){ - if ('string' == typeof opts) opts = { ui: opts }; - for (var opt in opts) this[opt](opts[opt]); - return this; -}; - -/** - * Run mocha, returning the Runner. - */ - -mocha.run = function(fn){ - var options = mocha.options; - mocha.globals('location'); - - var query = Mocha.utils.parseQuery(global.location.search || ''); - if (query.grep) mocha.grep(new RegExp(query.grep)); - if (query.fgrep) mocha.grep(query.fgrep); - if (query.invert) mocha.invert(); - - return Mocha.prototype.run.call(mocha, function(err){ - // The DOM Document is not available in Web Workers. - var document = global.document; - if (document && document.getElementById('mocha') && options.noHighlighting !== true) { - Mocha.utils.highlightTags('code'); - } - if (fn) fn(err); - }); -}; - -/** - * Expose the process shim. - */ - -Mocha.process = process; -})(); diff --git a/node_modules/mocha/node_modules/.bin/jade b/node_modules/mocha/node_modules/.bin/jade deleted file mode 120000 index 571fae7..0000000 --- a/node_modules/mocha/node_modules/.bin/jade +++ /dev/null @@ -1 +0,0 @@ -../jade/bin/jade \ No newline at end of file diff --git a/node_modules/mocha/node_modules/.bin/mkdirp b/node_modules/mocha/node_modules/.bin/mkdirp deleted file mode 120000 index 017896c..0000000 --- a/node_modules/mocha/node_modules/.bin/mkdirp +++ /dev/null @@ -1 +0,0 @@ -../mkdirp/bin/cmd.js \ No newline at end of file diff --git a/node_modules/mocha/node_modules/.bin/supports-color b/node_modules/mocha/node_modules/.bin/supports-color deleted file mode 120000 index af0f05e..0000000 --- a/node_modules/mocha/node_modules/.bin/supports-color +++ /dev/null @@ -1 +0,0 @@ -../supports-color/cli.js \ No newline at end of file diff --git a/node_modules/mocha/node_modules/commander/Readme.md b/node_modules/mocha/node_modules/commander/Readme.md deleted file mode 100644 index 7bb60b2..0000000 --- a/node_modules/mocha/node_modules/commander/Readme.md +++ /dev/null @@ -1,208 +0,0 @@ -# Commander.js - - The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander). - - [![Build Status](https://api.travis-ci.org/visionmedia/commander.js.svg)](http://travis-ci.org/visionmedia/commander.js) - -## Installation - - $ npm install commander - -## Option parsing - - Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('commander'); - -program - .version('0.0.1') - .option('-p, --peppers', 'Add peppers') - .option('-P, --pineapple', 'Add pineapple') - .option('-b, --bbq', 'Add bbq sauce') - .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') - .parse(process.argv); - -console.log('you ordered a pizza with:'); -if (program.peppers) console.log(' - peppers'); -if (program.pineapple) console.log(' - pineapple'); -if (program.bbq) console.log(' - bbq'); -console.log(' - %s cheese', program.cheese); -``` - - Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. - -## Automated --help - - The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: - -``` - $ ./examples/pizza --help - - Usage: pizza [options] - - Options: - - -V, --version output the version number - -p, --peppers Add peppers - -P, --pineapple Add pineapple - -b, --bbq Add bbq sauce - -c, --cheese Add the specified type of cheese [marble] - -h, --help output usage information - -``` - -## Coercion - -```js -function range(val) { - return val.split('..').map(Number); -} - -function list(val) { - return val.split(','); -} - -function collect(val, memo) { - memo.push(val); - return memo; -} - -function increaseVerbosity(v, total) { - return total + 1; -} - -program - .version('0.0.1') - .usage('[options] ') - .option('-i, --integer ', 'An integer argument', parseInt) - .option('-f, --float ', 'A float argument', parseFloat) - .option('-r, --range ..', 'A range', range) - .option('-l, --list ', 'A list', list) - .option('-o, --optional [value]', 'An optional value') - .option('-c, --collect [value]', 'A repeatable value', collect, []) - .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0) - .parse(process.argv); - -console.log(' int: %j', program.integer); -console.log(' float: %j', program.float); -console.log(' optional: %j', program.optional); -program.range = program.range || []; -console.log(' range: %j..%j', program.range[0], program.range[1]); -console.log(' list: %j', program.list); -console.log(' collect: %j', program.collect); -console.log(' verbosity: %j', program.verbose); -console.log(' args: %j', program.args); -``` - -## Custom help - - You can display arbitrary `-h, --help` information - by listening for "--help". Commander will automatically - exit once you are done so that the remainder of your program - does not execute causing undesired behaviours, for example - in the following executable "stuff" will not output when - `--help` is used. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('../'); - -function list(val) { - return val.split(',').map(Number); -} - -program - .version('0.0.1') - .option('-f, --foo', 'enable some foo') - .option('-b, --bar', 'enable some bar') - .option('-B, --baz', 'enable some baz'); - -// must be before .parse() since -// node's emit() is immediate - -program.on('--help', function(){ - console.log(' Examples:'); - console.log(''); - console.log(' $ custom-help --help'); - console.log(' $ custom-help -h'); - console.log(''); -}); - -program.parse(process.argv); - -console.log('stuff'); -``` - -yielding the following help output: - -``` - -Usage: custom-help [options] - -Options: - - -h, --help output usage information - -V, --version output the version number - -f, --foo enable some foo - -b, --bar enable some bar - -B, --baz enable some baz - -Examples: - - $ custom-help --help - $ custom-help -h - -``` - -## .outputHelp() - - Output help information without exiting. - -## .help() - - Output help information and exit immediately. - -## Links - - - [API documentation](http://visionmedia.github.com/commander.js/) - - [ascii tables](https://github.com/LearnBoost/cli-table) - - [progress bars](https://github.com/visionmedia/node-progress) - - [more progress bars](https://github.com/substack/node-multimeter) - - [examples](https://github.com/visionmedia/commander.js/tree/master/examples) - -## License - -(The MIT License) - -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> - -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/node_modules/mocha/node_modules/commander/index.js b/node_modules/mocha/node_modules/commander/index.js deleted file mode 100644 index 8378d19..0000000 --- a/node_modules/mocha/node_modules/commander/index.js +++ /dev/null @@ -1,876 +0,0 @@ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter; -var spawn = require('child_process').spawn; -var path = require('path'); -var dirname = path.dirname; -var basename = path.basename; - -/** - * Expose the root command. - */ - -exports = module.exports = new Command; - -/** - * Expose `Command`. - */ - -exports.Command = Command; - -/** - * Expose `Option`. - */ - -exports.Option = Option; - -/** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {String} flags - * @param {String} description - * @api public - */ - -function Option(flags, description) { - this.flags = flags; - this.required = ~flags.indexOf('<'); - this.optional = ~flags.indexOf('['); - this.bool = !~flags.indexOf('-no-'); - flags = flags.split(/[ ,|]+/); - if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); - this.long = flags.shift(); - this.description = description || ''; -} - -/** - * Return option name. - * - * @return {String} - * @api private - */ - -Option.prototype.name = function(){ - return this.long - .replace('--', '') - .replace('no-', ''); -}; - -/** - * Check if `arg` matches the short or long flag. - * - * @param {String} arg - * @return {Boolean} - * @api private - */ - -Option.prototype.is = function(arg){ - return arg == this.short - || arg == this.long; -}; - -/** - * Initialize a new `Command`. - * - * @param {String} name - * @api public - */ - -function Command(name) { - this.commands = []; - this.options = []; - this._execs = []; - this._args = []; - this._name = name; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Command.prototype.__proto__ = EventEmitter.prototype; - -/** - * Add command `name`. - * - * The `.action()` callback is invoked when the - * command `name` is specified via __ARGV__, - * and the remaining arguments are applied to the - * function for access. - * - * When the `name` is "*" an un-matched command - * will be passed as the first arg, followed by - * the rest of __ARGV__ remaining. - * - * Examples: - * - * program - * .version('0.0.1') - * .option('-C, --chdir ', 'change the working directory') - * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') - * .option('-T, --no-tests', 'ignore test hook') - * - * program - * .command('setup') - * .description('run remote setup commands') - * .action(function(){ - * console.log('setup'); - * }); - * - * program - * .command('exec ') - * .description('run the given remote command') - * .action(function(cmd){ - * console.log('exec "%s"', cmd); - * }); - * - * program - * .command('*') - * .description('deploy the given env') - * .action(function(env){ - * console.log('deploying "%s"', env); - * }); - * - * program.parse(process.argv); - * - * @param {String} name - * @param {String} [desc] - * @return {Command} the new command - * @api public - */ - -Command.prototype.command = function(name, desc) { - var args = name.split(/ +/); - var cmd = new Command(args.shift()); - if (desc) cmd.description(desc); - if (desc) this.executables = true; - if (desc) this._execs[cmd._name] = true; - this.commands.push(cmd); - cmd.parseExpectedArgs(args); - cmd.parent = this; - if (desc) return this; - return cmd; -}; - -/** - * Add an implicit `help [cmd]` subcommand - * which invokes `--help` for the given command. - * - * @api private - */ - -Command.prototype.addImplicitHelpCommand = function() { - this.command('help [cmd]', 'display help for [cmd]'); -}; - -/** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {Array} args - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parseExpectedArgs = function(args){ - if (!args.length) return; - var self = this; - args.forEach(function(arg){ - switch (arg[0]) { - case '<': - self._args.push({ required: true, name: arg.slice(1, -1) }); - break; - case '[': - self._args.push({ required: false, name: arg.slice(1, -1) }); - break; - } - }); - return this; -}; - -/** - * Register callback `fn` for the command. - * - * Examples: - * - * program - * .command('help') - * .description('display verbose help') - * .action(function(){ - * // output help here - * }); - * - * @param {Function} fn - * @return {Command} for chaining - * @api public - */ - -Command.prototype.action = function(fn){ - var self = this; - var listener = function(args, unknown){ - // Parse any so-far unknown options - args = args || []; - unknown = unknown || []; - - var parsed = self.parseOptions(unknown); - - // Output help if necessary - outputHelpIfNecessary(self, parsed.unknown); - - // If there are still any unknown options, then we simply - // die, unless someone asked for help, in which case we give it - // to them, and then we die. - if (parsed.unknown.length > 0) { - self.unknownOption(parsed.unknown[0]); - } - - // Leftover arguments need to be pushed back. Fixes issue #56 - if (parsed.args.length) args = parsed.args.concat(args); - - self._args.forEach(function(arg, i){ - if (arg.required && null == args[i]) { - self.missingArgument(arg.name); - } - }); - - // Always append ourselves to the end of the arguments, - // to make sure we match the number of arguments the user - // expects - if (self._args.length) { - args[self._args.length] = self; - } else { - args.push(self); - } - - fn.apply(this, args); - }; - this.parent.on(this._name, listener); - if (this._alias) this.parent.on(this._alias, listener); - return this; -}; - -/** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * Examples: - * - * // simple boolean defaulting to false - * program.option('-p, --pepper', 'add pepper'); - * - * --pepper - * program.pepper - * // => Boolean - * - * // simple boolean defaulting to true - * program.option('-C, --no-cheese', 'remove cheese'); - * - * program.cheese - * // => true - * - * --no-cheese - * program.cheese - * // => false - * - * // required argument - * program.option('-C, --chdir ', 'change the working directory'); - * - * --chdir /tmp - * program.chdir - * // => "/tmp" - * - * // optional argument - * program.option('-c, --cheese [type]', 'add cheese [marble]'); - * - * @param {String} flags - * @param {String} description - * @param {Function|Mixed} fn or default - * @param {Mixed} defaultValue - * @return {Command} for chaining - * @api public - */ - -Command.prototype.option = function(flags, description, fn, defaultValue){ - var self = this - , option = new Option(flags, description) - , oname = option.name() - , name = camelcase(oname); - - // default as 3rd arg - if ('function' != typeof fn) defaultValue = fn, fn = null; - - // preassign default value only for --no-*, [optional], or - if (false == option.bool || option.optional || option.required) { - // when --no-* we make sure default is true - if (false == option.bool) defaultValue = true; - // preassign only if we have a default - if (undefined !== defaultValue) self[name] = defaultValue; - } - - // register the option - this.options.push(option); - - // when it's passed assign the value - // and conditionally invoke the callback - this.on(oname, function(val){ - // coercion - if (null !== val && fn) val = fn(val, undefined === self[name] ? defaultValue : self[name]); - - // unassigned or bool - if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) { - // if no value, bool true, and we have a default, then use it! - if (null == val) { - self[name] = option.bool - ? defaultValue || true - : false; - } else { - self[name] = val; - } - } else if (null !== val) { - // reassign - self[name] = val; - } - }); - - return this; -}; - -/** - * Parse `argv`, settings options and invoking commands when defined. - * - * @param {Array} argv - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parse = function(argv){ - // implicit help - if (this.executables) this.addImplicitHelpCommand(); - - // store raw args - this.rawArgs = argv; - - // guess name - this._name = this._name || basename(argv[1], '.js'); - - // process argv - var parsed = this.parseOptions(this.normalize(argv.slice(2))); - var args = this.args = parsed.args; - - var result = this.parseArgs(this.args, parsed.unknown); - - // executable sub-commands - var name = result.args[0]; - if (this._execs[name]) return this.executeSubCommand(argv, args, parsed.unknown); - - return result; -}; - -/** - * Execute a sub-command executable. - * - * @param {Array} argv - * @param {Array} args - * @param {Array} unknown - * @api private - */ - -Command.prototype.executeSubCommand = function(argv, args, unknown) { - args = args.concat(unknown); - - if (!args.length) this.help(); - if ('help' == args[0] && 1 == args.length) this.help(); - - // --help - if ('help' == args[0]) { - args[0] = args[1]; - args[1] = '--help'; - } - - // executable - var dir = dirname(argv[1]); - var bin = basename(argv[1], '.js') + '-' + args[0]; - - // check for ./ first - var local = path.join(dir, bin); - - // run it - args = args.slice(1); - args.unshift(local); - var proc = spawn('node', args, { stdio: 'inherit', customFds: [0, 1, 2] }); - proc.on('error', function(err){ - if (err.code == "ENOENT") { - console.error('\n %s(1) does not exist, try --help\n', bin); - } else if (err.code == "EACCES") { - console.error('\n %s(1) not executable. try chmod or run with root\n', bin); - } - }); - - this.runningCommand = proc; -}; - -/** - * Normalize `args`, splitting joined short flags. For example - * the arg "-abc" is equivalent to "-a -b -c". - * This also normalizes equal sign and splits "--abc=def" into "--abc def". - * - * @param {Array} args - * @return {Array} - * @api private - */ - -Command.prototype.normalize = function(args){ - var ret = [] - , arg - , lastOpt - , index; - - for (var i = 0, len = args.length; i < len; ++i) { - arg = args[i]; - i > 0 && (lastOpt = this.optionFor(args[i-1])); - - if (lastOpt && lastOpt.required) { - ret.push(arg); - } else if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) { - arg.slice(1).split('').forEach(function(c){ - ret.push('-' + c); - }); - } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) { - ret.push(arg.slice(0, index), arg.slice(index + 1)); - } else { - ret.push(arg); - } - } - - return ret; -}; - -/** - * Parse command `args`. - * - * When listener(s) are available those - * callbacks are invoked, otherwise the "*" - * event is emitted and those actions are invoked. - * - * @param {Array} args - * @return {Command} for chaining - * @api private - */ - -Command.prototype.parseArgs = function(args, unknown){ - var cmds = this.commands - , len = cmds.length - , name; - - if (args.length) { - name = args[0]; - if (this.listeners(name).length) { - this.emit(args.shift(), args, unknown); - } else { - this.emit('*', args); - } - } else { - outputHelpIfNecessary(this, unknown); - - // If there were no args and we have unknown options, - // then they are extraneous and we need to error. - if (unknown.length > 0) { - this.unknownOption(unknown[0]); - } - } - - return this; -}; - -/** - * Return an option matching `arg` if any. - * - * @param {String} arg - * @return {Option} - * @api private - */ - -Command.prototype.optionFor = function(arg){ - for (var i = 0, len = this.options.length; i < len; ++i) { - if (this.options[i].is(arg)) { - return this.options[i]; - } - } -}; - -/** - * Parse options from `argv` returning `argv` - * void of these options. - * - * @param {Array} argv - * @return {Array} - * @api public - */ - -Command.prototype.parseOptions = function(argv){ - var args = [] - , len = argv.length - , literal - , option - , arg; - - var unknownOptions = []; - - // parse options - for (var i = 0; i < len; ++i) { - arg = argv[i]; - - // literal args after -- - if ('--' == arg) { - literal = true; - continue; - } - - if (literal) { - args.push(arg); - continue; - } - - // find matching Option - option = this.optionFor(arg); - - // option is defined - if (option) { - // requires arg - if (option.required) { - arg = argv[++i]; - if (null == arg) return this.optionMissingArgument(option); - this.emit(option.name(), arg); - // optional arg - } else if (option.optional) { - arg = argv[i+1]; - if (null == arg || ('-' == arg[0] && '-' != arg)) { - arg = null; - } else { - ++i; - } - this.emit(option.name(), arg); - // bool - } else { - this.emit(option.name()); - } - continue; - } - - // looks like an option - if (arg.length > 1 && '-' == arg[0]) { - unknownOptions.push(arg); - - // If the next argument looks like it might be - // an argument for this option, we pass it on. - // If it isn't, then it'll simply be ignored - if (argv[i+1] && '-' != argv[i+1][0]) { - unknownOptions.push(argv[++i]); - } - continue; - } - - // arg - args.push(arg); - } - - return { args: args, unknown: unknownOptions }; -}; - -/** - * Argument `name` is missing. - * - * @param {String} name - * @api private - */ - -Command.prototype.missingArgument = function(name){ - console.error(); - console.error(" error: missing required argument `%s'", name); - console.error(); - process.exit(1); -}; - -/** - * `Option` is missing an argument, but received `flag` or nothing. - * - * @param {String} option - * @param {String} flag - * @api private - */ - -Command.prototype.optionMissingArgument = function(option, flag){ - console.error(); - if (flag) { - console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); - } else { - console.error(" error: option `%s' argument missing", option.flags); - } - console.error(); - process.exit(1); -}; - -/** - * Unknown option `flag`. - * - * @param {String} flag - * @api private - */ - -Command.prototype.unknownOption = function(flag){ - console.error(); - console.error(" error: unknown option `%s'", flag); - console.error(); - process.exit(1); -}; - - -/** - * Set the program version to `str`. - * - * This method auto-registers the "-V, --version" flag - * which will print the version number when passed. - * - * @param {String} str - * @param {String} flags - * @return {Command} for chaining - * @api public - */ - -Command.prototype.version = function(str, flags){ - if (0 == arguments.length) return this._version; - this._version = str; - flags = flags || '-V, --version'; - this.option(flags, 'output the version number'); - this.on('version', function(){ - console.log(str); - process.exit(0); - }); - return this; -}; - -/** - * Set the description `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.description = function(str){ - if (0 == arguments.length) return this._description; - this._description = str; - return this; -}; - -/** - * Set an alias for the command - * - * @param {String} alias - * @return {String|Command} - * @api public - */ - -Command.prototype.alias = function(alias){ - if (0 == arguments.length) return this._alias; - this._alias = alias; - return this; -}; - -/** - * Set / get the command usage `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.usage = function(str){ - var args = this._args.map(function(arg){ - return arg.required - ? '<' + arg.name + '>' - : '[' + arg.name + ']'; - }); - - var usage = '[options' - + (this.commands.length ? '] [command' : '') - + ']' - + (this._args.length ? ' ' + args : ''); - - if (0 == arguments.length) return this._usage || usage; - this._usage = str; - - return this; -}; - -/** - * Return the largest option length. - * - * @return {Number} - * @api private - */ - -Command.prototype.largestOptionLength = function(){ - return this.options.reduce(function(max, option){ - return Math.max(max, option.flags.length); - }, 0); -}; - -/** - * Return help for options. - * - * @return {String} - * @api private - */ - -Command.prototype.optionHelp = function(){ - var width = this.largestOptionLength(); - - // Prepend the help information - return [pad('-h, --help', width) + ' ' + 'output usage information'] - .concat(this.options.map(function(option){ - return pad(option.flags, width) - + ' ' + option.description; - })) - .join('\n'); -}; - -/** - * Return command help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.commandHelp = function(){ - if (!this.commands.length) return ''; - return [ - '' - , ' Commands:' - , '' - , this.commands.map(function(cmd){ - var args = cmd._args.map(function(arg){ - return arg.required - ? '<' + arg.name + '>' - : '[' + arg.name + ']'; - }).join(' '); - - return cmd._name - + (cmd._alias - ? '|' + cmd._alias - : '') - + (cmd.options.length - ? ' [options]' - : '') + ' ' + args - + (cmd.description() - ? '\n ' + cmd.description() - : '') - + '\n'; - }).join('\n').replace(/^/gm, ' ') - , '' - ].join('\n'); -}; - -/** - * Return program help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.helpInformation = function(){ - return [ - '' - , ' Usage: ' + this._name - + (this._alias - ? '|' + this._alias - : '') - + ' ' + this.usage() - , '' + this.commandHelp() - , ' Options:' - , '' - , '' + this.optionHelp().replace(/^/gm, ' ') - , '' - , '' - ].join('\n'); -}; - -/** - * Output help information for this command - * - * @api public - */ - -Command.prototype.outputHelp = function(){ - process.stdout.write(this.helpInformation()); - this.emit('--help'); -}; - -/** - * Output help information and exit. - * - * @api public - */ - -Command.prototype.help = function(){ - this.outputHelp(); - process.exit(); -}; - -/** - * Camel-case the given `flag` - * - * @param {String} flag - * @return {String} - * @api private - */ - -function camelcase(flag) { - return flag.split('-').reduce(function(str, word){ - return str + word[0].toUpperCase() + word.slice(1); - }); -} - -/** - * Pad `str` to `width`. - * - * @param {String} str - * @param {Number} width - * @return {String} - * @api private - */ - -function pad(str, width) { - var len = Math.max(0, width - str.length); - return str + Array(len + 1).join(' '); -} - -/** - * Output help information if necessary - * - * @param {Command} command to output help for - * @param {Array} array of options to search for -h or --help - * @api private - */ - -function outputHelpIfNecessary(cmd, options) { - options = options || []; - for (var i = 0; i < options.length; i++) { - if (options[i] == '--help' || options[i] == '-h') { - cmd.outputHelp(); - process.exit(0); - } - } -} diff --git a/node_modules/mocha/node_modules/commander/package.json b/node_modules/mocha/node_modules/commander/package.json deleted file mode 100644 index f2b43dd..0000000 --- a/node_modules/mocha/node_modules/commander/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "name": "commander", - "version": "2.3.0", - "description": "the complete solution for node.js command-line programs", - "keywords": [ - "command", - "option", - "parser", - "prompt", - "stdin" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "repository": { - "type": "git", - "url": "https://github.com/visionmedia/commander.js.git" - }, - "devDependencies": { - "should": ">= 0.0.1" - }, - "scripts": { - "test": "make test" - }, - "main": "index", - "engines": { - "node": ">= 0.6.x" - }, - "files": [ - "index.js" - ], - "gitHead": "7e9f407ec03d4371a478c2fe417db4998ecb6169", - "bugs": { - "url": "https://github.com/visionmedia/commander.js/issues" - }, - "homepage": "https://github.com/visionmedia/commander.js", - "_id": "commander@2.3.0", - "_shasum": "fd430e889832ec353b9acd1de217c11cb3eef873", - "_from": "commander@2.3.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "somekittens", - "email": "rkoutnik@gmail.com" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "somekittens", - "email": "rkoutnik@gmail.com" - }, - { - "name": "zhiyelee", - "email": "zhiyelee@gmail.com" - }, - { - "name": "thethomaseffect", - "email": "thethomaseffect@gmail.com" - } - ], - "dist": { - "shasum": "fd430e889832ec353b9acd1de217c11cb3eef873", - "tarball": "http://registry.npmjs.org/commander/-/commander-2.3.0.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/commander/-/commander-2.3.0.tgz" -} diff --git a/node_modules/mocha/node_modules/debug/.jshintrc b/node_modules/mocha/node_modules/debug/.jshintrc deleted file mode 100644 index 299877f..0000000 --- a/node_modules/mocha/node_modules/debug/.jshintrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "laxbreak": true -} diff --git a/node_modules/mocha/node_modules/debug/.npmignore b/node_modules/mocha/node_modules/debug/.npmignore deleted file mode 100644 index 7e6163d..0000000 --- a/node_modules/mocha/node_modules/debug/.npmignore +++ /dev/null @@ -1,6 +0,0 @@ -support -test -examples -example -*.sock -dist diff --git a/node_modules/mocha/node_modules/debug/History.md b/node_modules/mocha/node_modules/debug/History.md deleted file mode 100644 index 79429ff..0000000 --- a/node_modules/mocha/node_modules/debug/History.md +++ /dev/null @@ -1,150 +0,0 @@ - -2.0.0 / 2014-09-01 -================== - - * package: update "browserify" to v5.11.0 - * node: use stderr rather than stdout for logging (#29, @stephenmathieson) - -1.0.4 / 2014-07-15 -================== - - * dist: recompile - * example: remove `console.info()` log usage - * example: add "Content-Type" UTF-8 header to browser example - * browser: place %c marker after the space character - * browser: reset the "content" color via `color: inherit` - * browser: add colors support for Firefox >= v31 - * debug: prefer an instance `log()` function over the global one (#119) - * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) - -1.0.3 / 2014-07-09 -================== - - * Add support for multiple wildcards in namespaces (#122, @seegno) - * browser: fix lint - -1.0.2 / 2014-06-10 -================== - - * browser: update color palette (#113, @gscottolson) - * common: make console logging function configurable (#108, @timoxley) - * node: fix %o colors on old node <= 0.8.x - * Makefile: find node path using shell/which (#109, @timoxley) - -1.0.1 / 2014-06-06 -================== - - * browser: use `removeItem()` to clear localStorage - * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) - * package: add "contributors" section - * node: fix comment typo - * README: list authors - -1.0.0 / 2014-06-04 -================== - - * make ms diff be global, not be scope - * debug: ignore empty strings in enable() - * node: make DEBUG_COLORS able to disable coloring - * *: export the `colors` array - * npmignore: don't publish the `dist` dir - * Makefile: refactor to use browserify - * package: add "browserify" as a dev dependency - * Readme: add Web Inspector Colors section - * node: reset terminal color for the debug content - * node: map "%o" to `util.inspect()` - * browser: map "%j" to `JSON.stringify()` - * debug: add custom "formatters" - * debug: use "ms" module for humanizing the diff - * Readme: add "bash" syntax highlighting - * browser: add Firebug color support - * browser: add colors for WebKit browsers - * node: apply log to `console` - * rewrite: abstract common logic for Node & browsers - * add .jshintrc file - -0.8.1 / 2014-04-14 -================== - - * package: re-add the "component" section - -0.8.0 / 2014-03-30 -================== - - * add `enable()` method for nodejs. Closes #27 - * change from stderr to stdout - * remove unnecessary index.js file - -0.7.4 / 2013-11-13 -================== - - * remove "browserify" key from package.json (fixes something in browserify) - -0.7.3 / 2013-10-30 -================== - - * fix: catch localStorage security error when cookies are blocked (Chrome) - * add debug(err) support. Closes #46 - * add .browser prop to package.json. Closes #42 - -0.7.2 / 2013-02-06 -================== - - * fix package.json - * fix: Mobile Safari (private mode) is broken with debug - * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript - -0.7.1 / 2013-02-05 -================== - - * add repository URL to package.json - * add DEBUG_COLORED to force colored output - * add browserify support - * fix component. Closes #24 - -0.7.0 / 2012-05-04 -================== - - * Added .component to package.json - * Added debug.component.js build - -0.6.0 / 2012-03-16 -================== - - * Added support for "-" prefix in DEBUG [Vinay Pulim] - * Added `.enabled` flag to the node version [TooTallNate] - -0.5.0 / 2012-02-02 -================== - - * Added: humanize diffs. Closes #8 - * Added `debug.disable()` to the CS variant - * Removed padding. Closes #10 - * Fixed: persist client-side variant again. Closes #9 - -0.4.0 / 2012-02-01 -================== - - * Added browser variant support for older browsers [TooTallNate] - * Added `debug.enable('project:*')` to browser variant [TooTallNate] - * Added padding to diff (moved it to the right) - -0.3.0 / 2012-01-26 -================== - - * Added millisecond diff when isatty, otherwise UTC string - -0.2.0 / 2012-01-22 -================== - - * Added wildcard support - -0.1.0 / 2011-12-02 -================== - - * Added: remove colors unless stderr isatty [TooTallNate] - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/mocha/node_modules/debug/Makefile b/node_modules/mocha/node_modules/debug/Makefile deleted file mode 100644 index b0bde6e..0000000 --- a/node_modules/mocha/node_modules/debug/Makefile +++ /dev/null @@ -1,33 +0,0 @@ - -# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 -THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) -THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) - -# BIN directory -BIN := $(THIS_DIR)/node_modules/.bin - -# applications -NODE ?= $(shell which node) -NPM ?= $(NODE) $(shell which npm) -BROWSERIFY ?= $(NODE) $(BIN)/browserify - -all: dist/debug.js - -install: node_modules - -clean: - @rm -rf node_modules dist - -dist: - @mkdir -p $@ - -dist/debug.js: node_modules browser.js debug.js dist - @$(BROWSERIFY) \ - --standalone debug \ - . > $@ - -node_modules: package.json - @NODE_ENV= $(NPM) install - @touch node_modules - -.PHONY: all install clean diff --git a/node_modules/mocha/node_modules/debug/Readme.md b/node_modules/mocha/node_modules/debug/Readme.md deleted file mode 100644 index e59b9ad..0000000 --- a/node_modules/mocha/node_modules/debug/Readme.md +++ /dev/null @@ -1,156 +0,0 @@ -# debug - - tiny node.js debugging utility modelled after node core's debugging technique. - -## Installation - -```bash -$ npm install debug -``` - -## Usage - - With `debug` you simply invoke the exported function to generate your debug function, passing it a name which will determine if a noop function is returned, or a decorated `console.error`, so all of the `console` format string goodies you're used to work fine. A unique color is selected per-function for visibility. - -Example _app.js_: - -```js -var debug = require('debug')('http') - , http = require('http') - , name = 'My App'; - -// fake app - -debug('booting %s', name); - -http.createServer(function(req, res){ - debug(req.method + ' ' + req.url); - res.end('hello\n'); -}).listen(3000, function(){ - debug('listening'); -}); - -// fake worker of some kind - -require('./worker'); -``` - -Example _worker.js_: - -```js -var debug = require('debug')('worker'); - -setInterval(function(){ - debug('doing some work'); -}, 1000); -``` - - The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: - - ![debug http and worker](http://f.cl.ly/items/18471z1H402O24072r1J/Screenshot.png) - - ![debug worker](http://f.cl.ly/items/1X413v1a3M0d3C2c1E0i/Screenshot.png) - -## Millisecond diff - - When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. - - ![](http://f.cl.ly/items/2i3h1d3t121M2Z1A3Q0N/Screenshot.png) - - When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: - - ![](http://f.cl.ly/items/112H3i0e0o0P0a2Q2r11/Screenshot.png) - -## Conventions - - If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". - -## Wildcards - - The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect.compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. - - You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". - -## Browser support - - Debug works in the browser as well, currently persisted by `localStorage`. For example if you have `worker:a` and `worker:b` as shown below, and wish to debug both type `debug.enable('worker:*')` in the console and refresh the page, this will remain until you disable with `debug.disable()`. - -```js -a = debug('worker:a'); -b = debug('worker:b'); - -setInterval(function(){ - a('doing some work'); -}, 1000); - -setInterval(function(){ - b('doing some work'); -}, 1200); -``` - -#### Web Inspector Colors - - Colors are also enabled on "Web Inspectors" that understand the `%c` formatting - option. These are WebKit web inspectors, Firefox ([since version - 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) - and the Firebug plugin for Firefox (any version). - - Colored output looks something like: - - ![](https://cloud.githubusercontent.com/assets/71256/3139768/b98c5fd8-e8ef-11e3-862a-f7253b6f47c6.png) - -### stderr vs stdout - -You can set an alternative logging method per-namespace by overriding the `log` method on a per-namespace or globally: - -Example _stderr.js_: - -```js -var debug = require('../'); -var log = debug('app:log'); - -// by default console.log is used -log('goes to stdout!'); - -var error = debug('app:error'); -// set this namespace to log via console.error -error.log = console.error.bind(console); // don't forget to bind to console! -error('goes to stderr'); -log('still goes to stdout!'); - -// set all output to go via console.warn -// overrides all per-namespace log settings -debug.log = console.warn.bind(console); -log('now goes to stderr via console.warn'); -error('still goes to stderr, but via console.warn now'); -``` - -## Authors - - - TJ Holowaychuk - - Nathan Rajlich - -## License - -(The MIT License) - -Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca> - -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/node_modules/mocha/node_modules/debug/browser.js b/node_modules/mocha/node_modules/debug/browser.js deleted file mode 100644 index ce6369f..0000000 --- a/node_modules/mocha/node_modules/debug/browser.js +++ /dev/null @@ -1,147 +0,0 @@ - -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; - -/** - * Colors. - */ - -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -function useColors() { - // is webkit? http://stackoverflow.com/a/16459606/376773 - return ('WebkitAppearance' in document.documentElement.style) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (window.console && (console.firebug || (console.exception && console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - return JSON.stringify(v); -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs() { - var args = arguments; - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return args; - - var c = 'color: ' + this.color; - args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); - return args; -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -function log() { - // This hackery is required for IE8, - // where the `console.log` function doesn't have 'apply' - return 'object' == typeof console - && 'function' == typeof console.log - && Function.prototype.apply.call(console.log, console, arguments); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - localStorage.removeItem('debug'); - } else { - localStorage.debug = namespaces; - } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = localStorage.debug; - } catch(e) {} - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); diff --git a/node_modules/mocha/node_modules/debug/component.json b/node_modules/mocha/node_modules/debug/component.json deleted file mode 100644 index db1ceed..0000000 --- a/node_modules/mocha/node_modules/debug/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "debug", - "repo": "visionmedia/debug", - "description": "small debugging utility", - "version": "2.0.0", - "keywords": [ - "debug", - "log", - "debugger" - ], - "main": "browser.js", - "scripts": [ - "browser.js", - "debug.js" - ], - "dependencies": { - "guille/ms.js": "0.6.1" - } -} diff --git a/node_modules/mocha/node_modules/debug/debug.js b/node_modules/mocha/node_modules/debug/debug.js deleted file mode 100644 index 7571a86..0000000 --- a/node_modules/mocha/node_modules/debug/debug.js +++ /dev/null @@ -1,197 +0,0 @@ - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = debug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; - -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lowercased letter, i.e. "n". - */ - -exports.formatters = {}; - -/** - * Previously assigned color. - */ - -var prevColor = 0; - -/** - * Previous log timestamp. - */ - -var prevTime; - -/** - * Select a color. - * - * @return {Number} - * @api private - */ - -function selectColor() { - return exports.colors[prevColor++ % exports.colors.length]; -} - -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function debug(namespace) { - - // define the `disabled` version - function disabled() { - } - disabled.enabled = false; - - // define the `enabled` version - function enabled() { - - var self = enabled; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // add the `color` if not set - if (null == self.useColors) self.useColors = exports.useColors(); - if (null == self.color && self.useColors) self.color = selectColor(); - - var args = Array.prototype.slice.call(arguments); - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %o - args = ['%o'].concat(args); - } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - if ('function' === typeof exports.formatArgs) { - args = exports.formatArgs.apply(self, args); - } - var logFn = enabled.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - enabled.enabled = true; - - var fn = exports.enabled(namespace) ? enabled : disabled; - - fn.namespace = namespace; - - return fn; -} - -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - var split = (namespaces || '').split(/[\s,]+/); - var len = split.length; - - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } -} - -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} - -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} diff --git a/node_modules/mocha/node_modules/debug/node.js b/node_modules/mocha/node_modules/debug/node.js deleted file mode 100644 index db86f64..0000000 --- a/node_modules/mocha/node_modules/debug/node.js +++ /dev/null @@ -1,129 +0,0 @@ - -/** - * Module dependencies. - */ - -var tty = require('tty'); -var util = require('util'); - -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - var debugColors = (process.env.DEBUG_COLORS || '').trim().toLowerCase(); - if (0 === debugColors.length) { - return tty.isatty(1); - } else { - return '0' !== debugColors - && 'no' !== debugColors - && 'false' !== debugColors - && 'disabled' !== debugColors; - } -} - -/** - * Map %o to `util.inspect()`, since Node doesn't do that out of the box. - */ - -var inspect = (4 === util.inspect.length ? - // node <= 0.8.x - function (v, colors) { - return util.inspect(v, void 0, void 0, colors); - } : - // node > 0.8.x - function (v, colors) { - return util.inspect(v, { colors: colors }); - } -); - -exports.formatters.o = function(v) { - return inspect(v, this.useColors) - .replace(/\s*\n\s*/g, ' '); -}; - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs() { - var args = arguments; - var useColors = this.useColors; - var name = this.namespace; - - if (useColors) { - var c = this.color; - - args[0] = ' \u001b[9' + c + 'm' + name + ' ' - + '\u001b[0m' - + args[0] + '\u001b[3' + c + 'm' - + ' +' + exports.humanize(this.diff) + '\u001b[0m'; - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; - } - return args; -} - -/** - * Invokes `console.error()` with the specified arguments. - */ - -function log() { - return console.error.apply(console, arguments); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ - -exports.enable(load()); diff --git a/node_modules/mocha/node_modules/debug/node_modules/ms/.npmignore b/node_modules/mocha/node_modules/debug/node_modules/ms/.npmignore deleted file mode 100644 index d1aa0ce..0000000 --- a/node_modules/mocha/node_modules/debug/node_modules/ms/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -node_modules -test -History.md -Makefile -component.json diff --git a/node_modules/mocha/node_modules/debug/node_modules/ms/README.md b/node_modules/mocha/node_modules/debug/node_modules/ms/README.md deleted file mode 100644 index d4ab12a..0000000 --- a/node_modules/mocha/node_modules/debug/node_modules/ms/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# ms.js: miliseconds conversion utility - -```js -ms('1d') // 86400000 -ms('10h') // 36000000 -ms('2h') // 7200000 -ms('1m') // 60000 -ms('5s') // 5000 -ms('100') // 100 -``` - -```js -ms(60000) // "1m" -ms(2 * 60000) // "2m" -ms(ms('10 hours')) // "10h" -``` - -```js -ms(60000, { long: true }) // "1 minute" -ms(2 * 60000, { long: true }) // "2 minutes" -ms(ms('10 hours', { long: true })) // "10 hours" -``` - -- Node/Browser compatible. Published as `ms` in NPM. -- If a number is supplied to `ms`, a string with a unit is returned. -- If a string that contains the number is supplied, it returns it as -a number (e.g: it returns `100` for `'100'`). -- If you pass a string with a number and a valid unit, the number of -equivalent ms is returned. - -## License - -MIT \ No newline at end of file diff --git a/node_modules/mocha/node_modules/debug/node_modules/ms/index.js b/node_modules/mocha/node_modules/debug/node_modules/ms/index.js deleted file mode 100644 index c5847f8..0000000 --- a/node_modules/mocha/node_modules/debug/node_modules/ms/index.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} options - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options){ - options = options || {}; - if ('string' == typeof val) return parse(val); - return options.long - ? long(val) - : short(val); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); - if (!match) return; - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 's': - return n * s; - case 'ms': - return n; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function short(ms) { - if (ms >= d) return Math.round(ms / d) + 'd'; - if (ms >= h) return Math.round(ms / h) + 'h'; - if (ms >= m) return Math.round(ms / m) + 'm'; - if (ms >= s) return Math.round(ms / s) + 's'; - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function long(ms) { - return plural(ms, d, 'day') - || plural(ms, h, 'hour') - || plural(ms, m, 'minute') - || plural(ms, s, 'second') - || ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) return; - if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; - return Math.ceil(ms / n) + ' ' + name + 's'; -} diff --git a/node_modules/mocha/node_modules/debug/node_modules/ms/package.json b/node_modules/mocha/node_modules/debug/node_modules/ms/package.json deleted file mode 100644 index f33e81a..0000000 --- a/node_modules/mocha/node_modules/debug/node_modules/ms/package.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "name": "ms", - "version": "0.6.2", - "description": "Tiny ms conversion utility", - "repository": { - "type": "git", - "url": "git://github.com/guille/ms.js.git" - }, - "main": "./index", - "devDependencies": { - "mocha": "*", - "expect.js": "*", - "serve": "*" - }, - "component": { - "scripts": { - "ms/index.js": "index.js" - } - }, - "bugs": { - "url": "https://github.com/guille/ms.js/issues" - }, - "_id": "ms@0.6.2", - "dist": { - "shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", - "tarball": "http://registry.npmjs.org/ms/-/ms-0.6.2.tgz" - }, - "_from": "ms@0.6.2", - "_npmVersion": "1.2.30", - "_npmUser": { - "name": "rauchg", - "email": "rauchg@gmail.com" - }, - "maintainers": [ - { - "name": "rauchg", - "email": "rauchg@gmail.com" - } - ], - "directories": {}, - "_shasum": "d89c2124c6fdc1353d65a8b77bf1aac4b193708c", - "_resolved": "https://registry.npmjs.org/ms/-/ms-0.6.2.tgz", - "readme": "# ms.js: miliseconds conversion utility\n\n```js\nms('1d') // 86400000\nms('10h') // 36000000\nms('2h') // 7200000\nms('1m') // 60000\nms('5s') // 5000\nms('100') // 100\n```\n\n```js\nms(60000) // \"1m\"\nms(2 * 60000) // \"2m\"\nms(ms('10 hours')) // \"10h\"\n```\n\n```js\nms(60000, { long: true }) // \"1 minute\"\nms(2 * 60000, { long: true }) // \"2 minutes\"\nms(ms('10 hours', { long: true })) // \"10 hours\"\n```\n\n- Node/Browser compatible. Published as `ms` in NPM.\n- If a number is supplied to `ms`, a string with a unit is returned.\n- If a string that contains the number is supplied, it returns it as\na number (e.g: it returns `100` for `'100'`).\n- If you pass a string with a number and a valid unit, the number of\nequivalent ms is returned.\n\n## License\n\nMIT", - "readmeFilename": "README.md", - "homepage": "https://github.com/guille/ms.js", - "scripts": {} -} diff --git a/node_modules/mocha/node_modules/debug/package.json b/node_modules/mocha/node_modules/debug/package.json deleted file mode 100644 index e3c906e..0000000 --- a/node_modules/mocha/node_modules/debug/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "name": "debug", - "version": "2.0.0", - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/debug.git" - }, - "description": "small debugging utility", - "keywords": [ - "debug", - "log", - "debugger" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "contributors": [ - { - "name": "Nathan Rajlich", - "email": "nathan@tootallnate.net", - "url": "http://n8.io" - } - ], - "dependencies": { - "ms": "0.6.2" - }, - "devDependencies": { - "browserify": "5.11.0", - "mocha": "*" - }, - "main": "./node.js", - "browser": "./browser.js", - "component": { - "scripts": { - "debug/index.js": "browser.js", - "debug/debug.js": "debug.js" - } - }, - "gitHead": "c61ae82bde19c6fdedfc6684817ff7eb541ff029", - "bugs": { - "url": "https://github.com/visionmedia/debug/issues" - }, - "homepage": "https://github.com/visionmedia/debug", - "_id": "debug@2.0.0", - "scripts": {}, - "_shasum": "89bd9df6732b51256bc6705342bba02ed12131ef", - "_from": "debug@2.0.0", - "_npmVersion": "1.4.21", - "_npmUser": { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - } - ], - "dist": { - "shasum": "89bd9df6732b51256bc6705342bba02ed12131ef", - "tarball": "http://registry.npmjs.org/debug/-/debug-2.0.0.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/debug/-/debug-2.0.0.tgz" -} diff --git a/node_modules/mocha/node_modules/diff/README.md b/node_modules/mocha/node_modules/diff/README.md deleted file mode 100644 index b867e19..0000000 --- a/node_modules/mocha/node_modules/diff/README.md +++ /dev/null @@ -1,181 +0,0 @@ -# jsdiff - -[![Build Status](https://secure.travis-ci.org/kpdecker/jsdiff.png)](http://travis-ci.org/kpdecker/jsdiff) - -A javascript text differencing implementation. - -Based on the algorithm proposed in -["An O(ND) Difference Algorithm and its Variations" (Myers, 1986)](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927). - -## Installation - - npm install diff - -or - - bower install jsdiff - -or - - git clone git://github.com/kpdecker/jsdiff.git - -## API - -* `JsDiff.diffChars(oldStr, newStr[, callback])` - diffs two blocks of text, comparing character by character. - - Returns a list of change objects (See below). - -* `JsDiff.diffWords(oldStr, newStr[, callback])` - diffs two blocks of text, comparing word by word, ignoring whitespace. - - Returns a list of change objects (See below). - -* `JsDiff.diffWordsWithSpace(oldStr, newStr[, callback])` - diffs two blocks of text, comparing word by word, treating whitespace as significant. - - Returns a list of change objects (See below). - -* `JsDiff.diffLines(oldStr, newStr[, callback])` - diffs two blocks of text, comparing line by line. - - Returns a list of change objects (See below). - -* `JsDiff.diffTrimmedLines(oldStr, newStr[, callback])` - diffs two blocks of text, comparing line by line, ignoring leading and trailing whitespace. - - Returns a list of change objects (See below). - -* `JsDiff.diffSentences(oldStr, newStr[, callback])` - diffs two blocks of text, comparing sentence by sentence. - - Returns a list of change objects (See below). - -* `JsDiff.diffCss(oldStr, newStr[, callback])` - diffs two blocks of text, comparing CSS tokens. - - Returns a list of change objects (See below). - -* `JsDiff.diffJson(oldObj, newObj[, callback])` - diffs two JSON objects, comparing the fields defined on each. The order of fields, etc does not matter in this comparison. - - Returns a list of change objects (See below). - -* `JsDiff.createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. - - Parameters: - * `oldFileName` : String to be output in the filename section of the patch for the removals - * `newFileName` : String to be output in the filename section of the patch for the additions - * `oldStr` : Original string value - * `newStr` : New string value - * `oldHeader` : Additional information to include in the old file header - * `newHeader` : Additional information to include in thew new file header - -* `JsDiff.createPatch(fileName, oldStr, newStr, oldHeader, newHeader)` - creates a unified diff patch. - - Just like JsDiff.createTwoFilesPatch, but with oldFileName being equal to newFileName. - -* `JsDiff.applyPatch(oldStr, diffStr)` - applies a unified diff patch. - - Return a string containing new version of provided data. - -* `convertChangesToXML(changes)` - converts a list of changes to a serialized XML format - - -All methods above which accept the optional callback method will run in sync mode when that parameter is omitted and in async mode when supplied. This allows for larger diffs without blocking the event loop. - -### Change Objects -Many of the methods above return change objects. These objects are consist of the following fields: - -* `value`: Text content -* `added`: True if the value was inserted into the new string -* `removed`: True of the value was removed from the old string - -Note that some cases may omit a particular flag field. Comparison on the flag fields should always be done in a truthy or falsy manner. - -## Examples - -Basic example in Node - -```js -require('colors') -var jsdiff = require('diff'); - -var one = 'beep boop'; -var other = 'beep boob blah'; - -var diff = jsdiff.diffChars(one, other); - -diff.forEach(function(part){ - // green for additions, red for deletions - // grey for common parts - var color = part.added ? 'green' : - part.removed ? 'red' : 'grey'; - process.stderr.write(part.value[color]); -}); - -console.log() -``` -Running the above program should yield - -Node Example - -Basic example in a web page - -```html -
      
      -
      -
      -```
      -
      -Open the above .html file in a browser and you should see
      -
      -Node Example
      -
      -**[Full online demo](http://kpdecker.github.com/jsdiff)**
      -
      -## License
      -
      -Software License Agreement (BSD License)
      -
      -Copyright (c) 2009-2011, Kevin Decker kpdecker@gmail.com
      -
      -All rights reserved.
      -
      -Redistribution and use of this software 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 Kevin Decker nor the names of its
      -  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 OWNER 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.
      -
      -
      -[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/kpdecker/jsdiff/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
      diff --git a/node_modules/mocha/node_modules/diff/diff.js b/node_modules/mocha/node_modules/diff/diff.js
      deleted file mode 100644
      index 421854a..0000000
      --- a/node_modules/mocha/node_modules/diff/diff.js
      +++ /dev/null
      @@ -1,619 +0,0 @@
      -/* See LICENSE file for terms of use */
      -
      -/*
      - * Text diff implementation.
      - *
      - * This library supports the following APIS:
      - * JsDiff.diffChars: Character by character diff
      - * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
      - * JsDiff.diffLines: Line based diff
      - *
      - * JsDiff.diffCss: Diff targeted at CSS content
      - *
      - * These methods are based on the implementation proposed in
      - * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
      - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
      - */
      -(function(global, undefined) {
      -  var objectPrototypeToString = Object.prototype.toString;
      -
      -  /*istanbul ignore next*/
      -  function map(arr, mapper, that) {
      -    if (Array.prototype.map) {
      -      return Array.prototype.map.call(arr, mapper, that);
      -    }
      -
      -    var other = new Array(arr.length);
      -
      -    for (var i = 0, n = arr.length; i < n; i++) {
      -      other[i] = mapper.call(that, arr[i], i, arr);
      -    }
      -    return other;
      -  }
      -  function clonePath(path) {
      -    return { newPos: path.newPos, components: path.components.slice(0) };
      -  }
      -  function removeEmpty(array) {
      -    var ret = [];
      -    for (var i = 0; i < array.length; i++) {
      -      if (array[i]) {
      -        ret.push(array[i]);
      -      }
      -    }
      -    return ret;
      -  }
      -  function escapeHTML(s) {
      -    var n = s;
      -    n = n.replace(/&/g, '&');
      -    n = n.replace(//g, '>');
      -    n = n.replace(/"/g, '"');
      -
      -    return n;
      -  }
      -
      -  // This function handles the presence of circular references by bailing out when encountering an
      -  // object that is already on the "stack" of items being processed.
      -  function canonicalize(obj, stack, replacementStack) {
      -    stack = stack || [];
      -    replacementStack = replacementStack || [];
      -
      -    var i;
      -
      -    for (i = 0; i < stack.length; i += 1) {
      -      if (stack[i] === obj) {
      -        return replacementStack[i];
      -      }
      -    }
      -
      -    var canonicalizedObj;
      -
      -    if ('[object Array]' === objectPrototypeToString.call(obj)) {
      -      stack.push(obj);
      -      canonicalizedObj = new Array(obj.length);
      -      replacementStack.push(canonicalizedObj);
      -      for (i = 0; i < obj.length; i += 1) {
      -        canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack);
      -      }
      -      stack.pop();
      -      replacementStack.pop();
      -    } else if (typeof obj === 'object' && obj !== null) {
      -      stack.push(obj);
      -      canonicalizedObj = {};
      -      replacementStack.push(canonicalizedObj);
      -      var sortedKeys = [],
      -          key;
      -      for (key in obj) {
      -        sortedKeys.push(key);
      -      }
      -      sortedKeys.sort();
      -      for (i = 0; i < sortedKeys.length; i += 1) {
      -        key = sortedKeys[i];
      -        canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack);
      -      }
      -      stack.pop();
      -      replacementStack.pop();
      -    } else {
      -      canonicalizedObj = obj;
      -    }
      -    return canonicalizedObj;
      -  }
      -
      -  function buildValues(components, newString, oldString, useLongestToken) {
      -    var componentPos = 0,
      -        componentLen = components.length,
      -        newPos = 0,
      -        oldPos = 0;
      -
      -    for (; componentPos < componentLen; componentPos++) {
      -      var component = components[componentPos];
      -      if (!component.removed) {
      -        if (!component.added && useLongestToken) {
      -          var value = newString.slice(newPos, newPos + component.count);
      -          value = map(value, function(value, i) {
      -            var oldValue = oldString[oldPos + i];
      -            return oldValue.length > value.length ? oldValue : value;
      -          });
      -
      -          component.value = value.join('');
      -        } else {
      -          component.value = newString.slice(newPos, newPos + component.count).join('');
      -        }
      -        newPos += component.count;
      -
      -        // Common case
      -        if (!component.added) {
      -          oldPos += component.count;
      -        }
      -      } else {
      -        component.value = oldString.slice(oldPos, oldPos + component.count).join('');
      -        oldPos += component.count;
      -
      -        // Reverse add and remove so removes are output first to match common convention
      -        // The diffing algorithm is tied to add then remove output and this is the simplest
      -        // route to get the desired output with minimal overhead.
      -        if (componentPos && components[componentPos - 1].added) {
      -          var tmp = components[componentPos - 1];
      -          components[componentPos - 1] = components[componentPos];
      -          components[componentPos] = tmp;
      -        }
      -      }
      -    }
      -
      -    return components;
      -  }
      -
      -  function Diff(ignoreWhitespace) {
      -    this.ignoreWhitespace = ignoreWhitespace;
      -  }
      -  Diff.prototype = {
      -    diff: function(oldString, newString, callback) {
      -      var self = this;
      -
      -      function done(value) {
      -        if (callback) {
      -          setTimeout(function() { callback(undefined, value); }, 0);
      -          return true;
      -        } else {
      -          return value;
      -        }
      -      }
      -
      -      // Handle the identity case (this is due to unrolling editLength == 0
      -      if (newString === oldString) {
      -        return done([{ value: newString }]);
      -      }
      -      if (!newString) {
      -        return done([{ value: oldString, removed: true }]);
      -      }
      -      if (!oldString) {
      -        return done([{ value: newString, added: true }]);
      -      }
      -
      -      newString = this.tokenize(newString);
      -      oldString = this.tokenize(oldString);
      -
      -      var newLen = newString.length, oldLen = oldString.length;
      -      var editLength = 1;
      -      var maxEditLength = newLen + oldLen;
      -      var bestPath = [{ newPos: -1, components: [] }];
      -
      -      // Seed editLength = 0, i.e. the content starts with the same values
      -      var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
      -      if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
      -        // Identity per the equality and tokenizer
      -        return done([{value: newString.join('')}]);
      -      }
      -
      -      // Main worker method. checks all permutations of a given edit length for acceptance.
      -      function execEditLength() {
      -        for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
      -          var basePath;
      -          var addPath = bestPath[diagonalPath - 1],
      -              removePath = bestPath[diagonalPath + 1],
      -              oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
      -          if (addPath) {
      -            // No one else is going to attempt to use this value, clear it
      -            bestPath[diagonalPath - 1] = undefined;
      -          }
      -
      -          var canAdd = addPath && addPath.newPos + 1 < newLen,
      -              canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
      -          if (!canAdd && !canRemove) {
      -            // If this path is a terminal then prune
      -            bestPath[diagonalPath] = undefined;
      -            continue;
      -          }
      -
      -          // Select the diagonal that we want to branch from. We select the prior
      -          // path whose position in the new string is the farthest from the origin
      -          // and does not pass the bounds of the diff graph
      -          if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
      -            basePath = clonePath(removePath);
      -            self.pushComponent(basePath.components, undefined, true);
      -          } else {
      -            basePath = addPath;   // No need to clone, we've pulled it from the list
      -            basePath.newPos++;
      -            self.pushComponent(basePath.components, true, undefined);
      -          }
      -
      -          oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
      -
      -          // If we have hit the end of both strings, then we are done
      -          if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
      -            return done(buildValues(basePath.components, newString, oldString, self.useLongestToken));
      -          } else {
      -            // Otherwise track this path as a potential candidate and continue.
      -            bestPath[diagonalPath] = basePath;
      -          }
      -        }
      -
      -        editLength++;
      -      }
      -
      -      // Performs the length of edit iteration. Is a bit fugly as this has to support the
      -      // sync and async mode which is never fun. Loops over execEditLength until a value
      -      // is produced.
      -      if (callback) {
      -        (function exec() {
      -          setTimeout(function() {
      -            // This should not happen, but we want to be safe.
      -            /*istanbul ignore next */
      -            if (editLength > maxEditLength) {
      -              return callback();
      -            }
      -
      -            if (!execEditLength()) {
      -              exec();
      -            }
      -          }, 0);
      -        }());
      -      } else {
      -        while (editLength <= maxEditLength) {
      -          var ret = execEditLength();
      -          if (ret) {
      -            return ret;
      -          }
      -        }
      -      }
      -    },
      -
      -    pushComponent: function(components, added, removed) {
      -      var last = components[components.length - 1];
      -      if (last && last.added === added && last.removed === removed) {
      -        // We need to clone here as the component clone operation is just
      -        // as shallow array clone
      -        components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
      -      } else {
      -        components.push({count: 1, added: added, removed: removed });
      -      }
      -    },
      -    extractCommon: function(basePath, newString, oldString, diagonalPath) {
      -      var newLen = newString.length,
      -          oldLen = oldString.length,
      -          newPos = basePath.newPos,
      -          oldPos = newPos - diagonalPath,
      -
      -          commonCount = 0;
      -      while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
      -        newPos++;
      -        oldPos++;
      -        commonCount++;
      -      }
      -
      -      if (commonCount) {
      -        basePath.components.push({count: commonCount});
      -      }
      -
      -      basePath.newPos = newPos;
      -      return oldPos;
      -    },
      -
      -    equals: function(left, right) {
      -      var reWhitespace = /\S/;
      -      return left === right || (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right));
      -    },
      -    tokenize: function(value) {
      -      return value.split('');
      -    }
      -  };
      -
      -  var CharDiff = new Diff();
      -
      -  var WordDiff = new Diff(true);
      -  var WordWithSpaceDiff = new Diff();
      -  WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
      -    return removeEmpty(value.split(/(\s+|\b)/));
      -  };
      -
      -  var CssDiff = new Diff(true);
      -  CssDiff.tokenize = function(value) {
      -    return removeEmpty(value.split(/([{}:;,]|\s+)/));
      -  };
      -
      -  var LineDiff = new Diff();
      -
      -  var TrimmedLineDiff = new Diff();
      -  TrimmedLineDiff.ignoreTrim = true;
      -
      -  LineDiff.tokenize = TrimmedLineDiff.tokenize = function(value) {
      -    var retLines = [],
      -        lines = value.split(/^/m);
      -    for (var i = 0; i < lines.length; i++) {
      -      var line = lines[i],
      -          lastLine = lines[i - 1],
      -          lastLineLastChar = lastLine && lastLine[lastLine.length - 1];
      -
      -      // Merge lines that may contain windows new lines
      -      if (line === '\n' && lastLineLastChar === '\r') {
      -          retLines[retLines.length - 1] = retLines[retLines.length - 1].slice(0, -1) + '\r\n';
      -      } else {
      -        if (this.ignoreTrim) {
      -          line = line.trim();
      -          // add a newline unless this is the last line.
      -          if (i < lines.length - 1) {
      -            line += '\n';
      -          }
      -        }
      -        retLines.push(line);
      -      }
      -    }
      -
      -    return retLines;
      -  };
      -
      -  var PatchDiff = new Diff();
      -  PatchDiff.tokenize = function(value) {
      -    var ret = [],
      -        linesAndNewlines = value.split(/(\n|\r\n)/);
      -
      -    // Ignore the final empty token that occurs if the string ends with a new line
      -    if (!linesAndNewlines[linesAndNewlines.length - 1]) {
      -      linesAndNewlines.pop();
      -    }
      -
      -    // Merge the content and line separators into single tokens
      -    for (var i = 0; i < linesAndNewlines.length; i++) {
      -      var line = linesAndNewlines[i];
      -
      -      if (i % 2) {
      -        ret[ret.length - 1] += line;
      -      } else {
      -        ret.push(line);
      -      }
      -    }
      -    return ret;
      -  };
      -
      -  var SentenceDiff = new Diff();
      -  SentenceDiff.tokenize = function(value) {
      -    return removeEmpty(value.split(/(\S.+?[.!?])(?=\s+|$)/));
      -  };
      -
      -  var JsonDiff = new Diff();
      -  // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
      -  // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
      -  JsonDiff.useLongestToken = true;
      -  JsonDiff.tokenize = LineDiff.tokenize;
      -  JsonDiff.equals = function(left, right) {
      -    return LineDiff.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
      -  };
      -
      -  var JsDiff = {
      -    Diff: Diff,
      -
      -    diffChars: function(oldStr, newStr, callback) { return CharDiff.diff(oldStr, newStr, callback); },
      -    diffWords: function(oldStr, newStr, callback) { return WordDiff.diff(oldStr, newStr, callback); },
      -    diffWordsWithSpace: function(oldStr, newStr, callback) { return WordWithSpaceDiff.diff(oldStr, newStr, callback); },
      -    diffLines: function(oldStr, newStr, callback) { return LineDiff.diff(oldStr, newStr, callback); },
      -    diffTrimmedLines: function(oldStr, newStr, callback) { return TrimmedLineDiff.diff(oldStr, newStr, callback); },
      -
      -    diffSentences: function(oldStr, newStr, callback) { return SentenceDiff.diff(oldStr, newStr, callback); },
      -
      -    diffCss: function(oldStr, newStr, callback) { return CssDiff.diff(oldStr, newStr, callback); },
      -    diffJson: function(oldObj, newObj, callback) {
      -      return JsonDiff.diff(
      -        typeof oldObj === 'string' ? oldObj : JSON.stringify(canonicalize(oldObj), undefined, '  '),
      -        typeof newObj === 'string' ? newObj : JSON.stringify(canonicalize(newObj), undefined, '  '),
      -        callback
      -      );
      -    },
      -
      -    createTwoFilesPatch: function(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader) {
      -      var ret = [];
      -
      -      if (oldFileName == newFileName) {
      -        ret.push('Index: ' + oldFileName);
      -      }
      -      ret.push('===================================================================');
      -      ret.push('--- ' + oldFileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
      -      ret.push('+++ ' + newFileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
      -
      -      var diff = PatchDiff.diff(oldStr, newStr);
      -      diff.push({value: '', lines: []});   // Append an empty value to make cleanup easier
      -
      -      // Formats a given set of lines for printing as context lines in a patch
      -      function contextLines(lines) {
      -        return map(lines, function(entry) { return ' ' + entry; });
      -      }
      -
      -      // Outputs the no newline at end of file warning if needed
      -      function eofNL(curRange, i, current) {
      -        var last = diff[diff.length - 2],
      -            isLast = i === diff.length - 2,
      -            isLastOfType = i === diff.length - 3 && current.added !== last.added;
      -
      -        // Figure out if this is the last line for the given file and missing NL
      -        if (!(/\n$/.test(current.value)) && (isLast || isLastOfType)) {
      -          curRange.push('\\ No newline at end of file');
      -        }
      -      }
      -
      -      var oldRangeStart = 0, newRangeStart = 0, curRange = [],
      -          oldLine = 1, newLine = 1;
      -      for (var i = 0; i < diff.length; i++) {
      -        var current = diff[i],
      -            lines = current.lines || current.value.replace(/\n$/, '').split('\n');
      -        current.lines = lines;
      -
      -        if (current.added || current.removed) {
      -          // If we have previous context, start with that
      -          if (!oldRangeStart) {
      -            var prev = diff[i - 1];
      -            oldRangeStart = oldLine;
      -            newRangeStart = newLine;
      -
      -            if (prev) {
      -              curRange = contextLines(prev.lines.slice(-4));
      -              oldRangeStart -= curRange.length;
      -              newRangeStart -= curRange.length;
      -            }
      -          }
      -
      -          // Output our changes
      -          curRange.push.apply(curRange, map(lines, function(entry) {
      -            return (current.added ? '+' : '-') + entry;
      -          }));
      -          eofNL(curRange, i, current);
      -
      -          // Track the updated file position
      -          if (current.added) {
      -            newLine += lines.length;
      -          } else {
      -            oldLine += lines.length;
      -          }
      -        } else {
      -          // Identical context lines. Track line changes
      -          if (oldRangeStart) {
      -            // Close out any changes that have been output (or join overlapping)
      -            if (lines.length <= 8 && i < diff.length - 2) {
      -              // Overlapping
      -              curRange.push.apply(curRange, contextLines(lines));
      -            } else {
      -              // end the range and output
      -              var contextSize = Math.min(lines.length, 4);
      -              ret.push(
      -                  '@@ -' + oldRangeStart + ',' + (oldLine - oldRangeStart + contextSize)
      -                  + ' +' + newRangeStart + ',' + (newLine - newRangeStart + contextSize)
      -                  + ' @@');
      -              ret.push.apply(ret, curRange);
      -              ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
      -              if (lines.length <= 4) {
      -                eofNL(ret, i, current);
      -              }
      -
      -              oldRangeStart = 0;
      -              newRangeStart = 0;
      -              curRange = [];
      -            }
      -          }
      -          oldLine += lines.length;
      -          newLine += lines.length;
      -        }
      -      }
      -
      -      return ret.join('\n') + '\n';
      -    },
      -
      -    createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
      -      return JsDiff.createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader);
      -    },
      -
      -    applyPatch: function(oldStr, uniDiff) {
      -      var diffstr = uniDiff.split('\n'),
      -          hunks = [],
      -          i = 0,
      -          remEOFNL = false,
      -          addEOFNL = false;
      -
      -      // Skip to the first change hunk
      -      while (i < diffstr.length && !(/^@@/.test(diffstr[i]))) {
      -        i++;
      -      }
      -
      -      // Parse the unified diff
      -      for (; i < diffstr.length; i++) {
      -        if (diffstr[i][0] === '@') {
      -          var chnukHeader = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
      -          hunks.unshift({
      -            start: chnukHeader[3],
      -            oldlength: +chnukHeader[2],
      -            removed: [],
      -            newlength: chnukHeader[4],
      -            added: []
      -          });
      -        } else if (diffstr[i][0] === '+') {
      -          hunks[0].added.push(diffstr[i].substr(1));
      -        } else if (diffstr[i][0] === '-') {
      -          hunks[0].removed.push(diffstr[i].substr(1));
      -        } else if (diffstr[i][0] === ' ') {
      -          hunks[0].added.push(diffstr[i].substr(1));
      -          hunks[0].removed.push(diffstr[i].substr(1));
      -        } else if (diffstr[i][0] === '\\') {
      -          if (diffstr[i - 1][0] === '+') {
      -            remEOFNL = true;
      -          } else if (diffstr[i - 1][0] === '-') {
      -            addEOFNL = true;
      -          }
      -        }
      -      }
      -
      -      // Apply the diff to the input
      -      var lines = oldStr.split('\n');
      -      for (i = hunks.length - 1; i >= 0; i--) {
      -        var hunk = hunks[i];
      -        // Sanity check the input string. Bail if we don't match.
      -        for (var j = 0; j < hunk.oldlength; j++) {
      -          if (lines[hunk.start - 1 + j] !== hunk.removed[j]) {
      -            return false;
      -          }
      -        }
      -        Array.prototype.splice.apply(lines, [hunk.start - 1, hunk.oldlength].concat(hunk.added));
      -      }
      -
      -      // Handle EOFNL insertion/removal
      -      if (remEOFNL) {
      -        while (!lines[lines.length - 1]) {
      -          lines.pop();
      -        }
      -      } else if (addEOFNL) {
      -        lines.push('');
      -      }
      -      return lines.join('\n');
      -    },
      -
      -    convertChangesToXML: function(changes) {
      -      var ret = [];
      -      for (var i = 0; i < changes.length; i++) {
      -        var change = changes[i];
      -        if (change.added) {
      -          ret.push('');
      -        } else if (change.removed) {
      -          ret.push('');
      -        }
      -
      -        ret.push(escapeHTML(change.value));
      -
      -        if (change.added) {
      -          ret.push('');
      -        } else if (change.removed) {
      -          ret.push('');
      -        }
      -      }
      -      return ret.join('');
      -    },
      -
      -    // See: http://code.google.com/p/google-diff-match-patch/wiki/API
      -    convertChangesToDMP: function(changes) {
      -      var ret = [],
      -          change,
      -          operation;
      -      for (var i = 0; i < changes.length; i++) {
      -        change = changes[i];
      -        if (change.added) {
      -          operation = 1;
      -        } else if (change.removed) {
      -          operation = -1;
      -        } else {
      -          operation = 0;
      -        }
      -
      -        ret.push([operation, change.value]);
      -      }
      -      return ret;
      -    },
      -
      -    canonicalize: canonicalize
      -  };
      -
      -  /*istanbul ignore next */
      -  /*global module */
      -  if (typeof module !== 'undefined' && module.exports) {
      -    module.exports = JsDiff;
      -  } else if (typeof define === 'function' && define.amd) {
      -    /*global define */
      -    define([], function() { return JsDiff; });
      -  } else if (typeof global.JsDiff === 'undefined') {
      -    global.JsDiff = JsDiff;
      -  }
      -}(this));
      diff --git a/node_modules/mocha/node_modules/diff/package.json b/node_modules/mocha/node_modules/diff/package.json
      deleted file mode 100644
      index e1887dd..0000000
      --- a/node_modules/mocha/node_modules/diff/package.json
      +++ /dev/null
      @@ -1,64 +0,0 @@
      -{
      -  "name": "diff",
      -  "version": "1.4.0",
      -  "description": "A javascript text diff implementation.",
      -  "keywords": [
      -    "diff",
      -    "javascript"
      -  ],
      -  "maintainers": [
      -    {
      -      "name": "kpdecker",
      -      "email": "kpdecker@gmail.com"
      -    }
      -  ],
      -  "bugs": {
      -    "url": "http://github.com/kpdecker/jsdiff/issues",
      -    "email": "kpdecker@gmail.com"
      -  },
      -  "licenses": [
      -    {
      -      "type": "BSD",
      -      "url": "http://github.com/kpdecker/jsdiff/blob/master/LICENSE"
      -    }
      -  ],
      -  "repository": {
      -    "type": "git",
      -    "url": "git://github.com/kpdecker/jsdiff.git"
      -  },
      -  "engines": {
      -    "node": ">=0.3.1"
      -  },
      -  "main": "./diff",
      -  "scripts": {
      -    "test": "istanbul cover node_modules/.bin/_mocha test/*.js && istanbul check-coverage --statements 100 --functions 100 --branches 100 --lines 100 coverage/coverage.json"
      -  },
      -  "dependencies": {},
      -  "devDependencies": {
      -    "colors": "^1.1.0",
      -    "istanbul": "^0.3.2",
      -    "mocha": "^2.2.4",
      -    "should": "^6.0.1"
      -  },
      -  "optionalDependencies": {},
      -  "files": [
      -    "diff.js"
      -  ],
      -  "gitHead": "27a750e9116e6ade6303bc24a9be72f6845e00ed",
      -  "homepage": "https://github.com/kpdecker/jsdiff",
      -  "_id": "diff@1.4.0",
      -  "_shasum": "7f28d2eb9ee7b15a97efd89ce63dcfdaa3ccbabf",
      -  "_from": "diff@1.4.0",
      -  "_npmVersion": "1.4.28",
      -  "_npmUser": {
      -    "name": "kpdecker",
      -    "email": "kpdecker@gmail.com"
      -  },
      -  "dist": {
      -    "shasum": "7f28d2eb9ee7b15a97efd89ce63dcfdaa3ccbabf",
      -    "tarball": "http://registry.npmjs.org/diff/-/diff-1.4.0.tgz"
      -  },
      -  "directories": {},
      -  "_resolved": "https://registry.npmjs.org/diff/-/diff-1.4.0.tgz",
      -  "readme": "ERROR: No README data found!"
      -}
      diff --git a/node_modules/mocha/node_modules/escape-string-regexp/index.js b/node_modules/mocha/node_modules/escape-string-regexp/index.js
      deleted file mode 100644
      index ac6572c..0000000
      --- a/node_modules/mocha/node_modules/escape-string-regexp/index.js
      +++ /dev/null
      @@ -1,11 +0,0 @@
      -'use strict';
      -
      -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
      -
      -module.exports = function (str) {
      -	if (typeof str !== 'string') {
      -		throw new TypeError('Expected a string');
      -	}
      -
      -	return str.replace(matchOperatorsRe,  '\\$&');
      -};
      diff --git a/node_modules/mocha/node_modules/escape-string-regexp/package.json b/node_modules/mocha/node_modules/escape-string-regexp/package.json
      deleted file mode 100644
      index 797f2c8..0000000
      --- a/node_modules/mocha/node_modules/escape-string-regexp/package.json
      +++ /dev/null
      @@ -1,70 +0,0 @@
      -{
      -  "name": "escape-string-regexp",
      -  "version": "1.0.2",
      -  "description": "Escape RegExp special characters",
      -  "license": "MIT",
      -  "repository": {
      -    "type": "git",
      -    "url": "https://github.com/sindresorhus/escape-string-regexp"
      -  },
      -  "author": {
      -    "name": "Sindre Sorhus",
      -    "email": "sindresorhus@gmail.com",
      -    "url": "http://sindresorhus.com"
      -  },
      -  "engines": {
      -    "node": ">=0.8.0"
      -  },
      -  "scripts": {
      -    "test": "mocha"
      -  },
      -  "files": [
      -    "index.js"
      -  ],
      -  "keywords": [
      -    "regex",
      -    "regexp",
      -    "re",
      -    "regular",
      -    "expression",
      -    "escape",
      -    "string",
      -    "str",
      -    "special",
      -    "characters"
      -  ],
      -  "devDependencies": {
      -    "mocha": "*"
      -  },
      -  "gitHead": "0587ee0ee03ea3fcbfa3c15cf67b47f214e20987",
      -  "bugs": {
      -    "url": "https://github.com/sindresorhus/escape-string-regexp/issues"
      -  },
      -  "homepage": "https://github.com/sindresorhus/escape-string-regexp",
      -  "_id": "escape-string-regexp@1.0.2",
      -  "_shasum": "4dbc2fe674e71949caf3fb2695ce7f2dc1d9a8d1",
      -  "_from": "escape-string-regexp@1.0.2",
      -  "_npmVersion": "1.4.23",
      -  "_npmUser": {
      -    "name": "jbnicolai",
      -    "email": "jappelman@xebia.com"
      -  },
      -  "maintainers": [
      -    {
      -      "name": "sindresorhus",
      -      "email": "sindresorhus@gmail.com"
      -    },
      -    {
      -      "name": "jbnicolai",
      -      "email": "jappelman@xebia.com"
      -    }
      -  ],
      -  "dist": {
      -    "shasum": "4dbc2fe674e71949caf3fb2695ce7f2dc1d9a8d1",
      -    "tarball": "http://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.2.tgz"
      -  },
      -  "directories": {},
      -  "_resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.2.tgz",
      -  "readme": "# escape-string-regexp [![Build Status](https://travis-ci.org/sindresorhus/escape-string-regexp.svg?branch=master)](https://travis-ci.org/sindresorhus/escape-string-regexp)\n\n> Escape RegExp special characters\n\n\n## Install\n\n```sh\n$ npm install --save escape-string-regexp\n```\n\n\n## Usage\n\n```js\nvar escapeStringRegexp = require('escape-string-regexp');\n\nvar escapedString = escapeStringRegexp('how much $ for a unicorn?');\n//=> how much \\$ for a unicorn\\?\n\nnew RegExp(escapedString);\n```\n\n\n## License\n\nMIT © [Sindre Sorhus](http://sindresorhus.com)\n",
      -  "readmeFilename": "readme.md"
      -}
      diff --git a/node_modules/mocha/node_modules/escape-string-regexp/readme.md b/node_modules/mocha/node_modules/escape-string-regexp/readme.md
      deleted file mode 100644
      index 808a963..0000000
      --- a/node_modules/mocha/node_modules/escape-string-regexp/readme.md
      +++ /dev/null
      @@ -1,27 +0,0 @@
      -# escape-string-regexp [![Build Status](https://travis-ci.org/sindresorhus/escape-string-regexp.svg?branch=master)](https://travis-ci.org/sindresorhus/escape-string-regexp)
      -
      -> Escape RegExp special characters
      -
      -
      -## Install
      -
      -```sh
      -$ npm install --save escape-string-regexp
      -```
      -
      -
      -## Usage
      -
      -```js
      -var escapeStringRegexp = require('escape-string-regexp');
      -
      -var escapedString = escapeStringRegexp('how much $ for a unicorn?');
      -//=> how much \$ for a unicorn\?
      -
      -new RegExp(escapedString);
      -```
      -
      -
      -## License
      -
      -MIT © [Sindre Sorhus](http://sindresorhus.com)
      diff --git a/node_modules/mocha/node_modules/glob/.npmignore b/node_modules/mocha/node_modules/glob/.npmignore
      deleted file mode 100644
      index 2af4b71..0000000
      --- a/node_modules/mocha/node_modules/glob/.npmignore
      +++ /dev/null
      @@ -1,2 +0,0 @@
      -.*.swp
      -test/a/
      diff --git a/node_modules/mocha/node_modules/glob/.travis.yml b/node_modules/mocha/node_modules/glob/.travis.yml
      deleted file mode 100644
      index baa0031..0000000
      --- a/node_modules/mocha/node_modules/glob/.travis.yml
      +++ /dev/null
      @@ -1,3 +0,0 @@
      -language: node_js
      -node_js:
      -  - 0.8
      diff --git a/node_modules/mocha/node_modules/glob/LICENSE b/node_modules/mocha/node_modules/glob/LICENSE
      deleted file mode 100644
      index 0c44ae7..0000000
      --- a/node_modules/mocha/node_modules/glob/LICENSE
      +++ /dev/null
      @@ -1,27 +0,0 @@
      -Copyright (c) Isaac Z. Schlueter ("Author")
      -All rights reserved.
      -
      -The BSD License
      -
      -Redistribution and use in source and binary forms, with or without
      -modification, are permitted provided that the following conditions
      -are met:
      -
      -1. Redistributions of source code must retain the above copyright
      -   notice, this list of conditions and the following disclaimer.
      -
      -2. 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.
      -
      -THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
      diff --git a/node_modules/mocha/node_modules/glob/README.md b/node_modules/mocha/node_modules/glob/README.md
      deleted file mode 100644
      index cc69164..0000000
      --- a/node_modules/mocha/node_modules/glob/README.md
      +++ /dev/null
      @@ -1,250 +0,0 @@
      -# Glob
      -
      -Match files using the patterns the shell uses, like stars and stuff.
      -
      -This is a glob implementation in JavaScript.  It uses the `minimatch`
      -library to do its matching.
      -
      -## Attention: node-glob users!
      -
      -The API has changed dramatically between 2.x and 3.x. This library is
      -now 100% JavaScript, and the integer flags have been replaced with an
      -options object.
      -
      -Also, there's an event emitter class, proper tests, and all the other
      -things you've come to expect from node modules.
      -
      -And best of all, no compilation!
      -
      -## Usage
      -
      -```javascript
      -var glob = require("glob")
      -
      -// options is optional
      -glob("**/*.js", options, function (er, files) {
      -  // files is an array of filenames.
      -  // If the `nonull` option is set, and nothing
      -  // was found, then files is ["**/*.js"]
      -  // er is an error object or null.
      -})
      -```
      -
      -## Features
      -
      -Please see the [minimatch
      -documentation](https://github.com/isaacs/minimatch) for more details.
      -
      -Supports these glob features:
      -
      -* Brace Expansion
      -* Extended glob matching
      -* "Globstar" `**` matching
      -
      -See:
      -
      -* `man sh`
      -* `man bash`
      -* `man 3 fnmatch`
      -* `man 5 gitignore`
      -* [minimatch documentation](https://github.com/isaacs/minimatch)
      -
      -## glob(pattern, [options], cb)
      -
      -* `pattern` {String} Pattern to be matched
      -* `options` {Object}
      -* `cb` {Function}
      -  * `err` {Error | null}
      -  * `matches` {Array} filenames found matching the pattern
      -
      -Perform an asynchronous glob search.
      -
      -## glob.sync(pattern, [options])
      -
      -* `pattern` {String} Pattern to be matched
      -* `options` {Object}
      -* return: {Array} filenames found matching the pattern
      -
      -Perform a synchronous glob search.
      -
      -## Class: glob.Glob
      -
      -Create a Glob object by instanting the `glob.Glob` class.
      -
      -```javascript
      -var Glob = require("glob").Glob
      -var mg = new Glob(pattern, options, cb)
      -```
      -
      -It's an EventEmitter, and starts walking the filesystem to find matches
      -immediately.
      -
      -### new glob.Glob(pattern, [options], [cb])
      -
      -* `pattern` {String} pattern to search for
      -* `options` {Object}
      -* `cb` {Function} Called when an error occurs, or matches are found
      -  * `err` {Error | null}
      -  * `matches` {Array} filenames found matching the pattern
      -
      -Note that if the `sync` flag is set in the options, then matches will
      -be immediately available on the `g.found` member.
      -
      -### Properties
      -
      -* `minimatch` The minimatch object that the glob uses.
      -* `options` The options object passed in.
      -* `error` The error encountered.  When an error is encountered, the
      -  glob object is in an undefined state, and should be discarded.
      -* `aborted` Boolean which is set to true when calling `abort()`.  There
      -  is no way at this time to continue a glob search after aborting, but
      -  you can re-use the statCache to avoid having to duplicate syscalls.
      -* `statCache` Collection of all the stat results the glob search
      -  performed.
      -* `cache` Convenience object.  Each field has the following possible
      -  values:
      -  * `false` - Path does not exist
      -  * `true` - Path exists
      -  * `1` - Path exists, and is not a directory
      -  * `2` - Path exists, and is a directory
      -  * `[file, entries, ...]` - Path exists, is a directory, and the
      -    array value is the results of `fs.readdir`
      -
      -### Events
      -
      -* `end` When the matching is finished, this is emitted with all the
      -  matches found.  If the `nonull` option is set, and no match was found,
      -  then the `matches` list contains the original pattern.  The matches
      -  are sorted, unless the `nosort` flag is set.
      -* `match` Every time a match is found, this is emitted with the matched.
      -* `error` Emitted when an unexpected error is encountered, or whenever
      -  any fs error occurs if `options.strict` is set.
      -* `abort` When `abort()` is called, this event is raised.
      -
      -### Methods
      -
      -* `abort` Stop the search.
      -
      -### Options
      -
      -All the options that can be passed to Minimatch can also be passed to
      -Glob to change pattern matching behavior.  Also, some have been added,
      -or have glob-specific ramifications.
      -
      -All options are false by default, unless otherwise noted.
      -
      -All options are added to the glob object, as well.
      -
      -* `cwd` The current working directory in which to search.  Defaults
      -  to `process.cwd()`.
      -* `root` The place where patterns starting with `/` will be mounted
      -  onto.  Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix
      -  systems, and `C:\` or some such on Windows.)
      -* `dot` Include `.dot` files in normal matches and `globstar` matches.
      -  Note that an explicit dot in a portion of the pattern will always
      -  match dot files.
      -* `nomount` By default, a pattern starting with a forward-slash will be
      -  "mounted" onto the root setting, so that a valid filesystem path is
      -  returned.  Set this flag to disable that behavior.
      -* `mark` Add a `/` character to directory matches.  Note that this
      -  requires additional stat calls.
      -* `nosort` Don't sort the results.
      -* `stat` Set to true to stat *all* results.  This reduces performance
      -  somewhat, and is completely unnecessary, unless `readdir` is presumed
      -  to be an untrustworthy indicator of file existence.  It will cause
      -  ELOOP to be triggered one level sooner in the case of cyclical
      -  symbolic links.
      -* `silent` When an unusual error is encountered
      -  when attempting to read a directory, a warning will be printed to
      -  stderr.  Set the `silent` option to true to suppress these warnings.
      -* `strict` When an unusual error is encountered
      -  when attempting to read a directory, the process will just continue on
      -  in search of other matches.  Set the `strict` option to raise an error
      -  in these cases.
      -* `cache` See `cache` property above.  Pass in a previously generated
      -  cache object to save some fs calls.
      -* `statCache` A cache of results of filesystem information, to prevent
      -  unnecessary stat calls.  While it should not normally be necessary to
      -  set this, you may pass the statCache from one glob() call to the
      -  options object of another, if you know that the filesystem will not
      -  change between calls.  (See "Race Conditions" below.)
      -* `sync` Perform a synchronous glob search.
      -* `nounique` In some cases, brace-expanded patterns can result in the
      -  same file showing up multiple times in the result set.  By default,
      -  this implementation prevents duplicates in the result set.
      -  Set this flag to disable that behavior.
      -* `nonull` Set to never return an empty set, instead returning a set
      -  containing the pattern itself.  This is the default in glob(3).
      -* `nocase` Perform a case-insensitive match.  Note that case-insensitive
      -  filesystems will sometimes result in glob returning results that are
      -  case-insensitively matched anyway, since readdir and stat will not
      -  raise an error.
      -* `debug` Set to enable debug logging in minimatch and glob.
      -* `globDebug` Set to enable debug logging in glob, but not minimatch.
      -
      -## Comparisons to other fnmatch/glob implementations
      -
      -While strict compliance with the existing standards is a worthwhile
      -goal, some discrepancies exist between node-glob and other
      -implementations, and are intentional.
      -
      -If the pattern starts with a `!` character, then it is negated.  Set the
      -`nonegate` flag to suppress this behavior, and treat leading `!`
      -characters normally.  This is perhaps relevant if you wish to start the
      -pattern with a negative extglob pattern like `!(a|B)`.  Multiple `!`
      -characters at the start of a pattern will negate the pattern multiple
      -times.
      -
      -If a pattern starts with `#`, then it is treated as a comment, and
      -will not match anything.  Use `\#` to match a literal `#` at the
      -start of a line, or set the `nocomment` flag to suppress this behavior.
      -
      -The double-star character `**` is supported by default, unless the
      -`noglobstar` flag is set.  This is supported in the manner of bsdglob
      -and bash 4.1, where `**` only has special significance if it is the only
      -thing in a path part.  That is, `a/**/b` will match `a/x/y/b`, but
      -`a/**b` will not.
      -
      -If an escaped pattern has no matches, and the `nonull` flag is set,
      -then glob returns the pattern as-provided, rather than
      -interpreting the character escapes.  For example,
      -`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
      -`"*a?"`.  This is akin to setting the `nullglob` option in bash, except
      -that it does not resolve escaped pattern characters.
      -
      -If brace expansion is not disabled, then it is performed before any
      -other interpretation of the glob pattern.  Thus, a pattern like
      -`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
      -**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
      -checked for validity.  Since those two are valid, matching proceeds.
      -
      -## Windows
      -
      -**Please only use forward-slashes in glob expressions.**
      -
      -Though windows uses either `/` or `\` as its path separator, only `/`
      -characters are used by this glob implementation.  You must use
      -forward-slashes **only** in glob expressions.  Back-slashes will always
      -be interpreted as escape characters, not path separators.
      -
      -Results from absolute patterns such as `/foo/*` are mounted onto the
      -root setting using `path.join`.  On windows, this will by default result
      -in `/foo/*` matching `C:\foo\bar.txt`.
      -
      -## Race Conditions
      -
      -Glob searching, by its very nature, is susceptible to race conditions,
      -since it relies on directory walking and such.
      -
      -As a result, it is possible that a file that exists when glob looks for
      -it may have been deleted or modified by the time it returns the result.
      -
      -As part of its internal implementation, this program caches all stat
      -and readdir calls that it makes, in order to cut down on system
      -overhead.  However, this also makes it even more susceptible to races,
      -especially if the cache or statCache objects are reused between glob
      -calls.
      -
      -Users are thus advised not to use a glob result as a guarantee of
      -filesystem state in the face of rapid changes.  For the vast majority
      -of operations, this is never a problem.
      diff --git a/node_modules/mocha/node_modules/glob/examples/g.js b/node_modules/mocha/node_modules/glob/examples/g.js
      deleted file mode 100644
      index be122df..0000000
      --- a/node_modules/mocha/node_modules/glob/examples/g.js
      +++ /dev/null
      @@ -1,9 +0,0 @@
      -var Glob = require("../").Glob
      -
      -var pattern = "test/a/**/[cg]/../[cg]"
      -console.log(pattern)
      -
      -var mg = new Glob(pattern, {mark: true, sync:true}, function (er, matches) {
      -  console.log("matches", matches)
      -})
      -console.log("after")
      diff --git a/node_modules/mocha/node_modules/glob/examples/usr-local.js b/node_modules/mocha/node_modules/glob/examples/usr-local.js
      deleted file mode 100644
      index 327a425..0000000
      --- a/node_modules/mocha/node_modules/glob/examples/usr-local.js
      +++ /dev/null
      @@ -1,9 +0,0 @@
      -var Glob = require("../").Glob
      -
      -var pattern = "{./*/*,/*,/usr/local/*}"
      -console.log(pattern)
      -
      -var mg = new Glob(pattern, {mark: true}, function (er, matches) {
      -  console.log("matches", matches)
      -})
      -console.log("after")
      diff --git a/node_modules/mocha/node_modules/glob/glob.js b/node_modules/mocha/node_modules/glob/glob.js
      deleted file mode 100644
      index f0118a4..0000000
      --- a/node_modules/mocha/node_modules/glob/glob.js
      +++ /dev/null
      @@ -1,675 +0,0 @@
      -// Approach:
      -//
      -// 1. Get the minimatch set
      -// 2. For each pattern in the set, PROCESS(pattern)
      -// 3. Store matches per-set, then uniq them
      -//
      -// PROCESS(pattern)
      -// Get the first [n] items from pattern that are all strings
      -// Join these together.  This is PREFIX.
      -//   If there is no more remaining, then stat(PREFIX) and
      -//   add to matches if it succeeds.  END.
      -// readdir(PREFIX) as ENTRIES
      -//   If fails, END
      -//   If pattern[n] is GLOBSTAR
      -//     // handle the case where the globstar match is empty
      -//     // by pruning it out, and testing the resulting pattern
      -//     PROCESS(pattern[0..n] + pattern[n+1 .. $])
      -//     // handle other cases.
      -//     for ENTRY in ENTRIES (not dotfiles)
      -//       // attach globstar + tail onto the entry
      -//       PROCESS(pattern[0..n] + ENTRY + pattern[n .. $])
      -//
      -//   else // not globstar
      -//     for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
      -//       Test ENTRY against pattern[n]
      -//       If fails, continue
      -//       If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
      -//
      -// Caveat:
      -//   Cache all stats and readdirs results to minimize syscall.  Since all
      -//   we ever care about is existence and directory-ness, we can just keep
      -//   `true` for files, and [children,...] for directories, or `false` for
      -//   things that don't exist.
      -
      -
      -
      -module.exports = glob
      -
      -var fs = require("graceful-fs")
      -, minimatch = require("minimatch")
      -, Minimatch = minimatch.Minimatch
      -, inherits = require("inherits")
      -, EE = require("events").EventEmitter
      -, path = require("path")
      -, isDir = {}
      -, assert = require("assert").ok
      -
      -function glob (pattern, options, cb) {
      -  if (typeof options === "function") cb = options, options = {}
      -  if (!options) options = {}
      -
      -  if (typeof options === "number") {
      -    deprecated()
      -    return
      -  }
      -
      -  var g = new Glob(pattern, options, cb)
      -  return g.sync ? g.found : g
      -}
      -
      -glob.fnmatch = deprecated
      -
      -function deprecated () {
      -  throw new Error("glob's interface has changed. Please see the docs.")
      -}
      -
      -glob.sync = globSync
      -function globSync (pattern, options) {
      -  if (typeof options === "number") {
      -    deprecated()
      -    return
      -  }
      -
      -  options = options || {}
      -  options.sync = true
      -  return glob(pattern, options)
      -}
      -
      -
      -glob.Glob = Glob
      -inherits(Glob, EE)
      -function Glob (pattern, options, cb) {
      -  if (!(this instanceof Glob)) {
      -    return new Glob(pattern, options, cb)
      -  }
      -
      -  if (typeof cb === "function") {
      -    this.on("error", cb)
      -    this.on("end", function (matches) {
      -      cb(null, matches)
      -    })
      -  }
      -
      -  options = options || {}
      -
      -  this.EOF = {}
      -  this._emitQueue = []
      -
      -  this.maxDepth = options.maxDepth || 1000
      -  this.maxLength = options.maxLength || Infinity
      -  this.cache = options.cache || {}
      -  this.statCache = options.statCache || {}
      -
      -  this.changedCwd = false
      -  var cwd = process.cwd()
      -  if (!options.hasOwnProperty("cwd")) this.cwd = cwd
      -  else {
      -    this.cwd = options.cwd
      -    this.changedCwd = path.resolve(options.cwd) !== cwd
      -  }
      -
      -  this.root = options.root || path.resolve(this.cwd, "/")
      -  this.root = path.resolve(this.root)
      -  if (process.platform === "win32")
      -    this.root = this.root.replace(/\\/g, "/")
      -
      -  this.nomount = !!options.nomount
      -
      -  if (!pattern) {
      -    throw new Error("must provide pattern")
      -  }
      -
      -  // base-matching: just use globstar for that.
      -  if (options.matchBase && -1 === pattern.indexOf("/")) {
      -    if (options.noglobstar) {
      -      throw new Error("base matching requires globstar")
      -    }
      -    pattern = "**/" + pattern
      -  }
      -
      -  this.strict = options.strict !== false
      -  this.dot = !!options.dot
      -  this.mark = !!options.mark
      -  this.sync = !!options.sync
      -  this.nounique = !!options.nounique
      -  this.nonull = !!options.nonull
      -  this.nosort = !!options.nosort
      -  this.nocase = !!options.nocase
      -  this.stat = !!options.stat
      -
      -  this.debug = !!options.debug || !!options.globDebug
      -  if (this.debug)
      -    this.log = console.error
      -
      -  this.silent = !!options.silent
      -
      -  var mm = this.minimatch = new Minimatch(pattern, options)
      -  this.options = mm.options
      -  pattern = this.pattern = mm.pattern
      -
      -  this.error = null
      -  this.aborted = false
      -
      -  // list of all the patterns that ** has resolved do, so
      -  // we can avoid visiting multiple times.
      -  this._globstars = {}
      -
      -  EE.call(this)
      -
      -  // process each pattern in the minimatch set
      -  var n = this.minimatch.set.length
      -
      -  // The matches are stored as {: true,...} so that
      -  // duplicates are automagically pruned.
      -  // Later, we do an Object.keys() on these.
      -  // Keep them as a list so we can fill in when nonull is set.
      -  this.matches = new Array(n)
      -
      -  this.minimatch.set.forEach(iterator.bind(this))
      -  function iterator (pattern, i, set) {
      -    this._process(pattern, 0, i, function (er) {
      -      if (er) this.emit("error", er)
      -      if (-- n <= 0) this._finish()
      -    })
      -  }
      -}
      -
      -Glob.prototype.log = function () {}
      -
      -Glob.prototype._finish = function () {
      -  assert(this instanceof Glob)
      -
      -  var nou = this.nounique
      -  , all = nou ? [] : {}
      -
      -  for (var i = 0, l = this.matches.length; i < l; i ++) {
      -    var matches = this.matches[i]
      -    this.log("matches[%d] =", i, matches)
      -    // do like the shell, and spit out the literal glob
      -    if (!matches) {
      -      if (this.nonull) {
      -        var literal = this.minimatch.globSet[i]
      -        if (nou) all.push(literal)
      -        else all[literal] = true
      -      }
      -    } else {
      -      // had matches
      -      var m = Object.keys(matches)
      -      if (nou) all.push.apply(all, m)
      -      else m.forEach(function (m) {
      -        all[m] = true
      -      })
      -    }
      -  }
      -
      -  if (!nou) all = Object.keys(all)
      -
      -  if (!this.nosort) {
      -    all = all.sort(this.nocase ? alphasorti : alphasort)
      -  }
      -
      -  if (this.mark) {
      -    // at *some* point we statted all of these
      -    all = all.map(function (m) {
      -      var sc = this.cache[m]
      -      if (!sc)
      -        return m
      -      var isDir = (Array.isArray(sc) || sc === 2)
      -      if (isDir && m.slice(-1) !== "/") {
      -        return m + "/"
      -      }
      -      if (!isDir && m.slice(-1) === "/") {
      -        return m.replace(/\/+$/, "")
      -      }
      -      return m
      -    }, this)
      -  }
      -
      -  this.log("emitting end", all)
      -
      -  this.EOF = this.found = all
      -  this.emitMatch(this.EOF)
      -}
      -
      -function alphasorti (a, b) {
      -  a = a.toLowerCase()
      -  b = b.toLowerCase()
      -  return alphasort(a, b)
      -}
      -
      -function alphasort (a, b) {
      -  return a > b ? 1 : a < b ? -1 : 0
      -}
      -
      -Glob.prototype.abort = function () {
      -  this.aborted = true
      -  this.emit("abort")
      -}
      -
      -Glob.prototype.pause = function () {
      -  if (this.paused) return
      -  if (this.sync)
      -    this.emit("error", new Error("Can't pause/resume sync glob"))
      -  this.paused = true
      -  this.emit("pause")
      -}
      -
      -Glob.prototype.resume = function () {
      -  if (!this.paused) return
      -  if (this.sync)
      -    this.emit("error", new Error("Can't pause/resume sync glob"))
      -  this.paused = false
      -  this.emit("resume")
      -  this._processEmitQueue()
      -  //process.nextTick(this.emit.bind(this, "resume"))
      -}
      -
      -Glob.prototype.emitMatch = function (m) {
      -  if (!this.stat || this.statCache[m] || m === this.EOF) {
      -    this._emitQueue.push(m)
      -    this._processEmitQueue()
      -  } else {
      -    this._stat(m, function(exists, isDir) {
      -      if (exists) {
      -        this._emitQueue.push(m)
      -        this._processEmitQueue()
      -      }
      -    })
      -  }
      -}
      -
      -Glob.prototype._processEmitQueue = function (m) {
      -  while (!this._processingEmitQueue &&
      -         !this.paused) {
      -    this._processingEmitQueue = true
      -    var m = this._emitQueue.shift()
      -    if (!m) {
      -      this._processingEmitQueue = false
      -      break
      -    }
      -
      -    this.log('emit!', m === this.EOF ? "end" : "match")
      -
      -    this.emit(m === this.EOF ? "end" : "match", m)
      -    this._processingEmitQueue = false
      -  }
      -}
      -
      -Glob.prototype._process = function (pattern, depth, index, cb_) {
      -  assert(this instanceof Glob)
      -
      -  var cb = function cb (er, res) {
      -    assert(this instanceof Glob)
      -    if (this.paused) {
      -      if (!this._processQueue) {
      -        this._processQueue = []
      -        this.once("resume", function () {
      -          var q = this._processQueue
      -          this._processQueue = null
      -          q.forEach(function (cb) { cb() })
      -        })
      -      }
      -      this._processQueue.push(cb_.bind(this, er, res))
      -    } else {
      -      cb_.call(this, er, res)
      -    }
      -  }.bind(this)
      -
      -  if (this.aborted) return cb()
      -
      -  if (depth > this.maxDepth) return cb()
      -
      -  // Get the first [n] parts of pattern that are all strings.
      -  var n = 0
      -  while (typeof pattern[n] === "string") {
      -    n ++
      -  }
      -  // now n is the index of the first one that is *not* a string.
      -
      -  // see if there's anything else
      -  var prefix
      -  switch (n) {
      -    // if not, then this is rather simple
      -    case pattern.length:
      -      prefix = pattern.join("/")
      -      this._stat(prefix, function (exists, isDir) {
      -        // either it's there, or it isn't.
      -        // nothing more to do, either way.
      -        if (exists) {
      -          if (prefix && isAbsolute(prefix) && !this.nomount) {
      -            if (prefix.charAt(0) === "/") {
      -              prefix = path.join(this.root, prefix)
      -            } else {
      -              prefix = path.resolve(this.root, prefix)
      -            }
      -          }
      -
      -          if (process.platform === "win32")
      -            prefix = prefix.replace(/\\/g, "/")
      -
      -          this.matches[index] = this.matches[index] || {}
      -          this.matches[index][prefix] = true
      -          this.emitMatch(prefix)
      -        }
      -        return cb()
      -      })
      -      return
      -
      -    case 0:
      -      // pattern *starts* with some non-trivial item.
      -      // going to readdir(cwd), but not include the prefix in matches.
      -      prefix = null
      -      break
      -
      -    default:
      -      // pattern has some string bits in the front.
      -      // whatever it starts with, whether that's "absolute" like /foo/bar,
      -      // or "relative" like "../baz"
      -      prefix = pattern.slice(0, n)
      -      prefix = prefix.join("/")
      -      break
      -  }
      -
      -  // get the list of entries.
      -  var read
      -  if (prefix === null) read = "."
      -  else if (isAbsolute(prefix) || isAbsolute(pattern.join("/"))) {
      -    if (!prefix || !isAbsolute(prefix)) {
      -      prefix = path.join("/", prefix)
      -    }
      -    read = prefix = path.resolve(prefix)
      -
      -    // if (process.platform === "win32")
      -    //   read = prefix = prefix.replace(/^[a-zA-Z]:|\\/g, "/")
      -
      -    this.log('absolute: ', prefix, this.root, pattern, read)
      -  } else {
      -    read = prefix
      -  }
      -
      -  this.log('readdir(%j)', read, this.cwd, this.root)
      -
      -  return this._readdir(read, function (er, entries) {
      -    if (er) {
      -      // not a directory!
      -      // this means that, whatever else comes after this, it can never match
      -      return cb()
      -    }
      -
      -    // globstar is special
      -    if (pattern[n] === minimatch.GLOBSTAR) {
      -      // test without the globstar, and with every child both below
      -      // and replacing the globstar.
      -      var s = [ pattern.slice(0, n).concat(pattern.slice(n + 1)) ]
      -      entries.forEach(function (e) {
      -        if (e.charAt(0) === "." && !this.dot) return
      -        // instead of the globstar
      -        s.push(pattern.slice(0, n).concat(e).concat(pattern.slice(n + 1)))
      -        // below the globstar
      -        s.push(pattern.slice(0, n).concat(e).concat(pattern.slice(n)))
      -      }, this)
      -
      -      s = s.filter(function (pattern) {
      -        var key = gsKey(pattern)
      -        var seen = !this._globstars[key]
      -        this._globstars[key] = true
      -        return seen
      -      }, this)
      -
      -      if (!s.length)
      -        return cb()
      -
      -      // now asyncForEach over this
      -      var l = s.length
      -      , errState = null
      -      s.forEach(function (gsPattern) {
      -        this._process(gsPattern, depth + 1, index, function (er) {
      -          if (errState) return
      -          if (er) return cb(errState = er)
      -          if (--l <= 0) return cb()
      -        })
      -      }, this)
      -
      -      return
      -    }
      -
      -    // not a globstar
      -    // It will only match dot entries if it starts with a dot, or if
      -    // dot is set.  Stuff like @(.foo|.bar) isn't allowed.
      -    var pn = pattern[n]
      -    var rawGlob = pattern[n]._glob
      -    , dotOk = this.dot || rawGlob.charAt(0) === "."
      -
      -    entries = entries.filter(function (e) {
      -      return (e.charAt(0) !== "." || dotOk) &&
      -             e.match(pattern[n])
      -    })
      -
      -    // If n === pattern.length - 1, then there's no need for the extra stat
      -    // *unless* the user has specified "mark" or "stat" explicitly.
      -    // We know that they exist, since the readdir returned them.
      -    if (n === pattern.length - 1 &&
      -        !this.mark &&
      -        !this.stat) {
      -      entries.forEach(function (e) {
      -        if (prefix) {
      -          if (prefix !== "/") e = prefix + "/" + e
      -          else e = prefix + e
      -        }
      -        if (e.charAt(0) === "/" && !this.nomount) {
      -          e = path.join(this.root, e)
      -        }
      -
      -        if (process.platform === "win32")
      -          e = e.replace(/\\/g, "/")
      -
      -        this.matches[index] = this.matches[index] || {}
      -        this.matches[index][e] = true
      -        this.emitMatch(e)
      -      }, this)
      -      return cb.call(this)
      -    }
      -
      -
      -    // now test all the remaining entries as stand-ins for that part
      -    // of the pattern.
      -    var l = entries.length
      -    , errState = null
      -    if (l === 0) return cb() // no matches possible
      -    entries.forEach(function (e) {
      -      var p = pattern.slice(0, n).concat(e).concat(pattern.slice(n + 1))
      -      this._process(p, depth + 1, index, function (er) {
      -        if (errState) return
      -        if (er) return cb(errState = er)
      -        if (--l === 0) return cb.call(this)
      -      })
      -    }, this)
      -  })
      -
      -}
      -
      -function gsKey (pattern) {
      -  return '**' + pattern.map(function (p) {
      -    return (p === minimatch.GLOBSTAR) ? '**' : (''+p)
      -  }).join('/')
      -}
      -
      -Glob.prototype._stat = function (f, cb) {
      -  assert(this instanceof Glob)
      -  var abs = f
      -  if (f.charAt(0) === "/") {
      -    abs = path.join(this.root, f)
      -  } else if (this.changedCwd) {
      -    abs = path.resolve(this.cwd, f)
      -  }
      -
      -  if (f.length > this.maxLength) {
      -    var er = new Error("Path name too long")
      -    er.code = "ENAMETOOLONG"
      -    er.path = f
      -    return this._afterStat(f, abs, cb, er)
      -  }
      -
      -  this.log('stat', [this.cwd, f, '=', abs])
      -
      -  if (!this.stat && this.cache.hasOwnProperty(f)) {
      -    var exists = this.cache[f]
      -    , isDir = exists && (Array.isArray(exists) || exists === 2)
      -    if (this.sync) return cb.call(this, !!exists, isDir)
      -    return process.nextTick(cb.bind(this, !!exists, isDir))
      -  }
      -
      -  var stat = this.statCache[abs]
      -  if (this.sync || stat) {
      -    var er
      -    try {
      -      stat = fs.statSync(abs)
      -    } catch (e) {
      -      er = e
      -    }
      -    this._afterStat(f, abs, cb, er, stat)
      -  } else {
      -    fs.stat(abs, this._afterStat.bind(this, f, abs, cb))
      -  }
      -}
      -
      -Glob.prototype._afterStat = function (f, abs, cb, er, stat) {
      -  var exists
      -  assert(this instanceof Glob)
      -
      -  if (abs.slice(-1) === "/" && stat && !stat.isDirectory()) {
      -    this.log("should be ENOTDIR, fake it")
      -
      -    er = new Error("ENOTDIR, not a directory '" + abs + "'")
      -    er.path = abs
      -    er.code = "ENOTDIR"
      -    stat = null
      -  }
      -
      -  var emit = !this.statCache[abs]
      -  this.statCache[abs] = stat
      -
      -  if (er || !stat) {
      -    exists = false
      -  } else {
      -    exists = stat.isDirectory() ? 2 : 1
      -    if (emit)
      -      this.emit('stat', f, stat)
      -  }
      -  this.cache[f] = this.cache[f] || exists
      -  cb.call(this, !!exists, exists === 2)
      -}
      -
      -Glob.prototype._readdir = function (f, cb) {
      -  assert(this instanceof Glob)
      -  var abs = f
      -  if (f.charAt(0) === "/") {
      -    abs = path.join(this.root, f)
      -  } else if (isAbsolute(f)) {
      -    abs = f
      -  } else if (this.changedCwd) {
      -    abs = path.resolve(this.cwd, f)
      -  }
      -
      -  if (f.length > this.maxLength) {
      -    var er = new Error("Path name too long")
      -    er.code = "ENAMETOOLONG"
      -    er.path = f
      -    return this._afterReaddir(f, abs, cb, er)
      -  }
      -
      -  this.log('readdir', [this.cwd, f, abs])
      -  if (this.cache.hasOwnProperty(f)) {
      -    var c = this.cache[f]
      -    if (Array.isArray(c)) {
      -      if (this.sync) return cb.call(this, null, c)
      -      return process.nextTick(cb.bind(this, null, c))
      -    }
      -
      -    if (!c || c === 1) {
      -      // either ENOENT or ENOTDIR
      -      var code = c ? "ENOTDIR" : "ENOENT"
      -      , er = new Error((c ? "Not a directory" : "Not found") + ": " + f)
      -      er.path = f
      -      er.code = code
      -      this.log(f, er)
      -      if (this.sync) return cb.call(this, er)
      -      return process.nextTick(cb.bind(this, er))
      -    }
      -
      -    // at this point, c === 2, meaning it's a dir, but we haven't
      -    // had to read it yet, or c === true, meaning it's *something*
      -    // but we don't have any idea what.  Need to read it, either way.
      -  }
      -
      -  if (this.sync) {
      -    var er, entries
      -    try {
      -      entries = fs.readdirSync(abs)
      -    } catch (e) {
      -      er = e
      -    }
      -    return this._afterReaddir(f, abs, cb, er, entries)
      -  }
      -
      -  fs.readdir(abs, this._afterReaddir.bind(this, f, abs, cb))
      -}
      -
      -Glob.prototype._afterReaddir = function (f, abs, cb, er, entries) {
      -  assert(this instanceof Glob)
      -  if (entries && !er) {
      -    this.cache[f] = entries
      -    // if we haven't asked to stat everything for suresies, then just
      -    // assume that everything in there exists, so we can avoid
      -    // having to stat it a second time.  This also gets us one step
      -    // further into ELOOP territory.
      -    if (!this.mark && !this.stat) {
      -      entries.forEach(function (e) {
      -        if (f === "/") e = f + e
      -        else e = f + "/" + e
      -        this.cache[e] = true
      -      }, this)
      -    }
      -
      -    return cb.call(this, er, entries)
      -  }
      -
      -  // now handle errors, and cache the information
      -  if (er) switch (er.code) {
      -    case "ENOTDIR": // totally normal. means it *does* exist.
      -      this.cache[f] = 1
      -      return cb.call(this, er)
      -    case "ENOENT": // not terribly unusual
      -    case "ELOOP":
      -    case "ENAMETOOLONG":
      -    case "UNKNOWN":
      -      this.cache[f] = false
      -      return cb.call(this, er)
      -    default: // some unusual error.  Treat as failure.
      -      this.cache[f] = false
      -      if (this.strict) this.emit("error", er)
      -      if (!this.silent) console.error("glob error", er)
      -      return cb.call(this, er)
      -  }
      -}
      -
      -var isAbsolute = process.platform === "win32" ? absWin : absUnix
      -
      -function absWin (p) {
      -  if (absUnix(p)) return true
      -  // pull off the device/UNC bit from a windows path.
      -  // from node's lib/path.js
      -  var splitDeviceRe =
      -      /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/
      -    , result = splitDeviceRe.exec(p)
      -    , device = result[1] || ''
      -    , isUnc = device && device.charAt(1) !== ':'
      -    , isAbsolute = !!result[2] || isUnc // UNC paths are always absolute
      -
      -  return isAbsolute
      -}
      -
      -function absUnix (p) {
      -  return p.charAt(0) === "/" || p === ""
      -}
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/.npmignore b/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/.npmignore
      deleted file mode 100644
      index c2658d7..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/.npmignore
      +++ /dev/null
      @@ -1 +0,0 @@
      -node_modules/
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/LICENSE b/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/LICENSE
      deleted file mode 100644
      index 0c44ae7..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/LICENSE
      +++ /dev/null
      @@ -1,27 +0,0 @@
      -Copyright (c) Isaac Z. Schlueter ("Author")
      -All rights reserved.
      -
      -The BSD License
      -
      -Redistribution and use in source and binary forms, with or without
      -modification, are permitted provided that the following conditions
      -are met:
      -
      -1. Redistributions of source code must retain the above copyright
      -   notice, this list of conditions and the following disclaimer.
      -
      -2. 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.
      -
      -THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/README.md b/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/README.md
      deleted file mode 100644
      index eb1a109..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/README.md
      +++ /dev/null
      @@ -1,26 +0,0 @@
      -# graceful-fs
      -
      -graceful-fs functions as a drop-in replacement for the fs module,
      -making various improvements.
      -
      -The improvements are meant to normalize behavior across different
      -platforms and environments, and to make filesystem access more
      -resilient to errors.
      -
      -## Improvements over fs module
      -
      -graceful-fs:
      -
      -* Queues up `open` and `readdir` calls, and retries them once
      -  something closes if there is an EMFILE error from too many file
      -  descriptors.
      -* fixes `lchmod` for Node versions prior to 0.6.2.
      -* implements `fs.lutimes` if possible. Otherwise it becomes a noop.
      -* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or
      -  `lchown` if the user isn't root.
      -* makes `lchmod` and `lchown` become noops, if not available.
      -* retries reading a file if `read` results in EAGAIN error.
      -
      -On Windows, it retries renaming a file for up to one second if `EACCESS`
      -or `EPERM` error occurs, likely because antivirus software has locked
      -the directory.
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/graceful-fs.js b/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/graceful-fs.js
      deleted file mode 100644
      index c84db91..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/graceful-fs.js
      +++ /dev/null
      @@ -1,160 +0,0 @@
      -// Monkey-patching the fs module.
      -// It's ugly, but there is simply no other way to do this.
      -var fs = module.exports = require('fs')
      -
      -var assert = require('assert')
      -
      -// fix up some busted stuff, mostly on windows and old nodes
      -require('./polyfills.js')
      -
      -// The EMFILE enqueuing stuff
      -
      -var util = require('util')
      -
      -function noop () {}
      -
      -var debug = noop
      -if (util.debuglog)
      -  debug = util.debuglog('gfs')
      -else if (/\bgfs\b/i.test(process.env.NODE_DEBUG || ''))
      -  debug = function() {
      -    var m = util.format.apply(util, arguments)
      -    m = 'GFS: ' + m.split(/\n/).join('\nGFS: ')
      -    console.error(m)
      -  }
      -
      -if (/\bgfs\b/i.test(process.env.NODE_DEBUG || '')) {
      -  process.on('exit', function() {
      -    debug('fds', fds)
      -    debug(queue)
      -    assert.equal(queue.length, 0)
      -  })
      -}
      -
      -
      -var originalOpen = fs.open
      -fs.open = open
      -
      -function open(path, flags, mode, cb) {
      -  if (typeof mode === "function") cb = mode, mode = null
      -  if (typeof cb !== "function") cb = noop
      -  new OpenReq(path, flags, mode, cb)
      -}
      -
      -function OpenReq(path, flags, mode, cb) {
      -  this.path = path
      -  this.flags = flags
      -  this.mode = mode
      -  this.cb = cb
      -  Req.call(this)
      -}
      -
      -util.inherits(OpenReq, Req)
      -
      -OpenReq.prototype.process = function() {
      -  originalOpen.call(fs, this.path, this.flags, this.mode, this.done)
      -}
      -
      -var fds = {}
      -OpenReq.prototype.done = function(er, fd) {
      -  debug('open done', er, fd)
      -  if (fd)
      -    fds['fd' + fd] = this.path
      -  Req.prototype.done.call(this, er, fd)
      -}
      -
      -
      -var originalReaddir = fs.readdir
      -fs.readdir = readdir
      -
      -function readdir(path, cb) {
      -  if (typeof cb !== "function") cb = noop
      -  new ReaddirReq(path, cb)
      -}
      -
      -function ReaddirReq(path, cb) {
      -  this.path = path
      -  this.cb = cb
      -  Req.call(this)
      -}
      -
      -util.inherits(ReaddirReq, Req)
      -
      -ReaddirReq.prototype.process = function() {
      -  originalReaddir.call(fs, this.path, this.done)
      -}
      -
      -ReaddirReq.prototype.done = function(er, files) {
      -  if (files && files.sort)
      -    files = files.sort()
      -  Req.prototype.done.call(this, er, files)
      -  onclose()
      -}
      -
      -
      -var originalClose = fs.close
      -fs.close = close
      -
      -function close (fd, cb) {
      -  debug('close', fd)
      -  if (typeof cb !== "function") cb = noop
      -  delete fds['fd' + fd]
      -  originalClose.call(fs, fd, function(er) {
      -    onclose()
      -    cb(er)
      -  })
      -}
      -
      -
      -var originalCloseSync = fs.closeSync
      -fs.closeSync = closeSync
      -
      -function closeSync (fd) {
      -  try {
      -    return originalCloseSync(fd)
      -  } finally {
      -    onclose()
      -  }
      -}
      -
      -
      -// Req class
      -function Req () {
      -  // start processing
      -  this.done = this.done.bind(this)
      -  this.failures = 0
      -  this.process()
      -}
      -
      -Req.prototype.done = function (er, result) {
      -  var tryAgain = false
      -  if (er) {
      -    var code = er.code
      -    var tryAgain = code === "EMFILE"
      -    if (process.platform === "win32")
      -      tryAgain = tryAgain || code === "OK"
      -  }
      -
      -  if (tryAgain) {
      -    this.failures ++
      -    enqueue(this)
      -  } else {
      -    var cb = this.cb
      -    cb(er, result)
      -  }
      -}
      -
      -var queue = []
      -
      -function enqueue(req) {
      -  queue.push(req)
      -  debug('enqueue %d %s', queue.length, req.constructor.name, req)
      -}
      -
      -function onclose() {
      -  var req = queue.shift()
      -  if (req) {
      -    debug('process', req.constructor.name, req)
      -    req.process()
      -  }
      -}
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/package.json b/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/package.json
      deleted file mode 100644
      index dc22856..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/package.json
      +++ /dev/null
      @@ -1,65 +0,0 @@
      -{
      -  "author": {
      -    "name": "Isaac Z. Schlueter",
      -    "email": "i@izs.me",
      -    "url": "http://blog.izs.me"
      -  },
      -  "name": "graceful-fs",
      -  "description": "A drop-in replacement for fs, making various improvements.",
      -  "version": "2.0.3",
      -  "repository": {
      -    "type": "git",
      -    "url": "git://github.com/isaacs/node-graceful-fs.git"
      -  },
      -  "main": "graceful-fs.js",
      -  "engines": {
      -    "node": ">=0.4.0"
      -  },
      -  "directories": {
      -    "test": "test"
      -  },
      -  "scripts": {
      -    "test": "tap test/*.js"
      -  },
      -  "keywords": [
      -    "fs",
      -    "module",
      -    "reading",
      -    "retry",
      -    "retries",
      -    "queue",
      -    "error",
      -    "errors",
      -    "handling",
      -    "EMFILE",
      -    "EAGAIN",
      -    "EINVAL",
      -    "EPERM",
      -    "EACCESS"
      -  ],
      -  "license": "BSD",
      -  "bugs": {
      -    "url": "https://github.com/isaacs/node-graceful-fs/issues"
      -  },
      -  "homepage": "https://github.com/isaacs/node-graceful-fs",
      -  "_id": "graceful-fs@2.0.3",
      -  "dist": {
      -    "shasum": "7cd2cdb228a4a3f36e95efa6cc142de7d1a136d0",
      -    "tarball": "http://registry.npmjs.org/graceful-fs/-/graceful-fs-2.0.3.tgz"
      -  },
      -  "_from": "graceful-fs@~2.0.0",
      -  "_npmVersion": "1.4.6",
      -  "_npmUser": {
      -    "name": "isaacs",
      -    "email": "i@izs.me"
      -  },
      -  "maintainers": [
      -    {
      -      "name": "isaacs",
      -      "email": "i@izs.me"
      -    }
      -  ],
      -  "_shasum": "7cd2cdb228a4a3f36e95efa6cc142de7d1a136d0",
      -  "_resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-2.0.3.tgz",
      -  "readme": "ERROR: No README data found!"
      -}
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/polyfills.js b/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/polyfills.js
      deleted file mode 100644
      index afc83b3..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/polyfills.js
      +++ /dev/null
      @@ -1,228 +0,0 @@
      -var fs = require('fs')
      -var constants = require('constants')
      -
      -var origCwd = process.cwd
      -var cwd = null
      -process.cwd = function() {
      -  if (!cwd)
      -    cwd = origCwd.call(process)
      -  return cwd
      -}
      -var chdir = process.chdir
      -process.chdir = function(d) {
      -  cwd = null
      -  chdir.call(process, d)
      -}
      -
      -// (re-)implement some things that are known busted or missing.
      -
      -// lchmod, broken prior to 0.6.2
      -// back-port the fix here.
      -if (constants.hasOwnProperty('O_SYMLINK') &&
      -    process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
      -  fs.lchmod = function (path, mode, callback) {
      -    callback = callback || noop
      -    fs.open( path
      -           , constants.O_WRONLY | constants.O_SYMLINK
      -           , mode
      -           , function (err, fd) {
      -      if (err) {
      -        callback(err)
      -        return
      -      }
      -      // prefer to return the chmod error, if one occurs,
      -      // but still try to close, and report closing errors if they occur.
      -      fs.fchmod(fd, mode, function (err) {
      -        fs.close(fd, function(err2) {
      -          callback(err || err2)
      -        })
      -      })
      -    })
      -  }
      -
      -  fs.lchmodSync = function (path, mode) {
      -    var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)
      -
      -    // prefer to return the chmod error, if one occurs,
      -    // but still try to close, and report closing errors if they occur.
      -    var err, err2
      -    try {
      -      var ret = fs.fchmodSync(fd, mode)
      -    } catch (er) {
      -      err = er
      -    }
      -    try {
      -      fs.closeSync(fd)
      -    } catch (er) {
      -      err2 = er
      -    }
      -    if (err || err2) throw (err || err2)
      -    return ret
      -  }
      -}
      -
      -
      -// lutimes implementation, or no-op
      -if (!fs.lutimes) {
      -  if (constants.hasOwnProperty("O_SYMLINK")) {
      -    fs.lutimes = function (path, at, mt, cb) {
      -      fs.open(path, constants.O_SYMLINK, function (er, fd) {
      -        cb = cb || noop
      -        if (er) return cb(er)
      -        fs.futimes(fd, at, mt, function (er) {
      -          fs.close(fd, function (er2) {
      -            return cb(er || er2)
      -          })
      -        })
      -      })
      -    }
      -
      -    fs.lutimesSync = function (path, at, mt) {
      -      var fd = fs.openSync(path, constants.O_SYMLINK)
      -        , err
      -        , err2
      -        , ret
      -
      -      try {
      -        var ret = fs.futimesSync(fd, at, mt)
      -      } catch (er) {
      -        err = er
      -      }
      -      try {
      -        fs.closeSync(fd)
      -      } catch (er) {
      -        err2 = er
      -      }
      -      if (err || err2) throw (err || err2)
      -      return ret
      -    }
      -
      -  } else if (fs.utimensat && constants.hasOwnProperty("AT_SYMLINK_NOFOLLOW")) {
      -    // maybe utimensat will be bound soonish?
      -    fs.lutimes = function (path, at, mt, cb) {
      -      fs.utimensat(path, at, mt, constants.AT_SYMLINK_NOFOLLOW, cb)
      -    }
      -
      -    fs.lutimesSync = function (path, at, mt) {
      -      return fs.utimensatSync(path, at, mt, constants.AT_SYMLINK_NOFOLLOW)
      -    }
      -
      -  } else {
      -    fs.lutimes = function (_a, _b, _c, cb) { process.nextTick(cb) }
      -    fs.lutimesSync = function () {}
      -  }
      -}
      -
      -
      -// https://github.com/isaacs/node-graceful-fs/issues/4
      -// Chown should not fail on einval or eperm if non-root.
      -
      -fs.chown = chownFix(fs.chown)
      -fs.fchown = chownFix(fs.fchown)
      -fs.lchown = chownFix(fs.lchown)
      -
      -fs.chownSync = chownFixSync(fs.chownSync)
      -fs.fchownSync = chownFixSync(fs.fchownSync)
      -fs.lchownSync = chownFixSync(fs.lchownSync)
      -
      -function chownFix (orig) {
      -  if (!orig) return orig
      -  return function (target, uid, gid, cb) {
      -    return orig.call(fs, target, uid, gid, function (er, res) {
      -      if (chownErOk(er)) er = null
      -      cb(er, res)
      -    })
      -  }
      -}
      -
      -function chownFixSync (orig) {
      -  if (!orig) return orig
      -  return function (target, uid, gid) {
      -    try {
      -      return orig.call(fs, target, uid, gid)
      -    } catch (er) {
      -      if (!chownErOk(er)) throw er
      -    }
      -  }
      -}
      -
      -function chownErOk (er) {
      -  // if there's no getuid, or if getuid() is something other than 0,
      -  // and the error is EINVAL or EPERM, then just ignore it.
      -  // This specific case is a silent failure in cp, install, tar,
      -  // and most other unix tools that manage permissions.
      -  // When running as root, or if other types of errors are encountered,
      -  // then it's strict.
      -  if (!er || (!process.getuid || process.getuid() !== 0)
      -      && (er.code === "EINVAL" || er.code === "EPERM")) return true
      -}
      -
      -
      -// if lchmod/lchown do not exist, then make them no-ops
      -if (!fs.lchmod) {
      -  fs.lchmod = function (path, mode, cb) {
      -    process.nextTick(cb)
      -  }
      -  fs.lchmodSync = function () {}
      -}
      -if (!fs.lchown) {
      -  fs.lchown = function (path, uid, gid, cb) {
      -    process.nextTick(cb)
      -  }
      -  fs.lchownSync = function () {}
      -}
      -
      -
      -
      -// on Windows, A/V software can lock the directory, causing this
      -// to fail with an EACCES or EPERM if the directory contains newly
      -// created files.  Try again on failure, for up to 1 second.
      -if (process.platform === "win32") {
      -  var rename_ = fs.rename
      -  fs.rename = function rename (from, to, cb) {
      -    var start = Date.now()
      -    rename_(from, to, function CB (er) {
      -      if (er
      -          && (er.code === "EACCES" || er.code === "EPERM")
      -          && Date.now() - start < 1000) {
      -        return rename_(from, to, CB)
      -      }
      -      cb(er)
      -    })
      -  }
      -}
      -
      -
      -// if read() returns EAGAIN, then just try it again.
      -var read = fs.read
      -fs.read = function (fd, buffer, offset, length, position, callback_) {
      -  var callback
      -  if (callback_ && typeof callback_ === 'function') {
      -    var eagCounter = 0
      -    callback = function (er, _, __) {
      -      if (er && er.code === 'EAGAIN' && eagCounter < 10) {
      -        eagCounter ++
      -        return read.call(fs, fd, buffer, offset, length, position, callback)
      -      }
      -      callback_.apply(this, arguments)
      -    }
      -  }
      -  return read.call(fs, fd, buffer, offset, length, position, callback)
      -}
      -
      -var readSync = fs.readSync
      -fs.readSync = function (fd, buffer, offset, length, position) {
      -  var eagCounter = 0
      -  while (true) {
      -    try {
      -      return readSync.call(fs, fd, buffer, offset, length, position)
      -    } catch (er) {
      -      if (er.code === 'EAGAIN' && eagCounter < 10) {
      -        eagCounter ++
      -        continue
      -      }
      -      throw er
      -    }
      -  }
      -}
      -
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/test/open.js b/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/test/open.js
      deleted file mode 100644
      index 104f36b..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/test/open.js
      +++ /dev/null
      @@ -1,39 +0,0 @@
      -var test = require('tap').test
      -var fs = require('../graceful-fs.js')
      -
      -test('graceful fs is monkeypatched fs', function (t) {
      -  t.equal(fs, require('fs'))
      -  t.end()
      -})
      -
      -test('open an existing file works', function (t) {
      -  var fd = fs.openSync(__filename, 'r')
      -  fs.closeSync(fd)
      -  fs.open(__filename, 'r', function (er, fd) {
      -    if (er) throw er
      -    fs.close(fd, function (er) {
      -      if (er) throw er
      -      t.pass('works')
      -      t.end()
      -    })
      -  })
      -})
      -
      -test('open a non-existing file throws', function (t) {
      -  var er
      -  try {
      -    var fd = fs.openSync('this file does not exist', 'r')
      -  } catch (x) {
      -    er = x
      -  }
      -  t.ok(er, 'should throw')
      -  t.notOk(fd, 'should not get an fd')
      -  t.equal(er.code, 'ENOENT')
      -
      -  fs.open('neither does this file', 'r', function (er, fd) {
      -    t.ok(er, 'should throw')
      -    t.notOk(fd, 'should not get an fd')
      -    t.equal(er.code, 'ENOENT')
      -    t.end()
      -  })
      -})
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/test/readdir-sort.js b/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/test/readdir-sort.js
      deleted file mode 100644
      index aeaedf1..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/graceful-fs/test/readdir-sort.js
      +++ /dev/null
      @@ -1,21 +0,0 @@
      -var test = require("tap").test
      -var fs = require("fs")
      -
      -var readdir = fs.readdir
      -fs.readdir = function(path, cb) {
      -  process.nextTick(function() {
      -    cb(null, ["b", "z", "a"])
      -  })
      -}
      -
      -var g = require("../")
      -
      -test("readdir reorder", function (t) {
      -  g.readdir("whatevers", function (er, files) {
      -    if (er)
      -      throw er
      -    console.error(files)
      -    t.same(files, [ "a", "b", "z" ])
      -    t.end()
      -  })
      -})
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/inherits/LICENSE b/node_modules/mocha/node_modules/glob/node_modules/inherits/LICENSE
      deleted file mode 100644
      index dea3013..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/inherits/LICENSE
      +++ /dev/null
      @@ -1,16 +0,0 @@
      -The ISC License
      -
      -Copyright (c) Isaac Z. Schlueter
      -
      -Permission to use, copy, modify, and/or distribute this software for any
      -purpose with or without fee is hereby granted, provided that the above
      -copyright notice and this permission notice appear in all copies.
      -
      -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
      -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
      -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
      -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
      -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
      -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
      -PERFORMANCE OF THIS SOFTWARE.
      -
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/inherits/README.md b/node_modules/mocha/node_modules/glob/node_modules/inherits/README.md
      deleted file mode 100644
      index b1c5665..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/inherits/README.md
      +++ /dev/null
      @@ -1,42 +0,0 @@
      -Browser-friendly inheritance fully compatible with standard node.js
      -[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).
      -
      -This package exports standard `inherits` from node.js `util` module in
      -node environment, but also provides alternative browser-friendly
      -implementation through [browser
      -field](https://gist.github.com/shtylman/4339901). Alternative
      -implementation is a literal copy of standard one located in standalone
      -module to avoid requiring of `util`. It also has a shim for old
      -browsers with no `Object.create` support.
      -
      -While keeping you sure you are using standard `inherits`
      -implementation in node.js environment, it allows bundlers such as
      -[browserify](https://github.com/substack/node-browserify) to not
      -include full `util` package to your client code if all you need is
      -just `inherits` function. It worth, because browser shim for `util`
      -package is large and `inherits` is often the single function you need
      -from it.
      -
      -It's recommended to use this package instead of
      -`require('util').inherits` for any code that has chances to be used
      -not only in node.js but in browser too.
      -
      -## usage
      -
      -```js
      -var inherits = require('inherits');
      -// then use exactly as the standard one
      -```
      -
      -## note on version ~1.0
      -
      -Version ~1.0 had completely different motivation and is not compatible
      -neither with 2.0 nor with standard node.js `inherits`.
      -
      -If you are using version ~1.0 and planning to switch to ~2.0, be
      -careful:
      -
      -* new version uses `super_` instead of `super` for referencing
      -  superclass
      -* new version overwrites current prototype while old one preserves any
      -  existing fields on it
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/inherits/inherits.js b/node_modules/mocha/node_modules/glob/node_modules/inherits/inherits.js
      deleted file mode 100644
      index 29f5e24..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/inherits/inherits.js
      +++ /dev/null
      @@ -1 +0,0 @@
      -module.exports = require('util').inherits
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/inherits/inherits_browser.js b/node_modules/mocha/node_modules/glob/node_modules/inherits/inherits_browser.js
      deleted file mode 100644
      index c1e78a7..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/inherits/inherits_browser.js
      +++ /dev/null
      @@ -1,23 +0,0 @@
      -if (typeof Object.create === 'function') {
      -  // implementation from standard node.js 'util' module
      -  module.exports = function inherits(ctor, superCtor) {
      -    ctor.super_ = superCtor
      -    ctor.prototype = Object.create(superCtor.prototype, {
      -      constructor: {
      -        value: ctor,
      -        enumerable: false,
      -        writable: true,
      -        configurable: true
      -      }
      -    });
      -  };
      -} else {
      -  // old school shim for old browsers
      -  module.exports = function inherits(ctor, superCtor) {
      -    ctor.super_ = superCtor
      -    var TempCtor = function () {}
      -    TempCtor.prototype = superCtor.prototype
      -    ctor.prototype = new TempCtor()
      -    ctor.prototype.constructor = ctor
      -  }
      -}
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/inherits/package.json b/node_modules/mocha/node_modules/glob/node_modules/inherits/package.json
      deleted file mode 100644
      index 4b9c2a1..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/inherits/package.json
      +++ /dev/null
      @@ -1,51 +0,0 @@
      -{
      -  "name": "inherits",
      -  "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()",
      -  "version": "2.0.1",
      -  "keywords": [
      -    "inheritance",
      -    "class",
      -    "klass",
      -    "oop",
      -    "object-oriented",
      -    "inherits",
      -    "browser",
      -    "browserify"
      -  ],
      -  "main": "./inherits.js",
      -  "browser": "./inherits_browser.js",
      -  "repository": {
      -    "type": "git",
      -    "url": "git://github.com/isaacs/inherits"
      -  },
      -  "license": "ISC",
      -  "scripts": {
      -    "test": "node test"
      -  },
      -  "bugs": {
      -    "url": "https://github.com/isaacs/inherits/issues"
      -  },
      -  "_id": "inherits@2.0.1",
      -  "dist": {
      -    "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1",
      -    "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz"
      -  },
      -  "_from": "inherits@2",
      -  "_npmVersion": "1.3.8",
      -  "_npmUser": {
      -    "name": "isaacs",
      -    "email": "i@izs.me"
      -  },
      -  "maintainers": [
      -    {
      -      "name": "isaacs",
      -      "email": "i@izs.me"
      -    }
      -  ],
      -  "directories": {},
      -  "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1",
      -  "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz",
      -  "readme": "Browser-friendly inheritance fully compatible with standard node.js\n[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).\n\nThis package exports standard `inherits` from node.js `util` module in\nnode environment, but also provides alternative browser-friendly\nimplementation through [browser\nfield](https://gist.github.com/shtylman/4339901). Alternative\nimplementation is a literal copy of standard one located in standalone\nmodule to avoid requiring of `util`. It also has a shim for old\nbrowsers with no `Object.create` support.\n\nWhile keeping you sure you are using standard `inherits`\nimplementation in node.js environment, it allows bundlers such as\n[browserify](https://github.com/substack/node-browserify) to not\ninclude full `util` package to your client code if all you need is\njust `inherits` function. It worth, because browser shim for `util`\npackage is large and `inherits` is often the single function you need\nfrom it.\n\nIt's recommended to use this package instead of\n`require('util').inherits` for any code that has chances to be used\nnot only in node.js but in browser too.\n\n## usage\n\n```js\nvar inherits = require('inherits');\n// then use exactly as the standard one\n```\n\n## note on version ~1.0\n\nVersion ~1.0 had completely different motivation and is not compatible\nneither with 2.0 nor with standard node.js `inherits`.\n\nIf you are using version ~1.0 and planning to switch to ~2.0, be\ncareful:\n\n* new version uses `super_` instead of `super` for referencing\n  superclass\n* new version overwrites current prototype while old one preserves any\n  existing fields on it\n",
      -  "readmeFilename": "README.md",
      -  "homepage": "https://github.com/isaacs/inherits"
      -}
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/inherits/test.js b/node_modules/mocha/node_modules/glob/node_modules/inherits/test.js
      deleted file mode 100644
      index fc53012..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/inherits/test.js
      +++ /dev/null
      @@ -1,25 +0,0 @@
      -var inherits = require('./inherits.js')
      -var assert = require('assert')
      -
      -function test(c) {
      -  assert(c.constructor === Child)
      -  assert(c.constructor.super_ === Parent)
      -  assert(Object.getPrototypeOf(c) === Child.prototype)
      -  assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype)
      -  assert(c instanceof Child)
      -  assert(c instanceof Parent)
      -}
      -
      -function Child() {
      -  Parent.call(this)
      -  test(this)
      -}
      -
      -function Parent() {}
      -
      -inherits(Child, Parent)
      -
      -var c = new Child
      -test(c)
      -
      -console.log('ok')
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/.npmignore b/node_modules/mocha/node_modules/glob/node_modules/minimatch/.npmignore
      deleted file mode 100644
      index 3c3629e..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/.npmignore
      +++ /dev/null
      @@ -1 +0,0 @@
      -node_modules
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/LICENSE b/node_modules/mocha/node_modules/glob/node_modules/minimatch/LICENSE
      deleted file mode 100644
      index 05a4010..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/LICENSE
      +++ /dev/null
      @@ -1,23 +0,0 @@
      -Copyright 2009, 2010, 2011 Isaac Z. Schlueter.
      -All rights reserved.
      -
      -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/node_modules/mocha/node_modules/glob/node_modules/minimatch/README.md b/node_modules/mocha/node_modules/glob/node_modules/minimatch/README.md
      deleted file mode 100644
      index 978268e..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/README.md
      +++ /dev/null
      @@ -1,218 +0,0 @@
      -# minimatch
      -
      -A minimal matching utility.
      -
      -[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch)
      -
      -
      -This is the matching library used internally by npm.
      -
      -Eventually, it will replace the C binding in node-glob.
      -
      -It works by converting glob expressions into JavaScript `RegExp`
      -objects.
      -
      -## Usage
      -
      -```javascript
      -var minimatch = require("minimatch")
      -
      -minimatch("bar.foo", "*.foo") // true!
      -minimatch("bar.foo", "*.bar") // false!
      -minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy!
      -```
      -
      -## Features
      -
      -Supports these glob features:
      -
      -* Brace Expansion
      -* Extended glob matching
      -* "Globstar" `**` matching
      -
      -See:
      -
      -* `man sh`
      -* `man bash`
      -* `man 3 fnmatch`
      -* `man 5 gitignore`
      -
      -## Minimatch Class
      -
      -Create a minimatch object by instanting the `minimatch.Minimatch` class.
      -
      -```javascript
      -var Minimatch = require("minimatch").Minimatch
      -var mm = new Minimatch(pattern, options)
      -```
      -
      -### Properties
      -
      -* `pattern` The original pattern the minimatch object represents.
      -* `options` The options supplied to the constructor.
      -* `set` A 2-dimensional array of regexp or string expressions.
      -  Each row in the
      -  array corresponds to a brace-expanded pattern.  Each item in the row
      -  corresponds to a single path-part.  For example, the pattern
      -  `{a,b/c}/d` would expand to a set of patterns like:
      -
      -        [ [ a, d ]
      -        , [ b, c, d ] ]
      -
      -    If a portion of the pattern doesn't have any "magic" in it
      -    (that is, it's something like `"foo"` rather than `fo*o?`), then it
      -    will be left as a string rather than converted to a regular
      -    expression.
      -
      -* `regexp` Created by the `makeRe` method.  A single regular expression
      -  expressing the entire pattern.  This is useful in cases where you wish
      -  to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
      -* `negate` True if the pattern is negated.
      -* `comment` True if the pattern is a comment.
      -* `empty` True if the pattern is `""`.
      -
      -### Methods
      -
      -* `makeRe` Generate the `regexp` member if necessary, and return it.
      -  Will return `false` if the pattern is invalid.
      -* `match(fname)` Return true if the filename matches the pattern, or
      -  false otherwise.
      -* `matchOne(fileArray, patternArray, partial)` Take a `/`-split
      -  filename, and match it against a single row in the `regExpSet`.  This
      -  method is mainly for internal use, but is exposed so that it can be
      -  used by a glob-walker that needs to avoid excessive filesystem calls.
      -
      -All other methods are internal, and will be called as necessary.
      -
      -## Functions
      -
      -The top-level exported function has a `cache` property, which is an LRU
      -cache set to store 100 items.  So, calling these methods repeatedly
      -with the same pattern and options will use the same Minimatch object,
      -saving the cost of parsing it multiple times.
      -
      -### minimatch(path, pattern, options)
      -
      -Main export.  Tests a path against the pattern using the options.
      -
      -```javascript
      -var isJS = minimatch(file, "*.js", { matchBase: true })
      -```
      -
      -### minimatch.filter(pattern, options)
      -
      -Returns a function that tests its
      -supplied argument, suitable for use with `Array.filter`.  Example:
      -
      -```javascript
      -var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true}))
      -```
      -
      -### minimatch.match(list, pattern, options)
      -
      -Match against the list of
      -files, in the style of fnmatch or glob.  If nothing is matched, and
      -options.nonull is set, then return a list containing the pattern itself.
      -
      -```javascript
      -var javascripts = minimatch.match(fileList, "*.js", {matchBase: true}))
      -```
      -
      -### minimatch.makeRe(pattern, options)
      -
      -Make a regular expression object from the pattern.
      -
      -## Options
      -
      -All options are `false` by default.
      -
      -### debug
      -
      -Dump a ton of stuff to stderr.
      -
      -### nobrace
      -
      -Do not expand `{a,b}` and `{1..3}` brace sets.
      -
      -### noglobstar
      -
      -Disable `**` matching against multiple folder names.
      -
      -### dot
      -
      -Allow patterns to match filenames starting with a period, even if
      -the pattern does not explicitly have a period in that spot.
      -
      -Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`
      -is set.
      -
      -### noext
      -
      -Disable "extglob" style patterns like `+(a|b)`.
      -
      -### nocase
      -
      -Perform a case-insensitive match.
      -
      -### nonull
      -
      -When a match is not found by `minimatch.match`, return a list containing
      -the pattern itself.  When set, an empty list is returned if there are
      -no matches.
      -
      -### matchBase
      -
      -If set, then patterns without slashes will be matched
      -against the basename of the path if it contains slashes.  For example,
      -`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.
      -
      -### nocomment
      -
      -Suppress the behavior of treating `#` at the start of a pattern as a
      -comment.
      -
      -### nonegate
      -
      -Suppress the behavior of treating a leading `!` character as negation.
      -
      -### flipNegate
      -
      -Returns from negate expressions the same as if they were not negated.
      -(Ie, true on a hit, false on a miss.)
      -
      -
      -## Comparisons to other fnmatch/glob implementations
      -
      -While strict compliance with the existing standards is a worthwhile
      -goal, some discrepancies exist between minimatch and other
      -implementations, and are intentional.
      -
      -If the pattern starts with a `!` character, then it is negated.  Set the
      -`nonegate` flag to suppress this behavior, and treat leading `!`
      -characters normally.  This is perhaps relevant if you wish to start the
      -pattern with a negative extglob pattern like `!(a|B)`.  Multiple `!`
      -characters at the start of a pattern will negate the pattern multiple
      -times.
      -
      -If a pattern starts with `#`, then it is treated as a comment, and
      -will not match anything.  Use `\#` to match a literal `#` at the
      -start of a line, or set the `nocomment` flag to suppress this behavior.
      -
      -The double-star character `**` is supported by default, unless the
      -`noglobstar` flag is set.  This is supported in the manner of bsdglob
      -and bash 4.1, where `**` only has special significance if it is the only
      -thing in a path part.  That is, `a/**/b` will match `a/x/y/b`, but
      -`a/**b` will not.
      -
      -If an escaped pattern has no matches, and the `nonull` flag is set,
      -then minimatch.match returns the pattern as-provided, rather than
      -interpreting the character escapes.  For example,
      -`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
      -`"*a?"`.  This is akin to setting the `nullglob` option in bash, except
      -that it does not resolve escaped pattern characters.
      -
      -If brace expansion is not disabled, then it is performed before any
      -other interpretation of the glob pattern.  Thus, a pattern like
      -`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
      -**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
      -checked for validity.  Since those two are valid, matching proceeds.
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/minimatch.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/minimatch.js
      deleted file mode 100644
      index c633f89..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/minimatch.js
      +++ /dev/null
      @@ -1,1055 +0,0 @@
      -;(function (require, exports, module, platform) {
      -
      -if (module) module.exports = minimatch
      -else exports.minimatch = minimatch
      -
      -if (!require) {
      -  require = function (id) {
      -    switch (id) {
      -      case "sigmund": return function sigmund (obj) {
      -        return JSON.stringify(obj)
      -      }
      -      case "path": return { basename: function (f) {
      -        f = f.split(/[\/\\]/)
      -        var e = f.pop()
      -        if (!e) e = f.pop()
      -        return e
      -      }}
      -      case "lru-cache": return function LRUCache () {
      -        // not quite an LRU, but still space-limited.
      -        var cache = {}
      -        var cnt = 0
      -        this.set = function (k, v) {
      -          cnt ++
      -          if (cnt >= 100) cache = {}
      -          cache[k] = v
      -        }
      -        this.get = function (k) { return cache[k] }
      -      }
      -    }
      -  }
      -}
      -
      -minimatch.Minimatch = Minimatch
      -
      -var LRU = require("lru-cache")
      -  , cache = minimatch.cache = new LRU({max: 100})
      -  , GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}
      -  , sigmund = require("sigmund")
      -
      -var path = require("path")
      -  // any single thing other than /
      -  // don't need to escape / when using new RegExp()
      -  , qmark = "[^/]"
      -
      -  // * => any number of characters
      -  , star = qmark + "*?"
      -
      -  // ** when dots are allowed.  Anything goes, except .. and .
      -  // not (^ or / followed by one or two dots followed by $ or /),
      -  // followed by anything, any number of times.
      -  , twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?"
      -
      -  // not a ^ or / followed by a dot,
      -  // followed by anything, any number of times.
      -  , twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?"
      -
      -  // characters that need to be escaped in RegExp.
      -  , reSpecials = charSet("().*{}+?[]^$\\!")
      -
      -// "abc" -> { a:true, b:true, c:true }
      -function charSet (s) {
      -  return s.split("").reduce(function (set, c) {
      -    set[c] = true
      -    return set
      -  }, {})
      -}
      -
      -// normalizes slashes.
      -var slashSplit = /\/+/
      -
      -minimatch.filter = filter
      -function filter (pattern, options) {
      -  options = options || {}
      -  return function (p, i, list) {
      -    return minimatch(p, pattern, options)
      -  }
      -}
      -
      -function ext (a, b) {
      -  a = a || {}
      -  b = b || {}
      -  var t = {}
      -  Object.keys(b).forEach(function (k) {
      -    t[k] = b[k]
      -  })
      -  Object.keys(a).forEach(function (k) {
      -    t[k] = a[k]
      -  })
      -  return t
      -}
      -
      -minimatch.defaults = function (def) {
      -  if (!def || !Object.keys(def).length) return minimatch
      -
      -  var orig = minimatch
      -
      -  var m = function minimatch (p, pattern, options) {
      -    return orig.minimatch(p, pattern, ext(def, options))
      -  }
      -
      -  m.Minimatch = function Minimatch (pattern, options) {
      -    return new orig.Minimatch(pattern, ext(def, options))
      -  }
      -
      -  return m
      -}
      -
      -Minimatch.defaults = function (def) {
      -  if (!def || !Object.keys(def).length) return Minimatch
      -  return minimatch.defaults(def).Minimatch
      -}
      -
      -
      -function minimatch (p, pattern, options) {
      -  if (typeof pattern !== "string") {
      -    throw new TypeError("glob pattern string required")
      -  }
      -
      -  if (!options) options = {}
      -
      -  // shortcut: comments match nothing.
      -  if (!options.nocomment && pattern.charAt(0) === "#") {
      -    return false
      -  }
      -
      -  // "" only matches ""
      -  if (pattern.trim() === "") return p === ""
      -
      -  return new Minimatch(pattern, options).match(p)
      -}
      -
      -function Minimatch (pattern, options) {
      -  if (!(this instanceof Minimatch)) {
      -    return new Minimatch(pattern, options, cache)
      -  }
      -
      -  if (typeof pattern !== "string") {
      -    throw new TypeError("glob pattern string required")
      -  }
      -
      -  if (!options) options = {}
      -  pattern = pattern.trim()
      -
      -  // windows: need to use /, not \
      -  // On other platforms, \ is a valid (albeit bad) filename char.
      -  if (platform === "win32") {
      -    pattern = pattern.split("\\").join("/")
      -  }
      -
      -  // lru storage.
      -  // these things aren't particularly big, but walking down the string
      -  // and turning it into a regexp can get pretty costly.
      -  var cacheKey = pattern + "\n" + sigmund(options)
      -  var cached = minimatch.cache.get(cacheKey)
      -  if (cached) return cached
      -  minimatch.cache.set(cacheKey, this)
      -
      -  this.options = options
      -  this.set = []
      -  this.pattern = pattern
      -  this.regexp = null
      -  this.negate = false
      -  this.comment = false
      -  this.empty = false
      -
      -  // make the set of regexps etc.
      -  this.make()
      -}
      -
      -Minimatch.prototype.debug = function() {}
      -
      -Minimatch.prototype.make = make
      -function make () {
      -  // don't do it more than once.
      -  if (this._made) return
      -
      -  var pattern = this.pattern
      -  var options = this.options
      -
      -  // empty patterns and comments match nothing.
      -  if (!options.nocomment && pattern.charAt(0) === "#") {
      -    this.comment = true
      -    return
      -  }
      -  if (!pattern) {
      -    this.empty = true
      -    return
      -  }
      -
      -  // step 1: figure out negation, etc.
      -  this.parseNegate()
      -
      -  // step 2: expand braces
      -  var set = this.globSet = this.braceExpand()
      -
      -  if (options.debug) this.debug = console.error
      -
      -  this.debug(this.pattern, set)
      -
      -  // step 3: now we have a set, so turn each one into a series of path-portion
      -  // matching patterns.
      -  // These will be regexps, except in the case of "**", which is
      -  // set to the GLOBSTAR object for globstar behavior,
      -  // and will not contain any / characters
      -  set = this.globParts = set.map(function (s) {
      -    return s.split(slashSplit)
      -  })
      -
      -  this.debug(this.pattern, set)
      -
      -  // glob --> regexps
      -  set = set.map(function (s, si, set) {
      -    return s.map(this.parse, this)
      -  }, this)
      -
      -  this.debug(this.pattern, set)
      -
      -  // filter out everything that didn't compile properly.
      -  set = set.filter(function (s) {
      -    return -1 === s.indexOf(false)
      -  })
      -
      -  this.debug(this.pattern, set)
      -
      -  this.set = set
      -}
      -
      -Minimatch.prototype.parseNegate = parseNegate
      -function parseNegate () {
      -  var pattern = this.pattern
      -    , negate = false
      -    , options = this.options
      -    , negateOffset = 0
      -
      -  if (options.nonegate) return
      -
      -  for ( var i = 0, l = pattern.length
      -      ; i < l && pattern.charAt(i) === "!"
      -      ; i ++) {
      -    negate = !negate
      -    negateOffset ++
      -  }
      -
      -  if (negateOffset) this.pattern = pattern.substr(negateOffset)
      -  this.negate = negate
      -}
      -
      -// Brace expansion:
      -// a{b,c}d -> abd acd
      -// a{b,}c -> abc ac
      -// a{0..3}d -> a0d a1d a2d a3d
      -// a{b,c{d,e}f}g -> abg acdfg acefg
      -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
      -//
      -// Invalid sets are not expanded.
      -// a{2..}b -> a{2..}b
      -// a{b}c -> a{b}c
      -minimatch.braceExpand = function (pattern, options) {
      -  return new Minimatch(pattern, options).braceExpand()
      -}
      -
      -Minimatch.prototype.braceExpand = braceExpand
      -function braceExpand (pattern, options) {
      -  options = options || this.options
      -  pattern = typeof pattern === "undefined"
      -    ? this.pattern : pattern
      -
      -  if (typeof pattern === "undefined") {
      -    throw new Error("undefined pattern")
      -  }
      -
      -  if (options.nobrace ||
      -      !pattern.match(/\{.*\}/)) {
      -    // shortcut. no need to expand.
      -    return [pattern]
      -  }
      -
      -  var escaping = false
      -
      -  // examples and comments refer to this crazy pattern:
      -  // a{b,c{d,e},{f,g}h}x{y,z}
      -  // expected:
      -  // abxy
      -  // abxz
      -  // acdxy
      -  // acdxz
      -  // acexy
      -  // acexz
      -  // afhxy
      -  // afhxz
      -  // aghxy
      -  // aghxz
      -
      -  // everything before the first \{ is just a prefix.
      -  // So, we pluck that off, and work with the rest,
      -  // and then prepend it to everything we find.
      -  if (pattern.charAt(0) !== "{") {
      -    this.debug(pattern)
      -    var prefix = null
      -    for (var i = 0, l = pattern.length; i < l; i ++) {
      -      var c = pattern.charAt(i)
      -      this.debug(i, c)
      -      if (c === "\\") {
      -        escaping = !escaping
      -      } else if (c === "{" && !escaping) {
      -        prefix = pattern.substr(0, i)
      -        break
      -      }
      -    }
      -
      -    // actually no sets, all { were escaped.
      -    if (prefix === null) {
      -      this.debug("no sets")
      -      return [pattern]
      -    }
      -
      -   var tail = braceExpand.call(this, pattern.substr(i), options)
      -    return tail.map(function (t) {
      -      return prefix + t
      -    })
      -  }
      -
      -  // now we have something like:
      -  // {b,c{d,e},{f,g}h}x{y,z}
      -  // walk through the set, expanding each part, until
      -  // the set ends.  then, we'll expand the suffix.
      -  // If the set only has a single member, then'll put the {} back
      -
      -  // first, handle numeric sets, since they're easier
      -  var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/)
      -  if (numset) {
      -    this.debug("numset", numset[1], numset[2])
      -    var suf = braceExpand.call(this, pattern.substr(numset[0].length), options)
      -      , start = +numset[1]
      -      , end = +numset[2]
      -      , inc = start > end ? -1 : 1
      -      , set = []
      -    for (var i = start; i != (end + inc); i += inc) {
      -      // append all the suffixes
      -      for (var ii = 0, ll = suf.length; ii < ll; ii ++) {
      -        set.push(i + suf[ii])
      -      }
      -    }
      -    return set
      -  }
      -
      -  // ok, walk through the set
      -  // We hope, somewhat optimistically, that there
      -  // will be a } at the end.
      -  // If the closing brace isn't found, then the pattern is
      -  // interpreted as braceExpand("\\" + pattern) so that
      -  // the leading \{ will be interpreted literally.
      -  var i = 1 // skip the \{
      -    , depth = 1
      -    , set = []
      -    , member = ""
      -    , sawEnd = false
      -    , escaping = false
      -
      -  function addMember () {
      -    set.push(member)
      -    member = ""
      -  }
      -
      -  this.debug("Entering for")
      -  FOR: for (i = 1, l = pattern.length; i < l; i ++) {
      -    var c = pattern.charAt(i)
      -    this.debug("", i, c)
      -
      -    if (escaping) {
      -      escaping = false
      -      member += "\\" + c
      -    } else {
      -      switch (c) {
      -        case "\\":
      -          escaping = true
      -          continue
      -
      -        case "{":
      -          depth ++
      -          member += "{"
      -          continue
      -
      -        case "}":
      -          depth --
      -          // if this closes the actual set, then we're done
      -          if (depth === 0) {
      -            addMember()
      -            // pluck off the close-brace
      -            i ++
      -            break FOR
      -          } else {
      -            member += c
      -            continue
      -          }
      -
      -        case ",":
      -          if (depth === 1) {
      -            addMember()
      -          } else {
      -            member += c
      -          }
      -          continue
      -
      -        default:
      -          member += c
      -          continue
      -      } // switch
      -    } // else
      -  } // for
      -
      -  // now we've either finished the set, and the suffix is
      -  // pattern.substr(i), or we have *not* closed the set,
      -  // and need to escape the leading brace
      -  if (depth !== 0) {
      -    this.debug("didn't close", pattern)
      -    return braceExpand.call(this, "\\" + pattern, options)
      -  }
      -
      -  // x{y,z} -> ["xy", "xz"]
      -  this.debug("set", set)
      -  this.debug("suffix", pattern.substr(i))
      -  var suf = braceExpand.call(this, pattern.substr(i), options)
      -  // ["b", "c{d,e}","{f,g}h"] ->
      -  //   [["b"], ["cd", "ce"], ["fh", "gh"]]
      -  var addBraces = set.length === 1
      -  this.debug("set pre-expanded", set)
      -  set = set.map(function (p) {
      -    return braceExpand.call(this, p, options)
      -  }, this)
      -  this.debug("set expanded", set)
      -
      -
      -  // [["b"], ["cd", "ce"], ["fh", "gh"]] ->
      -  //   ["b", "cd", "ce", "fh", "gh"]
      -  set = set.reduce(function (l, r) {
      -    return l.concat(r)
      -  })
      -
      -  if (addBraces) {
      -    set = set.map(function (s) {
      -      return "{" + s + "}"
      -    })
      -  }
      -
      -  // now attach the suffixes.
      -  var ret = []
      -  for (var i = 0, l = set.length; i < l; i ++) {
      -    for (var ii = 0, ll = suf.length; ii < ll; ii ++) {
      -      ret.push(set[i] + suf[ii])
      -    }
      -  }
      -  return ret
      -}
      -
      -// parse a component of the expanded set.
      -// At this point, no pattern may contain "/" in it
      -// so we're going to return a 2d array, where each entry is the full
      -// pattern, split on '/', and then turned into a regular expression.
      -// A regexp is made at the end which joins each array with an
      -// escaped /, and another full one which joins each regexp with |.
      -//
      -// Following the lead of Bash 4.1, note that "**" only has special meaning
      -// when it is the *only* thing in a path portion.  Otherwise, any series
      -// of * is equivalent to a single *.  Globstar behavior is enabled by
      -// default, and can be disabled by setting options.noglobstar.
      -Minimatch.prototype.parse = parse
      -var SUBPARSE = {}
      -function parse (pattern, isSub) {
      -  var options = this.options
      -
      -  // shortcuts
      -  if (!options.noglobstar && pattern === "**") return GLOBSTAR
      -  if (pattern === "") return ""
      -
      -  var re = ""
      -    , hasMagic = !!options.nocase
      -    , escaping = false
      -    // ? => one single character
      -    , patternListStack = []
      -    , plType
      -    , stateChar
      -    , inClass = false
      -    , reClassStart = -1
      -    , classStart = -1
      -    // . and .. never match anything that doesn't start with .,
      -    // even when options.dot is set.
      -    , patternStart = pattern.charAt(0) === "." ? "" // anything
      -      // not (start or / followed by . or .. followed by / or end)
      -      : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))"
      -      : "(?!\\.)"
      -    , self = this
      -
      -  function clearStateChar () {
      -    if (stateChar) {
      -      // we had some state-tracking character
      -      // that wasn't consumed by this pass.
      -      switch (stateChar) {
      -        case "*":
      -          re += star
      -          hasMagic = true
      -          break
      -        case "?":
      -          re += qmark
      -          hasMagic = true
      -          break
      -        default:
      -          re += "\\"+stateChar
      -          break
      -      }
      -      self.debug('clearStateChar %j %j', stateChar, re)
      -      stateChar = false
      -    }
      -  }
      -
      -  for ( var i = 0, len = pattern.length, c
      -      ; (i < len) && (c = pattern.charAt(i))
      -      ; i ++ ) {
      -
      -    this.debug("%s\t%s %s %j", pattern, i, re, c)
      -
      -    // skip over any that are escaped.
      -    if (escaping && reSpecials[c]) {
      -      re += "\\" + c
      -      escaping = false
      -      continue
      -    }
      -
      -    SWITCH: switch (c) {
      -      case "/":
      -        // completely not allowed, even escaped.
      -        // Should already be path-split by now.
      -        return false
      -
      -      case "\\":
      -        clearStateChar()
      -        escaping = true
      -        continue
      -
      -      // the various stateChar values
      -      // for the "extglob" stuff.
      -      case "?":
      -      case "*":
      -      case "+":
      -      case "@":
      -      case "!":
      -        this.debug("%s\t%s %s %j <-- stateChar", pattern, i, re, c)
      -
      -        // all of those are literals inside a class, except that
      -        // the glob [!a] means [^a] in regexp
      -        if (inClass) {
      -          this.debug('  in class')
      -          if (c === "!" && i === classStart + 1) c = "^"
      -          re += c
      -          continue
      -        }
      -
      -        // if we already have a stateChar, then it means
      -        // that there was something like ** or +? in there.
      -        // Handle the stateChar, then proceed with this one.
      -        self.debug('call clearStateChar %j', stateChar)
      -        clearStateChar()
      -        stateChar = c
      -        // if extglob is disabled, then +(asdf|foo) isn't a thing.
      -        // just clear the statechar *now*, rather than even diving into
      -        // the patternList stuff.
      -        if (options.noext) clearStateChar()
      -        continue
      -
      -      case "(":
      -        if (inClass) {
      -          re += "("
      -          continue
      -        }
      -
      -        if (!stateChar) {
      -          re += "\\("
      -          continue
      -        }
      -
      -        plType = stateChar
      -        patternListStack.push({ type: plType
      -                              , start: i - 1
      -                              , reStart: re.length })
      -        // negation is (?:(?!js)[^/]*)
      -        re += stateChar === "!" ? "(?:(?!" : "(?:"
      -        this.debug('plType %j %j', stateChar, re)
      -        stateChar = false
      -        continue
      -
      -      case ")":
      -        if (inClass || !patternListStack.length) {
      -          re += "\\)"
      -          continue
      -        }
      -
      -        clearStateChar()
      -        hasMagic = true
      -        re += ")"
      -        plType = patternListStack.pop().type
      -        // negation is (?:(?!js)[^/]*)
      -        // The others are (?:)
      -        switch (plType) {
      -          case "!":
      -            re += "[^/]*?)"
      -            break
      -          case "?":
      -          case "+":
      -          case "*": re += plType
      -          case "@": break // the default anyway
      -        }
      -        continue
      -
      -      case "|":
      -        if (inClass || !patternListStack.length || escaping) {
      -          re += "\\|"
      -          escaping = false
      -          continue
      -        }
      -
      -        clearStateChar()
      -        re += "|"
      -        continue
      -
      -      // these are mostly the same in regexp and glob
      -      case "[":
      -        // swallow any state-tracking char before the [
      -        clearStateChar()
      -
      -        if (inClass) {
      -          re += "\\" + c
      -          continue
      -        }
      -
      -        inClass = true
      -        classStart = i
      -        reClassStart = re.length
      -        re += c
      -        continue
      -
      -      case "]":
      -        //  a right bracket shall lose its special
      -        //  meaning and represent itself in
      -        //  a bracket expression if it occurs
      -        //  first in the list.  -- POSIX.2 2.8.3.2
      -        if (i === classStart + 1 || !inClass) {
      -          re += "\\" + c
      -          escaping = false
      -          continue
      -        }
      -
      -        // finish up the class.
      -        hasMagic = true
      -        inClass = false
      -        re += c
      -        continue
      -
      -      default:
      -        // swallow any state char that wasn't consumed
      -        clearStateChar()
      -
      -        if (escaping) {
      -          // no need
      -          escaping = false
      -        } else if (reSpecials[c]
      -                   && !(c === "^" && inClass)) {
      -          re += "\\"
      -        }
      -
      -        re += c
      -
      -    } // switch
      -  } // for
      -
      -
      -  // handle the case where we left a class open.
      -  // "[abc" is valid, equivalent to "\[abc"
      -  if (inClass) {
      -    // split where the last [ was, and escape it
      -    // this is a huge pita.  We now have to re-walk
      -    // the contents of the would-be class to re-translate
      -    // any characters that were passed through as-is
      -    var cs = pattern.substr(classStart + 1)
      -      , sp = this.parse(cs, SUBPARSE)
      -    re = re.substr(0, reClassStart) + "\\[" + sp[0]
      -    hasMagic = hasMagic || sp[1]
      -  }
      -
      -  // handle the case where we had a +( thing at the *end*
      -  // of the pattern.
      -  // each pattern list stack adds 3 chars, and we need to go through
      -  // and escape any | chars that were passed through as-is for the regexp.
      -  // Go through and escape them, taking care not to double-escape any
      -  // | chars that were already escaped.
      -  var pl
      -  while (pl = patternListStack.pop()) {
      -    var tail = re.slice(pl.reStart + 3)
      -    // maybe some even number of \, then maybe 1 \, followed by a |
      -    tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) {
      -      if (!$2) {
      -        // the | isn't already escaped, so escape it.
      -        $2 = "\\"
      -      }
      -
      -      // need to escape all those slashes *again*, without escaping the
      -      // one that we need for escaping the | character.  As it works out,
      -      // escaping an even number of slashes can be done by simply repeating
      -      // it exactly after itself.  That's why this trick works.
      -      //
      -      // I am sorry that you have to see this.
      -      return $1 + $1 + $2 + "|"
      -    })
      -
      -    this.debug("tail=%j\n   %s", tail, tail)
      -    var t = pl.type === "*" ? star
      -          : pl.type === "?" ? qmark
      -          : "\\" + pl.type
      -
      -    hasMagic = true
      -    re = re.slice(0, pl.reStart)
      -       + t + "\\("
      -       + tail
      -  }
      -
      -  // handle trailing things that only matter at the very end.
      -  clearStateChar()
      -  if (escaping) {
      -    // trailing \\
      -    re += "\\\\"
      -  }
      -
      -  // only need to apply the nodot start if the re starts with
      -  // something that could conceivably capture a dot
      -  var addPatternStart = false
      -  switch (re.charAt(0)) {
      -    case ".":
      -    case "[":
      -    case "(": addPatternStart = true
      -  }
      -
      -  // if the re is not "" at this point, then we need to make sure
      -  // it doesn't match against an empty path part.
      -  // Otherwise a/* will match a/, which it should not.
      -  if (re !== "" && hasMagic) re = "(?=.)" + re
      -
      -  if (addPatternStart) re = patternStart + re
      -
      -  // parsing just a piece of a larger pattern.
      -  if (isSub === SUBPARSE) {
      -    return [ re, hasMagic ]
      -  }
      -
      -  // skip the regexp for non-magical patterns
      -  // unescape anything in it, though, so that it'll be
      -  // an exact match against a file etc.
      -  if (!hasMagic) {
      -    return globUnescape(pattern)
      -  }
      -
      -  var flags = options.nocase ? "i" : ""
      -    , regExp = new RegExp("^" + re + "$", flags)
      -
      -  regExp._glob = pattern
      -  regExp._src = re
      -
      -  return regExp
      -}
      -
      -minimatch.makeRe = function (pattern, options) {
      -  return new Minimatch(pattern, options || {}).makeRe()
      -}
      -
      -Minimatch.prototype.makeRe = makeRe
      -function makeRe () {
      -  if (this.regexp || this.regexp === false) return this.regexp
      -
      -  // at this point, this.set is a 2d array of partial
      -  // pattern strings, or "**".
      -  //
      -  // It's better to use .match().  This function shouldn't
      -  // be used, really, but it's pretty convenient sometimes,
      -  // when you just want to work with a regex.
      -  var set = this.set
      -
      -  if (!set.length) return this.regexp = false
      -  var options = this.options
      -
      -  var twoStar = options.noglobstar ? star
      -      : options.dot ? twoStarDot
      -      : twoStarNoDot
      -    , flags = options.nocase ? "i" : ""
      -
      -  var re = set.map(function (pattern) {
      -    return pattern.map(function (p) {
      -      return (p === GLOBSTAR) ? twoStar
      -           : (typeof p === "string") ? regExpEscape(p)
      -           : p._src
      -    }).join("\\\/")
      -  }).join("|")
      -
      -  // must match entire pattern
      -  // ending in a * or ** will make it less strict.
      -  re = "^(?:" + re + ")$"
      -
      -  // can match anything, as long as it's not this.
      -  if (this.negate) re = "^(?!" + re + ").*$"
      -
      -  try {
      -    return this.regexp = new RegExp(re, flags)
      -  } catch (ex) {
      -    return this.regexp = false
      -  }
      -}
      -
      -minimatch.match = function (list, pattern, options) {
      -  var mm = new Minimatch(pattern, options)
      -  list = list.filter(function (f) {
      -    return mm.match(f)
      -  })
      -  if (options.nonull && !list.length) {
      -    list.push(pattern)
      -  }
      -  return list
      -}
      -
      -Minimatch.prototype.match = match
      -function match (f, partial) {
      -  this.debug("match", f, this.pattern)
      -  // short-circuit in the case of busted things.
      -  // comments, etc.
      -  if (this.comment) return false
      -  if (this.empty) return f === ""
      -
      -  if (f === "/" && partial) return true
      -
      -  var options = this.options
      -
      -  // windows: need to use /, not \
      -  // On other platforms, \ is a valid (albeit bad) filename char.
      -  if (platform === "win32") {
      -    f = f.split("\\").join("/")
      -  }
      -
      -  // treat the test path as a set of pathparts.
      -  f = f.split(slashSplit)
      -  this.debug(this.pattern, "split", f)
      -
      -  // just ONE of the pattern sets in this.set needs to match
      -  // in order for it to be valid.  If negating, then just one
      -  // match means that we have failed.
      -  // Either way, return on the first hit.
      -
      -  var set = this.set
      -  this.debug(this.pattern, "set", set)
      -
      -  var splitFile = path.basename(f.join("/")).split("/")
      -
      -  for (var i = 0, l = set.length; i < l; i ++) {
      -    var pattern = set[i], file = f
      -    if (options.matchBase && pattern.length === 1) {
      -      file = splitFile
      -    }
      -    var hit = this.matchOne(file, pattern, partial)
      -    if (hit) {
      -      if (options.flipNegate) return true
      -      return !this.negate
      -    }
      -  }
      -
      -  // didn't get any hits.  this is success if it's a negative
      -  // pattern, failure otherwise.
      -  if (options.flipNegate) return false
      -  return this.negate
      -}
      -
      -// set partial to true to test if, for example,
      -// "/a/b" matches the start of "/*/b/*/d"
      -// Partial means, if you run out of file before you run
      -// out of pattern, then that's fine, as long as all
      -// the parts match.
      -Minimatch.prototype.matchOne = function (file, pattern, partial) {
      -  var options = this.options
      -
      -  this.debug("matchOne",
      -              { "this": this
      -              , file: file
      -              , pattern: pattern })
      -
      -  this.debug("matchOne", file.length, pattern.length)
      -
      -  for ( var fi = 0
      -          , pi = 0
      -          , fl = file.length
      -          , pl = pattern.length
      -      ; (fi < fl) && (pi < pl)
      -      ; fi ++, pi ++ ) {
      -
      -    this.debug("matchOne loop")
      -    var p = pattern[pi]
      -      , f = file[fi]
      -
      -    this.debug(pattern, p, f)
      -
      -    // should be impossible.
      -    // some invalid regexp stuff in the set.
      -    if (p === false) return false
      -
      -    if (p === GLOBSTAR) {
      -      this.debug('GLOBSTAR', [pattern, p, f])
      -
      -      // "**"
      -      // a/**/b/**/c would match the following:
      -      // a/b/x/y/z/c
      -      // a/x/y/z/b/c
      -      // a/b/x/b/x/c
      -      // a/b/c
      -      // To do this, take the rest of the pattern after
      -      // the **, and see if it would match the file remainder.
      -      // If so, return success.
      -      // If not, the ** "swallows" a segment, and try again.
      -      // This is recursively awful.
      -      //
      -      // a/**/b/**/c matching a/b/x/y/z/c
      -      // - a matches a
      -      // - doublestar
      -      //   - matchOne(b/x/y/z/c, b/**/c)
      -      //     - b matches b
      -      //     - doublestar
      -      //       - matchOne(x/y/z/c, c) -> no
      -      //       - matchOne(y/z/c, c) -> no
      -      //       - matchOne(z/c, c) -> no
      -      //       - matchOne(c, c) yes, hit
      -      var fr = fi
      -        , pr = pi + 1
      -      if (pr === pl) {
      -        this.debug('** at the end')
      -        // a ** at the end will just swallow the rest.
      -        // We have found a match.
      -        // however, it will not swallow /.x, unless
      -        // options.dot is set.
      -        // . and .. are *never* matched by **, for explosively
      -        // exponential reasons.
      -        for ( ; fi < fl; fi ++) {
      -          if (file[fi] === "." || file[fi] === ".." ||
      -              (!options.dot && file[fi].charAt(0) === ".")) return false
      -        }
      -        return true
      -      }
      -
      -      // ok, let's see if we can swallow whatever we can.
      -      WHILE: while (fr < fl) {
      -        var swallowee = file[fr]
      -
      -        this.debug('\nglobstar while',
      -                    file, fr, pattern, pr, swallowee)
      -
      -        // XXX remove this slice.  Just pass the start index.
      -        if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
      -          this.debug('globstar found match!', fr, fl, swallowee)
      -          // found a match.
      -          return true
      -        } else {
      -          // can't swallow "." or ".." ever.
      -          // can only swallow ".foo" when explicitly asked.
      -          if (swallowee === "." || swallowee === ".." ||
      -              (!options.dot && swallowee.charAt(0) === ".")) {
      -            this.debug("dot detected!", file, fr, pattern, pr)
      -            break WHILE
      -          }
      -
      -          // ** swallows a segment, and continue.
      -          this.debug('globstar swallow a segment, and continue')
      -          fr ++
      -        }
      -      }
      -      // no match was found.
      -      // However, in partial mode, we can't say this is necessarily over.
      -      // If there's more *pattern* left, then 
      -      if (partial) {
      -        // ran out of file
      -        this.debug("\n>>> no match, partial?", file, fr, pattern, pr)
      -        if (fr === fl) return true
      -      }
      -      return false
      -    }
      -
      -    // something other than **
      -    // non-magic patterns just have to match exactly
      -    // patterns with magic have been turned into regexps.
      -    var hit
      -    if (typeof p === "string") {
      -      if (options.nocase) {
      -        hit = f.toLowerCase() === p.toLowerCase()
      -      } else {
      -        hit = f === p
      -      }
      -      this.debug("string match", p, f, hit)
      -    } else {
      -      hit = f.match(p)
      -      this.debug("pattern match", p, f, hit)
      -    }
      -
      -    if (!hit) return false
      -  }
      -
      -  // Note: ending in / means that we'll get a final ""
      -  // at the end of the pattern.  This can only match a
      -  // corresponding "" at the end of the file.
      -  // If the file ends in /, then it can only match a
      -  // a pattern that ends in /, unless the pattern just
      -  // doesn't have any more for it. But, a/b/ should *not*
      -  // match "a/b/*", even though "" matches against the
      -  // [^/]*? pattern, except in partial mode, where it might
      -  // simply not be reached yet.
      -  // However, a/b/ should still satisfy a/*
      -
      -  // now either we fell off the end of the pattern, or we're done.
      -  if (fi === fl && pi === pl) {
      -    // ran out of pattern and filename at the same time.
      -    // an exact hit!
      -    return true
      -  } else if (fi === fl) {
      -    // ran out of file, but still had pattern left.
      -    // this is ok if we're doing the match as part of
      -    // a glob fs traversal.
      -    return partial
      -  } else if (pi === pl) {
      -    // ran out of pattern, still have file left.
      -    // this is only acceptable if we're on the very last
      -    // empty segment of a file with a trailing slash.
      -    // a/* should match a/b/
      -    var emptyFileEnd = (fi === fl - 1) && (file[fi] === "")
      -    return emptyFileEnd
      -  }
      -
      -  // should be unreachable.
      -  throw new Error("wtf?")
      -}
      -
      -
      -// replace stuff like \* with *
      -function globUnescape (s) {
      -  return s.replace(/\\(.)/g, "$1")
      -}
      -
      -
      -function regExpEscape (s) {
      -  return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
      -}
      -
      -})( typeof require === "function" ? require : null,
      -    this,
      -    typeof module === "object" ? module : null,
      -    typeof process === "object" ? process.platform : "win32"
      -  )
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.npmignore b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.npmignore
      deleted file mode 100644
      index 07e6e47..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.npmignore
      +++ /dev/null
      @@ -1 +0,0 @@
      -/node_modules
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.travis.yml b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.travis.yml
      deleted file mode 100644
      index 4af02b3..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.travis.yml
      +++ /dev/null
      @@ -1,8 +0,0 @@
      -language: node_js
      -node_js:
      -  - '0.8'
      -  - '0.10'
      -  - '0.12'
      -  - 'iojs'
      -before_install:
      -  - npm install -g npm@latest
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS
      deleted file mode 100644
      index 4a0bc50..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/CONTRIBUTORS
      +++ /dev/null
      @@ -1,14 +0,0 @@
      -# Authors, sorted by whether or not they are me
      -Isaac Z. Schlueter 
      -Brian Cottingham 
      -Carlos Brito Lage 
      -Jesse Dailey 
      -Kevin O'Hara 
      -Marco Rogers 
      -Mark Cavage 
      -Marko Mikulicic 
      -Nathan Rajlich 
      -Satheesh Natesan 
      -Trent Mick 
      -ashleybrener 
      -n4kz 
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/LICENSE b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/LICENSE
      deleted file mode 100644
      index 19129e3..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/LICENSE
      +++ /dev/null
      @@ -1,15 +0,0 @@
      -The ISC License
      -
      -Copyright (c) Isaac Z. Schlueter and Contributors
      -
      -Permission to use, copy, modify, and/or distribute this software for any
      -purpose with or without fee is hereby granted, provided that the above
      -copyright notice and this permission notice appear in all copies.
      -
      -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
      -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
      -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
      -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/README.md b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/README.md
      deleted file mode 100644
      index a8bba68..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/README.md
      +++ /dev/null
      @@ -1,109 +0,0 @@
      -# lru cache
      -
      -A cache object that deletes the least-recently-used items.
      -
      -## Usage:
      -
      -```javascript
      -var LRU = require("lru-cache")
      -  , options = { max: 500
      -              , length: function (n) { return n * 2 }
      -              , dispose: function (key, n) { n.close() }
      -              , maxAge: 1000 * 60 * 60 }
      -  , cache = LRU(options)
      -  , otherCache = LRU(50) // sets just the max size
      -
      -cache.set("key", "value")
      -cache.get("key") // "value"
      -
      -cache.reset()    // empty the cache
      -```
      -
      -If you put more stuff in it, then items will fall out.
      -
      -If you try to put an oversized thing in it, then it'll fall out right
      -away.
      -
      -## Options
      -
      -* `max` The maximum size of the cache, checked by applying the length
      -  function to all values in the cache.  Not setting this is kind of
      -  silly, since that's the whole purpose of this lib, but it defaults
      -  to `Infinity`.
      -* `maxAge` Maximum age in ms.  Items are not pro-actively pruned out
      -  as they age, but if you try to get an item that is too old, it'll
      -  drop it and return undefined instead of giving it to you.
      -* `length` Function that is used to calculate the length of stored
      -  items.  If you're storing strings or buffers, then you probably want
      -  to do something like `function(n){return n.length}`.  The default is
      -  `function(n){return 1}`, which is fine if you want to store `n`
      -  like-sized things.
      -* `dispose` Function that is called on items when they are dropped
      -  from the cache.  This can be handy if you want to close file
      -  descriptors or do other cleanup tasks when items are no longer
      -  accessible.  Called with `key, value`.  It's called *before*
      -  actually removing the item from the internal cache, so if you want
      -  to immediately put it back in, you'll have to do that in a
      -  `nextTick` or `setTimeout` callback or it won't do anything.
      -* `stale` By default, if you set a `maxAge`, it'll only actually pull
      -  stale items out of the cache when you `get(key)`.  (That is, it's
      -  not pre-emptively doing a `setTimeout` or anything.)  If you set
      -  `stale:true`, it'll return the stale value before deleting it.  If
      -  you don't set this, then it'll return `undefined` when you try to
      -  get a stale entry, as if it had already been deleted.
      -
      -## API
      -
      -* `set(key, value, maxAge)`
      -* `get(key) => value`
      -
      -    Both of these will update the "recently used"-ness of the key.
      -    They do what you think. `max` is optional and overrides the
      -    cache `max` option if provided.
      -
      -* `peek(key)`
      -
      -    Returns the key value (or `undefined` if not found) without
      -    updating the "recently used"-ness of the key.
      -
      -    (If you find yourself using this a lot, you *might* be using the
      -    wrong sort of data structure, but there are some use cases where
      -    it's handy.)
      -
      -* `del(key)`
      -
      -    Deletes a key out of the cache.
      -
      -* `reset()`
      -
      -    Clear the cache entirely, throwing away all values.
      -
      -* `has(key)`
      -
      -    Check if a key is in the cache, without updating the recent-ness
      -    or deleting it for being stale.
      -
      -* `forEach(function(value,key,cache), [thisp])`
      -
      -    Just like `Array.prototype.forEach`.  Iterates over all the keys
      -    in the cache, in order of recent-ness.  (Ie, more recently used
      -    items are iterated over first.)
      -
      -* `keys()`
      -
      -    Return an array of the keys in the cache.
      -
      -* `values()`
      -
      -    Return an array of the values in the cache.
      -
      -* `length()`
      -
      -    Return total length of objects in cache taking into account
      -    `length` options function.
      -
      -* `itemCount()`
      -
      -    Return total quantity of objects currently in cache. Note, that
      -    `stale` (see options) items are returned as part of this item
      -    count.
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js
      deleted file mode 100644
      index d66e7a2..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js
      +++ /dev/null
      @@ -1,274 +0,0 @@
      -;(function () { // closure for web browsers
      -
      -if (typeof module === 'object' && module.exports) {
      -  module.exports = LRUCache
      -} else {
      -  // just set the global for non-node platforms.
      -  this.LRUCache = LRUCache
      -}
      -
      -function hOP (obj, key) {
      -  return Object.prototype.hasOwnProperty.call(obj, key)
      -}
      -
      -function naiveLength () { return 1 }
      -
      -function LRUCache (options) {
      -  if (!(this instanceof LRUCache))
      -    return new LRUCache(options)
      -
      -  if (typeof options === 'number')
      -    options = { max: options }
      -
      -  if (!options)
      -    options = {}
      -
      -  this._max = options.max
      -  // Kind of weird to have a default max of Infinity, but oh well.
      -  if (!this._max || !(typeof this._max === "number") || this._max <= 0 )
      -    this._max = Infinity
      -
      -  this._lengthCalculator = options.length || naiveLength
      -  if (typeof this._lengthCalculator !== "function")
      -    this._lengthCalculator = naiveLength
      -
      -  this._allowStale = options.stale || false
      -  this._maxAge = options.maxAge || null
      -  this._dispose = options.dispose
      -  this.reset()
      -}
      -
      -// resize the cache when the max changes.
      -Object.defineProperty(LRUCache.prototype, "max",
      -  { set : function (mL) {
      -      if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity
      -      this._max = mL
      -      if (this._length > this._max) trim(this)
      -    }
      -  , get : function () { return this._max }
      -  , enumerable : true
      -  })
      -
      -// resize the cache when the lengthCalculator changes.
      -Object.defineProperty(LRUCache.prototype, "lengthCalculator",
      -  { set : function (lC) {
      -      if (typeof lC !== "function") {
      -        this._lengthCalculator = naiveLength
      -        this._length = this._itemCount
      -        for (var key in this._cache) {
      -          this._cache[key].length = 1
      -        }
      -      } else {
      -        this._lengthCalculator = lC
      -        this._length = 0
      -        for (var key in this._cache) {
      -          this._cache[key].length = this._lengthCalculator(this._cache[key].value)
      -          this._length += this._cache[key].length
      -        }
      -      }
      -
      -      if (this._length > this._max) trim(this)
      -    }
      -  , get : function () { return this._lengthCalculator }
      -  , enumerable : true
      -  })
      -
      -Object.defineProperty(LRUCache.prototype, "length",
      -  { get : function () { return this._length }
      -  , enumerable : true
      -  })
      -
      -
      -Object.defineProperty(LRUCache.prototype, "itemCount",
      -  { get : function () { return this._itemCount }
      -  , enumerable : true
      -  })
      -
      -LRUCache.prototype.forEach = function (fn, thisp) {
      -  thisp = thisp || this
      -  var i = 0
      -  var itemCount = this._itemCount
      -
      -  for (var k = this._mru - 1; k >= 0 && i < itemCount; k--) if (this._lruList[k]) {
      -    i++
      -    var hit = this._lruList[k]
      -    if (isStale(this, hit)) {
      -      del(this, hit)
      -      if (!this._allowStale) hit = undefined
      -    }
      -    if (hit) {
      -      fn.call(thisp, hit.value, hit.key, this)
      -    }
      -  }
      -}
      -
      -LRUCache.prototype.keys = function () {
      -  var keys = new Array(this._itemCount)
      -  var i = 0
      -  for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
      -    var hit = this._lruList[k]
      -    keys[i++] = hit.key
      -  }
      -  return keys
      -}
      -
      -LRUCache.prototype.values = function () {
      -  var values = new Array(this._itemCount)
      -  var i = 0
      -  for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
      -    var hit = this._lruList[k]
      -    values[i++] = hit.value
      -  }
      -  return values
      -}
      -
      -LRUCache.prototype.reset = function () {
      -  if (this._dispose && this._cache) {
      -    for (var k in this._cache) {
      -      this._dispose(k, this._cache[k].value)
      -    }
      -  }
      -
      -  this._cache = Object.create(null) // hash of items by key
      -  this._lruList = Object.create(null) // list of items in order of use recency
      -  this._mru = 0 // most recently used
      -  this._lru = 0 // least recently used
      -  this._length = 0 // number of items in the list
      -  this._itemCount = 0
      -}
      -
      -// Provided for debugging/dev purposes only. No promises whatsoever that
      -// this API stays stable.
      -LRUCache.prototype.dump = function () {
      -  return this._cache
      -}
      -
      -LRUCache.prototype.dumpLru = function () {
      -  return this._lruList
      -}
      -
      -LRUCache.prototype.set = function (key, value, maxAge) {
      -  maxAge = maxAge || this._maxAge
      -  var now = maxAge ? Date.now() : 0
      -
      -  if (hOP(this._cache, key)) {
      -    // dispose of the old one before overwriting
      -    if (this._dispose)
      -      this._dispose(key, this._cache[key].value)
      -
      -    this._cache[key].now = now
      -    this._cache[key].maxAge = maxAge
      -    this._cache[key].value = value
      -    this.get(key)
      -    return true
      -  }
      -
      -  var len = this._lengthCalculator(value)
      -  var hit = new Entry(key, value, this._mru++, len, now, maxAge)
      -
      -  // oversized objects fall out of cache automatically.
      -  if (hit.length > this._max) {
      -    if (this._dispose) this._dispose(key, value)
      -    return false
      -  }
      -
      -  this._length += hit.length
      -  this._lruList[hit.lu] = this._cache[key] = hit
      -  this._itemCount ++
      -
      -  if (this._length > this._max)
      -    trim(this)
      -
      -  return true
      -}
      -
      -LRUCache.prototype.has = function (key) {
      -  if (!hOP(this._cache, key)) return false
      -  var hit = this._cache[key]
      -  if (isStale(this, hit)) {
      -    return false
      -  }
      -  return true
      -}
      -
      -LRUCache.prototype.get = function (key) {
      -  return get(this, key, true)
      -}
      -
      -LRUCache.prototype.peek = function (key) {
      -  return get(this, key, false)
      -}
      -
      -LRUCache.prototype.pop = function () {
      -  var hit = this._lruList[this._lru]
      -  del(this, hit)
      -  return hit || null
      -}
      -
      -LRUCache.prototype.del = function (key) {
      -  del(this, this._cache[key])
      -}
      -
      -function get (self, key, doUse) {
      -  var hit = self._cache[key]
      -  if (hit) {
      -    if (isStale(self, hit)) {
      -      del(self, hit)
      -      if (!self._allowStale) hit = undefined
      -    } else {
      -      if (doUse) use(self, hit)
      -    }
      -    if (hit) hit = hit.value
      -  }
      -  return hit
      -}
      -
      -function isStale(self, hit) {
      -  if (!hit || (!hit.maxAge && !self._maxAge)) return false
      -  var stale = false;
      -  var diff = Date.now() - hit.now
      -  if (hit.maxAge) {
      -    stale = diff > hit.maxAge
      -  } else {
      -    stale = self._maxAge && (diff > self._maxAge)
      -  }
      -  return stale;
      -}
      -
      -function use (self, hit) {
      -  shiftLU(self, hit)
      -  hit.lu = self._mru ++
      -  self._lruList[hit.lu] = hit
      -}
      -
      -function trim (self) {
      -  while (self._lru < self._mru && self._length > self._max)
      -    del(self, self._lruList[self._lru])
      -}
      -
      -function shiftLU (self, hit) {
      -  delete self._lruList[ hit.lu ]
      -  while (self._lru < self._mru && !self._lruList[self._lru]) self._lru ++
      -}
      -
      -function del (self, hit) {
      -  if (hit) {
      -    if (self._dispose) self._dispose(hit.key, hit.value)
      -    self._length -= hit.length
      -    self._itemCount --
      -    delete self._cache[ hit.key ]
      -    shiftLU(self, hit)
      -  }
      -}
      -
      -// classy, since V8 prefers predictable objects.
      -function Entry (key, value, lu, length, now, maxAge) {
      -  this.key = key
      -  this.value = value
      -  this.lu = lu
      -  this.length = length
      -  this.now = now
      -  if (maxAge) this.maxAge = maxAge
      -}
      -
      -})()
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json
      deleted file mode 100644
      index 31e0128..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json
      +++ /dev/null
      @@ -1,58 +0,0 @@
      -{
      -  "name": "lru-cache",
      -  "description": "A cache object that deletes the least-recently-used items.",
      -  "version": "2.6.5",
      -  "author": {
      -    "name": "Isaac Z. Schlueter",
      -    "email": "i@izs.me"
      -  },
      -  "keywords": [
      -    "mru",
      -    "lru",
      -    "cache"
      -  ],
      -  "scripts": {
      -    "test": "tap test --gc"
      -  },
      -  "main": "lib/lru-cache.js",
      -  "repository": {
      -    "type": "git",
      -    "url": "git://github.com/isaacs/node-lru-cache.git"
      -  },
      -  "devDependencies": {
      -    "tap": "^1.2.0",
      -    "weak": ""
      -  },
      -  "license": "ISC",
      -  "gitHead": "7062a0c891bfb80a294be9217e4de0f882e75776",
      -  "bugs": {
      -    "url": "https://github.com/isaacs/node-lru-cache/issues"
      -  },
      -  "homepage": "https://github.com/isaacs/node-lru-cache#readme",
      -  "_id": "lru-cache@2.6.5",
      -  "_shasum": "e56d6354148ede8d7707b58d143220fd08df0fd5",
      -  "_from": "lru-cache@2",
      -  "_npmVersion": "3.0.0",
      -  "_nodeVersion": "2.2.1",
      -  "_npmUser": {
      -    "name": "isaacs",
      -    "email": "isaacs@npmjs.com"
      -  },
      -  "dist": {
      -    "shasum": "e56d6354148ede8d7707b58d143220fd08df0fd5",
      -    "tarball": "http://registry.npmjs.org/lru-cache/-/lru-cache-2.6.5.tgz"
      -  },
      -  "maintainers": [
      -    {
      -      "name": "isaacs",
      -      "email": "isaacs@npmjs.com"
      -    },
      -    {
      -      "name": "othiym23",
      -      "email": "ogd@aoaioxxysz.net"
      -    }
      -  ],
      -  "directories": {},
      -  "_resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-2.6.5.tgz",
      -  "readme": "ERROR: No README data found!"
      -}
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/basic.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/basic.js
      deleted file mode 100644
      index 949113e..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/basic.js
      +++ /dev/null
      @@ -1,395 +0,0 @@
      -var test = require("tap").test
      -  , LRU = require("../")
      -
      -test("basic", function (t) {
      -  var cache = new LRU({max: 10})
      -  cache.set("key", "value")
      -  t.equal(cache.get("key"), "value")
      -  t.equal(cache.get("nada"), undefined)
      -  t.equal(cache.length, 1)
      -  t.equal(cache.max, 10)
      -  t.end()
      -})
      -
      -test("least recently set", function (t) {
      -  var cache = new LRU(2)
      -  cache.set("a", "A")
      -  cache.set("b", "B")
      -  cache.set("c", "C")
      -  t.equal(cache.get("c"), "C")
      -  t.equal(cache.get("b"), "B")
      -  t.equal(cache.get("a"), undefined)
      -  t.end()
      -})
      -
      -test("lru recently gotten", function (t) {
      -  var cache = new LRU(2)
      -  cache.set("a", "A")
      -  cache.set("b", "B")
      -  cache.get("a")
      -  cache.set("c", "C")
      -  t.equal(cache.get("c"), "C")
      -  t.equal(cache.get("b"), undefined)
      -  t.equal(cache.get("a"), "A")
      -  t.end()
      -})
      -
      -test("del", function (t) {
      -  var cache = new LRU(2)
      -  cache.set("a", "A")
      -  cache.del("a")
      -  t.equal(cache.get("a"), undefined)
      -  t.end()
      -})
      -
      -test("max", function (t) {
      -  var cache = new LRU(3)
      -
      -  // test changing the max, verify that the LRU items get dropped.
      -  cache.max = 100
      -  for (var i = 0; i < 100; i ++) cache.set(i, i)
      -  t.equal(cache.length, 100)
      -  for (var i = 0; i < 100; i ++) {
      -    t.equal(cache.get(i), i)
      -  }
      -  cache.max = 3
      -  t.equal(cache.length, 3)
      -  for (var i = 0; i < 97; i ++) {
      -    t.equal(cache.get(i), undefined)
      -  }
      -  for (var i = 98; i < 100; i ++) {
      -    t.equal(cache.get(i), i)
      -  }
      -
      -  // now remove the max restriction, and try again.
      -  cache.max = "hello"
      -  for (var i = 0; i < 100; i ++) cache.set(i, i)
      -  t.equal(cache.length, 100)
      -  for (var i = 0; i < 100; i ++) {
      -    t.equal(cache.get(i), i)
      -  }
      -  // should trigger an immediate resize
      -  cache.max = 3
      -  t.equal(cache.length, 3)
      -  for (var i = 0; i < 97; i ++) {
      -    t.equal(cache.get(i), undefined)
      -  }
      -  for (var i = 98; i < 100; i ++) {
      -    t.equal(cache.get(i), i)
      -  }
      -  t.end()
      -})
      -
      -test("reset", function (t) {
      -  var cache = new LRU(10)
      -  cache.set("a", "A")
      -  cache.set("b", "B")
      -  cache.reset()
      -  t.equal(cache.length, 0)
      -  t.equal(cache.max, 10)
      -  t.equal(cache.get("a"), undefined)
      -  t.equal(cache.get("b"), undefined)
      -  t.end()
      -})
      -
      -
      -// Note: `.dump()` is a debugging tool only. No guarantees are made
      -// about the format/layout of the response.
      -test("dump", function (t) {
      -  var cache = new LRU(10)
      -  var d = cache.dump();
      -  t.equal(Object.keys(d).length, 0, "nothing in dump for empty cache")
      -  cache.set("a", "A")
      -  var d = cache.dump()  // { a: { key: "a", value: "A", lu: 0 } }
      -  t.ok(d.a)
      -  t.equal(d.a.key, "a")
      -  t.equal(d.a.value, "A")
      -  t.equal(d.a.lu, 0)
      -
      -  cache.set("b", "B")
      -  cache.get("b")
      -  d = cache.dump()
      -  t.ok(d.b)
      -  t.equal(d.b.key, "b")
      -  t.equal(d.b.value, "B")
      -  t.equal(d.b.lu, 2)
      -
      -  t.end()
      -})
      -
      -
      -test("basic with weighed length", function (t) {
      -  var cache = new LRU({
      -    max: 100,
      -    length: function (item) { return item.size }
      -  })
      -  cache.set("key", {val: "value", size: 50})
      -  t.equal(cache.get("key").val, "value")
      -  t.equal(cache.get("nada"), undefined)
      -  t.equal(cache.lengthCalculator(cache.get("key")), 50)
      -  t.equal(cache.length, 50)
      -  t.equal(cache.max, 100)
      -  t.end()
      -})
      -
      -
      -test("weighed length item too large", function (t) {
      -  var cache = new LRU({
      -    max: 10,
      -    length: function (item) { return item.size }
      -  })
      -  t.equal(cache.max, 10)
      -
      -  // should fall out immediately
      -  cache.set("key", {val: "value", size: 50})
      -
      -  t.equal(cache.length, 0)
      -  t.equal(cache.get("key"), undefined)
      -  t.end()
      -})
      -
      -test("least recently set with weighed length", function (t) {
      -  var cache = new LRU({
      -    max:8,
      -    length: function (item) { return item.length }
      -  })
      -  cache.set("a", "A")
      -  cache.set("b", "BB")
      -  cache.set("c", "CCC")
      -  cache.set("d", "DDDD")
      -  t.equal(cache.get("d"), "DDDD")
      -  t.equal(cache.get("c"), "CCC")
      -  t.equal(cache.get("b"), undefined)
      -  t.equal(cache.get("a"), undefined)
      -  t.end()
      -})
      -
      -test("lru recently gotten with weighed length", function (t) {
      -  var cache = new LRU({
      -    max: 8,
      -    length: function (item) { return item.length }
      -  })
      -  cache.set("a", "A")
      -  cache.set("b", "BB")
      -  cache.set("c", "CCC")
      -  cache.get("a")
      -  cache.get("b")
      -  cache.set("d", "DDDD")
      -  t.equal(cache.get("c"), undefined)
      -  t.equal(cache.get("d"), "DDDD")
      -  t.equal(cache.get("b"), "BB")
      -  t.equal(cache.get("a"), "A")
      -  t.end()
      -})
      -
      -test("set returns proper booleans", function(t) {
      -  var cache = new LRU({
      -    max: 5,
      -    length: function (item) { return item.length }
      -  })
      -
      -  t.equal(cache.set("a", "A"), true)
      -
      -  // should return false for max exceeded
      -  t.equal(cache.set("b", "donuts"), false)
      -
      -  t.equal(cache.set("b", "B"), true)
      -  t.equal(cache.set("c", "CCCC"), true)
      -  t.end()
      -})
      -
      -test("drop the old items", function(t) {
      -  var cache = new LRU({
      -    max: 5,
      -    maxAge: 50
      -  })
      -
      -  cache.set("a", "A")
      -
      -  setTimeout(function () {
      -    cache.set("b", "b")
      -    t.equal(cache.get("a"), "A")
      -  }, 25)
      -
      -  setTimeout(function () {
      -    cache.set("c", "C")
      -    // timed out
      -    t.notOk(cache.get("a"))
      -  }, 60 + 25)
      -
      -  setTimeout(function () {
      -    t.notOk(cache.get("b"))
      -    t.equal(cache.get("c"), "C")
      -  }, 90)
      -
      -  setTimeout(function () {
      -    t.notOk(cache.get("c"))
      -    t.end()
      -  }, 155)
      -})
      -
      -test("individual item can have it's own maxAge", function(t) {
      -  var cache = new LRU({
      -    max: 5,
      -    maxAge: 50
      -  })
      -
      -  cache.set("a", "A", 20)
      -  setTimeout(function () {
      -    t.notOk(cache.get("a"))
      -    t.end()
      -  }, 25)
      -})
      -
      -test("individual item can have it's own maxAge > cache's", function(t) {
      -  var cache = new LRU({
      -    max: 5,
      -    maxAge: 20
      -  })
      -
      -  cache.set("a", "A", 50)
      -  setTimeout(function () {
      -    t.equal(cache.get("a"), "A")
      -    t.end()
      -  }, 25)
      -})
      -
      -test("disposal function", function(t) {
      -  var disposed = false
      -  var cache = new LRU({
      -    max: 1,
      -    dispose: function (k, n) {
      -      disposed = n
      -    }
      -  })
      -
      -  cache.set(1, 1)
      -  cache.set(2, 2)
      -  t.equal(disposed, 1)
      -  cache.set(3, 3)
      -  t.equal(disposed, 2)
      -  cache.reset()
      -  t.equal(disposed, 3)
      -  t.end()
      -})
      -
      -test("disposal function on too big of item", function(t) {
      -  var disposed = false
      -  var cache = new LRU({
      -    max: 1,
      -    length: function (k) {
      -      return k.length
      -    },
      -    dispose: function (k, n) {
      -      disposed = n
      -    }
      -  })
      -  var obj = [ 1, 2 ]
      -
      -  t.equal(disposed, false)
      -  cache.set("obj", obj)
      -  t.equal(disposed, obj)
      -  t.end()
      -})
      -
      -test("has()", function(t) {
      -  var cache = new LRU({
      -    max: 1,
      -    maxAge: 10
      -  })
      -
      -  cache.set('foo', 'bar')
      -  t.equal(cache.has('foo'), true)
      -  cache.set('blu', 'baz')
      -  t.equal(cache.has('foo'), false)
      -  t.equal(cache.has('blu'), true)
      -  setTimeout(function() {
      -    t.equal(cache.has('blu'), false)
      -    t.end()
      -  }, 15)
      -})
      -
      -test("stale", function(t) {
      -  var cache = new LRU({
      -    maxAge: 10,
      -    stale: true
      -  })
      -
      -  cache.set('foo', 'bar')
      -  t.equal(cache.get('foo'), 'bar')
      -  t.equal(cache.has('foo'), true)
      -  setTimeout(function() {
      -    t.equal(cache.has('foo'), false)
      -    t.equal(cache.get('foo'), 'bar')
      -    t.equal(cache.get('foo'), undefined)
      -    t.end()
      -  }, 15)
      -})
      -
      -test("lru update via set", function(t) {
      -  var cache = LRU({ max: 2 });
      -
      -  cache.set('foo', 1);
      -  cache.set('bar', 2);
      -  cache.del('bar');
      -  cache.set('baz', 3);
      -  cache.set('qux', 4);
      -
      -  t.equal(cache.get('foo'), undefined)
      -  t.equal(cache.get('bar'), undefined)
      -  t.equal(cache.get('baz'), 3)
      -  t.equal(cache.get('qux'), 4)
      -  t.end()
      -})
      -
      -test("least recently set w/ peek", function (t) {
      -  var cache = new LRU(2)
      -  cache.set("a", "A")
      -  cache.set("b", "B")
      -  t.equal(cache.peek("a"), "A")
      -  cache.set("c", "C")
      -  t.equal(cache.get("c"), "C")
      -  t.equal(cache.get("b"), "B")
      -  t.equal(cache.get("a"), undefined)
      -  t.end()
      -})
      -
      -test("pop the least used item", function (t) {
      -  var cache = new LRU(3)
      -  , last
      -
      -  cache.set("a", "A")
      -  cache.set("b", "B")
      -  cache.set("c", "C")
      -
      -  t.equal(cache.length, 3)
      -  t.equal(cache.max, 3)
      -
      -  // Ensure we pop a, c, b
      -  cache.get("b", "B")
      -
      -  last = cache.pop()
      -  t.equal(last.key, "a")
      -  t.equal(last.value, "A")
      -  t.equal(cache.length, 2)
      -  t.equal(cache.max, 3)
      -
      -  last = cache.pop()
      -  t.equal(last.key, "c")
      -  t.equal(last.value, "C")
      -  t.equal(cache.length, 1)
      -  t.equal(cache.max, 3)
      -
      -  last = cache.pop()
      -  t.equal(last.key, "b")
      -  t.equal(last.value, "B")
      -  t.equal(cache.length, 0)
      -  t.equal(cache.max, 3)
      -
      -  last = cache.pop()
      -  t.equal(last, null)
      -  t.equal(cache.length, 0)
      -  t.equal(cache.max, 3)
      -
      -  t.end()
      -})
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/foreach.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/foreach.js
      deleted file mode 100644
      index 4190417..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/foreach.js
      +++ /dev/null
      @@ -1,120 +0,0 @@
      -var test = require('tap').test
      -var LRU = require('../')
      -
      -test('forEach', function (t) {
      -  var l = new LRU(5)
      -  for (var i = 0; i < 10; i ++) {
      -    l.set(i.toString(), i.toString(2))
      -  }
      -
      -  var i = 9
      -  l.forEach(function (val, key, cache) {
      -    t.equal(cache, l)
      -    t.equal(key, i.toString())
      -    t.equal(val, i.toString(2))
      -    i -= 1
      -  })
      -
      -  // get in order of most recently used
      -  l.get(6)
      -  l.get(8)
      -
      -  var order = [ 8, 6, 9, 7, 5 ]
      -  var i = 0
      -
      -  l.forEach(function (val, key, cache) {
      -    var j = order[i ++]
      -    t.equal(cache, l)
      -    t.equal(key, j.toString())
      -    t.equal(val, j.toString(2))
      -  })
      -  t.equal(i, order.length);
      -
      -  t.end()
      -})
      -
      -test('keys() and values()', function (t) {
      -  var l = new LRU(5)
      -  for (var i = 0; i < 10; i ++) {
      -    l.set(i.toString(), i.toString(2))
      -  }
      -
      -  t.similar(l.keys(), ['9', '8', '7', '6', '5'])
      -  t.similar(l.values(), ['1001', '1000', '111', '110', '101'])
      -
      -  // get in order of most recently used
      -  l.get(6)
      -  l.get(8)
      -
      -  t.similar(l.keys(), ['8', '6', '9', '7', '5'])
      -  t.similar(l.values(), ['1000', '110', '1001', '111', '101'])
      -
      -  t.end()
      -})
      -
      -test('all entries are iterated over', function(t) {
      -  var l = new LRU(5)
      -  for (var i = 0; i < 10; i ++) {
      -    l.set(i.toString(), i.toString(2))
      -  }
      -
      -  var i = 0
      -  l.forEach(function (val, key, cache) {
      -    if (i > 0) {
      -      cache.del(key)
      -    }
      -    i += 1
      -  })
      -
      -  t.equal(i, 5)
      -  t.equal(l.keys().length, 1)
      -
      -  t.end()
      -})
      -
      -test('all stale entries are removed', function(t) {
      -  var l = new LRU({ max: 5, maxAge: -5, stale: true })
      -  for (var i = 0; i < 10; i ++) {
      -    l.set(i.toString(), i.toString(2))
      -  }
      -
      -  var i = 0
      -  l.forEach(function () {
      -    i += 1
      -  })
      -
      -  t.equal(i, 5)
      -  t.equal(l.keys().length, 0)
      -
      -  t.end()
      -})
      -
      -test('expires', function (t) {
      -  var l = new LRU({
      -    max: 10,
      -    maxAge: 50
      -  })
      -  for (var i = 0; i < 10; i++) {
      -    l.set(i.toString(), i.toString(2), ((i % 2) ? 25 : undefined))
      -  }
      -
      -  var i = 0
      -  var order = [ 8, 6, 4, 2, 0 ]
      -  setTimeout(function () {
      -    l.forEach(function (val, key, cache) {
      -      var j = order[i++]
      -      t.equal(cache, l)
      -      t.equal(key, j.toString())
      -      t.equal(val, j.toString(2))
      -    })
      -    t.equal(i, order.length);
      -
      -    setTimeout(function () {
      -      var count = 0;
      -      l.forEach(function (val, key, cache) { count++; })
      -      t.equal(0, count);
      -      t.end()
      -    }, 25)
      -
      -  }, 26)
      -})
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js
      deleted file mode 100644
      index b5912f6..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js
      +++ /dev/null
      @@ -1,51 +0,0 @@
      -#!/usr/bin/env node --expose_gc
      -
      -
      -var weak = require('weak');
      -var test = require('tap').test
      -var LRU = require('../')
      -var l = new LRU({ max: 10 })
      -var refs = 0
      -function X() {
      -  refs ++
      -  weak(this, deref)
      -}
      -
      -function deref() {
      -  refs --
      -}
      -
      -test('no leaks', function (t) {
      -  // fill up the cache
      -  for (var i = 0; i < 100; i++) {
      -    l.set(i, new X);
      -    // throw some gets in there, too.
      -    if (i % 2 === 0)
      -      l.get(i / 2)
      -  }
      -
      -  gc()
      -
      -  var start = process.memoryUsage()
      -
      -  // capture the memory
      -  var startRefs = refs
      -
      -  // do it again, but more
      -  for (var i = 0; i < 10000; i++) {
      -    l.set(i, new X);
      -    // throw some gets in there, too.
      -    if (i % 2 === 0)
      -      l.get(i / 2)
      -  }
      -
      -  gc()
      -
      -  var end = process.memoryUsage()
      -  t.equal(refs, startRefs, 'no leaky refs')
      -
      -  console.error('start: %j\n' +
      -                'end:   %j', start, end);
      -  t.pass();
      -  t.end();
      -})
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/LICENSE b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/LICENSE
      deleted file mode 100644
      index 19129e3..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/LICENSE
      +++ /dev/null
      @@ -1,15 +0,0 @@
      -The ISC License
      -
      -Copyright (c) Isaac Z. Schlueter and Contributors
      -
      -Permission to use, copy, modify, and/or distribute this software for any
      -purpose with or without fee is hereby granted, provided that the above
      -copyright notice and this permission notice appear in all copies.
      -
      -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
      -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
      -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
      -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
      -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
      -IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/README.md b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/README.md
      deleted file mode 100644
      index 25a38a5..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/README.md
      +++ /dev/null
      @@ -1,53 +0,0 @@
      -# sigmund
      -
      -Quick and dirty signatures for Objects.
      -
      -This is like a much faster `deepEquals` comparison, which returns a
      -string key suitable for caches and the like.
      -
      -## Usage
      -
      -```javascript
      -function doSomething (someObj) {
      -  var key = sigmund(someObj, maxDepth) // max depth defaults to 10
      -  var cached = cache.get(key)
      -  if (cached) return cached
      -
      -  var result = expensiveCalculation(someObj)
      -  cache.set(key, result)
      -  return result
      -}
      -```
      -
      -The resulting key will be as unique and reproducible as calling
      -`JSON.stringify` or `util.inspect` on the object, but is much faster.
      -In order to achieve this speed, some differences are glossed over.
      -For example, the object `{0:'foo'}` will be treated identically to the
      -array `['foo']`.
      -
      -Also, just as there is no way to summon the soul from the scribblings
      -of a cocaine-addled psychoanalyst, there is no way to revive the object
      -from the signature string that sigmund gives you.  In fact, it's
      -barely even readable.
      -
      -As with `util.inspect` and `JSON.stringify`, larger objects will
      -produce larger signature strings.
      -
      -Because sigmund is a bit less strict than the more thorough
      -alternatives, the strings will be shorter, and also there is a
      -slightly higher chance for collisions.  For example, these objects
      -have the same signature:
      -
      -    var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]}
      -    var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']}
      -
      -Like a good Freudian, sigmund is most effective when you already have
      -some understanding of what you're looking for.  It can help you help
      -yourself, but you must be willing to do some work as well.
      -
      -Cycles are handled, and cyclical objects are silently omitted (though
      -the key is included in the signature output.)
      -
      -The second argument is the maximum depth, which defaults to 10,
      -because that is the maximum object traversal depth covered by most
      -insurance carriers.
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/bench.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/bench.js
      deleted file mode 100644
      index 5acfd6d..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/bench.js
      +++ /dev/null
      @@ -1,283 +0,0 @@
      -// different ways to id objects
      -// use a req/res pair, since it's crazy deep and cyclical
      -
      -// sparseFE10 and sigmund are usually pretty close, which is to be expected,
      -// since they are essentially the same algorithm, except that sigmund handles
      -// regular expression objects properly.
      -
      -
      -var http = require('http')
      -var util = require('util')
      -var sigmund = require('./sigmund.js')
      -var sreq, sres, creq, cres, test
      -
      -http.createServer(function (q, s) {
      -  sreq = q
      -  sres = s
      -  sres.end('ok')
      -  this.close(function () { setTimeout(function () {
      -    start()
      -  }, 200) })
      -}).listen(1337, function () {
      -  creq = http.get({ port: 1337 })
      -  creq.on('response', function (s) { cres = s })
      -})
      -
      -function start () {
      -  test = [sreq, sres, creq, cres]
      -  // test = sreq
      -  // sreq.sres = sres
      -  // sreq.creq = creq
      -  // sreq.cres = cres
      -
      -  for (var i in exports.compare) {
      -    console.log(i)
      -    var hash = exports.compare[i]()
      -    console.log(hash)
      -    console.log(hash.length)
      -    console.log('')
      -  }
      -
      -  require('bench').runMain()
      -}
      -
      -function customWs (obj, md, d) {
      -  d = d || 0
      -  var to = typeof obj
      -  if (to === 'undefined' || to === 'function' || to === null) return ''
      -  if (d > md || !obj || to !== 'object') return ('' + obj).replace(/[\n ]+/g, '')
      -
      -  if (Array.isArray(obj)) {
      -    return obj.map(function (i, _, __) {
      -      return customWs(i, md, d + 1)
      -    }).reduce(function (a, b) { return a + b }, '')
      -  }
      -
      -  var keys = Object.keys(obj)
      -  return keys.map(function (k, _, __) {
      -    return k + ':' + customWs(obj[k], md, d + 1)
      -  }).reduce(function (a, b) { return a + b }, '')
      -}
      -
      -function custom (obj, md, d) {
      -  d = d || 0
      -  var to = typeof obj
      -  if (to === 'undefined' || to === 'function' || to === null) return ''
      -  if (d > md || !obj || to !== 'object') return '' + obj
      -
      -  if (Array.isArray(obj)) {
      -    return obj.map(function (i, _, __) {
      -      return custom(i, md, d + 1)
      -    }).reduce(function (a, b) { return a + b }, '')
      -  }
      -
      -  var keys = Object.keys(obj)
      -  return keys.map(function (k, _, __) {
      -    return k + ':' + custom(obj[k], md, d + 1)
      -  }).reduce(function (a, b) { return a + b }, '')
      -}
      -
      -function sparseFE2 (obj, maxDepth) {
      -  var seen = []
      -  var soFar = ''
      -  function ch (v, depth) {
      -    if (depth > maxDepth) return
      -    if (typeof v === 'function' || typeof v === 'undefined') return
      -    if (typeof v !== 'object' || !v) {
      -      soFar += v
      -      return
      -    }
      -    if (seen.indexOf(v) !== -1 || depth === maxDepth) return
      -    seen.push(v)
      -    soFar += '{'
      -    Object.keys(v).forEach(function (k, _, __) {
      -      // pseudo-private values.  skip those.
      -      if (k.charAt(0) === '_') return
      -      var to = typeof v[k]
      -      if (to === 'function' || to === 'undefined') return
      -      soFar += k + ':'
      -      ch(v[k], depth + 1)
      -    })
      -    soFar += '}'
      -  }
      -  ch(obj, 0)
      -  return soFar
      -}
      -
      -function sparseFE (obj, maxDepth) {
      -  var seen = []
      -  var soFar = ''
      -  function ch (v, depth) {
      -    if (depth > maxDepth) return
      -    if (typeof v === 'function' || typeof v === 'undefined') return
      -    if (typeof v !== 'object' || !v) {
      -      soFar += v
      -      return
      -    }
      -    if (seen.indexOf(v) !== -1 || depth === maxDepth) return
      -    seen.push(v)
      -    soFar += '{'
      -    Object.keys(v).forEach(function (k, _, __) {
      -      // pseudo-private values.  skip those.
      -      if (k.charAt(0) === '_') return
      -      var to = typeof v[k]
      -      if (to === 'function' || to === 'undefined') return
      -      soFar += k
      -      ch(v[k], depth + 1)
      -    })
      -  }
      -  ch(obj, 0)
      -  return soFar
      -}
      -
      -function sparse (obj, maxDepth) {
      -  var seen = []
      -  var soFar = ''
      -  function ch (v, depth) {
      -    if (depth > maxDepth) return
      -    if (typeof v === 'function' || typeof v === 'undefined') return
      -    if (typeof v !== 'object' || !v) {
      -      soFar += v
      -      return
      -    }
      -    if (seen.indexOf(v) !== -1 || depth === maxDepth) return
      -    seen.push(v)
      -    soFar += '{'
      -    for (var k in v) {
      -      // pseudo-private values.  skip those.
      -      if (k.charAt(0) === '_') continue
      -      var to = typeof v[k]
      -      if (to === 'function' || to === 'undefined') continue
      -      soFar += k
      -      ch(v[k], depth + 1)
      -    }
      -  }
      -  ch(obj, 0)
      -  return soFar
      -}
      -
      -function noCommas (obj, maxDepth) {
      -  var seen = []
      -  var soFar = ''
      -  function ch (v, depth) {
      -    if (depth > maxDepth) return
      -    if (typeof v === 'function' || typeof v === 'undefined') return
      -    if (typeof v !== 'object' || !v) {
      -      soFar += v
      -      return
      -    }
      -    if (seen.indexOf(v) !== -1 || depth === maxDepth) return
      -    seen.push(v)
      -    soFar += '{'
      -    for (var k in v) {
      -      // pseudo-private values.  skip those.
      -      if (k.charAt(0) === '_') continue
      -      var to = typeof v[k]
      -      if (to === 'function' || to === 'undefined') continue
      -      soFar += k + ':'
      -      ch(v[k], depth + 1)
      -    }
      -    soFar += '}'
      -  }
      -  ch(obj, 0)
      -  return soFar
      -}
      -
      -
      -function flatten (obj, maxDepth) {
      -  var seen = []
      -  var soFar = ''
      -  function ch (v, depth) {
      -    if (depth > maxDepth) return
      -    if (typeof v === 'function' || typeof v === 'undefined') return
      -    if (typeof v !== 'object' || !v) {
      -      soFar += v
      -      return
      -    }
      -    if (seen.indexOf(v) !== -1 || depth === maxDepth) return
      -    seen.push(v)
      -    soFar += '{'
      -    for (var k in v) {
      -      // pseudo-private values.  skip those.
      -      if (k.charAt(0) === '_') continue
      -      var to = typeof v[k]
      -      if (to === 'function' || to === 'undefined') continue
      -      soFar += k + ':'
      -      ch(v[k], depth + 1)
      -      soFar += ','
      -    }
      -    soFar += '}'
      -  }
      -  ch(obj, 0)
      -  return soFar
      -}
      -
      -exports.compare =
      -{
      -  // 'custom 2': function () {
      -  //   return custom(test, 2, 0)
      -  // },
      -  // 'customWs 2': function () {
      -  //   return customWs(test, 2, 0)
      -  // },
      -  'JSON.stringify (guarded)': function () {
      -    var seen = []
      -    return JSON.stringify(test, function (k, v) {
      -      if (typeof v !== 'object' || !v) return v
      -      if (seen.indexOf(v) !== -1) return undefined
      -      seen.push(v)
      -      return v
      -    })
      -  },
      -
      -  'flatten 10': function () {
      -    return flatten(test, 10)
      -  },
      -
      -  // 'flattenFE 10': function () {
      -  //   return flattenFE(test, 10)
      -  // },
      -
      -  'noCommas 10': function () {
      -    return noCommas(test, 10)
      -  },
      -
      -  'sparse 10': function () {
      -    return sparse(test, 10)
      -  },
      -
      -  'sparseFE 10': function () {
      -    return sparseFE(test, 10)
      -  },
      -
      -  'sparseFE2 10': function () {
      -    return sparseFE2(test, 10)
      -  },
      -
      -  sigmund: function() {
      -    return sigmund(test, 10)
      -  },
      -
      -
      -  // 'util.inspect 1': function () {
      -  //   return util.inspect(test, false, 1, false)
      -  // },
      -  // 'util.inspect undefined': function () {
      -  //   util.inspect(test)
      -  // },
      -  // 'util.inspect 2': function () {
      -  //   util.inspect(test, false, 2, false)
      -  // },
      -  // 'util.inspect 3': function () {
      -  //   util.inspect(test, false, 3, false)
      -  // },
      -  // 'util.inspect 4': function () {
      -  //   util.inspect(test, false, 4, false)
      -  // },
      -  // 'util.inspect Infinity': function () {
      -  //   util.inspect(test, false, Infinity, false)
      -  // }
      -}
      -
      -/** results
      -**/
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json
      deleted file mode 100644
      index a0a65d5..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json
      +++ /dev/null
      @@ -1,60 +0,0 @@
      -{
      -  "name": "sigmund",
      -  "version": "1.0.1",
      -  "description": "Quick and dirty signatures for Objects.",
      -  "main": "sigmund.js",
      -  "directories": {
      -    "test": "test"
      -  },
      -  "dependencies": {},
      -  "devDependencies": {
      -    "tap": "~0.3.0"
      -  },
      -  "scripts": {
      -    "test": "tap test/*.js",
      -    "bench": "node bench.js"
      -  },
      -  "repository": {
      -    "type": "git",
      -    "url": "git://github.com/isaacs/sigmund.git"
      -  },
      -  "keywords": [
      -    "object",
      -    "signature",
      -    "key",
      -    "data",
      -    "psychoanalysis"
      -  ],
      -  "author": {
      -    "name": "Isaac Z. Schlueter",
      -    "email": "i@izs.me",
      -    "url": "http://blog.izs.me/"
      -  },
      -  "license": "ISC",
      -  "gitHead": "527f97aa5bb253d927348698c0cd3bb267d098c6",
      -  "bugs": {
      -    "url": "https://github.com/isaacs/sigmund/issues"
      -  },
      -  "homepage": "https://github.com/isaacs/sigmund#readme",
      -  "_id": "sigmund@1.0.1",
      -  "_shasum": "3ff21f198cad2175f9f3b781853fd94d0d19b590",
      -  "_from": "sigmund@~1.0.0",
      -  "_npmVersion": "2.10.0",
      -  "_nodeVersion": "2.0.1",
      -  "_npmUser": {
      -    "name": "isaacs",
      -    "email": "isaacs@npmjs.com"
      -  },
      -  "dist": {
      -    "shasum": "3ff21f198cad2175f9f3b781853fd94d0d19b590",
      -    "tarball": "http://registry.npmjs.org/sigmund/-/sigmund-1.0.1.tgz"
      -  },
      -  "maintainers": [
      -    {
      -      "name": "isaacs",
      -      "email": "i@izs.me"
      -    }
      -  ],
      -  "_resolved": "https://registry.npmjs.org/sigmund/-/sigmund-1.0.1.tgz",
      -  "readme": "ERROR: No README data found!"
      -}
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/sigmund.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/sigmund.js
      deleted file mode 100644
      index 82c7ab8..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/sigmund.js
      +++ /dev/null
      @@ -1,39 +0,0 @@
      -module.exports = sigmund
      -function sigmund (subject, maxSessions) {
      -    maxSessions = maxSessions || 10;
      -    var notes = [];
      -    var analysis = '';
      -    var RE = RegExp;
      -
      -    function psychoAnalyze (subject, session) {
      -        if (session > maxSessions) return;
      -
      -        if (typeof subject === 'function' ||
      -            typeof subject === 'undefined') {
      -            return;
      -        }
      -
      -        if (typeof subject !== 'object' || !subject ||
      -            (subject instanceof RE)) {
      -            analysis += subject;
      -            return;
      -        }
      -
      -        if (notes.indexOf(subject) !== -1 || session === maxSessions) return;
      -
      -        notes.push(subject);
      -        analysis += '{';
      -        Object.keys(subject).forEach(function (issue, _, __) {
      -            // pseudo-private values.  skip those.
      -            if (issue.charAt(0) === '_') return;
      -            var to = typeof subject[issue];
      -            if (to === 'function' || to === 'undefined') return;
      -            analysis += issue;
      -            psychoAnalyze(subject[issue], session + 1);
      -        });
      -    }
      -    psychoAnalyze(subject, 0);
      -    return analysis;
      -}
      -
      -// vim: set softtabstop=4 shiftwidth=4:
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/test/basic.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/test/basic.js
      deleted file mode 100644
      index 50c53a1..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/node_modules/sigmund/test/basic.js
      +++ /dev/null
      @@ -1,24 +0,0 @@
      -var test = require('tap').test
      -var sigmund = require('../sigmund.js')
      -
      -
      -// occasionally there are duplicates
      -// that's an acceptable edge-case.  JSON.stringify and util.inspect
      -// have some collision potential as well, though less, and collision
      -// detection is expensive.
      -var hash = '{abc/def/g{0h1i2{jkl'
      -var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]}
      -var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']}
      -
      -var obj3 = JSON.parse(JSON.stringify(obj1))
      -obj3.c = /def/
      -obj3.g[2].cycle = obj3
      -var cycleHash = '{abc/def/g{0h1i2{jklcycle'
      -
      -test('basic', function (t) {
      -    t.equal(sigmund(obj1), hash)
      -    t.equal(sigmund(obj2), hash)
      -    t.equal(sigmund(obj3), cycleHash)
      -    t.end()
      -})
      -
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/package.json b/node_modules/mocha/node_modules/glob/node_modules/minimatch/package.json
      deleted file mode 100644
      index 0d6667b..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/package.json
      +++ /dev/null
      @@ -1,57 +0,0 @@
      -{
      -  "author": {
      -    "name": "Isaac Z. Schlueter",
      -    "email": "i@izs.me",
      -    "url": "http://blog.izs.me"
      -  },
      -  "name": "minimatch",
      -  "description": "a glob matcher in javascript",
      -  "version": "0.2.14",
      -  "repository": {
      -    "type": "git",
      -    "url": "git://github.com/isaacs/minimatch.git"
      -  },
      -  "main": "minimatch.js",
      -  "scripts": {
      -    "test": "tap test/*.js"
      -  },
      -  "engines": {
      -    "node": "*"
      -  },
      -  "dependencies": {
      -    "lru-cache": "2",
      -    "sigmund": "~1.0.0"
      -  },
      -  "devDependencies": {
      -    "tap": ""
      -  },
      -  "license": {
      -    "type": "MIT",
      -    "url": "http://github.com/isaacs/minimatch/raw/master/LICENSE"
      -  },
      -  "bugs": {
      -    "url": "https://github.com/isaacs/minimatch/issues"
      -  },
      -  "homepage": "https://github.com/isaacs/minimatch",
      -  "_id": "minimatch@0.2.14",
      -  "dist": {
      -    "shasum": "c74e780574f63c6f9a090e90efbe6ef53a6a756a",
      -    "tarball": "http://registry.npmjs.org/minimatch/-/minimatch-0.2.14.tgz"
      -  },
      -  "_from": "minimatch@~0.2.11",
      -  "_npmVersion": "1.3.17",
      -  "_npmUser": {
      -    "name": "isaacs",
      -    "email": "i@izs.me"
      -  },
      -  "maintainers": [
      -    {
      -      "name": "isaacs",
      -      "email": "i@izs.me"
      -    }
      -  ],
      -  "directories": {},
      -  "_shasum": "c74e780574f63c6f9a090e90efbe6ef53a6a756a",
      -  "_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-0.2.14.tgz",
      -  "readme": "ERROR: No README data found!"
      -}
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/basic.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/basic.js
      deleted file mode 100644
      index ae7ac73..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/basic.js
      +++ /dev/null
      @@ -1,399 +0,0 @@
      -// http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test
      -//
      -// TODO: Some of these tests do very bad things with backslashes, and will
      -// most likely fail badly on windows.  They should probably be skipped.
      -
      -var tap = require("tap")
      -  , globalBefore = Object.keys(global)
      -  , mm = require("../")
      -  , files = [ "a", "b", "c", "d", "abc"
      -            , "abd", "abe", "bb", "bcd"
      -            , "ca", "cb", "dd", "de"
      -            , "bdir/", "bdir/cfile"]
      -  , next = files.concat([ "a-b", "aXb"
      -                        , ".x", ".y" ])
      -
      -
      -var patterns =
      -  [ "http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test"
      -  , ["a*", ["a", "abc", "abd", "abe"]]
      -  , ["X*", ["X*"], {nonull: true}]
      -
      -  // allow null glob expansion
      -  , ["X*", []]
      -
      -  // isaacs: Slightly different than bash/sh/ksh
      -  // \\* is not un-escaped to literal "*" in a failed match,
      -  // but it does make it get treated as a literal star
      -  , ["\\*", ["\\*"], {nonull: true}]
      -  , ["\\**", ["\\**"], {nonull: true}]
      -  , ["\\*\\*", ["\\*\\*"], {nonull: true}]
      -
      -  , ["b*/", ["bdir/"]]
      -  , ["c*", ["c", "ca", "cb"]]
      -  , ["**", files]
      -
      -  , ["\\.\\./*/", ["\\.\\./*/"], {nonull: true}]
      -  , ["s/\\..*//", ["s/\\..*//"], {nonull: true}]
      -
      -  , "legendary larry crashes bashes"
      -  , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/"
      -    , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/"], {nonull: true}]
      -  , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/"
      -    , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/"], {nonull: true}]
      -
      -  , "character classes"
      -  , ["[a-c]b*", ["abc", "abd", "abe", "bb", "cb"]]
      -  , ["[a-y]*[^c]", ["abd", "abe", "bb", "bcd",
      -     "bdir/", "ca", "cb", "dd", "de"]]
      -  , ["a*[^c]", ["abd", "abe"]]
      -  , function () { files.push("a-b", "aXb") }
      -  , ["a[X-]b", ["a-b", "aXb"]]
      -  , function () { files.push(".x", ".y") }
      -  , ["[^a-c]*", ["d", "dd", "de"]]
      -  , function () { files.push("a*b/", "a*b/ooo") }
      -  , ["a\\*b/*", ["a*b/ooo"]]
      -  , ["a\\*?/*", ["a*b/ooo"]]
      -  , ["*\\\\!*", [], {null: true}, ["echo !7"]]
      -  , ["*\\!*", ["echo !7"], null, ["echo !7"]]
      -  , ["*.\\*", ["r.*"], null, ["r.*"]]
      -  , ["a[b]c", ["abc"]]
      -  , ["a[\\b]c", ["abc"]]
      -  , ["a?c", ["abc"]]
      -  , ["a\\*c", [], {null: true}, ["abc"]]
      -  , ["", [""], { null: true }, [""]]
      -
      -  , "http://www.opensource.apple.com/source/bash/bash-23/" +
      -    "bash/tests/glob-test"
      -  , function () { files.push("man/", "man/man1/", "man/man1/bash.1") }
      -  , ["*/man*/bash.*", ["man/man1/bash.1"]]
      -  , ["man/man1/bash.1", ["man/man1/bash.1"]]
      -  , ["a***c", ["abc"], null, ["abc"]]
      -  , ["a*****?c", ["abc"], null, ["abc"]]
      -  , ["?*****??", ["abc"], null, ["abc"]]
      -  , ["*****??", ["abc"], null, ["abc"]]
      -  , ["?*****?c", ["abc"], null, ["abc"]]
      -  , ["?***?****c", ["abc"], null, ["abc"]]
      -  , ["?***?****?", ["abc"], null, ["abc"]]
      -  , ["?***?****", ["abc"], null, ["abc"]]
      -  , ["*******c", ["abc"], null, ["abc"]]
      -  , ["*******?", ["abc"], null, ["abc"]]
      -  , ["a*cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]]
      -  , ["a**?**cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]]
      -  , ["a**?**cd**?**??k***", ["abcdecdhjk"], null, ["abcdecdhjk"]]
      -  , ["a**?**cd**?**??***k", ["abcdecdhjk"], null, ["abcdecdhjk"]]
      -  , ["a**?**cd**?**??***k**", ["abcdecdhjk"], null, ["abcdecdhjk"]]
      -  , ["a****c**?**??*****", ["abcdecdhjk"], null, ["abcdecdhjk"]]
      -  , ["[-abc]", ["-"], null, ["-"]]
      -  , ["[abc-]", ["-"], null, ["-"]]
      -  , ["\\", ["\\"], null, ["\\"]]
      -  , ["[\\\\]", ["\\"], null, ["\\"]]
      -  , ["[[]", ["["], null, ["["]]
      -  , ["[", ["["], null, ["["]]
      -  , ["[*", ["[abc"], null, ["[abc"]]
      -  , "a right bracket shall lose its special meaning and\n" +
      -    "represent itself in a bracket expression if it occurs\n" +
      -    "first in the list.  -- POSIX.2 2.8.3.2"
      -  , ["[]]", ["]"], null, ["]"]]
      -  , ["[]-]", ["]"], null, ["]"]]
      -  , ["[a-\z]", ["p"], null, ["p"]]
      -  , ["??**********?****?", [], { null: true }, ["abc"]]
      -  , ["??**********?****c", [], { null: true }, ["abc"]]
      -  , ["?************c****?****", [], { null: true }, ["abc"]]
      -  , ["*c*?**", [], { null: true }, ["abc"]]
      -  , ["a*****c*?**", [], { null: true }, ["abc"]]
      -  , ["a********???*******", [], { null: true }, ["abc"]]
      -  , ["[]", [], { null: true }, ["a"]]
      -  , ["[abc", [], { null: true }, ["["]]
      -
      -  , "nocase tests"
      -  , ["XYZ", ["xYz"], { nocase: true, null: true }
      -    , ["xYz", "ABC", "IjK"]]
      -  , ["ab*", ["ABC"], { nocase: true, null: true }
      -    , ["xYz", "ABC", "IjK"]]
      -  , ["[ia]?[ck]", ["ABC", "IjK"], { nocase: true, null: true }
      -    , ["xYz", "ABC", "IjK"]]
      -
      -  // [ pattern, [matches], MM opts, files, TAP opts]
      -  , "onestar/twostar"
      -  , ["{/*,*}", [], {null: true}, ["/asdf/asdf/asdf"]]
      -  , ["{/?,*}", ["/a", "bb"], {null: true}
      -    , ["/a", "/b/b", "/a/b/c", "bb"]]
      -
      -  , "dots should not match unless requested"
      -  , ["**", ["a/b"], {}, ["a/b", "a/.d", ".a/.d"]]
      -
      -  // .. and . can only match patterns starting with .,
      -  // even when options.dot is set.
      -  , function () {
      -      files = ["a/./b", "a/../b", "a/c/b", "a/.d/b"]
      -    }
      -  , ["a/*/b", ["a/c/b", "a/.d/b"], {dot: true}]
      -  , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: true}]
      -  , ["a/*/b", ["a/c/b"], {dot:false}]
      -  , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: false}]
      -
      -
      -  // this also tests that changing the options needs
      -  // to change the cache key, even if the pattern is
      -  // the same!
      -  , ["**", ["a/b","a/.d",".a/.d"], { dot: true }
      -    , [ ".a/.d", "a/.d", "a/b"]]
      -
      -  , "paren sets cannot contain slashes"
      -  , ["*(a/b)", ["*(a/b)"], {nonull: true}, ["a/b"]]
      -
      -  // brace sets trump all else.
      -  //
      -  // invalid glob pattern.  fails on bash4 and bsdglob.
      -  // however, in this implementation, it's easier just
      -  // to do the intuitive thing, and let brace-expansion
      -  // actually come before parsing any extglob patterns,
      -  // like the documentation seems to say.
      -  //
      -  // XXX: if anyone complains about this, either fix it
      -  // or tell them to grow up and stop complaining.
      -  //
      -  // bash/bsdglob says this:
      -  // , ["*(a|{b),c)}", ["*(a|{b),c)}"], {}, ["a", "ab", "ac", "ad"]]
      -  // but we do this instead:
      -  , ["*(a|{b),c)}", ["a", "ab", "ac"], {}, ["a", "ab", "ac", "ad"]]
      -
      -  // test partial parsing in the presence of comment/negation chars
      -  , ["[!a*", ["[!ab"], {}, ["[!ab", "[ab"]]
      -  , ["[#a*", ["[#ab"], {}, ["[#ab", "[ab"]]
      -
      -  // like: {a,b|c\\,d\\\|e} except it's unclosed, so it has to be escaped.
      -  , ["+(a|*\\|c\\\\|d\\\\\\|e\\\\\\\\|f\\\\\\\\\\|g"
      -    , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g"]
      -    , {}
      -    , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g", "a", "b\\c"]]
      -
      -
      -  // crazy nested {,,} and *(||) tests.
      -  , function () {
      -      files = [ "a", "b", "c", "d"
      -              , "ab", "ac", "ad"
      -              , "bc", "cb"
      -              , "bc,d", "c,db", "c,d"
      -              , "d)", "(b|c", "*(b|c"
      -              , "b|c", "b|cc", "cb|c"
      -              , "x(a|b|c)", "x(a|c)"
      -              , "(a|b|c)", "(a|c)"]
      -    }
      -  , ["*(a|{b,c})", ["a", "b", "c", "ab", "ac"]]
      -  , ["{a,*(b|c,d)}", ["a","(b|c", "*(b|c", "d)"]]
      -  // a
      -  // *(b|c)
      -  // *(b|d)
      -  , ["{a,*(b|{c,d})}", ["a","b", "bc", "cb", "c", "d"]]
      -  , ["*(a|{b|c,c})", ["a", "b", "c", "ab", "ac", "bc", "cb"]]
      -
      -
      -  // test various flag settings.
      -  , [ "*(a|{b|c,c})", ["x(a|b|c)", "x(a|c)", "(a|b|c)", "(a|c)"]
      -    , { noext: true } ]
      -  , ["a?b", ["x/y/acb", "acb/"], {matchBase: true}
      -    , ["x/y/acb", "acb/", "acb/d/e", "x/y/acb/d"] ]
      -  , ["#*", ["#a", "#b"], {nocomment: true}, ["#a", "#b", "c#d"]]
      -
      -
      -  // begin channelling Boole and deMorgan...
      -  , "negation tests"
      -  , function () {
      -      files = ["d", "e", "!ab", "!abc", "a!b", "\\!a"]
      -    }
      -
      -  // anything that is NOT a* matches.
      -  , ["!a*", ["\\!a", "d", "e", "!ab", "!abc"]]
      -
      -  // anything that IS !a* matches.
      -  , ["!a*", ["!ab", "!abc"], {nonegate: true}]
      -
      -  // anything that IS a* matches
      -  , ["!!a*", ["a!b"]]
      -
      -  // anything that is NOT !a* matches
      -  , ["!\\!a*", ["a!b", "d", "e", "\\!a"]]
      -
      -  // negation nestled within a pattern
      -  , function () {
      -      files = [ "foo.js"
      -              , "foo.bar"
      -              // can't match this one without negative lookbehind.
      -              , "foo.js.js"
      -              , "blar.js"
      -              , "foo."
      -              , "boo.js.boo" ]
      -    }
      -  , ["*.!(js)", ["foo.bar", "foo.", "boo.js.boo"] ]
      -
      -  // https://github.com/isaacs/minimatch/issues/5
      -  , function () {
      -      files = [ 'a/b/.x/c'
      -              , 'a/b/.x/c/d'
      -              , 'a/b/.x/c/d/e'
      -              , 'a/b/.x'
      -              , 'a/b/.x/'
      -              , 'a/.x/b'
      -              , '.x'
      -              , '.x/'
      -              , '.x/a'
      -              , '.x/a/b'
      -              , 'a/.x/b/.x/c'
      -              , '.x/.x' ]
      -  }
      -  , ["**/.x/**", [ '.x/'
      -                 , '.x/a'
      -                 , '.x/a/b'
      -                 , 'a/.x/b'
      -                 , 'a/b/.x/'
      -                 , 'a/b/.x/c'
      -                 , 'a/b/.x/c/d'
      -                 , 'a/b/.x/c/d/e' ] ]
      -
      -  ]
      -
      -var regexps =
      -  [ '/^(?:(?=.)a[^/]*?)$/',
      -    '/^(?:(?=.)X[^/]*?)$/',
      -    '/^(?:(?=.)X[^/]*?)$/',
      -    '/^(?:\\*)$/',
      -    '/^(?:(?=.)\\*[^/]*?)$/',
      -    '/^(?:\\*\\*)$/',
      -    '/^(?:(?=.)b[^/]*?\\/)$/',
      -    '/^(?:(?=.)c[^/]*?)$/',
      -    '/^(?:(?:(?!(?:\\/|^)\\.).)*?)$/',
      -    '/^(?:\\.\\.\\/(?!\\.)(?=.)[^/]*?\\/)$/',
      -    '/^(?:s\\/(?=.)\\.\\.[^/]*?\\/)$/',
      -    '/^(?:\\/\\^root:\\/\\{s\\/(?=.)\\^[^:][^/]*?:[^:][^/]*?:\\([^:]\\)[^/]*?\\.[^/]*?\\$\\/1\\/)$/',
      -    '/^(?:\\/\\^root:\\/\\{s\\/(?=.)\\^[^:][^/]*?:[^:][^/]*?:\\([^:]\\)[^/]*?\\.[^/]*?\\$\\/\u0001\\/)$/',
      -    '/^(?:(?!\\.)(?=.)[a-c]b[^/]*?)$/',
      -    '/^(?:(?!\\.)(?=.)[a-y][^/]*?[^c])$/',
      -    '/^(?:(?=.)a[^/]*?[^c])$/',
      -    '/^(?:(?=.)a[X-]b)$/',
      -    '/^(?:(?!\\.)(?=.)[^a-c][^/]*?)$/',
      -    '/^(?:a\\*b\\/(?!\\.)(?=.)[^/]*?)$/',
      -    '/^(?:(?=.)a\\*[^/]\\/(?!\\.)(?=.)[^/]*?)$/',
      -    '/^(?:(?!\\.)(?=.)[^/]*?\\\\\\![^/]*?)$/',
      -    '/^(?:(?!\\.)(?=.)[^/]*?\\![^/]*?)$/',
      -    '/^(?:(?!\\.)(?=.)[^/]*?\\.\\*)$/',
      -    '/^(?:(?=.)a[b]c)$/',
      -    '/^(?:(?=.)a[b]c)$/',
      -    '/^(?:(?=.)a[^/]c)$/',
      -    '/^(?:a\\*c)$/',
      -    'false',
      -    '/^(?:(?!\\.)(?=.)[^/]*?\\/(?=.)man[^/]*?\\/(?=.)bash\\.[^/]*?)$/',
      -    '/^(?:man\\/man1\\/bash\\.1)$/',
      -    '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?c)$/',
      -    '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]c)$/',
      -    '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/])$/',
      -    '/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/])$/',
      -    '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]c)$/',
      -    '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?c)$/',
      -    '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/])$/',
      -    '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?)$/',
      -    '/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c)$/',
      -    '/^(?:(?!\\.)(?=.)[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/])$/',
      -    '/^(?:(?=.)a[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k)$/',
      -    '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k)$/',
      -    '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/]k[^/]*?[^/]*?[^/]*?)$/',
      -    '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?k)$/',
      -    '/^(?:(?=.)a[^/]*?[^/]*?[^/][^/]*?[^/]*?cd[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?k[^/]*?[^/]*?)$/',
      -    '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?)$/',
      -    '/^(?:(?!\\.)(?=.)[-abc])$/',
      -    '/^(?:(?!\\.)(?=.)[abc-])$/',
      -    '/^(?:\\\\)$/',
      -    '/^(?:(?!\\.)(?=.)[\\\\])$/',
      -    '/^(?:(?!\\.)(?=.)[\\[])$/',
      -    '/^(?:\\[)$/',
      -    '/^(?:(?=.)\\[(?!\\.)(?=.)[^/]*?)$/',
      -    '/^(?:(?!\\.)(?=.)[\\]])$/',
      -    '/^(?:(?!\\.)(?=.)[\\]-])$/',
      -    '/^(?:(?!\\.)(?=.)[a-z])$/',
      -    '/^(?:(?!\\.)(?=.)[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/])$/',
      -    '/^(?:(?!\\.)(?=.)[^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?c)$/',
      -    '/^(?:(?!\\.)(?=.)[^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/]*?[^/]*?[^/]*?[^/]*?)$/',
      -    '/^(?:(?!\\.)(?=.)[^/]*?c[^/]*?[^/][^/]*?[^/]*?)$/',
      -    '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?c[^/]*?[^/][^/]*?[^/]*?)$/',
      -    '/^(?:(?=.)a[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/][^/][^/][^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?[^/]*?)$/',
      -    '/^(?:\\[\\])$/',
      -    '/^(?:\\[abc)$/',
      -    '/^(?:(?=.)XYZ)$/i',
      -    '/^(?:(?=.)ab[^/]*?)$/i',
      -    '/^(?:(?!\\.)(?=.)[ia][^/][ck])$/i',
      -    '/^(?:\\/(?!\\.)(?=.)[^/]*?|(?!\\.)(?=.)[^/]*?)$/',
      -    '/^(?:\\/(?!\\.)(?=.)[^/]|(?!\\.)(?=.)[^/]*?)$/',
      -    '/^(?:(?:(?!(?:\\/|^)\\.).)*?)$/',
      -    '/^(?:a\\/(?!(?:^|\\/)\\.{1,2}(?:$|\\/))(?=.)[^/]*?\\/b)$/',
      -    '/^(?:a\\/(?=.)\\.[^/]*?\\/b)$/',
      -    '/^(?:a\\/(?!\\.)(?=.)[^/]*?\\/b)$/',
      -    '/^(?:a\\/(?=.)\\.[^/]*?\\/b)$/',
      -    '/^(?:(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?)$/',
      -    '/^(?:(?!\\.)(?=.)[^/]*?\\(a\\/b\\))$/',
      -    '/^(?:(?!\\.)(?=.)(?:a|b)*|(?!\\.)(?=.)(?:a|c)*)$/',
      -    '/^(?:(?=.)\\[(?=.)\\!a[^/]*?)$/',
      -    '/^(?:(?=.)\\[(?=.)#a[^/]*?)$/',
      -    '/^(?:(?=.)\\+\\(a\\|[^/]*?\\|c\\\\\\\\\\|d\\\\\\\\\\|e\\\\\\\\\\\\\\\\\\|f\\\\\\\\\\\\\\\\\\|g)$/',
      -    '/^(?:(?!\\.)(?=.)(?:a|b)*|(?!\\.)(?=.)(?:a|c)*)$/',
      -    '/^(?:a|(?!\\.)(?=.)[^/]*?\\(b\\|c|d\\))$/',
      -    '/^(?:a|(?!\\.)(?=.)(?:b|c)*|(?!\\.)(?=.)(?:b|d)*)$/',
      -    '/^(?:(?!\\.)(?=.)(?:a|b|c)*|(?!\\.)(?=.)(?:a|c)*)$/',
      -    '/^(?:(?!\\.)(?=.)[^/]*?\\(a\\|b\\|c\\)|(?!\\.)(?=.)[^/]*?\\(a\\|c\\))$/',
      -    '/^(?:(?=.)a[^/]b)$/',
      -    '/^(?:(?=.)#[^/]*?)$/',
      -    '/^(?!^(?:(?=.)a[^/]*?)$).*$/',
      -    '/^(?:(?=.)\\!a[^/]*?)$/',
      -    '/^(?:(?=.)a[^/]*?)$/',
      -    '/^(?!^(?:(?=.)\\!a[^/]*?)$).*$/',
      -    '/^(?:(?!\\.)(?=.)[^/]*?\\.(?:(?!js)[^/]*?))$/',
      -    '/^(?:(?:(?!(?:\\/|^)\\.).)*?\\/\\.x\\/(?:(?!(?:\\/|^)\\.).)*?)$/' ]
      -var re = 0;
      -
      -tap.test("basic tests", function (t) {
      -  var start = Date.now()
      -
      -  // [ pattern, [matches], MM opts, files, TAP opts]
      -  patterns.forEach(function (c) {
      -    if (typeof c === "function") return c()
      -    if (typeof c === "string") return t.comment(c)
      -
      -    var pattern = c[0]
      -      , expect = c[1].sort(alpha)
      -      , options = c[2] || {}
      -      , f = c[3] || files
      -      , tapOpts = c[4] || {}
      -
      -    // options.debug = true
      -    var m = new mm.Minimatch(pattern, options)
      -    var r = m.makeRe()
      -    var expectRe = regexps[re++]
      -    tapOpts.re = String(r) || JSON.stringify(r)
      -    tapOpts.files = JSON.stringify(f)
      -    tapOpts.pattern = pattern
      -    tapOpts.set = m.set
      -    tapOpts.negated = m.negate
      -
      -    var actual = mm.match(f, pattern, options)
      -    actual.sort(alpha)
      -
      -    t.equivalent( actual, expect
      -                , JSON.stringify(pattern) + " " + JSON.stringify(expect)
      -                , tapOpts )
      -
      -    t.equal(tapOpts.re, expectRe, tapOpts)
      -  })
      -
      -  t.comment("time=" + (Date.now() - start) + "ms")
      -  t.end()
      -})
      -
      -tap.test("global leak test", function (t) {
      -  var globalAfter = Object.keys(global)
      -  t.equivalent(globalAfter, globalBefore, "no new globals, please")
      -  t.end()
      -})
      -
      -function alpha (a, b) {
      -  return a > b ? 1 : -1
      -}
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/brace-expand.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/brace-expand.js
      deleted file mode 100644
      index 7ee278a..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/brace-expand.js
      +++ /dev/null
      @@ -1,33 +0,0 @@
      -var tap = require("tap")
      -  , minimatch = require("../")
      -
      -tap.test("brace expansion", function (t) {
      -  // [ pattern, [expanded] ]
      -  ; [ [ "a{b,c{d,e},{f,g}h}x{y,z}"
      -      , [ "abxy"
      -        , "abxz"
      -        , "acdxy"
      -        , "acdxz"
      -        , "acexy"
      -        , "acexz"
      -        , "afhxy"
      -        , "afhxz"
      -        , "aghxy"
      -        , "aghxz" ] ]
      -    , [ "a{1..5}b"
      -      , [ "a1b"
      -        , "a2b"
      -        , "a3b"
      -        , "a4b"
      -        , "a5b" ] ]
      -    , [ "a{b}c", ["a{b}c"] ]
      -  ].forEach(function (tc) {
      -    var p = tc[0]
      -      , expect = tc[1]
      -    t.equivalent(minimatch.braceExpand(p), expect, p)
      -  })
      -  console.error("ending")
      -  t.end()
      -})
      -
      -
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/caching.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/caching.js
      deleted file mode 100644
      index 0fec4b0..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/caching.js
      +++ /dev/null
      @@ -1,14 +0,0 @@
      -var Minimatch = require("../minimatch.js").Minimatch
      -var tap = require("tap")
      -tap.test("cache test", function (t) {
      -  var mm1 = new Minimatch("a?b")
      -  var mm2 = new Minimatch("a?b")
      -  t.equal(mm1, mm2, "should get the same object")
      -  // the lru should drop it after 100 entries
      -  for (var i = 0; i < 100; i ++) {
      -    new Minimatch("a"+i)
      -  }
      -  mm2 = new Minimatch("a?b")
      -  t.notEqual(mm1, mm2, "cache should have dropped")
      -  t.end()
      -})
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/defaults.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/defaults.js
      deleted file mode 100644
      index 25f1f60..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/defaults.js
      +++ /dev/null
      @@ -1,274 +0,0 @@
      -// http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test
      -//
      -// TODO: Some of these tests do very bad things with backslashes, and will
      -// most likely fail badly on windows.  They should probably be skipped.
      -
      -var tap = require("tap")
      -  , globalBefore = Object.keys(global)
      -  , mm = require("../")
      -  , files = [ "a", "b", "c", "d", "abc"
      -            , "abd", "abe", "bb", "bcd"
      -            , "ca", "cb", "dd", "de"
      -            , "bdir/", "bdir/cfile"]
      -  , next = files.concat([ "a-b", "aXb"
      -                        , ".x", ".y" ])
      -
      -tap.test("basic tests", function (t) {
      -  var start = Date.now()
      -
      -  // [ pattern, [matches], MM opts, files, TAP opts]
      -  ; [ "http://www.bashcookbook.com/bashinfo" +
      -      "/source/bash-1.14.7/tests/glob-test"
      -    , ["a*", ["a", "abc", "abd", "abe"]]
      -    , ["X*", ["X*"], {nonull: true}]
      -
      -    // allow null glob expansion
      -    , ["X*", []]
      -
      -    // isaacs: Slightly different than bash/sh/ksh
      -    // \\* is not un-escaped to literal "*" in a failed match,
      -    // but it does make it get treated as a literal star
      -    , ["\\*", ["\\*"], {nonull: true}]
      -    , ["\\**", ["\\**"], {nonull: true}]
      -    , ["\\*\\*", ["\\*\\*"], {nonull: true}]
      -
      -    , ["b*/", ["bdir/"]]
      -    , ["c*", ["c", "ca", "cb"]]
      -    , ["**", files]
      -
      -    , ["\\.\\./*/", ["\\.\\./*/"], {nonull: true}]
      -    , ["s/\\..*//", ["s/\\..*//"], {nonull: true}]
      -
      -    , "legendary larry crashes bashes"
      -    , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/"
      -      , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/"], {nonull: true}]
      -    , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/"
      -      , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/"], {nonull: true}]
      -
      -    , "character classes"
      -    , ["[a-c]b*", ["abc", "abd", "abe", "bb", "cb"]]
      -    , ["[a-y]*[^c]", ["abd", "abe", "bb", "bcd",
      -       "bdir/", "ca", "cb", "dd", "de"]]
      -    , ["a*[^c]", ["abd", "abe"]]
      -    , function () { files.push("a-b", "aXb") }
      -    , ["a[X-]b", ["a-b", "aXb"]]
      -    , function () { files.push(".x", ".y") }
      -    , ["[^a-c]*", ["d", "dd", "de"]]
      -    , function () { files.push("a*b/", "a*b/ooo") }
      -    , ["a\\*b/*", ["a*b/ooo"]]
      -    , ["a\\*?/*", ["a*b/ooo"]]
      -    , ["*\\\\!*", [], {null: true}, ["echo !7"]]
      -    , ["*\\!*", ["echo !7"], null, ["echo !7"]]
      -    , ["*.\\*", ["r.*"], null, ["r.*"]]
      -    , ["a[b]c", ["abc"]]
      -    , ["a[\\b]c", ["abc"]]
      -    , ["a?c", ["abc"]]
      -    , ["a\\*c", [], {null: true}, ["abc"]]
      -    , ["", [""], { null: true }, [""]]
      -
      -    , "http://www.opensource.apple.com/source/bash/bash-23/" +
      -      "bash/tests/glob-test"
      -    , function () { files.push("man/", "man/man1/", "man/man1/bash.1") }
      -    , ["*/man*/bash.*", ["man/man1/bash.1"]]
      -    , ["man/man1/bash.1", ["man/man1/bash.1"]]
      -    , ["a***c", ["abc"], null, ["abc"]]
      -    , ["a*****?c", ["abc"], null, ["abc"]]
      -    , ["?*****??", ["abc"], null, ["abc"]]
      -    , ["*****??", ["abc"], null, ["abc"]]
      -    , ["?*****?c", ["abc"], null, ["abc"]]
      -    , ["?***?****c", ["abc"], null, ["abc"]]
      -    , ["?***?****?", ["abc"], null, ["abc"]]
      -    , ["?***?****", ["abc"], null, ["abc"]]
      -    , ["*******c", ["abc"], null, ["abc"]]
      -    , ["*******?", ["abc"], null, ["abc"]]
      -    , ["a*cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]]
      -    , ["a**?**cd**?**??k", ["abcdecdhjk"], null, ["abcdecdhjk"]]
      -    , ["a**?**cd**?**??k***", ["abcdecdhjk"], null, ["abcdecdhjk"]]
      -    , ["a**?**cd**?**??***k", ["abcdecdhjk"], null, ["abcdecdhjk"]]
      -    , ["a**?**cd**?**??***k**", ["abcdecdhjk"], null, ["abcdecdhjk"]]
      -    , ["a****c**?**??*****", ["abcdecdhjk"], null, ["abcdecdhjk"]]
      -    , ["[-abc]", ["-"], null, ["-"]]
      -    , ["[abc-]", ["-"], null, ["-"]]
      -    , ["\\", ["\\"], null, ["\\"]]
      -    , ["[\\\\]", ["\\"], null, ["\\"]]
      -    , ["[[]", ["["], null, ["["]]
      -    , ["[", ["["], null, ["["]]
      -    , ["[*", ["[abc"], null, ["[abc"]]
      -    , "a right bracket shall lose its special meaning and\n" +
      -      "represent itself in a bracket expression if it occurs\n" +
      -      "first in the list.  -- POSIX.2 2.8.3.2"
      -    , ["[]]", ["]"], null, ["]"]]
      -    , ["[]-]", ["]"], null, ["]"]]
      -    , ["[a-\z]", ["p"], null, ["p"]]
      -    , ["??**********?****?", [], { null: true }, ["abc"]]
      -    , ["??**********?****c", [], { null: true }, ["abc"]]
      -    , ["?************c****?****", [], { null: true }, ["abc"]]
      -    , ["*c*?**", [], { null: true }, ["abc"]]
      -    , ["a*****c*?**", [], { null: true }, ["abc"]]
      -    , ["a********???*******", [], { null: true }, ["abc"]]
      -    , ["[]", [], { null: true }, ["a"]]
      -    , ["[abc", [], { null: true }, ["["]]
      -
      -    , "nocase tests"
      -    , ["XYZ", ["xYz"], { nocase: true, null: true }
      -      , ["xYz", "ABC", "IjK"]]
      -    , ["ab*", ["ABC"], { nocase: true, null: true }
      -      , ["xYz", "ABC", "IjK"]]
      -    , ["[ia]?[ck]", ["ABC", "IjK"], { nocase: true, null: true }
      -      , ["xYz", "ABC", "IjK"]]
      -
      -    // [ pattern, [matches], MM opts, files, TAP opts]
      -    , "onestar/twostar"
      -    , ["{/*,*}", [], {null: true}, ["/asdf/asdf/asdf"]]
      -    , ["{/?,*}", ["/a", "bb"], {null: true}
      -      , ["/a", "/b/b", "/a/b/c", "bb"]]
      -
      -    , "dots should not match unless requested"
      -    , ["**", ["a/b"], {}, ["a/b", "a/.d", ".a/.d"]]
      -
      -    // .. and . can only match patterns starting with .,
      -    // even when options.dot is set.
      -    , function () {
      -        files = ["a/./b", "a/../b", "a/c/b", "a/.d/b"]
      -      }
      -    , ["a/*/b", ["a/c/b", "a/.d/b"], {dot: true}]
      -    , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: true}]
      -    , ["a/*/b", ["a/c/b"], {dot:false}]
      -    , ["a/.*/b", ["a/./b", "a/../b", "a/.d/b"], {dot: false}]
      -
      -
      -    // this also tests that changing the options needs
      -    // to change the cache key, even if the pattern is
      -    // the same!
      -    , ["**", ["a/b","a/.d",".a/.d"], { dot: true }
      -      , [ ".a/.d", "a/.d", "a/b"]]
      -
      -    , "paren sets cannot contain slashes"
      -    , ["*(a/b)", ["*(a/b)"], {nonull: true}, ["a/b"]]
      -
      -    // brace sets trump all else.
      -    //
      -    // invalid glob pattern.  fails on bash4 and bsdglob.
      -    // however, in this implementation, it's easier just
      -    // to do the intuitive thing, and let brace-expansion
      -    // actually come before parsing any extglob patterns,
      -    // like the documentation seems to say.
      -    //
      -    // XXX: if anyone complains about this, either fix it
      -    // or tell them to grow up and stop complaining.
      -    //
      -    // bash/bsdglob says this:
      -    // , ["*(a|{b),c)}", ["*(a|{b),c)}"], {}, ["a", "ab", "ac", "ad"]]
      -    // but we do this instead:
      -    , ["*(a|{b),c)}", ["a", "ab", "ac"], {}, ["a", "ab", "ac", "ad"]]
      -
      -    // test partial parsing in the presence of comment/negation chars
      -    , ["[!a*", ["[!ab"], {}, ["[!ab", "[ab"]]
      -    , ["[#a*", ["[#ab"], {}, ["[#ab", "[ab"]]
      -
      -    // like: {a,b|c\\,d\\\|e} except it's unclosed, so it has to be escaped.
      -    , ["+(a|*\\|c\\\\|d\\\\\\|e\\\\\\\\|f\\\\\\\\\\|g"
      -      , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g"]
      -      , {}
      -      , ["+(a|b\\|c\\\\|d\\\\|e\\\\\\\\|f\\\\\\\\|g", "a", "b\\c"]]
      -
      -
      -    // crazy nested {,,} and *(||) tests.
      -    , function () {
      -        files = [ "a", "b", "c", "d"
      -                , "ab", "ac", "ad"
      -                , "bc", "cb"
      -                , "bc,d", "c,db", "c,d"
      -                , "d)", "(b|c", "*(b|c"
      -                , "b|c", "b|cc", "cb|c"
      -                , "x(a|b|c)", "x(a|c)"
      -                , "(a|b|c)", "(a|c)"]
      -      }
      -    , ["*(a|{b,c})", ["a", "b", "c", "ab", "ac"]]
      -    , ["{a,*(b|c,d)}", ["a","(b|c", "*(b|c", "d)"]]
      -    // a
      -    // *(b|c)
      -    // *(b|d)
      -    , ["{a,*(b|{c,d})}", ["a","b", "bc", "cb", "c", "d"]]
      -    , ["*(a|{b|c,c})", ["a", "b", "c", "ab", "ac", "bc", "cb"]]
      -
      -
      -    // test various flag settings.
      -    , [ "*(a|{b|c,c})", ["x(a|b|c)", "x(a|c)", "(a|b|c)", "(a|c)"]
      -      , { noext: true } ]
      -    , ["a?b", ["x/y/acb", "acb/"], {matchBase: true}
      -      , ["x/y/acb", "acb/", "acb/d/e", "x/y/acb/d"] ]
      -    , ["#*", ["#a", "#b"], {nocomment: true}, ["#a", "#b", "c#d"]]
      -
      -
      -    // begin channelling Boole and deMorgan...
      -    , "negation tests"
      -    , function () {
      -        files = ["d", "e", "!ab", "!abc", "a!b", "\\!a"]
      -      }
      -
      -    // anything that is NOT a* matches.
      -    , ["!a*", ["\\!a", "d", "e", "!ab", "!abc"]]
      -
      -    // anything that IS !a* matches.
      -    , ["!a*", ["!ab", "!abc"], {nonegate: true}]
      -
      -    // anything that IS a* matches
      -    , ["!!a*", ["a!b"]]
      -
      -    // anything that is NOT !a* matches
      -    , ["!\\!a*", ["a!b", "d", "e", "\\!a"]]
      -
      -    // negation nestled within a pattern
      -    , function () {
      -        files = [ "foo.js"
      -                , "foo.bar"
      -                // can't match this one without negative lookbehind.
      -                , "foo.js.js"
      -                , "blar.js"
      -                , "foo."
      -                , "boo.js.boo" ]
      -      }
      -    , ["*.!(js)", ["foo.bar", "foo.", "boo.js.boo"] ]
      -
      -    ].forEach(function (c) {
      -      if (typeof c === "function") return c()
      -      if (typeof c === "string") return t.comment(c)
      -
      -      var pattern = c[0]
      -        , expect = c[1].sort(alpha)
      -        , options = c[2] || {}
      -        , f = c[3] || files
      -        , tapOpts = c[4] || {}
      -
      -      // options.debug = true
      -      var Class = mm.defaults(options).Minimatch
      -      var m = new Class(pattern, {})
      -      var r = m.makeRe()
      -      tapOpts.re = String(r) || JSON.stringify(r)
      -      tapOpts.files = JSON.stringify(f)
      -      tapOpts.pattern = pattern
      -      tapOpts.set = m.set
      -      tapOpts.negated = m.negate
      -
      -      var actual = mm.match(f, pattern, options)
      -      actual.sort(alpha)
      -
      -      t.equivalent( actual, expect
      -                  , JSON.stringify(pattern) + " " + JSON.stringify(expect)
      -                  , tapOpts )
      -    })
      -
      -  t.comment("time=" + (Date.now() - start) + "ms")
      -  t.end()
      -})
      -
      -tap.test("global leak test", function (t) {
      -  var globalAfter = Object.keys(global)
      -  t.equivalent(globalAfter, globalBefore, "no new globals, please")
      -  t.end()
      -})
      -
      -function alpha (a, b) {
      -  return a > b ? 1 : -1
      -}
      diff --git a/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/extglob-ending-with-state-char.js b/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/extglob-ending-with-state-char.js
      deleted file mode 100644
      index 6676e26..0000000
      --- a/node_modules/mocha/node_modules/glob/node_modules/minimatch/test/extglob-ending-with-state-char.js
      +++ /dev/null
      @@ -1,8 +0,0 @@
      -var test = require('tap').test
      -var minimatch = require('../')
      -
      -test('extglob ending with statechar', function(t) {
      -  t.notOk(minimatch('ax', 'a?(b*)'))
      -  t.ok(minimatch('ax', '?(a*|b)'))
      -  t.end()
      -})
      diff --git a/node_modules/mocha/node_modules/glob/package.json b/node_modules/mocha/node_modules/glob/package.json
      deleted file mode 100644
      index d4ff1fc..0000000
      --- a/node_modules/mocha/node_modules/glob/package.json
      +++ /dev/null
      @@ -1,58 +0,0 @@
      -{
      -  "author": {
      -    "name": "Isaac Z. Schlueter",
      -    "email": "i@izs.me",
      -    "url": "http://blog.izs.me/"
      -  },
      -  "name": "glob",
      -  "description": "a little globber",
      -  "version": "3.2.3",
      -  "repository": {
      -    "type": "git",
      -    "url": "git://github.com/isaacs/node-glob.git"
      -  },
      -  "main": "glob.js",
      -  "engines": {
      -    "node": "*"
      -  },
      -  "dependencies": {
      -    "minimatch": "~0.2.11",
      -    "graceful-fs": "~2.0.0",
      -    "inherits": "2"
      -  },
      -  "devDependencies": {
      -    "tap": "~0.4.0",
      -    "mkdirp": "0",
      -    "rimraf": "1"
      -  },
      -  "scripts": {
      -    "test": "tap test/*.js"
      -  },
      -  "license": "BSD",
      -  "bugs": {
      -    "url": "https://github.com/isaacs/node-glob/issues"
      -  },
      -  "_id": "glob@3.2.3",
      -  "dist": {
      -    "shasum": "e313eeb249c7affaa5c475286b0e115b59839467",
      -    "tarball": "http://registry.npmjs.org/glob/-/glob-3.2.3.tgz"
      -  },
      -  "_from": "glob@3.2.3",
      -  "_npmVersion": "1.3.2",
      -  "_npmUser": {
      -    "name": "isaacs",
      -    "email": "i@izs.me"
      -  },
      -  "maintainers": [
      -    {
      -      "name": "isaacs",
      -      "email": "i@izs.me"
      -    }
      -  ],
      -  "directories": {},
      -  "_shasum": "e313eeb249c7affaa5c475286b0e115b59839467",
      -  "_resolved": "https://registry.npmjs.org/glob/-/glob-3.2.3.tgz",
      -  "readme": "# Glob\n\nMatch files using the patterns the shell uses, like stars and stuff.\n\nThis is a glob implementation in JavaScript.  It uses the `minimatch`\nlibrary to do its matching.\n\n## Attention: node-glob users!\n\nThe API has changed dramatically between 2.x and 3.x. This library is\nnow 100% JavaScript, and the integer flags have been replaced with an\noptions object.\n\nAlso, there's an event emitter class, proper tests, and all the other\nthings you've come to expect from node modules.\n\nAnd best of all, no compilation!\n\n## Usage\n\n```javascript\nvar glob = require(\"glob\")\n\n// options is optional\nglob(\"**/*.js\", options, function (er, files) {\n  // files is an array of filenames.\n  // If the `nonull` option is set, and nothing\n  // was found, then files is [\"**/*.js\"]\n  // er is an error object or null.\n})\n```\n\n## Features\n\nPlease see the [minimatch\ndocumentation](https://github.com/isaacs/minimatch) for more details.\n\nSupports these glob features:\n\n* Brace Expansion\n* Extended glob matching\n* \"Globstar\" `**` matching\n\nSee:\n\n* `man sh`\n* `man bash`\n* `man 3 fnmatch`\n* `man 5 gitignore`\n* [minimatch documentation](https://github.com/isaacs/minimatch)\n\n## glob(pattern, [options], cb)\n\n* `pattern` {String} Pattern to be matched\n* `options` {Object}\n* `cb` {Function}\n  * `err` {Error | null}\n  * `matches` {Array} filenames found matching the pattern\n\nPerform an asynchronous glob search.\n\n## glob.sync(pattern, [options])\n\n* `pattern` {String} Pattern to be matched\n* `options` {Object}\n* return: {Array} filenames found matching the pattern\n\nPerform a synchronous glob search.\n\n## Class: glob.Glob\n\nCreate a Glob object by instanting the `glob.Glob` class.\n\n```javascript\nvar Glob = require(\"glob\").Glob\nvar mg = new Glob(pattern, options, cb)\n```\n\nIt's an EventEmitter, and starts walking the filesystem to find matches\nimmediately.\n\n### new glob.Glob(pattern, [options], [cb])\n\n* `pattern` {String} pattern to search for\n* `options` {Object}\n* `cb` {Function} Called when an error occurs, or matches are found\n  * `err` {Error | null}\n  * `matches` {Array} filenames found matching the pattern\n\nNote that if the `sync` flag is set in the options, then matches will\nbe immediately available on the `g.found` member.\n\n### Properties\n\n* `minimatch` The minimatch object that the glob uses.\n* `options` The options object passed in.\n* `error` The error encountered.  When an error is encountered, the\n  glob object is in an undefined state, and should be discarded.\n* `aborted` Boolean which is set to true when calling `abort()`.  There\n  is no way at this time to continue a glob search after aborting, but\n  you can re-use the statCache to avoid having to duplicate syscalls.\n* `statCache` Collection of all the stat results the glob search\n  performed.\n* `cache` Convenience object.  Each field has the following possible\n  values:\n  * `false` - Path does not exist\n  * `true` - Path exists\n  * `1` - Path exists, and is not a directory\n  * `2` - Path exists, and is a directory\n  * `[file, entries, ...]` - Path exists, is a directory, and the\n    array value is the results of `fs.readdir`\n\n### Events\n\n* `end` When the matching is finished, this is emitted with all the\n  matches found.  If the `nonull` option is set, and no match was found,\n  then the `matches` list contains the original pattern.  The matches\n  are sorted, unless the `nosort` flag is set.\n* `match` Every time a match is found, this is emitted with the matched.\n* `error` Emitted when an unexpected error is encountered, or whenever\n  any fs error occurs if `options.strict` is set.\n* `abort` When `abort()` is called, this event is raised.\n\n### Methods\n\n* `abort` Stop the search.\n\n### Options\n\nAll the options that can be passed to Minimatch can also be passed to\nGlob to change pattern matching behavior.  Also, some have been added,\nor have glob-specific ramifications.\n\nAll options are false by default, unless otherwise noted.\n\nAll options are added to the glob object, as well.\n\n* `cwd` The current working directory in which to search.  Defaults\n  to `process.cwd()`.\n* `root` The place where patterns starting with `/` will be mounted\n  onto.  Defaults to `path.resolve(options.cwd, \"/\")` (`/` on Unix\n  systems, and `C:\\` or some such on Windows.)\n* `dot` Include `.dot` files in normal matches and `globstar` matches.\n  Note that an explicit dot in a portion of the pattern will always\n  match dot files.\n* `nomount` By default, a pattern starting with a forward-slash will be\n  \"mounted\" onto the root setting, so that a valid filesystem path is\n  returned.  Set this flag to disable that behavior.\n* `mark` Add a `/` character to directory matches.  Note that this\n  requires additional stat calls.\n* `nosort` Don't sort the results.\n* `stat` Set to true to stat *all* results.  This reduces performance\n  somewhat, and is completely unnecessary, unless `readdir` is presumed\n  to be an untrustworthy indicator of file existence.  It will cause\n  ELOOP to be triggered one level sooner in the case of cyclical\n  symbolic links.\n* `silent` When an unusual error is encountered\n  when attempting to read a directory, a warning will be printed to\n  stderr.  Set the `silent` option to true to suppress these warnings.\n* `strict` When an unusual error is encountered\n  when attempting to read a directory, the process will just continue on\n  in search of other matches.  Set the `strict` option to raise an error\n  in these cases.\n* `cache` See `cache` property above.  Pass in a previously generated\n  cache object to save some fs calls.\n* `statCache` A cache of results of filesystem information, to prevent\n  unnecessary stat calls.  While it should not normally be necessary to\n  set this, you may pass the statCache from one glob() call to the\n  options object of another, if you know that the filesystem will not\n  change between calls.  (See \"Race Conditions\" below.)\n* `sync` Perform a synchronous glob search.\n* `nounique` In some cases, brace-expanded patterns can result in the\n  same file showing up multiple times in the result set.  By default,\n  this implementation prevents duplicates in the result set.\n  Set this flag to disable that behavior.\n* `nonull` Set to never return an empty set, instead returning a set\n  containing the pattern itself.  This is the default in glob(3).\n* `nocase` Perform a case-insensitive match.  Note that case-insensitive\n  filesystems will sometimes result in glob returning results that are\n  case-insensitively matched anyway, since readdir and stat will not\n  raise an error.\n* `debug` Set to enable debug logging in minimatch and glob.\n* `globDebug` Set to enable debug logging in glob, but not minimatch.\n\n## Comparisons to other fnmatch/glob implementations\n\nWhile strict compliance with the existing standards is a worthwhile\ngoal, some discrepancies exist between node-glob and other\nimplementations, and are intentional.\n\nIf the pattern starts with a `!` character, then it is negated.  Set the\n`nonegate` flag to suppress this behavior, and treat leading `!`\ncharacters normally.  This is perhaps relevant if you wish to start the\npattern with a negative extglob pattern like `!(a|B)`.  Multiple `!`\ncharacters at the start of a pattern will negate the pattern multiple\ntimes.\n\nIf a pattern starts with `#`, then it is treated as a comment, and\nwill not match anything.  Use `\\#` to match a literal `#` at the\nstart of a line, or set the `nocomment` flag to suppress this behavior.\n\nThe double-star character `**` is supported by default, unless the\n`noglobstar` flag is set.  This is supported in the manner of bsdglob\nand bash 4.1, where `**` only has special significance if it is the only\nthing in a path part.  That is, `a/**/b` will match `a/x/y/b`, but\n`a/**b` will not.\n\nIf an escaped pattern has no matches, and the `nonull` flag is set,\nthen glob returns the pattern as-provided, rather than\ninterpreting the character escapes.  For example,\n`glob.match([], \"\\\\*a\\\\?\")` will return `\"\\\\*a\\\\?\"` rather than\n`\"*a?\"`.  This is akin to setting the `nullglob` option in bash, except\nthat it does not resolve escaped pattern characters.\n\nIf brace expansion is not disabled, then it is performed before any\nother interpretation of the glob pattern.  Thus, a pattern like\n`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded\n**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are\nchecked for validity.  Since those two are valid, matching proceeds.\n\n## Windows\n\n**Please only use forward-slashes in glob expressions.**\n\nThough windows uses either `/` or `\\` as its path separator, only `/`\ncharacters are used by this glob implementation.  You must use\nforward-slashes **only** in glob expressions.  Back-slashes will always\nbe interpreted as escape characters, not path separators.\n\nResults from absolute patterns such as `/foo/*` are mounted onto the\nroot setting using `path.join`.  On windows, this will by default result\nin `/foo/*` matching `C:\\foo\\bar.txt`.\n\n## Race Conditions\n\nGlob searching, by its very nature, is susceptible to race conditions,\nsince it relies on directory walking and such.\n\nAs a result, it is possible that a file that exists when glob looks for\nit may have been deleted or modified by the time it returns the result.\n\nAs part of its internal implementation, this program caches all stat\nand readdir calls that it makes, in order to cut down on system\noverhead.  However, this also makes it even more susceptible to races,\nespecially if the cache or statCache objects are reused between glob\ncalls.\n\nUsers are thus advised not to use a glob result as a guarantee of\nfilesystem state in the face of rapid changes.  For the vast majority\nof operations, this is never a problem.\n",
      -  "readmeFilename": "README.md",
      -  "homepage": "https://github.com/isaacs/node-glob"
      -}
      diff --git a/node_modules/mocha/node_modules/glob/test/00-setup.js b/node_modules/mocha/node_modules/glob/test/00-setup.js
      deleted file mode 100644
      index 245afaf..0000000
      --- a/node_modules/mocha/node_modules/glob/test/00-setup.js
      +++ /dev/null
      @@ -1,176 +0,0 @@
      -// just a little pre-run script to set up the fixtures.
      -// zz-finish cleans it up
      -
      -var mkdirp = require("mkdirp")
      -var path = require("path")
      -var i = 0
      -var tap = require("tap")
      -var fs = require("fs")
      -var rimraf = require("rimraf")
      -
      -var files =
      -[ "a/.abcdef/x/y/z/a"
      -, "a/abcdef/g/h"
      -, "a/abcfed/g/h"
      -, "a/b/c/d"
      -, "a/bc/e/f"
      -, "a/c/d/c/b"
      -, "a/cb/e/f"
      -]
      -
      -var symlinkTo = path.resolve(__dirname, "a/symlink/a/b/c")
      -var symlinkFrom = "../.."
      -
      -files = files.map(function (f) {
      -  return path.resolve(__dirname, f)
      -})
      -
      -tap.test("remove fixtures", function (t) {
      -  rimraf(path.resolve(__dirname, "a"), function (er) {
      -    t.ifError(er, "remove fixtures")
      -    t.end()
      -  })
      -})
      -
      -files.forEach(function (f) {
      -  tap.test(f, function (t) {
      -    var d = path.dirname(f)
      -    mkdirp(d, 0755, function (er) {
      -      if (er) {
      -        t.fail(er)
      -        return t.bailout()
      -      }
      -      fs.writeFile(f, "i like tests", function (er) {
      -        t.ifError(er, "make file")
      -        t.end()
      -      })
      -    })
      -  })
      -})
      -
      -if (process.platform !== "win32") {
      -  tap.test("symlinky", function (t) {
      -    var d = path.dirname(symlinkTo)
      -    console.error("mkdirp", d)
      -    mkdirp(d, 0755, function (er) {
      -      t.ifError(er)
      -      fs.symlink(symlinkFrom, symlinkTo, "dir", function (er) {
      -        t.ifError(er, "make symlink")
      -        t.end()
      -      })
      -    })
      -  })
      -}
      -
      -;["foo","bar","baz","asdf","quux","qwer","rewq"].forEach(function (w) {
      -  w = "/tmp/glob-test/" + w
      -  tap.test("create " + w, function (t) {
      -    mkdirp(w, function (er) {
      -      if (er)
      -        throw er
      -      t.pass(w)
      -      t.end()
      -    })
      -  })
      -})
      -
      -
      -// generate the bash pattern test-fixtures if possible
      -if (process.platform === "win32" || !process.env.TEST_REGEN) {
      -  console.error("Windows, or TEST_REGEN unset.  Using cached fixtures.")
      -  return
      -}
      -
      -var spawn = require("child_process").spawn;
      -var globs =
      -  // put more patterns here.
      -  // anything that would be directly in / should be in /tmp/glob-test
      -  ["test/a/*/+(c|g)/./d"
      -  ,"test/a/**/[cg]/../[cg]"
      -  ,"test/a/{b,c,d,e,f}/**/g"
      -  ,"test/a/b/**"
      -  ,"test/**/g"
      -  ,"test/a/abc{fed,def}/g/h"
      -  ,"test/a/abc{fed/g,def}/**/"
      -  ,"test/a/abc{fed/g,def}/**///**/"
      -  ,"test/**/a/**/"
      -  ,"test/+(a|b|c)/a{/,bc*}/**"
      -  ,"test/*/*/*/f"
      -  ,"test/**/f"
      -  ,"test/a/symlink/a/b/c/a/b/c/a/b/c//a/b/c////a/b/c/**/b/c/**"
      -  ,"{./*/*,/tmp/glob-test/*}"
      -  ,"{/tmp/glob-test/*,*}" // evil owl face!  how you taunt me!
      -  ,"test/a/!(symlink)/**"
      -  ]
      -var bashOutput = {}
      -var fs = require("fs")
      -
      -globs.forEach(function (pattern) {
      -  tap.test("generate fixture " + pattern, function (t) {
      -    var cmd = "shopt -s globstar && " +
      -              "shopt -s extglob && " +
      -              "shopt -s nullglob && " +
      -              // "shopt >&2; " +
      -              "eval \'for i in " + pattern + "; do echo $i; done\'"
      -    var cp = spawn("bash", ["-c", cmd], { cwd: path.dirname(__dirname) })
      -    var out = []
      -    cp.stdout.on("data", function (c) {
      -      out.push(c)
      -    })
      -    cp.stderr.pipe(process.stderr)
      -    cp.on("close", function (code) {
      -      out = flatten(out)
      -      if (!out)
      -        out = []
      -      else
      -        out = cleanResults(out.split(/\r*\n/))
      -
      -      bashOutput[pattern] = out
      -      t.notOk(code, "bash test should finish nicely")
      -      t.end()
      -    })
      -  })
      -})
      -
      -tap.test("save fixtures", function (t) {
      -  var fname = path.resolve(__dirname, "bash-results.json")
      -  var data = JSON.stringify(bashOutput, null, 2) + "\n"
      -  fs.writeFile(fname, data, function (er) {
      -    t.ifError(er)
      -    t.end()
      -  })
      -})
      -
      -function cleanResults (m) {
      -  // normalize discrepancies in ordering, duplication,
      -  // and ending slashes.
      -  return m.map(function (m) {
      -    return m.replace(/\/+/g, "/").replace(/\/$/, "")
      -  }).sort(alphasort).reduce(function (set, f) {
      -    if (f !== set[set.length - 1]) set.push(f)
      -    return set
      -  }, []).sort(alphasort).map(function (f) {
      -    // de-windows
      -    return (process.platform !== 'win32') ? f
      -           : f.replace(/^[a-zA-Z]:\\\\/, '/').replace(/\\/g, '/')
      -  })
      -}
      -
      -function flatten (chunks) {
      -  var s = 0
      -  chunks.forEach(function (c) { s += c.length })
      -  var out = new Buffer(s)
      -  s = 0
      -  chunks.forEach(function (c) {
      -    c.copy(out, s)
      -    s += c.length
      -  })
      -
      -  return out.toString().trim()
      -}
      -
      -function alphasort (a, b) {
      -  a = a.toLowerCase()
      -  b = b.toLowerCase()
      -  return a > b ? 1 : a < b ? -1 : 0
      -}
      diff --git a/node_modules/mocha/node_modules/glob/test/bash-comparison.js b/node_modules/mocha/node_modules/glob/test/bash-comparison.js
      deleted file mode 100644
      index 239ed1a..0000000
      --- a/node_modules/mocha/node_modules/glob/test/bash-comparison.js
      +++ /dev/null
      @@ -1,63 +0,0 @@
      -// basic test
      -// show that it does the same thing by default as the shell.
      -var tap = require("tap")
      -, child_process = require("child_process")
      -, bashResults = require("./bash-results.json")
      -, globs = Object.keys(bashResults)
      -, glob = require("../")
      -, path = require("path")
      -
      -// run from the root of the project
      -// this is usually where you're at anyway, but be sure.
      -process.chdir(path.resolve(__dirname, ".."))
      -
      -function alphasort (a, b) {
      -  a = a.toLowerCase()
      -  b = b.toLowerCase()
      -  return a > b ? 1 : a < b ? -1 : 0
      -}
      -
      -globs.forEach(function (pattern) {
      -  var expect = bashResults[pattern]
      -  // anything regarding the symlink thing will fail on windows, so just skip it
      -  if (process.platform === "win32" &&
      -      expect.some(function (m) {
      -        return /\/symlink\//.test(m)
      -      }))
      -    return
      -
      -  tap.test(pattern, function (t) {
      -    glob(pattern, function (er, matches) {
      -      if (er)
      -        throw er
      -
      -      // sort and unmark, just to match the shell results
      -      matches = cleanResults(matches)
      -
      -      t.deepEqual(matches, expect, pattern)
      -      t.end()
      -    })
      -  })
      -
      -  tap.test(pattern + " sync", function (t) {
      -    var matches = cleanResults(glob.sync(pattern))
      -
      -    t.deepEqual(matches, expect, "should match shell")
      -    t.end()
      -  })
      -})
      -
      -function cleanResults (m) {
      -  // normalize discrepancies in ordering, duplication,
      -  // and ending slashes.
      -  return m.map(function (m) {
      -    return m.replace(/\/+/g, "/").replace(/\/$/, "")
      -  }).sort(alphasort).reduce(function (set, f) {
      -    if (f !== set[set.length - 1]) set.push(f)
      -    return set
      -  }, []).sort(alphasort).map(function (f) {
      -    // de-windows
      -    return (process.platform !== 'win32') ? f
      -           : f.replace(/^[a-zA-Z]:[\/\\]+/, '/').replace(/[\\\/]+/g, '/')
      -  })
      -}
      diff --git a/node_modules/mocha/node_modules/glob/test/bash-results.json b/node_modules/mocha/node_modules/glob/test/bash-results.json
      deleted file mode 100644
      index a9bc347..0000000
      --- a/node_modules/mocha/node_modules/glob/test/bash-results.json
      +++ /dev/null
      @@ -1,350 +0,0 @@
      -{
      -  "test/a/*/+(c|g)/./d": [
      -    "test/a/b/c/./d"
      -  ],
      -  "test/a/**/[cg]/../[cg]": [
      -    "test/a/abcdef/g/../g",
      -    "test/a/abcfed/g/../g",
      -    "test/a/b/c/../c",
      -    "test/a/c/../c",
      -    "test/a/c/d/c/../c",
      -    "test/a/symlink/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/../c"
      -  ],
      -  "test/a/{b,c,d,e,f}/**/g": [],
      -  "test/a/b/**": [
      -    "test/a/b",
      -    "test/a/b/c",
      -    "test/a/b/c/d"
      -  ],
      -  "test/**/g": [
      -    "test/a/abcdef/g",
      -    "test/a/abcfed/g"
      -  ],
      -  "test/a/abc{fed,def}/g/h": [
      -    "test/a/abcdef/g/h",
      -    "test/a/abcfed/g/h"
      -  ],
      -  "test/a/abc{fed/g,def}/**/": [
      -    "test/a/abcdef",
      -    "test/a/abcdef/g",
      -    "test/a/abcfed/g"
      -  ],
      -  "test/a/abc{fed/g,def}/**///**/": [
      -    "test/a/abcdef",
      -    "test/a/abcdef/g",
      -    "test/a/abcfed/g"
      -  ],
      -  "test/**/a/**/": [
      -    "test/a",
      -    "test/a/abcdef",
      -    "test/a/abcdef/g",
      -    "test/a/abcfed",
      -    "test/a/abcfed/g",
      -    "test/a/b",
      -    "test/a/b/c",
      -    "test/a/bc",
      -    "test/a/bc/e",
      -    "test/a/c",
      -    "test/a/c/d",
      -    "test/a/c/d/c",
      -    "test/a/cb",
      -    "test/a/cb/e",
      -    "test/a/symlink",
      -    "test/a/symlink/a",
      -    "test/a/symlink/a/b",
      -    "test/a/symlink/a/b/c",
      -    "test/a/symlink/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b"
      -  ],
      -  "test/+(a|b|c)/a{/,bc*}/**": [
      -    "test/a/abcdef",
      -    "test/a/abcdef/g",
      -    "test/a/abcdef/g/h",
      -    "test/a/abcfed",
      -    "test/a/abcfed/g",
      -    "test/a/abcfed/g/h"
      -  ],
      -  "test/*/*/*/f": [
      -    "test/a/bc/e/f",
      -    "test/a/cb/e/f"
      -  ],
      -  "test/**/f": [
      -    "test/a/bc/e/f",
      -    "test/a/cb/e/f"
      -  ],
      -  "test/a/symlink/a/b/c/a/b/c/a/b/c//a/b/c////a/b/c/**/b/c/**": [
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b",
      -    "test/a/symlink/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c/a/b/c"
      -  ],
      -  "{./*/*,/tmp/glob-test/*}": [
      -    "./examples/g.js",
      -    "./examples/usr-local.js",
      -    "./node_modules/graceful-fs",
      -    "./node_modules/inherits",
      -    "./node_modules/minimatch",
      -    "./node_modules/mkdirp",
      -    "./node_modules/rimraf",
      -    "./node_modules/tap",
      -    "./test/00-setup.js",
      -    "./test/a",
      -    "./test/bash-comparison.js",
      -    "./test/bash-results.json",
      -    "./test/cwd-test.js",
      -    "./test/globstar-match.js",
      -    "./test/mark.js",
      -    "./test/nocase-nomagic.js",
      -    "./test/pause-resume.js",
      -    "./test/root-nomount.js",
      -    "./test/root.js",
      -    "./test/stat.js",
      -    "./test/zz-cleanup.js",
      -    "/tmp/glob-test/asdf",
      -    "/tmp/glob-test/bar",
      -    "/tmp/glob-test/baz",
      -    "/tmp/glob-test/foo",
      -    "/tmp/glob-test/quux",
      -    "/tmp/glob-test/qwer",
      -    "/tmp/glob-test/rewq"
      -  ],
      -  "{/tmp/glob-test/*,*}": [
      -    "/tmp/glob-test/asdf",
      -    "/tmp/glob-test/bar",
      -    "/tmp/glob-test/baz",
      -    "/tmp/glob-test/foo",
      -    "/tmp/glob-test/quux",
      -    "/tmp/glob-test/qwer",
      -    "/tmp/glob-test/rewq",
      -    "examples",
      -    "glob.js",
      -    "LICENSE",
      -    "node_modules",
      -    "package.json",
      -    "README.md",
      -    "test"
      -  ],
      -  "test/a/!(symlink)/**": [
      -    "test/a/abcdef",
      -    "test/a/abcdef/g",
      -    "test/a/abcdef/g/h",
      -    "test/a/abcfed",
      -    "test/a/abcfed/g",
      -    "test/a/abcfed/g/h",
      -    "test/a/b",
      -    "test/a/b/c",
      -    "test/a/b/c/d",
      -    "test/a/bc",
      -    "test/a/bc/e",
      -    "test/a/bc/e/f",
      -    "test/a/c",
      -    "test/a/c/d",
      -    "test/a/c/d/c",
      -    "test/a/c/d/c/b",
      -    "test/a/cb",
      -    "test/a/cb/e",
      -    "test/a/cb/e/f"
      -  ]
      -}
      diff --git a/node_modules/mocha/node_modules/glob/test/cwd-test.js b/node_modules/mocha/node_modules/glob/test/cwd-test.js
      deleted file mode 100644
      index 352c27e..0000000
      --- a/node_modules/mocha/node_modules/glob/test/cwd-test.js
      +++ /dev/null
      @@ -1,55 +0,0 @@
      -var tap = require("tap")
      -
      -var origCwd = process.cwd()
      -process.chdir(__dirname)
      -
      -tap.test("changing cwd and searching for **/d", function (t) {
      -  var glob = require('../')
      -  var path = require('path')
      -  t.test('.', function (t) {
      -    glob('**/d', function (er, matches) {
      -      t.ifError(er)
      -      t.like(matches, [ 'a/b/c/d', 'a/c/d' ])
      -      t.end()
      -    })
      -  })
      -
      -  t.test('a', function (t) {
      -    glob('**/d', {cwd:path.resolve('a')}, function (er, matches) {
      -      t.ifError(er)
      -      t.like(matches, [ 'b/c/d', 'c/d' ])
      -      t.end()
      -    })
      -  })
      -
      -  t.test('a/b', function (t) {
      -    glob('**/d', {cwd:path.resolve('a/b')}, function (er, matches) {
      -      t.ifError(er)
      -      t.like(matches, [ 'c/d' ])
      -      t.end()
      -    })
      -  })
      -
      -  t.test('a/b/', function (t) {
      -    glob('**/d', {cwd:path.resolve('a/b/')}, function (er, matches) {
      -      t.ifError(er)
      -      t.like(matches, [ 'c/d' ])
      -      t.end()
      -    })
      -  })
      -
      -  t.test('.', function (t) {
      -    glob('**/d', {cwd: process.cwd()}, function (er, matches) {
      -      t.ifError(er)
      -      t.like(matches, [ 'a/b/c/d', 'a/c/d' ])
      -      t.end()
      -    })
      -  })
      -
      -  t.test('cd -', function (t) {
      -    process.chdir(origCwd)
      -    t.end()
      -  })
      -
      -  t.end()
      -})
      diff --git a/node_modules/mocha/node_modules/glob/test/globstar-match.js b/node_modules/mocha/node_modules/glob/test/globstar-match.js
      deleted file mode 100644
      index 9b234fa..0000000
      --- a/node_modules/mocha/node_modules/glob/test/globstar-match.js
      +++ /dev/null
      @@ -1,19 +0,0 @@
      -var Glob = require("../glob.js").Glob
      -var test = require('tap').test
      -
      -test('globstar should not have dupe matches', function(t) {
      -  var pattern = 'a/**/[gh]'
      -  var g = new Glob(pattern, { cwd: __dirname })
      -  var matches = []
      -  g.on('match', function(m) {
      -    console.error('match %j', m)
      -    matches.push(m)
      -  })
      -  g.on('end', function(set) {
      -    console.error('set', set)
      -    matches = matches.sort()
      -    set = set.sort()
      -    t.same(matches, set, 'should have same set of matches')
      -    t.end()
      -  })
      -})
      diff --git a/node_modules/mocha/node_modules/glob/test/mark.js b/node_modules/mocha/node_modules/glob/test/mark.js
      deleted file mode 100644
      index ed68a33..0000000
      --- a/node_modules/mocha/node_modules/glob/test/mark.js
      +++ /dev/null
      @@ -1,74 +0,0 @@
      -var test = require("tap").test
      -var glob = require('../')
      -process.chdir(__dirname)
      -
      -test("mark, no / on pattern", function (t) {
      -  glob("a/*", {mark: true}, function (er, results) {
      -    if (er)
      -      throw er
      -    var expect = [ 'a/abcdef/',
      -                   'a/abcfed/',
      -                   'a/b/',
      -                   'a/bc/',
      -                   'a/c/',
      -                   'a/cb/' ]
      -
      -    if (process.platform !== "win32")
      -      expect.push('a/symlink/')
      -
      -    t.same(results, expect)
      -    t.end()
      -  })
      -})
      -
      -test("mark=false, no / on pattern", function (t) {
      -  glob("a/*", function (er, results) {
      -    if (er)
      -      throw er
      -    var expect = [ 'a/abcdef',
      -                   'a/abcfed',
      -                   'a/b',
      -                   'a/bc',
      -                   'a/c',
      -                   'a/cb' ]
      -
      -    if (process.platform !== "win32")
      -      expect.push('a/symlink')
      -    t.same(results, expect)
      -    t.end()
      -  })
      -})
      -
      -test("mark=true, / on pattern", function (t) {
      -  glob("a/*/", {mark: true}, function (er, results) {
      -    if (er)
      -      throw er
      -    var expect = [ 'a/abcdef/',
      -                    'a/abcfed/',
      -                    'a/b/',
      -                    'a/bc/',
      -                    'a/c/',
      -                    'a/cb/' ]
      -    if (process.platform !== "win32")
      -      expect.push('a/symlink/')
      -    t.same(results, expect)
      -    t.end()
      -  })
      -})
      -
      -test("mark=false, / on pattern", function (t) {
      -  glob("a/*/", function (er, results) {
      -    if (er)
      -      throw er
      -    var expect = [ 'a/abcdef/',
      -                   'a/abcfed/',
      -                   'a/b/',
      -                   'a/bc/',
      -                   'a/c/',
      -                   'a/cb/' ]
      -    if (process.platform !== "win32")
      -      expect.push('a/symlink/')
      -    t.same(results, expect)
      -    t.end()
      -  })
      -})
      diff --git a/node_modules/mocha/node_modules/glob/test/nocase-nomagic.js b/node_modules/mocha/node_modules/glob/test/nocase-nomagic.js
      deleted file mode 100644
      index d862970..0000000
      --- a/node_modules/mocha/node_modules/glob/test/nocase-nomagic.js
      +++ /dev/null
      @@ -1,113 +0,0 @@
      -var fs = require('graceful-fs');
      -var test = require('tap').test;
      -var glob = require('../');
      -
      -test('mock fs', function(t) {
      -  var stat = fs.stat
      -  var statSync = fs.statSync
      -  var readdir = fs.readdir
      -  var readdirSync = fs.readdirSync
      -
      -  function fakeStat(path) {
      -    var ret
      -    switch (path.toLowerCase()) {
      -      case '/tmp': case '/tmp/':
      -        ret = { isDirectory: function() { return true } }
      -        break
      -      case '/tmp/a':
      -        ret = { isDirectory: function() { return false } }
      -        break
      -    }
      -    return ret
      -  }
      -
      -  fs.stat = function(path, cb) {
      -    var f = fakeStat(path);
      -    if (f) {
      -      process.nextTick(function() {
      -        cb(null, f)
      -      })
      -    } else {
      -      stat.call(fs, path, cb)
      -    }
      -  }
      -
      -  fs.statSync = function(path) {
      -    return fakeStat(path) || statSync.call(fs, path)
      -  }
      -
      -  function fakeReaddir(path) {
      -    var ret
      -    switch (path.toLowerCase()) {
      -      case '/tmp': case '/tmp/':
      -        ret = [ 'a', 'A' ]
      -        break
      -      case '/':
      -        ret = ['tmp', 'tMp', 'tMP', 'TMP']
      -    }
      -    return ret
      -  }
      -
      -  fs.readdir = function(path, cb) {
      -    var f = fakeReaddir(path)
      -    if (f)
      -      process.nextTick(function() {
      -        cb(null, f)
      -      })
      -    else
      -      readdir.call(fs, path, cb)
      -  }
      -
      -  fs.readdirSync = function(path) {
      -    return fakeReaddir(path) || readdirSync.call(fs, path)
      -  }
      -
      -  t.pass('mocked')
      -  t.end()
      -})
      -
      -test('nocase, nomagic', function(t) {
      -  var n = 2
      -  var want = [ '/TMP/A',
      -               '/TMP/a',
      -               '/tMP/A',
      -               '/tMP/a',
      -               '/tMp/A',
      -               '/tMp/a',
      -               '/tmp/A',
      -               '/tmp/a' ]
      -  glob('/tmp/a', { nocase: true }, function(er, res) {
      -    if (er)
      -      throw er
      -    t.same(res.sort(), want)
      -    if (--n === 0) t.end()
      -  })
      -  glob('/tmp/A', { nocase: true }, function(er, res) {
      -    if (er)
      -      throw er
      -    t.same(res.sort(), want)
      -    if (--n === 0) t.end()
      -  })
      -})
      -
      -test('nocase, with some magic', function(t) {
      -  t.plan(2)
      -  var want = [ '/TMP/A',
      -               '/TMP/a',
      -               '/tMP/A',
      -               '/tMP/a',
      -               '/tMp/A',
      -               '/tMp/a',
      -               '/tmp/A',
      -               '/tmp/a' ]
      -  glob('/tmp/*', { nocase: true }, function(er, res) {
      -    if (er)
      -      throw er
      -    t.same(res.sort(), want)
      -  })
      -  glob('/tmp/*', { nocase: true }, function(er, res) {
      -    if (er)
      -      throw er
      -    t.same(res.sort(), want)
      -  })
      -})
      diff --git a/node_modules/mocha/node_modules/glob/test/pause-resume.js b/node_modules/mocha/node_modules/glob/test/pause-resume.js
      deleted file mode 100644
      index e1ffbab..0000000
      --- a/node_modules/mocha/node_modules/glob/test/pause-resume.js
      +++ /dev/null
      @@ -1,73 +0,0 @@
      -// show that no match events happen while paused.
      -var tap = require("tap")
      -, child_process = require("child_process")
      -// just some gnarly pattern with lots of matches
      -, pattern = "test/a/!(symlink)/**"
      -, bashResults = require("./bash-results.json")
      -, patterns = Object.keys(bashResults)
      -, glob = require("../")
      -, Glob = glob.Glob
      -, path = require("path")
      -
      -// run from the root of the project
      -// this is usually where you're at anyway, but be sure.
      -process.chdir(path.resolve(__dirname, ".."))
      -
      -function alphasort (a, b) {
      -  a = a.toLowerCase()
      -  b = b.toLowerCase()
      -  return a > b ? 1 : a < b ? -1 : 0
      -}
      -
      -function cleanResults (m) {
      -  // normalize discrepancies in ordering, duplication,
      -  // and ending slashes.
      -  return m.map(function (m) {
      -    return m.replace(/\/+/g, "/").replace(/\/$/, "")
      -  }).sort(alphasort).reduce(function (set, f) {
      -    if (f !== set[set.length - 1]) set.push(f)
      -    return set
      -  }, []).sort(alphasort).map(function (f) {
      -    // de-windows
      -    return (process.platform !== 'win32') ? f
      -           : f.replace(/^[a-zA-Z]:\\\\/, '/').replace(/\\/g, '/')
      -  })
      -}
      -
      -var globResults = []
      -tap.test("use a Glob object, and pause/resume it", function (t) {
      -  var g = new Glob(pattern)
      -  , paused = false
      -  , res = []
      -  , expect = bashResults[pattern]
      -
      -  g.on("pause", function () {
      -    console.error("pause")
      -  })
      -
      -  g.on("resume", function () {
      -    console.error("resume")
      -  })
      -
      -  g.on("match", function (m) {
      -    t.notOk(g.paused, "must not be paused")
      -    globResults.push(m)
      -    g.pause()
      -    t.ok(g.paused, "must be paused")
      -    setTimeout(g.resume.bind(g), 10)
      -  })
      -
      -  g.on("end", function (matches) {
      -    t.pass("reached glob end")
      -    globResults = cleanResults(globResults)
      -    matches = cleanResults(matches)
      -    t.deepEqual(matches, globResults,
      -      "end event matches should be the same as match events")
      -
      -    t.deepEqual(matches, expect,
      -      "glob matches should be the same as bash results")
      -
      -    t.end()
      -  })
      -})
      -
      diff --git a/node_modules/mocha/node_modules/glob/test/root-nomount.js b/node_modules/mocha/node_modules/glob/test/root-nomount.js
      deleted file mode 100644
      index 3ac5979..0000000
      --- a/node_modules/mocha/node_modules/glob/test/root-nomount.js
      +++ /dev/null
      @@ -1,39 +0,0 @@
      -var tap = require("tap")
      -
      -var origCwd = process.cwd()
      -process.chdir(__dirname)
      -
      -tap.test("changing root and searching for /b*/**", function (t) {
      -  var glob = require('../')
      -  var path = require('path')
      -  t.test('.', function (t) {
      -    glob('/b*/**', { globDebug: true, root: '.', nomount: true }, function (er, matches) {
      -      t.ifError(er)
      -      t.like(matches, [])
      -      t.end()
      -    })
      -  })
      -
      -  t.test('a', function (t) {
      -    glob('/b*/**', { globDebug: true, root: path.resolve('a'), nomount: true }, function (er, matches) {
      -      t.ifError(er)
      -      t.like(matches, [ '/b', '/b/c', '/b/c/d', '/bc', '/bc/e', '/bc/e/f' ])
      -      t.end()
      -    })
      -  })
      -
      -  t.test('root=a, cwd=a/b', function (t) {
      -    glob('/b*/**', { globDebug: true, root: 'a', cwd: path.resolve('a/b'), nomount: true }, function (er, matches) {
      -      t.ifError(er)
      -      t.like(matches, [ '/b', '/b/c', '/b/c/d', '/bc', '/bc/e', '/bc/e/f' ])
      -      t.end()
      -    })
      -  })
      -
      -  t.test('cd -', function (t) {
      -    process.chdir(origCwd)
      -    t.end()
      -  })
      -
      -  t.end()
      -})
      diff --git a/node_modules/mocha/node_modules/glob/test/root.js b/node_modules/mocha/node_modules/glob/test/root.js
      deleted file mode 100644
      index 95c23f9..0000000
      --- a/node_modules/mocha/node_modules/glob/test/root.js
      +++ /dev/null
      @@ -1,46 +0,0 @@
      -var t = require("tap")
      -
      -var origCwd = process.cwd()
      -process.chdir(__dirname)
      -
      -var glob = require('../')
      -var path = require('path')
      -
      -t.test('.', function (t) {
      -  glob('/b*/**', { globDebug: true, root: '.' }, function (er, matches) {
      -    t.ifError(er)
      -    t.like(matches, [])
      -    t.end()
      -  })
      -})
      -
      -
      -t.test('a', function (t) {
      -  console.error("root=" + path.resolve('a'))
      -  glob('/b*/**', { globDebug: true, root: path.resolve('a') }, function (er, matches) {
      -    t.ifError(er)
      -    var wanted = [
      -        '/b', '/b/c', '/b/c/d', '/bc', '/bc/e', '/bc/e/f'
      -      ].map(function (m) {
      -        return path.join(path.resolve('a'), m).replace(/\\/g, '/')
      -      })
      -
      -    t.like(matches, wanted)
      -    t.end()
      -  })
      -})
      -
      -t.test('root=a, cwd=a/b', function (t) {
      -  glob('/b*/**', { globDebug: true, root: 'a', cwd: path.resolve('a/b') }, function (er, matches) {
      -    t.ifError(er)
      -    t.like(matches, [ '/b', '/b/c', '/b/c/d', '/bc', '/bc/e', '/bc/e/f' ].map(function (m) {
      -      return path.join(path.resolve('a'), m).replace(/\\/g, '/')
      -    }))
      -    t.end()
      -  })
      -})
      -
      -t.test('cd -', function (t) {
      -  process.chdir(origCwd)
      -  t.end()
      -})
      diff --git a/node_modules/mocha/node_modules/glob/test/stat.js b/node_modules/mocha/node_modules/glob/test/stat.js
      deleted file mode 100644
      index 6291711..0000000
      --- a/node_modules/mocha/node_modules/glob/test/stat.js
      +++ /dev/null
      @@ -1,32 +0,0 @@
      -var glob = require('../')
      -var test = require('tap').test
      -var path = require('path')
      -
      -test('stat all the things', function(t) {
      -  var g = new glob.Glob('a/*abc*/**', { stat: true, cwd: __dirname })
      -  var matches = []
      -  g.on('match', function(m) {
      -    matches.push(m)
      -  })
      -  var stats = []
      -  g.on('stat', function(m) {
      -    stats.push(m)
      -  })
      -  g.on('end', function(eof) {
      -    stats = stats.sort()
      -    matches = matches.sort()
      -    eof = eof.sort()
      -    t.same(stats, matches)
      -    t.same(eof, matches)
      -    var cache = Object.keys(this.statCache)
      -    t.same(cache.map(function (f) {
      -      return path.relative(__dirname, f)
      -    }).sort(), matches)
      -
      -    cache.forEach(function(c) {
      -      t.equal(typeof this.statCache[c], 'object')
      -    }, this)
      -
      -    t.end()
      -  })
      -})
      diff --git a/node_modules/mocha/node_modules/glob/test/zz-cleanup.js b/node_modules/mocha/node_modules/glob/test/zz-cleanup.js
      deleted file mode 100644
      index e085f0f..0000000
      --- a/node_modules/mocha/node_modules/glob/test/zz-cleanup.js
      +++ /dev/null
      @@ -1,11 +0,0 @@
      -// remove the fixtures
      -var tap = require("tap")
      -, rimraf = require("rimraf")
      -, path = require("path")
      -
      -tap.test("cleanup fixtures", function (t) {
      -  rimraf(path.resolve(__dirname, "a"), function (er) {
      -    t.ifError(er, "removed")
      -    t.end()
      -  })
      -})
      diff --git a/node_modules/mocha/node_modules/growl/History.md b/node_modules/mocha/node_modules/growl/History.md
      deleted file mode 100644
      index a4b7b49..0000000
      --- a/node_modules/mocha/node_modules/growl/History.md
      +++ /dev/null
      @@ -1,63 +0,0 @@
      -
      -1.7.0 / 2012-12-30 
      -==================
      -
      -  * support transient notifications in Gnome
      -
      -1.6.1 / 2012-09-25 
      -==================
      -
      -  * restore compatibility with node < 0.8 [fgnass]
      -
      -1.6.0 / 2012-09-06 
      -==================
      -
      -  * add notification center support [drudge]
      -
      -1.5.1 / 2012-04-08 
      -==================
      -
      -  * Merge pull request #16 from KyleAMathews/patch-1
      -  * Fixes #15
      -
      -1.5.0 / 2012-02-08 
      -==================
      -
      -  * Added windows support [perfusorius]
      -
      -1.4.1 / 2011-12-28 
      -==================
      -
      -  * Fixed: dont exit(). Closes #9
      -
      -1.4.0 / 2011-12-17 
      -==================
      -
      -  * Changed API: `growl.notify()` -> `growl()`
      -
      -1.3.0 / 2011-12-17 
      -==================
      -
      -  * Added support for Ubuntu/Debian/Linux users [niftylettuce]
      -  * Fixed: send notifications even if title not specified [alessioalex]
      -
      -1.2.0 / 2011-10-06 
      -==================
      -
      -  * Add support for priority.
      -
      -1.1.0 / 2011-03-15 
      -==================
      -
      -  * Added optional callbacks
      -  * Added parsing of version
      -
      -1.0.1 / 2010-03-26
      -==================
      -
      -  * Fixed; sys.exec -> child_process.exec to support latest node
      -
      -1.0.0 / 2010-03-19
      -==================
      -  
      -  * Initial release
      diff --git a/node_modules/mocha/node_modules/growl/Readme.md b/node_modules/mocha/node_modules/growl/Readme.md
      deleted file mode 100644
      index 48d717c..0000000
      --- a/node_modules/mocha/node_modules/growl/Readme.md
      +++ /dev/null
      @@ -1,99 +0,0 @@
      -# Growl for nodejs
      -
      -Growl support for Nodejs. This is essentially a port of my [Ruby Growl Library](http://github.com/visionmedia/growl). Ubuntu/Linux support added thanks to [@niftylettuce](http://github.com/niftylettuce). 
      -
      -## Installation
      -
      -### Install 
      -
      -### Mac OS X (Darwin):
      -
      -  Install [growlnotify(1)](http://growl.info/extras.php#growlnotify). On OS X 10.8, Notification Center is supported using [terminal-notifier](https://github.com/alloy/terminal-notifier). To install:
      -  
      -      $ sudo gem install terminal-notifier
      -      
      -  Install [npm](http://npmjs.org/) and run:
      -  
      -      $ npm install growl
      -
      -### Ubuntu (Linux):
      -
      -  Install `notify-send` through the [libnotify-bin](http://packages.ubuntu.com/libnotify-bin) package:
      -
      -      $ sudo apt-get install libnotify-bin
      -
      -  Install [npm](http://npmjs.org/) and run:
      -  
      -      $ npm install growl
      -
      -### Windows:
      -
      -  Download and install [Growl for Windows](http://www.growlforwindows.com/gfw/default.aspx)
      -
      -  Download [growlnotify](http://www.growlforwindows.com/gfw/help/growlnotify.aspx) - **IMPORTANT :** Unpack growlnotify to a folder that is present in your path!
      -
      -  Install [npm](http://npmjs.org/) and run:
      -  
      -      $ npm install growl
      -
      -## Examples
      -
      -Callback functions are optional
      -
      -    var growl = require('growl')
      -    growl('You have mail!')
      -    growl('5 new messages', { sticky: true })
      -    growl('5 new emails', { title: 'Email Client', image: 'Safari', sticky: true })
      -    growl('Message with title', { title: 'Title'})
      -    growl('Set priority', { priority: 2 })
      -    growl('Show Safari icon', { image: 'Safari' })
      -    growl('Show icon', { image: 'path/to/icon.icns' })
      -    growl('Show image', { image: 'path/to/my.image.png' })
      -    growl('Show png filesystem icon', { image: 'png' })
      -    growl('Show pdf filesystem icon', { image: 'article.pdf' })
      -    growl('Show pdf filesystem icon', { image: 'article.pdf' }, function(err){
      -      // ... notified
      -    })
      -
      -## Options
      -
      -  - title
      -    - notification title
      -  - name
      -    - application name
      -  - priority
      -    - priority for the notification (default is 0)
      -  - sticky
      -    - weither or not the notification should remainin until closed
      -  - image
      -    - Auto-detects the context:
      -      - path to an icon sets --iconpath
      -      - path to an image sets --image
      -      - capitalized word sets --appIcon
      -      - filename uses extname as --icon
      -      - otherwise treated as --icon
      -      
      -## License 
      -
      -(The MIT License)
      -
      -Copyright (c) 2009 TJ Holowaychuk 
      -
      -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/node_modules/mocha/node_modules/growl/lib/growl.js b/node_modules/mocha/node_modules/growl/lib/growl.js
      deleted file mode 100644
      index c034c3e..0000000
      --- a/node_modules/mocha/node_modules/growl/lib/growl.js
      +++ /dev/null
      @@ -1,234 +0,0 @@
      -// Growl - Copyright TJ Holowaychuk  (MIT Licensed)
      -
      -/**
      - * Module dependencies.
      - */
      -
      -var exec = require('child_process').exec
      -  , fs = require('fs')
      -  , path = require('path')
      -  , exists = fs.existsSync || path.existsSync
      -  , os = require('os')
      -  , quote = JSON.stringify
      -  , cmd;
      -
      -function which(name) {
      -  var paths = process.env.PATH.split(':');
      -  var loc;
      -  
      -  for (var i = 0, len = paths.length; i < len; ++i) {
      -    loc = path.join(paths[i], name);
      -    if (exists(loc)) return loc;
      -  }
      -}
      -
      -switch(os.type()) {
      -  case 'Darwin':
      -    if (which('terminal-notifier')) {
      -      cmd = {
      -          type: "Darwin-NotificationCenter"
      -        , pkg: "terminal-notifier"
      -        , msg: '-message'
      -        , title: '-title'
      -        , subtitle: '-subtitle'
      -        , priority: {
      -              cmd: '-execute'
      -            , range: []
      -          }
      -      };
      -    } else {
      -      cmd = {
      -          type: "Darwin-Growl"
      -        , pkg: "growlnotify"
      -        , msg: '-m'
      -        , sticky: '--sticky'
      -        , priority: {
      -              cmd: '--priority'
      -            , range: [
      -                -2
      -              , -1
      -              , 0
      -              , 1
      -              , 2
      -              , "Very Low"
      -              , "Moderate"
      -              , "Normal"
      -              , "High"
      -              , "Emergency"
      -            ]
      -          }
      -      };
      -    }
      -    break;
      -  case 'Linux':
      -    cmd = {
      -        type: "Linux"
      -      , pkg: "notify-send"
      -      , msg: ''
      -      , sticky: '-t 0'
      -      , icon: '-i'
      -      , priority: {
      -          cmd: '-u'
      -        , range: [
      -            "low"
      -          , "normal"
      -          , "critical"
      -        ]
      -      }
      -    };
      -    break;
      -  case 'Windows_NT':
      -    cmd = {
      -        type: "Windows"
      -      , pkg: "growlnotify"
      -      , msg: ''
      -      , sticky: '/s:true'
      -      , title: '/t:'
      -      , icon: '/i:'
      -      , priority: {
      -            cmd: '/p:'
      -          , range: [
      -              -2
      -            , -1
      -            , 0
      -            , 1
      -            , 2
      -          ]
      -        }
      -    };
      -    break;
      -}
      -
      -/**
      - * Expose `growl`.
      - */
      -
      -exports = module.exports = growl;
      -
      -/**
      - * Node-growl version.
      - */
      -
      -exports.version = '1.4.1'
      -
      -/**
      - * Send growl notification _msg_ with _options_.
      - *
      - * Options:
      - *
      - *  - title   Notification title
      - *  - sticky  Make the notification stick (defaults to false)
      - *  - priority  Specify an int or named key (default is 0)
      - *  - name    Application name (defaults to growlnotify)
      - *  - image
      - *    - path to an icon sets --iconpath
      - *    - path to an image sets --image
      - *    - capitalized word sets --appIcon
      - *    - filename uses extname as --icon
      - *    - otherwise treated as --icon
      - *
      - * Examples:
      - *
      - *   growl('New email')
      - *   growl('5 new emails', { title: 'Thunderbird' })
      - *   growl('Email sent', function(){
      - *     // ... notification sent
      - *   })
      - *
      - * @param {string} msg
      - * @param {object} options
      - * @param {function} fn
      - * @api public
      - */
      -
      -function growl(msg, options, fn) {
      -  var image
      -    , args
      -    , options = options || {}
      -    , fn = fn || function(){};
      -
      -  // noop
      -  if (!cmd) return fn(new Error('growl not supported on this platform'));
      -  args = [cmd.pkg];
      -
      -  // image
      -  if (image = options.image) {
      -    switch(cmd.type) {
      -      case 'Darwin-Growl':
      -        var flag, ext = path.extname(image).substr(1)
      -        flag = flag || ext == 'icns' && 'iconpath'
      -        flag = flag || /^[A-Z]/.test(image) && 'appIcon'
      -        flag = flag || /^png|gif|jpe?g$/.test(ext) && 'image'
      -        flag = flag || ext && (image = ext) && 'icon'
      -        flag = flag || 'icon'
      -        args.push('--' + flag, quote(image))
      -        break;
      -      case 'Linux':
      -        args.push(cmd.icon, quote(image));
      -        // libnotify defaults to sticky, set a hint for transient notifications
      -        if (!options.sticky) args.push('--hint=int:transient:1');
      -        break;
      -      case 'Windows':
      -        args.push(cmd.icon + quote(image));
      -        break;
      -    }
      -  }
      -
      -  // sticky
      -  if (options.sticky) args.push(cmd.sticky);
      -
      -  // priority
      -  if (options.priority) {
      -    var priority = options.priority + '';
      -    var checkindexOf = cmd.priority.range.indexOf(priority);
      -    if (~cmd.priority.range.indexOf(priority)) {
      -      args.push(cmd.priority, options.priority);
      -    }
      -  }
      -
      -  // name
      -  if (options.name && cmd.type === "Darwin-Growl") {
      -    args.push('--name', options.name);
      -  }
      -
      -  switch(cmd.type) {
      -    case 'Darwin-Growl':
      -      args.push(cmd.msg);
      -      args.push(quote(msg));
      -      if (options.title) args.push(quote(options.title));
      -      break;
      -    case 'Darwin-NotificationCenter':
      -      args.push(cmd.msg);
      -      args.push(quote(msg));
      -      if (options.title) {
      -        args.push(cmd.title);
      -        args.push(quote(options.title));
      -      }
      -      if (options.subtitle) {
      -        args.push(cmd.subtitle);
      -        args.push(quote(options.subtitle));
      -      }
      -      break;
      -    case 'Darwin-Growl':
      -      args.push(cmd.msg);
      -      args.push(quote(msg));
      -      if (options.title) args.push(quote(options.title));
      -      break;
      -    case 'Linux':
      -      if (options.title) {
      -        args.push(quote(options.title));
      -        args.push(cmd.msg);
      -        args.push(quote(msg));
      -      } else {
      -        args.push(quote(msg));
      -      }
      -      break;
      -    case 'Windows':
      -      args.push(quote(msg));
      -      if (options.title) args.push(cmd.title + quote(options.title));
      -      break;
      -  }
      -
      -  // execute
      -  exec(args.join(' '), fn);
      -};
      diff --git a/node_modules/mocha/node_modules/growl/package.json b/node_modules/mocha/node_modules/growl/package.json
      deleted file mode 100644
      index 7477b97..0000000
      --- a/node_modules/mocha/node_modules/growl/package.json
      +++ /dev/null
      @@ -1,46 +0,0 @@
      -{
      -  "name": "growl",
      -  "version": "1.8.1",
      -  "description": "Growl unobtrusive notifications",
      -  "author": {
      -    "name": "TJ Holowaychuk",
      -    "email": "tj@vision-media.ca"
      -  },
      -  "maintainers": [
      -    {
      -      "name": "tjholowaychuk",
      -      "email": "tj@vision-media.ca"
      -    },
      -    {
      -      "name": "jbnicolai",
      -      "email": "jappelman@xebia.com"
      -    }
      -  ],
      -  "repository": {
      -    "type": "git",
      -    "url": "git://github.com/visionmedia/node-growl.git"
      -  },
      -  "main": "./lib/growl.js",
      -  "gitHead": "882ced3155a57f566887c884d5c6dccb7df435c1",
      -  "bugs": {
      -    "url": "https://github.com/visionmedia/node-growl/issues"
      -  },
      -  "homepage": "https://github.com/visionmedia/node-growl",
      -  "_id": "growl@1.8.1",
      -  "scripts": {},
      -  "_shasum": "4b2dec8d907e93db336624dcec0183502f8c9428",
      -  "_from": "growl@1.8.1",
      -  "_npmVersion": "1.4.20",
      -  "_npmUser": {
      -    "name": "jbnicolai",
      -    "email": "jappelman@xebia.com"
      -  },
      -  "dist": {
      -    "shasum": "4b2dec8d907e93db336624dcec0183502f8c9428",
      -    "tarball": "http://registry.npmjs.org/growl/-/growl-1.8.1.tgz"
      -  },
      -  "directories": {},
      -  "_resolved": "https://registry.npmjs.org/growl/-/growl-1.8.1.tgz",
      -  "readme": "# Growl for nodejs\n\nGrowl support for Nodejs. This is essentially a port of my [Ruby Growl Library](http://github.com/visionmedia/growl). Ubuntu/Linux support added thanks to [@niftylettuce](http://github.com/niftylettuce). \n\n## Installation\n\n### Install \n\n### Mac OS X (Darwin):\n\n  Install [growlnotify(1)](http://growl.info/extras.php#growlnotify). On OS X 10.8, Notification Center is supported using [terminal-notifier](https://github.com/alloy/terminal-notifier). To install:\n  \n      $ sudo gem install terminal-notifier\n      \n  Install [npm](http://npmjs.org/) and run:\n  \n      $ npm install growl\n\n### Ubuntu (Linux):\n\n  Install `notify-send` through the [libnotify-bin](http://packages.ubuntu.com/libnotify-bin) package:\n\n      $ sudo apt-get install libnotify-bin\n\n  Install [npm](http://npmjs.org/) and run:\n  \n      $ npm install growl\n\n### Windows:\n\n  Download and install [Growl for Windows](http://www.growlforwindows.com/gfw/default.aspx)\n\n  Download [growlnotify](http://www.growlforwindows.com/gfw/help/growlnotify.aspx) - **IMPORTANT :** Unpack growlnotify to a folder that is present in your path!\n\n  Install [npm](http://npmjs.org/) and run:\n  \n      $ npm install growl\n\n## Examples\n\nCallback functions are optional\n\n    var growl = require('growl')\n    growl('You have mail!')\n    growl('5 new messages', { sticky: true })\n    growl('5 new emails', { title: 'Email Client', image: 'Safari', sticky: true })\n    growl('Message with title', { title: 'Title'})\n    growl('Set priority', { priority: 2 })\n    growl('Show Safari icon', { image: 'Safari' })\n    growl('Show icon', { image: 'path/to/icon.icns' })\n    growl('Show image', { image: 'path/to/my.image.png' })\n    growl('Show png filesystem icon', { image: 'png' })\n    growl('Show pdf filesystem icon', { image: 'article.pdf' })\n    growl('Show pdf filesystem icon', { image: 'article.pdf' }, function(err){\n      // ... notified\n    })\n\n## Options\n\n  - title\n    - notification title\n  - name\n    - application name\n  - priority\n    - priority for the notification (default is 0)\n  - sticky\n    - weither or not the notification should remainin until closed\n  - image\n    - Auto-detects the context:\n      - path to an icon sets --iconpath\n      - path to an image sets --image\n      - capitalized word sets --appIcon\n      - filename uses extname as --icon\n      - otherwise treated as --icon\n      \n## License \n\n(The MIT License)\n\nCopyright (c) 2009 TJ Holowaychuk \n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n",
      -  "readmeFilename": "Readme.md"
      -}
      diff --git a/node_modules/mocha/node_modules/growl/test.js b/node_modules/mocha/node_modules/growl/test.js
      deleted file mode 100644
      index cf22d90..0000000
      --- a/node_modules/mocha/node_modules/growl/test.js
      +++ /dev/null
      @@ -1,20 +0,0 @@
      -
      -var growl = require('./lib/growl')
      -
      -growl('You have mail!')
      -growl('5 new messages', { sticky: true })
      -growl('5 new emails', { title: 'Email Client', image: 'Safari', sticky: true })
      -growl('Message with title', { title: 'Title'})
      -growl('Set priority', { priority: 2 })
      -growl('Show Safari icon', { image: 'Safari' })
      -growl('Show icon', { image: 'path/to/icon.icns' })
      -growl('Show image', { image: 'path/to/my.image.png' })
      -growl('Show png filesystem icon', { image: 'png' })
      -growl('Show pdf filesystem icon', { image: 'article.pdf' })
      -growl('Show pdf filesystem icon', { image: 'article.pdf' }, function(){
      -  console.log('callback');
      -})
      -growl('Show pdf filesystem icon', { title: 'Use show()', image: 'article.pdf' })
      -growl('here \' are \n some \\ characters that " need escaping', {}, function(error, stdout, stderr) {
      -  if (error !== null) throw new Error('escaping failed:\n' + stdout + stderr);
      -})
      diff --git a/node_modules/mocha/node_modules/jade/.npmignore b/node_modules/mocha/node_modules/jade/.npmignore
      deleted file mode 100644
      index b9af3d4..0000000
      --- a/node_modules/mocha/node_modules/jade/.npmignore
      +++ /dev/null
      @@ -1,15 +0,0 @@
      -test
      -support
      -benchmarks
      -examples
      -lib-cov
      -coverage.html
      -.gitmodules
      -.travis.yml
      -History.md
      -Readme.md
      -Makefile
      -test/
      -support/
      -benchmarks/
      -examples/
      diff --git a/node_modules/mocha/node_modules/jade/LICENSE b/node_modules/mocha/node_modules/jade/LICENSE
      deleted file mode 100644
      index 8ad0e0d..0000000
      --- a/node_modules/mocha/node_modules/jade/LICENSE
      +++ /dev/null
      @@ -1,22 +0,0 @@
      -(The MIT License)
      -
      -Copyright (c) 2009-2010 TJ Holowaychuk 
      -
      -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.
      \ No newline at end of file
      diff --git a/node_modules/mocha/node_modules/jade/bin/jade b/node_modules/mocha/node_modules/jade/bin/jade
      deleted file mode 100755
      index 7e6002f..0000000
      --- a/node_modules/mocha/node_modules/jade/bin/jade
      +++ /dev/null
      @@ -1,147 +0,0 @@
      -#!/usr/bin/env node
      -
      -/**
      - * Module dependencies.
      - */
      -
      -var fs = require('fs')
      -  , program = require('commander')
      -  , path = require('path')
      -  , basename = path.basename
      -  , dirname = path.dirname
      -  , resolve = path.resolve
      -  , join = path.join
      -  , mkdirp = require('mkdirp')
      -  , jade = require('../');
      -
      -// jade options
      -
      -var options = {};
      -
      -// options
      -
      -program
      -  .version(jade.version)
      -  .usage('[options] [dir|file ...]')
      -  .option('-o, --obj ', 'javascript options object')
      -  .option('-O, --out 
      ', 'output the compiled html to ') - .option('-p, --path ', 'filename used to resolve includes') - .option('-P, --pretty', 'compile pretty html output') - .option('-c, --client', 'compile for client-side runtime.js') - .option('-D, --no-debug', 'compile without debugging (smaller functions)') - -program.on('--help', function(){ - console.log(' Examples:'); - console.log(''); - console.log(' # translate jade the templates dir'); - console.log(' $ jade templates'); - console.log(''); - console.log(' # create {foo,bar}.html'); - console.log(' $ jade {foo,bar}.jade'); - console.log(''); - console.log(' # jade over stdio'); - console.log(' $ jade < my.jade > my.html'); - console.log(''); - console.log(' # jade over stdio'); - console.log(' $ echo "h1 Jade!" | jade'); - console.log(''); - console.log(' # foo, bar dirs rendering to /tmp'); - console.log(' $ jade foo bar --out /tmp '); - console.log(''); -}); - -program.parse(process.argv); - -// options given, parse them - -if (program.obj) options = eval('(' + program.obj + ')'); - -// --filename - -if (program.path) options.filename = program.path; - -// --no-debug - -options.compileDebug = program.debug; - -// --client - -options.client = program.client; - -// --pretty - -options.pretty = program.pretty; - -// left-over args are file paths - -var files = program.args; - -// compile files - -if (files.length) { - console.log(); - files.forEach(renderFile); - process.on('exit', console.log); -// stdio -} else { - stdin(); -} - -/** - * Compile from stdin. - */ - -function stdin() { - var buf = ''; - process.stdin.setEncoding('utf8'); - process.stdin.on('data', function(chunk){ buf += chunk; }); - process.stdin.on('end', function(){ - var fn = jade.compile(buf, options); - var output = options.client - ? fn.toString() - : fn(options); - process.stdout.write(output); - }).resume(); -} - -/** - * Process the given path, compiling the jade files found. - * Always walk the subdirectories. - */ - -function renderFile(path) { - var re = /\.jade$/; - fs.lstat(path, function(err, stat) { - if (err) throw err; - // Found jade file - if (stat.isFile() && re.test(path)) { - fs.readFile(path, 'utf8', function(err, str){ - if (err) throw err; - options.filename = path; - var fn = jade.compile(str, options); - var extname = options.client ? '.js' : '.html'; - path = path.replace(re, extname); - if (program.out) path = join(program.out, basename(path)); - var dir = resolve(dirname(path)); - mkdirp(dir, 0755, function(err){ - if (err) throw err; - var output = options.client - ? fn.toString() - : fn(options); - fs.writeFile(path, output, function(err){ - if (err) throw err; - console.log(' \033[90mrendered \033[36m%s\033[0m', path); - }); - }); - }); - // Found directory - } else if (stat.isDirectory()) { - fs.readdir(path, function(err, files) { - if (err) throw err; - files.map(function(filename) { - return path + '/' + filename; - }).forEach(renderFile); - }); - } - }); -} diff --git a/node_modules/mocha/node_modules/jade/index.js b/node_modules/mocha/node_modules/jade/index.js deleted file mode 100644 index 8ad059f..0000000 --- a/node_modules/mocha/node_modules/jade/index.js +++ /dev/null @@ -1,4 +0,0 @@ - -module.exports = process.env.JADE_COV - ? require('./lib-cov/jade') - : require('./lib/jade'); \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/jade.js b/node_modules/mocha/node_modules/jade/jade.js deleted file mode 100644 index 1983a20..0000000 --- a/node_modules/mocha/node_modules/jade/jade.js +++ /dev/null @@ -1,3586 +0,0 @@ -(function() { - -// CommonJS require() - -function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - } - -require.modules = {}; - -require.resolve = function (path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; - -require.register = function (path, fn){ - require.modules[path] = fn; - }; - -require.relative = function (parent) { - return function(p){ - if ('.' != p.charAt(0)) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }; - - -require.register("compiler.js", function(module, exports, require){ - -/*! - * Jade - Compiler - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var nodes = require('./nodes') - , filters = require('./filters') - , doctypes = require('./doctypes') - , selfClosing = require('./self-closing') - , runtime = require('./runtime') - , utils = require('./utils'); - - - if (!Object.keys) { - Object.keys = function(obj){ - var arr = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - arr.push(key); - } - } - return arr; - } - } - - if (!String.prototype.trimLeft) { - String.prototype.trimLeft = function(){ - return this.replace(/^\s+/, ''); - } - } - - - -/** - * Initialize `Compiler` with the given `node`. - * - * @param {Node} node - * @param {Object} options - * @api public - */ - -var Compiler = module.exports = function Compiler(node, options) { - this.options = options = options || {}; - this.node = node; - this.hasCompiledDoctype = false; - this.hasCompiledTag = false; - this.pp = options.pretty || false; - this.debug = false !== options.compileDebug; - this.indents = 0; - this.parentIndents = 0; - if (options.doctype) this.setDoctype(options.doctype); -}; - -/** - * Compiler prototype. - */ - -Compiler.prototype = { - - /** - * Compile parse tree to JavaScript. - * - * @api public - */ - - compile: function(){ - this.buf = ['var interp;']; - if (this.pp) this.buf.push("var __indent = [];"); - this.lastBufferedIdx = -1; - this.visit(this.node); - return this.buf.join('\n'); - }, - - /** - * Sets the default doctype `name`. Sets terse mode to `true` when - * html 5 is used, causing self-closing tags to end with ">" vs "/>", - * and boolean attributes are not mirrored. - * - * @param {string} name - * @api public - */ - - setDoctype: function(name){ - var doctype = doctypes[(name || 'default').toLowerCase()]; - doctype = doctype || ''; - this.doctype = doctype; - this.terse = '5' == name || 'html' == name; - this.xml = 0 == this.doctype.indexOf(' 1 && !escape && block.nodes[0].isText && block.nodes[1].isText) - this.prettyIndent(1, true); - - for (var i = 0; i < len; ++i) { - // Pretty print text - if (pp && i > 0 && !escape && block.nodes[i].isText && block.nodes[i-1].isText) - this.prettyIndent(1, false); - - this.visit(block.nodes[i]); - // Multiple text nodes are separated by newlines - if (block.nodes[i+1] && block.nodes[i].isText && block.nodes[i+1].isText) - this.buffer('\\n'); - } - }, - - /** - * Visit `doctype`. Sets terse mode to `true` when html 5 - * is used, causing self-closing tags to end with ">" vs "/>", - * and boolean attributes are not mirrored. - * - * @param {Doctype} doctype - * @api public - */ - - visitDoctype: function(doctype){ - if (doctype && (doctype.val || !this.doctype)) { - this.setDoctype(doctype.val || 'default'); - } - - if (this.doctype) this.buffer(this.doctype); - this.hasCompiledDoctype = true; - }, - - /** - * Visit `mixin`, generating a function that - * may be called within the template. - * - * @param {Mixin} mixin - * @api public - */ - - visitMixin: function(mixin){ - var name = mixin.name.replace(/-/g, '_') + '_mixin' - , args = mixin.args || '' - , block = mixin.block - , attrs = mixin.attrs - , pp = this.pp; - - if (mixin.call) { - if (pp) this.buf.push("__indent.push('" + Array(this.indents + 1).join(' ') + "');") - if (block || attrs.length) { - - this.buf.push(name + '.call({'); - - if (block) { - this.buf.push('block: function(){'); - - // Render block with no indents, dynamically added when rendered - this.parentIndents++; - var _indents = this.indents; - this.indents = 0; - this.visit(mixin.block); - this.indents = _indents; - this.parentIndents--; - - if (attrs.length) { - this.buf.push('},'); - } else { - this.buf.push('}'); - } - } - - if (attrs.length) { - var val = this.attrs(attrs); - if (val.inherits) { - this.buf.push('attributes: merge({' + val.buf - + '}, attributes), escaped: merge(' + val.escaped + ', escaped, true)'); - } else { - this.buf.push('attributes: {' + val.buf + '}, escaped: ' + val.escaped); - } - } - - if (args) { - this.buf.push('}, ' + args + ');'); - } else { - this.buf.push('});'); - } - - } else { - this.buf.push(name + '(' + args + ');'); - } - if (pp) this.buf.push("__indent.pop();") - } else { - this.buf.push('var ' + name + ' = function(' + args + '){'); - this.buf.push('var block = this.block, attributes = this.attributes || {}, escaped = this.escaped || {};'); - this.parentIndents++; - this.visit(block); - this.parentIndents--; - this.buf.push('};'); - } - }, - - /** - * Visit `tag` buffering tag markup, generating - * attributes, visiting the `tag`'s code and block. - * - * @param {Tag} tag - * @api public - */ - - visitTag: function(tag){ - this.indents++; - var name = tag.name - , pp = this.pp; - - if (tag.buffer) name = "' + (" + name + ") + '"; - - if (!this.hasCompiledTag) { - if (!this.hasCompiledDoctype && 'html' == name) { - this.visitDoctype(); - } - this.hasCompiledTag = true; - } - - // pretty print - if (pp && !tag.isInline()) - this.prettyIndent(0, true); - - if ((~selfClosing.indexOf(name) || tag.selfClosing) && !this.xml) { - this.buffer('<' + name); - this.visitAttributes(tag.attrs); - this.terse - ? this.buffer('>') - : this.buffer('/>'); - } else { - // Optimize attributes buffering - if (tag.attrs.length) { - this.buffer('<' + name); - if (tag.attrs.length) this.visitAttributes(tag.attrs); - this.buffer('>'); - } else { - this.buffer('<' + name + '>'); - } - if (tag.code) this.visitCode(tag.code); - this.escape = 'pre' == tag.name; - this.visit(tag.block); - - // pretty print - if (pp && !tag.isInline() && 'pre' != tag.name && !tag.canInline()) - this.prettyIndent(0, true); - - this.buffer(''); - } - this.indents--; - }, - - /** - * Visit `filter`, throwing when the filter does not exist. - * - * @param {Filter} filter - * @api public - */ - - visitFilter: function(filter){ - var fn = filters[filter.name]; - - // unknown filter - if (!fn) { - if (filter.isASTFilter) { - throw new Error('unknown ast filter "' + filter.name + ':"'); - } else { - throw new Error('unknown filter ":' + filter.name + '"'); - } - } - - if (filter.isASTFilter) { - this.buf.push(fn(filter.block, this, filter.attrs)); - } else { - var text = filter.block.nodes.map(function(node){ return node.val }).join('\n'); - filter.attrs = filter.attrs || {}; - filter.attrs.filename = this.options.filename; - this.buffer(utils.text(fn(text, filter.attrs))); - } - }, - - /** - * Visit `text` node. - * - * @param {Text} text - * @api public - */ - - visitText: function(text){ - text = utils.text(text.val.replace(/\\/g, '\\\\')); - if (this.escape) text = escape(text); - this.buffer(text); - }, - - /** - * Visit a `comment`, only buffering when the buffer flag is set. - * - * @param {Comment} comment - * @api public - */ - - visitComment: function(comment){ - if (!comment.buffer) return; - if (this.pp) this.prettyIndent(1, true); - this.buffer(''); - }, - - /** - * Visit a `BlockComment`. - * - * @param {Comment} comment - * @api public - */ - - visitBlockComment: function(comment){ - if (!comment.buffer) return; - if (0 == comment.val.trim().indexOf('if')) { - this.buffer(''); - } else { - this.buffer(''); - } - }, - - /** - * Visit `code`, respecting buffer / escape flags. - * If the code is followed by a block, wrap it in - * a self-calling function. - * - * @param {Code} code - * @api public - */ - - visitCode: function(code){ - // Wrap code blocks with {}. - // we only wrap unbuffered code blocks ATM - // since they are usually flow control - - // Buffer code - if (code.buffer) { - var val = code.val.trimLeft(); - this.buf.push('var __val__ = ' + val); - val = 'null == __val__ ? "" : __val__'; - if (code.escape) val = 'escape(' + val + ')'; - this.buf.push("buf.push(" + val + ");"); - } else { - this.buf.push(code.val); - } - - // Block support - if (code.block) { - if (!code.buffer) this.buf.push('{'); - this.visit(code.block); - if (!code.buffer) this.buf.push('}'); - } - }, - - /** - * Visit `each` block. - * - * @param {Each} each - * @api public - */ - - visitEach: function(each){ - this.buf.push('' - + '// iterate ' + each.obj + '\n' - + ';(function(){\n' - + ' if (\'number\' == typeof ' + each.obj + '.length) {\n' - + ' for (var ' + each.key + ' = 0, $$l = ' + each.obj + '.length; ' + each.key + ' < $$l; ' + each.key + '++) {\n' - + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); - - this.visit(each.block); - - this.buf.push('' - + ' }\n' - + ' } else {\n' - + ' for (var ' + each.key + ' in ' + each.obj + ') {\n' - + ' if (' + each.obj + '.hasOwnProperty(' + each.key + ')){' - + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); - - this.visit(each.block); - - this.buf.push(' }\n'); - - this.buf.push(' }\n }\n}).call(this);\n'); - }, - - /** - * Visit `attrs`. - * - * @param {Array} attrs - * @api public - */ - - visitAttributes: function(attrs){ - var val = this.attrs(attrs); - if (val.inherits) { - this.buf.push("buf.push(attrs(merge({ " + val.buf + - " }, attributes), merge(" + val.escaped + ", escaped, true)));"); - } else if (val.constant) { - eval('var buf={' + val.buf + '};'); - this.buffer(runtime.attrs(buf, JSON.parse(val.escaped)), true); - } else { - this.buf.push("buf.push(attrs({ " + val.buf + " }, " + val.escaped + "));"); - } - }, - - /** - * Compile attributes. - */ - - attrs: function(attrs){ - var buf = [] - , classes = [] - , escaped = {} - , constant = attrs.every(function(attr){ return isConstant(attr.val) }) - , inherits = false; - - if (this.terse) buf.push('terse: true'); - - attrs.forEach(function(attr){ - if (attr.name == 'attributes') return inherits = true; - escaped[attr.name] = attr.escaped; - if (attr.name == 'class') { - classes.push('(' + attr.val + ')'); - } else { - var pair = "'" + attr.name + "':(" + attr.val + ')'; - buf.push(pair); - } - }); - - if (classes.length) { - classes = classes.join(" + ' ' + "); - buf.push("class: " + classes); - } - - return { - buf: buf.join(', ').replace('class:', '"class":'), - escaped: JSON.stringify(escaped), - inherits: inherits, - constant: constant - }; - } -}; - -/** - * Check if expression can be evaluated to a constant - * - * @param {String} expression - * @return {Boolean} - * @api private - */ - -function isConstant(val){ - // Check strings/literals - if (/^ *("([^"\\]*(\\.[^"\\]*)*)"|'([^'\\]*(\\.[^'\\]*)*)'|true|false|null|undefined) *$/i.test(val)) - return true; - - // Check numbers - if (!isNaN(Number(val))) - return true; - - // Check arrays - var matches; - if (matches = /^ *\[(.*)\] *$/.exec(val)) - return matches[1].split(',').every(isConstant); - - return false; -} - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -function escape(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -} -}); // module: compiler.js - -require.register("doctypes.js", function(module, exports, require){ - -/*! - * Jade - doctypes - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = { - '5': '' - , 'default': '' - , 'xml': '' - , 'transitional': '' - , 'strict': '' - , 'frameset': '' - , '1.1': '' - , 'basic': '' - , 'mobile': '' -}; -}); // module: doctypes.js - -require.register("filters.js", function(module, exports, require){ - -/*! - * Jade - filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = { - - /** - * Wrap text with CDATA block. - */ - - cdata: function(str){ - return ''; - }, - - /** - * Transform sass to css, wrapped in style tags. - */ - - sass: function(str){ - str = str.replace(/\\n/g, '\n'); - var sass = require('sass').render(str).replace(/\n/g, '\\n'); - return ''; - }, - - /** - * Transform stylus to css, wrapped in style tags. - */ - - stylus: function(str, options){ - var ret; - str = str.replace(/\\n/g, '\n'); - var stylus = require('stylus'); - stylus(str, options).render(function(err, css){ - if (err) throw err; - ret = css.replace(/\n/g, '\\n'); - }); - return ''; - }, - - /** - * Transform less to css, wrapped in style tags. - */ - - less: function(str){ - var ret; - str = str.replace(/\\n/g, '\n'); - require('less').render(str, function(err, css){ - if (err) throw err; - ret = ''; - }); - return ret; - }, - - /** - * Transform markdown to html. - */ - - markdown: function(str){ - var md; - - // support markdown / discount - try { - md = require('markdown'); - } catch (err){ - try { - md = require('discount'); - } catch (err) { - try { - md = require('markdown-js'); - } catch (err) { - try { - md = require('marked'); - } catch (err) { - throw new - Error('Cannot find markdown library, install markdown, discount, or marked.'); - } - } - } - } - - str = str.replace(/\\n/g, '\n'); - return md.parse(str).replace(/\n/g, '\\n').replace(/'/g,'''); - }, - - /** - * Transform coffeescript to javascript. - */ - - coffeescript: function(str){ - str = str.replace(/\\n/g, '\n'); - var js = require('coffee-script').compile(str).replace(/\\/g, '\\\\').replace(/\n/g, '\\n'); - return ''; - } -}; - -}); // module: filters.js - -require.register("inline-tags.js", function(module, exports, require){ - -/*! - * Jade - inline tags - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = [ - 'a' - , 'abbr' - , 'acronym' - , 'b' - , 'br' - , 'code' - , 'em' - , 'font' - , 'i' - , 'img' - , 'ins' - , 'kbd' - , 'map' - , 'samp' - , 'small' - , 'span' - , 'strong' - , 'sub' - , 'sup' -]; -}); // module: inline-tags.js - -require.register("jade.js", function(module, exports, require){ -/*! - * Jade - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Parser = require('./parser') - , Lexer = require('./lexer') - , Compiler = require('./compiler') - , runtime = require('./runtime') - -/** - * Library version. - */ - -exports.version = '0.26.1'; - -/** - * Expose self closing tags. - */ - -exports.selfClosing = require('./self-closing'); - -/** - * Default supported doctypes. - */ - -exports.doctypes = require('./doctypes'); - -/** - * Text filters. - */ - -exports.filters = require('./filters'); - -/** - * Utilities. - */ - -exports.utils = require('./utils'); - -/** - * Expose `Compiler`. - */ - -exports.Compiler = Compiler; - -/** - * Expose `Parser`. - */ - -exports.Parser = Parser; - -/** - * Expose `Lexer`. - */ - -exports.Lexer = Lexer; - -/** - * Nodes. - */ - -exports.nodes = require('./nodes'); - -/** - * Jade runtime helpers. - */ - -exports.runtime = runtime; - -/** - * Template function cache. - */ - -exports.cache = {}; - -/** - * Parse the given `str` of jade and return a function body. - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api private - */ - -function parse(str, options){ - try { - // Parse - var parser = new Parser(str, options.filename, options); - - // Compile - var compiler = new (options.compiler || Compiler)(parser.parse(), options) - , js = compiler.compile(); - - // Debug compiler - if (options.debug) { - console.error('\nCompiled Function:\n\n\033[90m%s\033[0m', js.replace(/^/gm, ' ')); - } - - return '' - + 'var buf = [];\n' - + (options.self - ? 'var self = locals || {};\n' + js - : 'with (locals || {}) {\n' + js + '\n}\n') - + 'return buf.join("");'; - } catch (err) { - parser = parser.context(); - runtime.rethrow(err, parser.filename, parser.lexer.lineno); - } -} - -/** - * Compile a `Function` representation of the given jade `str`. - * - * Options: - * - * - `compileDebug` when `false` debugging code is stripped from the compiled template - * - `client` when `true` the helper functions `escape()` etc will reference `jade.escape()` - * for use with the Jade client-side runtime.js - * - * @param {String} str - * @param {Options} options - * @return {Function} - * @api public - */ - -exports.compile = function(str, options){ - var options = options || {} - , client = options.client - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined' - , fn; - - if (options.compileDebug !== false) { - fn = [ - 'var __jade = [{ lineno: 1, filename: ' + filename + ' }];' - , 'try {' - , parse(String(str), options) - , '} catch (err) {' - , ' rethrow(err, __jade[0].filename, __jade[0].lineno);' - , '}' - ].join('\n'); - } else { - fn = parse(String(str), options); - } - - if (client) { - fn = 'attrs = attrs || jade.attrs; escape = escape || jade.escape; rethrow = rethrow || jade.rethrow; merge = merge || jade.merge;\n' + fn; - } - - fn = new Function('locals, attrs, escape, rethrow, merge', fn); - - if (client) return fn; - - return function(locals){ - return fn(locals, runtime.attrs, runtime.escape, runtime.rethrow, runtime.merge); - }; -}; - -/** - * Render the given `str` of jade and invoke - * the callback `fn(err, str)`. - * - * Options: - * - * - `cache` enable template caching - * - `filename` filename required for `include` / `extends` and caching - * - * @param {String} str - * @param {Object|Function} options or fn - * @param {Function} fn - * @api public - */ - -exports.render = function(str, options, fn){ - // swap args - if ('function' == typeof options) { - fn = options, options = {}; - } - - // cache requires .filename - if (options.cache && !options.filename) { - return fn(new Error('the "filename" option is required for caching')); - } - - try { - var path = options.filename; - var tmpl = options.cache - ? exports.cache[path] || (exports.cache[path] = exports.compile(str, options)) - : exports.compile(str, options); - fn(null, tmpl(options)); - } catch (err) { - fn(err); - } -}; - -/** - * Render a Jade file at the given `path` and callback `fn(err, str)`. - * - * @param {String} path - * @param {Object|Function} options or callback - * @param {Function} fn - * @api public - */ - -exports.renderFile = function(path, options, fn){ - var key = path + ':string'; - - if ('function' == typeof options) { - fn = options, options = {}; - } - - try { - options.filename = path; - var str = options.cache - ? exports.cache[key] || (exports.cache[key] = fs.readFileSync(path, 'utf8')) - : fs.readFileSync(path, 'utf8'); - exports.render(str, options, fn); - } catch (err) { - fn(err); - } -}; - -/** - * Express support. - */ - -exports.__express = exports.renderFile; - -}); // module: jade.js - -require.register("lexer.js", function(module, exports, require){ - -/*! - * Jade - Lexer - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Initialize `Lexer` with the given `str`. - * - * Options: - * - * - `colons` allow colons for attr delimiters - * - * @param {String} str - * @param {Object} options - * @api private - */ - -var Lexer = module.exports = function Lexer(str, options) { - options = options || {}; - this.input = str.replace(/\r\n|\r/g, '\n'); - this.colons = options.colons; - this.deferredTokens = []; - this.lastIndents = 0; - this.lineno = 1; - this.stash = []; - this.indentStack = []; - this.indentRe = null; - this.pipeless = false; -}; - -/** - * Lexer prototype. - */ - -Lexer.prototype = { - - /** - * Construct a token with the given `type` and `val`. - * - * @param {String} type - * @param {String} val - * @return {Object} - * @api private - */ - - tok: function(type, val){ - return { - type: type - , line: this.lineno - , val: val - } - }, - - /** - * Consume the given `len` of input. - * - * @param {Number} len - * @api private - */ - - consume: function(len){ - this.input = this.input.substr(len); - }, - - /** - * Scan for `type` with the given `regexp`. - * - * @param {String} type - * @param {RegExp} regexp - * @return {Object} - * @api private - */ - - scan: function(regexp, type){ - var captures; - if (captures = regexp.exec(this.input)) { - this.consume(captures[0].length); - return this.tok(type, captures[1]); - } - }, - - /** - * Defer the given `tok`. - * - * @param {Object} tok - * @api private - */ - - defer: function(tok){ - this.deferredTokens.push(tok); - }, - - /** - * Lookahead `n` tokens. - * - * @param {Number} n - * @return {Object} - * @api private - */ - - lookahead: function(n){ - var fetch = n - this.stash.length; - while (fetch-- > 0) this.stash.push(this.next()); - return this.stash[--n]; - }, - - /** - * Return the indexOf `start` / `end` delimiters. - * - * @param {String} start - * @param {String} end - * @return {Number} - * @api private - */ - - indexOfDelimiters: function(start, end){ - var str = this.input - , nstart = 0 - , nend = 0 - , pos = 0; - for (var i = 0, len = str.length; i < len; ++i) { - if (start == str.charAt(i)) { - ++nstart; - } else if (end == str.charAt(i)) { - if (++nend == nstart) { - pos = i; - break; - } - } - } - return pos; - }, - - /** - * Stashed token. - */ - - stashed: function() { - return this.stash.length - && this.stash.shift(); - }, - - /** - * Deferred token. - */ - - deferred: function() { - return this.deferredTokens.length - && this.deferredTokens.shift(); - }, - - /** - * end-of-source. - */ - - eos: function() { - if (this.input.length) return; - if (this.indentStack.length) { - this.indentStack.shift(); - return this.tok('outdent'); - } else { - return this.tok('eos'); - } - }, - - /** - * Blank line. - */ - - blank: function() { - var captures; - if (captures = /^\n *\n/.exec(this.input)) { - this.consume(captures[0].length - 1); - if (this.pipeless) return this.tok('text', ''); - return this.next(); - } - }, - - /** - * Comment. - */ - - comment: function() { - var captures; - if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('comment', captures[2]); - tok.buffer = '-' != captures[1]; - return tok; - } - }, - - /** - * Interpolated tag. - */ - - interpolation: function() { - var captures; - if (captures = /^#\{(.*?)\}/.exec(this.input)) { - this.consume(captures[0].length); - return this.tok('interpolation', captures[1]); - } - }, - - /** - * Tag. - */ - - tag: function() { - var captures; - if (captures = /^(\w[-:\w]*)(\/?)/.exec(this.input)) { - this.consume(captures[0].length); - var tok, name = captures[1]; - if (':' == name[name.length - 1]) { - name = name.slice(0, -1); - tok = this.tok('tag', name); - this.defer(this.tok(':')); - while (' ' == this.input[0]) this.input = this.input.substr(1); - } else { - tok = this.tok('tag', name); - } - tok.selfClosing = !! captures[2]; - return tok; - } - }, - - /** - * Filter. - */ - - filter: function() { - return this.scan(/^:(\w+)/, 'filter'); - }, - - /** - * Doctype. - */ - - doctype: function() { - return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype'); - }, - - /** - * Id. - */ - - id: function() { - return this.scan(/^#([\w-]+)/, 'id'); - }, - - /** - * Class. - */ - - className: function() { - return this.scan(/^\.([\w-]+)/, 'class'); - }, - - /** - * Text. - */ - - text: function() { - return this.scan(/^(?:\| ?| ?)?([^\n]+)/, 'text'); - }, - - /** - * Extends. - */ - - "extends": function() { - return this.scan(/^extends? +([^\n]+)/, 'extends'); - }, - - /** - * Block prepend. - */ - - prepend: function() { - var captures; - if (captures = /^prepend +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = 'prepend' - , name = captures[1] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Block append. - */ - - append: function() { - var captures; - if (captures = /^append +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = 'append' - , name = captures[1] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Block. - */ - - block: function() { - var captures; - if (captures = /^block\b *(?:(prepend|append) +)?([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = captures[1] || 'replace' - , name = captures[2] - , tok = this.tok('block', name); - - tok.mode = mode; - return tok; - } - }, - - /** - * Yield. - */ - - yield: function() { - return this.scan(/^yield */, 'yield'); - }, - - /** - * Include. - */ - - include: function() { - return this.scan(/^include +([^\n]+)/, 'include'); - }, - - /** - * Case. - */ - - "case": function() { - return this.scan(/^case +([^\n]+)/, 'case'); - }, - - /** - * When. - */ - - when: function() { - return this.scan(/^when +([^:\n]+)/, 'when'); - }, - - /** - * Default. - */ - - "default": function() { - return this.scan(/^default */, 'default'); - }, - - /** - * Assignment. - */ - - assignment: function() { - var captures; - if (captures = /^(\w+) += *([^;\n]+)( *;? *)/.exec(this.input)) { - this.consume(captures[0].length); - var name = captures[1] - , val = captures[2]; - return this.tok('code', 'var ' + name + ' = (' + val + ');'); - } - }, - - /** - * Call mixin. - */ - - call: function(){ - var captures; - if (captures = /^\+([-\w]+)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('call', captures[1]); - - // Check for args (not attributes) - if (captures = /^ *\((.*?)\)/.exec(this.input)) { - if (!/^ *[-\w]+ *=/.test(captures[1])) { - this.consume(captures[0].length); - tok.args = captures[1]; - } - } - - return tok; - } - }, - - /** - * Mixin. - */ - - mixin: function(){ - var captures; - if (captures = /^mixin +([-\w]+)(?: *\((.*)\))?/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('mixin', captures[1]); - tok.args = captures[2]; - return tok; - } - }, - - /** - * Conditional. - */ - - conditional: function() { - var captures; - if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var type = captures[1] - , js = captures[2]; - - switch (type) { - case 'if': js = 'if (' + js + ')'; break; - case 'unless': js = 'if (!(' + js + '))'; break; - case 'else if': js = 'else if (' + js + ')'; break; - case 'else': js = 'else'; break; - } - - return this.tok('code', js); - } - }, - - /** - * While. - */ - - "while": function() { - var captures; - if (captures = /^while +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - return this.tok('code', 'while (' + captures[1] + ')'); - } - }, - - /** - * Each. - */ - - each: function() { - var captures; - if (captures = /^(?:- *)?(?:each|for) +(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('each', captures[1]); - tok.key = captures[2] || '$index'; - tok.code = captures[3]; - return tok; - } - }, - - /** - * Code. - */ - - code: function() { - var captures; - if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var flags = captures[1]; - captures[1] = captures[2]; - var tok = this.tok('code', captures[1]); - tok.escape = flags[0] === '='; - tok.buffer = flags[0] === '=' || flags[1] === '='; - return tok; - } - }, - - /** - * Attributes. - */ - - attrs: function() { - if ('(' == this.input.charAt(0)) { - var index = this.indexOfDelimiters('(', ')') - , str = this.input.substr(1, index-1) - , tok = this.tok('attrs') - , len = str.length - , colons = this.colons - , states = ['key'] - , escapedAttr - , key = '' - , val = '' - , quote - , c - , p; - - function state(){ - return states[states.length - 1]; - } - - function interpolate(attr) { - return attr.replace(/#\{([^}]+)\}/g, function(_, expr){ - return quote + " + (" + expr + ") + " + quote; - }); - } - - this.consume(index + 1); - tok.attrs = {}; - tok.escaped = {}; - - function parse(c) { - var real = c; - // TODO: remove when people fix ":" - if (colons && ':' == c) c = '='; - switch (c) { - case ',': - case '\n': - switch (state()) { - case 'expr': - case 'array': - case 'string': - case 'object': - val += c; - break; - default: - states.push('key'); - val = val.trim(); - key = key.trim(); - if ('' == key) return; - key = key.replace(/^['"]|['"]$/g, '').replace('!', ''); - tok.escaped[key] = escapedAttr; - tok.attrs[key] = '' == val - ? true - : interpolate(val); - key = val = ''; - } - break; - case '=': - switch (state()) { - case 'key char': - key += real; - break; - case 'val': - case 'expr': - case 'array': - case 'string': - case 'object': - val += real; - break; - default: - escapedAttr = '!' != p; - states.push('val'); - } - break; - case '(': - if ('val' == state() - || 'expr' == state()) states.push('expr'); - val += c; - break; - case ')': - if ('expr' == state() - || 'val' == state()) states.pop(); - val += c; - break; - case '{': - if ('val' == state()) states.push('object'); - val += c; - break; - case '}': - if ('object' == state()) states.pop(); - val += c; - break; - case '[': - if ('val' == state()) states.push('array'); - val += c; - break; - case ']': - if ('array' == state()) states.pop(); - val += c; - break; - case '"': - case "'": - switch (state()) { - case 'key': - states.push('key char'); - break; - case 'key char': - states.pop(); - break; - case 'string': - if (c == quote) states.pop(); - val += c; - break; - default: - states.push('string'); - val += c; - quote = c; - } - break; - case '': - break; - default: - switch (state()) { - case 'key': - case 'key char': - key += c; - break; - default: - val += c; - } - } - p = c; - } - - for (var i = 0; i < len; ++i) { - parse(str.charAt(i)); - } - - parse(','); - - if ('/' == this.input.charAt(0)) { - this.consume(1); - tok.selfClosing = true; - } - - return tok; - } - }, - - /** - * Indent | Outdent | Newline. - */ - - indent: function() { - var captures, re; - - // established regexp - if (this.indentRe) { - captures = this.indentRe.exec(this.input); - // determine regexp - } else { - // tabs - re = /^\n(\t*) */; - captures = re.exec(this.input); - - // spaces - if (captures && !captures[1].length) { - re = /^\n( *)/; - captures = re.exec(this.input); - } - - // established - if (captures && captures[1].length) this.indentRe = re; - } - - if (captures) { - var tok - , indents = captures[1].length; - - ++this.lineno; - this.consume(indents + 1); - - if (' ' == this.input[0] || '\t' == this.input[0]) { - throw new Error('Invalid indentation, you can use tabs or spaces but not both'); - } - - // blank line - if ('\n' == this.input[0]) return this.tok('newline'); - - // outdent - if (this.indentStack.length && indents < this.indentStack[0]) { - while (this.indentStack.length && this.indentStack[0] > indents) { - this.stash.push(this.tok('outdent')); - this.indentStack.shift(); - } - tok = this.stash.pop(); - // indent - } else if (indents && indents != this.indentStack[0]) { - this.indentStack.unshift(indents); - tok = this.tok('indent', indents); - // newline - } else { - tok = this.tok('newline'); - } - - return tok; - } - }, - - /** - * Pipe-less text consumed only when - * pipeless is true; - */ - - pipelessText: function() { - if (this.pipeless) { - if ('\n' == this.input[0]) return; - var i = this.input.indexOf('\n'); - if (-1 == i) i = this.input.length; - var str = this.input.substr(0, i); - this.consume(str.length); - return this.tok('text', str); - } - }, - - /** - * ':' - */ - - colon: function() { - return this.scan(/^: */, ':'); - }, - - /** - * Return the next token object, or those - * previously stashed by lookahead. - * - * @return {Object} - * @api private - */ - - advance: function(){ - return this.stashed() - || this.next(); - }, - - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ - - next: function() { - return this.deferred() - || this.blank() - || this.eos() - || this.pipelessText() - || this.yield() - || this.doctype() - || this.interpolation() - || this["case"]() - || this.when() - || this["default"]() - || this["extends"]() - || this.append() - || this.prepend() - || this.block() - || this.include() - || this.mixin() - || this.call() - || this.conditional() - || this.each() - || this["while"]() - || this.assignment() - || this.tag() - || this.filter() - || this.code() - || this.id() - || this.className() - || this.attrs() - || this.indent() - || this.comment() - || this.colon() - || this.text(); - } -}; - -}); // module: lexer.js - -require.register("nodes/attrs.js", function(module, exports, require){ - -/*! - * Jade - nodes - Attrs - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'), - Block = require('./block'); - -/** - * Initialize a `Attrs` node. - * - * @api public - */ - -var Attrs = module.exports = function Attrs() { - this.attrs = []; -}; - -/** - * Inherit from `Node`. - */ - -Attrs.prototype = new Node; -Attrs.prototype.constructor = Attrs; - - -/** - * Set attribute `name` to `val`, keep in mind these become - * part of a raw js object literal, so to quote a value you must - * '"quote me"', otherwise or example 'user.name' is literal JavaScript. - * - * @param {String} name - * @param {String} val - * @param {Boolean} escaped - * @return {Tag} for chaining - * @api public - */ - -Attrs.prototype.setAttribute = function(name, val, escaped){ - this.attrs.push({ name: name, val: val, escaped: escaped }); - return this; -}; - -/** - * Remove attribute `name` when present. - * - * @param {String} name - * @api public - */ - -Attrs.prototype.removeAttribute = function(name){ - for (var i = 0, len = this.attrs.length; i < len; ++i) { - if (this.attrs[i] && this.attrs[i].name == name) { - delete this.attrs[i]; - } - } -}; - -/** - * Get attribute value by `name`. - * - * @param {String} name - * @return {String} - * @api public - */ - -Attrs.prototype.getAttribute = function(name){ - for (var i = 0, len = this.attrs.length; i < len; ++i) { - if (this.attrs[i] && this.attrs[i].name == name) { - return this.attrs[i].val; - } - } -}; - -}); // module: nodes/attrs.js - -require.register("nodes/block-comment.js", function(module, exports, require){ - -/*! - * Jade - nodes - BlockComment - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `BlockComment` with the given `block`. - * - * @param {String} val - * @param {Block} block - * @param {Boolean} buffer - * @api public - */ - -var BlockComment = module.exports = function BlockComment(val, block, buffer) { - this.block = block; - this.val = val; - this.buffer = buffer; -}; - -/** - * Inherit from `Node`. - */ - -BlockComment.prototype = new Node; -BlockComment.prototype.constructor = BlockComment; - -}); // module: nodes/block-comment.js - -require.register("nodes/block.js", function(module, exports, require){ - -/*! - * Jade - nodes - Block - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Block` with an optional `node`. - * - * @param {Node} node - * @api public - */ - -var Block = module.exports = function Block(node){ - this.nodes = []; - if (node) this.push(node); -}; - -/** - * Inherit from `Node`. - */ - -Block.prototype = new Node; -Block.prototype.constructor = Block; - - -/** - * Block flag. - */ - -Block.prototype.isBlock = true; - -/** - * Replace the nodes in `other` with the nodes - * in `this` block. - * - * @param {Block} other - * @api private - */ - -Block.prototype.replace = function(other){ - other.nodes = this.nodes; -}; - -/** - * Pust the given `node`. - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Block.prototype.push = function(node){ - return this.nodes.push(node); -}; - -/** - * Check if this block is empty. - * - * @return {Boolean} - * @api public - */ - -Block.prototype.isEmpty = function(){ - return 0 == this.nodes.length; -}; - -/** - * Unshift the given `node`. - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Block.prototype.unshift = function(node){ - return this.nodes.unshift(node); -}; - -/** - * Return the "last" block, or the first `yield` node. - * - * @return {Block} - * @api private - */ - -Block.prototype.includeBlock = function(){ - var ret = this - , node; - - for (var i = 0, len = this.nodes.length; i < len; ++i) { - node = this.nodes[i]; - if (node.yield) return node; - else if (node.textOnly) continue; - else if (node.includeBlock) ret = node.includeBlock(); - else if (node.block && !node.block.isEmpty()) ret = node.block.includeBlock(); - } - - return ret; -}; - -/** - * Return a clone of this block. - * - * @return {Block} - * @api private - */ - -Block.prototype.clone = function(){ - var clone = new Block; - for (var i = 0, len = this.nodes.length; i < len; ++i) { - clone.push(this.nodes[i].clone()); - } - return clone; -}; - - -}); // module: nodes/block.js - -require.register("nodes/case.js", function(module, exports, require){ - -/*! - * Jade - nodes - Case - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Case` with `expr`. - * - * @param {String} expr - * @api public - */ - -var Case = exports = module.exports = function Case(expr, block){ - this.expr = expr; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Case.prototype = new Node; -Case.prototype.constructor = Case; - - -var When = exports.When = function When(expr, block){ - this.expr = expr; - this.block = block; - this.debug = false; -}; - -/** - * Inherit from `Node`. - */ - -When.prototype = new Node; -When.prototype.constructor = When; - - - -}); // module: nodes/case.js - -require.register("nodes/code.js", function(module, exports, require){ - -/*! - * Jade - nodes - Code - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Code` node with the given code `val`. - * Code may also be optionally buffered and escaped. - * - * @param {String} val - * @param {Boolean} buffer - * @param {Boolean} escape - * @api public - */ - -var Code = module.exports = function Code(val, buffer, escape) { - this.val = val; - this.buffer = buffer; - this.escape = escape; - if (val.match(/^ *else/)) this.debug = false; -}; - -/** - * Inherit from `Node`. - */ - -Code.prototype = new Node; -Code.prototype.constructor = Code; - -}); // module: nodes/code.js - -require.register("nodes/comment.js", function(module, exports, require){ - -/*! - * Jade - nodes - Comment - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Comment` with the given `val`, optionally `buffer`, - * otherwise the comment may render in the output. - * - * @param {String} val - * @param {Boolean} buffer - * @api public - */ - -var Comment = module.exports = function Comment(val, buffer) { - this.val = val; - this.buffer = buffer; -}; - -/** - * Inherit from `Node`. - */ - -Comment.prototype = new Node; -Comment.prototype.constructor = Comment; - -}); // module: nodes/comment.js - -require.register("nodes/doctype.js", function(module, exports, require){ - -/*! - * Jade - nodes - Doctype - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Doctype` with the given `val`. - * - * @param {String} val - * @api public - */ - -var Doctype = module.exports = function Doctype(val) { - this.val = val; -}; - -/** - * Inherit from `Node`. - */ - -Doctype.prototype = new Node; -Doctype.prototype.constructor = Doctype; - -}); // module: nodes/doctype.js - -require.register("nodes/each.js", function(module, exports, require){ - -/*! - * Jade - nodes - Each - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize an `Each` node, representing iteration - * - * @param {String} obj - * @param {String} val - * @param {String} key - * @param {Block} block - * @api public - */ - -var Each = module.exports = function Each(obj, val, key, block) { - this.obj = obj; - this.val = val; - this.key = key; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Each.prototype = new Node; -Each.prototype.constructor = Each; - -}); // module: nodes/each.js - -require.register("nodes/filter.js", function(module, exports, require){ - -/*! - * Jade - nodes - Filter - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node') - , Block = require('./block'); - -/** - * Initialize a `Filter` node with the given - * filter `name` and `block`. - * - * @param {String} name - * @param {Block|Node} block - * @api public - */ - -var Filter = module.exports = function Filter(name, block, attrs) { - this.name = name; - this.block = block; - this.attrs = attrs; - this.isASTFilter = !block.nodes.every(function(node){ return node.isText }); -}; - -/** - * Inherit from `Node`. - */ - -Filter.prototype = new Node; -Filter.prototype.constructor = Filter; - -}); // module: nodes/filter.js - -require.register("nodes/index.js", function(module, exports, require){ - -/*! - * Jade - nodes - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -exports.Node = require('./node'); -exports.Tag = require('./tag'); -exports.Code = require('./code'); -exports.Each = require('./each'); -exports.Case = require('./case'); -exports.Text = require('./text'); -exports.Block = require('./block'); -exports.Mixin = require('./mixin'); -exports.Filter = require('./filter'); -exports.Comment = require('./comment'); -exports.Literal = require('./literal'); -exports.BlockComment = require('./block-comment'); -exports.Doctype = require('./doctype'); - -}); // module: nodes/index.js - -require.register("nodes/literal.js", function(module, exports, require){ - -/*! - * Jade - nodes - Literal - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Literal` node with the given `str. - * - * @param {String} str - * @api public - */ - -var Literal = module.exports = function Literal(str) { - this.str = str - .replace(/\\/g, "\\\\") - .replace(/\n|\r\n/g, "\\n") - .replace(/'/g, "\\'"); -}; - -/** - * Inherit from `Node`. - */ - -Literal.prototype = new Node; -Literal.prototype.constructor = Literal; - - -}); // module: nodes/literal.js - -require.register("nodes/mixin.js", function(module, exports, require){ - -/*! - * Jade - nodes - Mixin - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Attrs = require('./attrs'); - -/** - * Initialize a new `Mixin` with `name` and `block`. - * - * @param {String} name - * @param {String} args - * @param {Block} block - * @api public - */ - -var Mixin = module.exports = function Mixin(name, args, block, call){ - this.name = name; - this.args = args; - this.block = block; - this.attrs = []; - this.call = call; -}; - -/** - * Inherit from `Attrs`. - */ - -Mixin.prototype = new Attrs; -Mixin.prototype.constructor = Mixin; - - - -}); // module: nodes/mixin.js - -require.register("nodes/node.js", function(module, exports, require){ - -/*! - * Jade - nodes - Node - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Initialize a `Node`. - * - * @api public - */ - -var Node = module.exports = function Node(){}; - -/** - * Clone this node (return itself) - * - * @return {Node} - * @api private - */ - -Node.prototype.clone = function(){ - return this; -}; - -}); // module: nodes/node.js - -require.register("nodes/tag.js", function(module, exports, require){ - -/*! - * Jade - nodes - Tag - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Attrs = require('./attrs'), - Block = require('./block'), - inlineTags = require('../inline-tags'); - -/** - * Initialize a `Tag` node with the given tag `name` and optional `block`. - * - * @param {String} name - * @param {Block} block - * @api public - */ - -var Tag = module.exports = function Tag(name, block) { - this.name = name; - this.attrs = []; - this.block = block || new Block; -}; - -/** - * Inherit from `Attrs`. - */ - -Tag.prototype = new Attrs; -Tag.prototype.constructor = Tag; - - -/** - * Clone this tag. - * - * @return {Tag} - * @api private - */ - -Tag.prototype.clone = function(){ - var clone = new Tag(this.name, this.block.clone()); - clone.line = this.line; - clone.attrs = this.attrs; - clone.textOnly = this.textOnly; - return clone; -}; - -/** - * Check if this tag is an inline tag. - * - * @return {Boolean} - * @api private - */ - -Tag.prototype.isInline = function(){ - return ~inlineTags.indexOf(this.name); -}; - -/** - * Check if this tag's contents can be inlined. Used for pretty printing. - * - * @return {Boolean} - * @api private - */ - -Tag.prototype.canInline = function(){ - var nodes = this.block.nodes; - - function isInline(node){ - // Recurse if the node is a block - if (node.isBlock) return node.nodes.every(isInline); - return node.isText || (node.isInline && node.isInline()); - } - - // Empty tag - if (!nodes.length) return true; - - // Text-only or inline-only tag - if (1 == nodes.length) return isInline(nodes[0]); - - // Multi-line inline-only tag - if (this.block.nodes.every(isInline)) { - for (var i = 1, len = nodes.length; i < len; ++i) { - if (nodes[i-1].isText && nodes[i].isText) - return false; - } - return true; - } - - // Mixed tag - return false; -}; -}); // module: nodes/tag.js - -require.register("nodes/text.js", function(module, exports, require){ - -/*! - * Jade - nodes - Text - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Text` node with optional `line`. - * - * @param {String} line - * @api public - */ - -var Text = module.exports = function Text(line) { - this.val = ''; - if ('string' == typeof line) this.val = line; -}; - -/** - * Inherit from `Node`. - */ - -Text.prototype = new Node; -Text.prototype.constructor = Text; - - -/** - * Flag as text. - */ - -Text.prototype.isText = true; -}); // module: nodes/text.js - -require.register("parser.js", function(module, exports, require){ - -/*! - * Jade - Parser - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Lexer = require('./lexer') - , nodes = require('./nodes'); - -/** - * Initialize `Parser` with the given input `str` and `filename`. - * - * @param {String} str - * @param {String} filename - * @param {Object} options - * @api public - */ - -var Parser = exports = module.exports = function Parser(str, filename, options){ - this.input = str; - this.lexer = new Lexer(str, options); - this.filename = filename; - this.blocks = {}; - this.mixins = {}; - this.options = options; - this.contexts = [this]; -}; - -/** - * Tags that may not contain tags. - */ - -var textOnly = exports.textOnly = ['script', 'style']; - -/** - * Parser prototype. - */ - -Parser.prototype = { - - /** - * Push `parser` onto the context stack, - * or pop and return a `Parser`. - */ - - context: function(parser){ - if (parser) { - this.contexts.push(parser); - } else { - return this.contexts.pop(); - } - }, - - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ - - advance: function(){ - return this.lexer.advance(); - }, - - /** - * Skip `n` tokens. - * - * @param {Number} n - * @api private - */ - - skip: function(n){ - while (n--) this.advance(); - }, - - /** - * Single token lookahead. - * - * @return {Object} - * @api private - */ - - peek: function() { - return this.lookahead(1); - }, - - /** - * Return lexer lineno. - * - * @return {Number} - * @api private - */ - - line: function() { - return this.lexer.lineno; - }, - - /** - * `n` token lookahead. - * - * @param {Number} n - * @return {Object} - * @api private - */ - - lookahead: function(n){ - return this.lexer.lookahead(n); - }, - - /** - * Parse input returning a string of js for evaluation. - * - * @return {String} - * @api public - */ - - parse: function(){ - var block = new nodes.Block, parser; - block.line = this.line(); - - while ('eos' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else { - block.push(this.parseExpr()); - } - } - - if (parser = this.extending) { - this.context(parser); - var ast = parser.parse(); - this.context(); - // hoist mixins - for (var name in this.mixins) - ast.unshift(this.mixins[name]); - return ast; - } - - return block; - }, - - /** - * Expect the given type, or throw an exception. - * - * @param {String} type - * @api private - */ - - expect: function(type){ - if (this.peek().type === type) { - return this.advance(); - } else { - throw new Error('expected "' + type + '", but got "' + this.peek().type + '"'); - } - }, - - /** - * Accept the given `type`. - * - * @param {String} type - * @api private - */ - - accept: function(type){ - if (this.peek().type === type) { - return this.advance(); - } - }, - - /** - * tag - * | doctype - * | mixin - * | include - * | filter - * | comment - * | text - * | each - * | code - * | yield - * | id - * | class - * | interpolation - */ - - parseExpr: function(){ - switch (this.peek().type) { - case 'tag': - return this.parseTag(); - case 'mixin': - return this.parseMixin(); - case 'block': - return this.parseBlock(); - case 'case': - return this.parseCase(); - case 'when': - return this.parseWhen(); - case 'default': - return this.parseDefault(); - case 'extends': - return this.parseExtends(); - case 'include': - return this.parseInclude(); - case 'doctype': - return this.parseDoctype(); - case 'filter': - return this.parseFilter(); - case 'comment': - return this.parseComment(); - case 'text': - return this.parseText(); - case 'each': - return this.parseEach(); - case 'code': - return this.parseCode(); - case 'call': - return this.parseCall(); - case 'interpolation': - return this.parseInterpolation(); - case 'yield': - this.advance(); - var block = new nodes.Block; - block.yield = true; - return block; - case 'id': - case 'class': - var tok = this.advance(); - this.lexer.defer(this.lexer.tok('tag', 'div')); - this.lexer.defer(tok); - return this.parseExpr(); - default: - throw new Error('unexpected token "' + this.peek().type + '"'); - } - }, - - /** - * Text - */ - - parseText: function(){ - var tok = this.expect('text') - , node = new nodes.Text(tok.val); - node.line = this.line(); - return node; - }, - - /** - * ':' expr - * | block - */ - - parseBlockExpansion: function(){ - if (':' == this.peek().type) { - this.advance(); - return new nodes.Block(this.parseExpr()); - } else { - return this.block(); - } - }, - - /** - * case - */ - - parseCase: function(){ - var val = this.expect('case').val - , node = new nodes.Case(val); - node.line = this.line(); - node.block = this.block(); - return node; - }, - - /** - * when - */ - - parseWhen: function(){ - var val = this.expect('when').val - return new nodes.Case.When(val, this.parseBlockExpansion()); - }, - - /** - * default - */ - - parseDefault: function(){ - this.expect('default'); - return new nodes.Case.When('default', this.parseBlockExpansion()); - }, - - /** - * code - */ - - parseCode: function(){ - var tok = this.expect('code') - , node = new nodes.Code(tok.val, tok.buffer, tok.escape) - , block - , i = 1; - node.line = this.line(); - while (this.lookahead(i) && 'newline' == this.lookahead(i).type) ++i; - block = 'indent' == this.lookahead(i).type; - if (block) { - this.skip(i-1); - node.block = this.block(); - } - return node; - }, - - /** - * comment - */ - - parseComment: function(){ - var tok = this.expect('comment') - , node; - - if ('indent' == this.peek().type) { - node = new nodes.BlockComment(tok.val, this.block(), tok.buffer); - } else { - node = new nodes.Comment(tok.val, tok.buffer); - } - - node.line = this.line(); - return node; - }, - - /** - * doctype - */ - - parseDoctype: function(){ - var tok = this.expect('doctype') - , node = new nodes.Doctype(tok.val); - node.line = this.line(); - return node; - }, - - /** - * filter attrs? text-block - */ - - parseFilter: function(){ - var block - , tok = this.expect('filter') - , attrs = this.accept('attrs'); - - this.lexer.pipeless = true; - block = this.parseTextBlock(); - this.lexer.pipeless = false; - - var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); - node.line = this.line(); - return node; - }, - - /** - * tag ':' attrs? block - */ - - parseASTFilter: function(){ - var block - , tok = this.expect('tag') - , attrs = this.accept('attrs'); - - this.expect(':'); - block = this.block(); - - var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); - node.line = this.line(); - return node; - }, - - /** - * each block - */ - - parseEach: function(){ - var tok = this.expect('each') - , node = new nodes.Each(tok.code, tok.val, tok.key); - node.line = this.line(); - node.block = this.block(); - return node; - }, - - /** - * 'extends' name - */ - - parseExtends: function(){ - var path = require('path') - , fs = require('fs') - , dirname = path.dirname - , basename = path.basename - , join = path.join; - - if (!this.filename) - throw new Error('the "filename" option is required to extend templates'); - - var path = this.expect('extends').val.trim() - , dir = dirname(this.filename); - - var path = join(dir, path + '.jade') - , str = fs.readFileSync(path, 'utf8') - , parser = new Parser(str, path, this.options); - - parser.blocks = this.blocks; - parser.contexts = this.contexts; - this.extending = parser; - - // TODO: null node - return new nodes.Literal(''); - }, - - /** - * 'block' name block - */ - - parseBlock: function(){ - var block = this.expect('block') - , mode = block.mode - , name = block.val.trim(); - - block = 'indent' == this.peek().type - ? this.block() - : new nodes.Block(new nodes.Literal('')); - - var prev = this.blocks[name]; - - if (prev) { - switch (prev.mode) { - case 'append': - block.nodes = block.nodes.concat(prev.nodes); - prev = block; - break; - case 'prepend': - block.nodes = prev.nodes.concat(block.nodes); - prev = block; - break; - } - } - - block.mode = mode; - return this.blocks[name] = prev || block; - }, - - /** - * include block? - */ - - parseInclude: function(){ - var path = require('path') - , fs = require('fs') - , dirname = path.dirname - , basename = path.basename - , join = path.join; - - var path = this.expect('include').val.trim() - , dir = dirname(this.filename); - - if (!this.filename) - throw new Error('the "filename" option is required to use includes'); - - // no extension - if (!~basename(path).indexOf('.')) { - path += '.jade'; - } - - // non-jade - if ('.jade' != path.substr(-5)) { - var path = join(dir, path) - , str = fs.readFileSync(path, 'utf8'); - return new nodes.Literal(str); - } - - var path = join(dir, path) - , str = fs.readFileSync(path, 'utf8') - , parser = new Parser(str, path, this.options); - parser.blocks = this.blocks; - parser.mixins = this.mixins; - - this.context(parser); - var ast = parser.parse(); - this.context(); - ast.filename = path; - - if ('indent' == this.peek().type) { - ast.includeBlock().push(this.block()); - } - - return ast; - }, - - /** - * call ident block - */ - - parseCall: function(){ - var tok = this.expect('call') - , name = tok.val - , args = tok.args - , mixin = new nodes.Mixin(name, args, new nodes.Block, true); - - this.tag(mixin); - if (mixin.block.isEmpty()) mixin.block = null; - return mixin; - }, - - /** - * mixin block - */ - - parseMixin: function(){ - var tok = this.expect('mixin') - , name = tok.val - , args = tok.args - , mixin; - - // definition - if ('indent' == this.peek().type) { - mixin = new nodes.Mixin(name, args, this.block(), false); - this.mixins[name] = mixin; - return mixin; - // call - } else { - return new nodes.Mixin(name, args, null, true); - } - }, - - /** - * indent (text | newline)* outdent - */ - - parseTextBlock: function(){ - var block = new nodes.Block; - block.line = this.line(); - var spaces = this.expect('indent').val; - if (null == this._spaces) this._spaces = spaces; - var indent = Array(spaces - this._spaces + 1).join(' '); - while ('outdent' != this.peek().type) { - switch (this.peek().type) { - case 'newline': - this.advance(); - break; - case 'indent': - this.parseTextBlock().nodes.forEach(function(node){ - block.push(node); - }); - break; - default: - var text = new nodes.Text(indent + this.advance().val); - text.line = this.line(); - block.push(text); - } - } - - if (spaces == this._spaces) this._spaces = null; - this.expect('outdent'); - return block; - }, - - /** - * indent expr* outdent - */ - - block: function(){ - var block = new nodes.Block; - block.line = this.line(); - this.expect('indent'); - while ('outdent' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else { - block.push(this.parseExpr()); - } - } - this.expect('outdent'); - return block; - }, - - /** - * interpolation (attrs | class | id)* (text | code | ':')? newline* block? - */ - - parseInterpolation: function(){ - var tok = this.advance(); - var tag = new nodes.Tag(tok.val); - tag.buffer = true; - return this.tag(tag); - }, - - /** - * tag (attrs | class | id)* (text | code | ':')? newline* block? - */ - - parseTag: function(){ - // ast-filter look-ahead - var i = 2; - if ('attrs' == this.lookahead(i).type) ++i; - if (':' == this.lookahead(i).type) { - if ('indent' == this.lookahead(++i).type) { - return this.parseASTFilter(); - } - } - - var tok = this.advance() - , tag = new nodes.Tag(tok.val); - - tag.selfClosing = tok.selfClosing; - - return this.tag(tag); - }, - - /** - * Parse tag. - */ - - tag: function(tag){ - var dot; - - tag.line = this.line(); - - // (attrs | class | id)* - out: - while (true) { - switch (this.peek().type) { - case 'id': - case 'class': - var tok = this.advance(); - tag.setAttribute(tok.type, "'" + tok.val + "'"); - continue; - case 'attrs': - var tok = this.advance() - , obj = tok.attrs - , escaped = tok.escaped - , names = Object.keys(obj); - - if (tok.selfClosing) tag.selfClosing = true; - - for (var i = 0, len = names.length; i < len; ++i) { - var name = names[i] - , val = obj[name]; - tag.setAttribute(name, val, escaped[name]); - } - continue; - default: - break out; - } - } - - // check immediate '.' - if ('.' == this.peek().val) { - dot = tag.textOnly = true; - this.advance(); - } - - // (text | code | ':')? - switch (this.peek().type) { - case 'text': - tag.block.push(this.parseText()); - break; - case 'code': - tag.code = this.parseCode(); - break; - case ':': - this.advance(); - tag.block = new nodes.Block; - tag.block.push(this.parseExpr()); - break; - } - - // newline* - while ('newline' == this.peek().type) this.advance(); - - tag.textOnly = tag.textOnly || ~textOnly.indexOf(tag.name); - - // script special-case - if ('script' == tag.name) { - var type = tag.getAttribute('type'); - if (!dot && type && 'text/javascript' != type.replace(/^['"]|['"]$/g, '')) { - tag.textOnly = false; - } - } - - // block? - if ('indent' == this.peek().type) { - if (tag.textOnly) { - this.lexer.pipeless = true; - tag.block = this.parseTextBlock(); - this.lexer.pipeless = false; - } else { - var block = this.block(); - if (tag.block) { - for (var i = 0, len = block.nodes.length; i < len; ++i) { - tag.block.push(block.nodes[i]); - } - } else { - tag.block = block; - } - } - } - - return tag; - } -}; - -}); // module: parser.js - -require.register("runtime.js", function(module, exports, require){ - -/*! - * Jade - runtime - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Lame Array.isArray() polyfill for now. - */ - -if (!Array.isArray) { - Array.isArray = function(arr){ - return '[object Array]' == Object.prototype.toString.call(arr); - }; -} - -/** - * Lame Object.keys() polyfill for now. - */ - -if (!Object.keys) { - Object.keys = function(obj){ - var arr = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - arr.push(key); - } - } - return arr; - } -} - -/** - * Merge two attribute objects giving precedence - * to values in object `b`. Classes are special-cased - * allowing for arrays and merging/joining appropriately - * resulting in a string. - * - * @param {Object} a - * @param {Object} b - * @return {Object} a - * @api private - */ - -exports.merge = function merge(a, b) { - var ac = a['class']; - var bc = b['class']; - - if (ac || bc) { - ac = ac || []; - bc = bc || []; - if (!Array.isArray(ac)) ac = [ac]; - if (!Array.isArray(bc)) bc = [bc]; - ac = ac.filter(nulls); - bc = bc.filter(nulls); - a['class'] = ac.concat(bc).join(' '); - } - - for (var key in b) { - if (key != 'class') { - a[key] = b[key]; - } - } - - return a; -}; - -/** - * Filter null `val`s. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function nulls(val) { - return val != null; -} - -/** - * Render the given attributes object. - * - * @param {Object} obj - * @param {Object} escaped - * @return {String} - * @api private - */ - -exports.attrs = function attrs(obj, escaped){ - var buf = [] - , terse = obj.terse; - - delete obj.terse; - var keys = Object.keys(obj) - , len = keys.length; - - if (len) { - buf.push(''); - for (var i = 0; i < len; ++i) { - var key = keys[i] - , val = obj[key]; - - if ('boolean' == typeof val || null == val) { - if (val) { - terse - ? buf.push(key) - : buf.push(key + '="' + key + '"'); - } - } else if (0 == key.indexOf('data') && 'string' != typeof val) { - buf.push(key + "='" + JSON.stringify(val) + "'"); - } else if ('class' == key && Array.isArray(val)) { - buf.push(key + '="' + exports.escape(val.join(' ')) + '"'); - } else if (escaped && escaped[key]) { - buf.push(key + '="' + exports.escape(val) + '"'); - } else { - buf.push(key + '="' + val + '"'); - } - } - } - - return buf.join(' '); -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function escape(html){ - return String(html) - .replace(/&(?!(\w+|\#\d+);)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -/** - * Re-throw the given `err` in context to the - * the jade in `filename` at the given `lineno`. - * - * @param {Error} err - * @param {String} filename - * @param {String} lineno - * @api private - */ - -exports.rethrow = function rethrow(err, filename, lineno){ - if (!filename) throw err; - - var context = 3 - , str = require('fs').readFileSync(filename, 'utf8') - , lines = str.split('\n') - , start = Math.max(lineno - context, 0) - , end = Math.min(lines.length, lineno + context); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' > ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'Jade') + ':' + lineno - + '\n' + context + '\n\n' + err.message; - throw err; -}; - -}); // module: runtime.js - -require.register("self-closing.js", function(module, exports, require){ - -/*! - * Jade - self closing tags - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = [ - 'meta' - , 'img' - , 'link' - , 'input' - , 'source' - , 'area' - , 'base' - , 'col' - , 'br' - , 'hr' -]; -}); // module: self-closing.js - -require.register("utils.js", function(module, exports, require){ - -/*! - * Jade - utils - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Convert interpolation in the given string to JavaScript. - * - * @param {String} str - * @return {String} - * @api private - */ - -var interpolate = exports.interpolate = function(str){ - return str.replace(/(\\)?([#!]){(.*?)}/g, function(str, escape, flag, code){ - return escape - ? str - : "' + " - + ('!' == flag ? '' : 'escape') - + "((interp = " + code.replace(/\\'/g, "'") - + ") == null ? '' : interp) + '"; - }); -}; - -/** - * Escape single quotes in `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -var escape = exports.escape = function(str) { - return str.replace(/'/g, "\\'"); -}; - -/** - * Interpolate, and escape the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.text = function(str){ - return interpolate(escape(str)); -}; -}); // module: utils.js - -window.jade = require("jade"); -})(); diff --git a/node_modules/mocha/node_modules/jade/jade.md b/node_modules/mocha/node_modules/jade/jade.md deleted file mode 100644 index 051dc03..0000000 --- a/node_modules/mocha/node_modules/jade/jade.md +++ /dev/null @@ -1,510 +0,0 @@ - -# Jade - - The jade template engine for node.js - -## Synopsis - - jade [-h|--help] [-v|--version] [-o|--obj STR] - [-O|--out DIR] [-p|--path PATH] [-P|--pretty] - [-c|--client] [-D|--no-debug] - -## Examples - - translate jade the templates dir - - $ jade templates - - create {foo,bar}.html - - $ jade {foo,bar}.jade - - jade over stdio - - $ jade < my.jade > my.html - - jade over s - - $ echo "h1 Jade!" | jade - - foo, bar dirs rendering to /tmp - - $ jade foo bar --out /tmp - - compile client-side templates without debugging - instrumentation, making the output javascript - very light-weight. This requires runtime.js - in your projects. - - $ jade --client --no-debug < my.jade - -## Tags - - Tags are simply nested via whitespace, closing - tags defined for you. These indents are called "blocks". - - ul - li - a Foo - li - a Bar - - You may have several tags in one "block": - - ul - li - a Foo - a Bar - a Baz - -## Self-closing Tags - - Some tags are flagged as self-closing by default, such - as `meta`, `link`, and so on. To explicitly self-close - a tag simply append the `/` character: - - foo/ - foo(bar='baz')/ - - Would yield: - - - - -## Attributes - - Tag attributes look similar to HTML, however - the values are regular JavaScript, here are - some examples: - - a(href='google.com') Google - a(class='button', href='google.com') Google - - As mentioned the attribute values are just JavaScript, - this means ternary operations and other JavaScript expressions - work just fine: - - body(class=user.authenticated ? 'authenticated' : 'anonymous') - a(href=user.website || 'http://google.com') - - Multiple lines work too: - - input(type='checkbox', - name='agreement', - checked) - - Multiple lines without the comma work fine: - - input(type='checkbox' - name='agreement' - checked) - - Funky whitespace? fine: - - input( - type='checkbox' - name='agreement' - checked) - -## Boolean attributes - - Boolean attributes are mirrored by Jade, and accept - bools, aka _true_ or _false_. When no value is specified - _true_ is assumed. For example: - - input(type="checkbox", checked) - // => "" - - For example if the checkbox was for an agreement, perhaps `user.agreed` - was _true_ the following would also output 'checked="checked"': - - input(type="checkbox", checked=user.agreed) - -## Class attributes - - The _class_ attribute accepts an array of classes, - this can be handy when generated from a javascript - function etc: - - classes = ['foo', 'bar', 'baz'] - a(class=classes) - // => "" - -## Class literal - - Classes may be defined using a ".CLASSNAME" syntax: - - .button - // => "
      " - - Or chained: - - .large.button - // => "
      " - - The previous defaulted to divs, however you - may also specify the tag type: - - h1.title My Title - // => "

      My Title

      " - -## Id literal - - Much like the class literal there's an id literal: - - #user-1 - // => "
      " - - Again we may specify the tag as well: - - ul#menu - li: a(href='/home') Home - li: a(href='/store') Store - li: a(href='/contact') Contact - - Finally all of these may be used in any combination, - the following are all valid tags: - - a.button#contact(style: 'color: red') Contact - a.button(style: 'color: red')#contact Contact - a(style: 'color: red').button#contact Contact - -## Block expansion - - Jade supports the concept of "block expansion", in which - using a trailing ":" after a tag will inject a block: - - ul - li: a Foo - li: a Bar - li: a Baz - -## Text - - Arbitrary text may follow tags: - - p Welcome to my site - - yields: - -

      Welcome to my site

      - -## Pipe text - - Another form of text is "pipe" text. Pipes act - as the text margin for large bodies of text. - - p - | This is a large - | body of text for - | this tag. - | - | Nothing too - | exciting. - - yields: - -

      This is a large - body of text for - this tag. - - Nothing too - exciting. -

      - - Using pipes we can also specify regular Jade tags - within the text: - - p - | Click to visit - a(href='http://google.com') Google - | if you want. - -## Text only tags - - As an alternative to pipe text you may add - a trailing "." to indicate that the block - contains nothing but plain-text, no tags: - - p. - This is a large - body of text for - this tag. - - Nothing too - exciting. - - Some tags are text-only by default, for example - _script_, _textarea_, and _style_ tags do not - contain nested HTML so Jade implies the trailing ".": - - script - if (foo) { - bar(); - } - - style - body { - padding: 50px; - font: 14px Helvetica; - } - -## Template script tags - - Sometimes it's useful to define HTML in script - tags using Jade, typically for client-side templates. - - To do this simply give the _script_ tag an arbitrary - _type_ attribute such as _text/x-template_: - - script(type='text/template') - h1 Look! - p Jade still works in here! - -## Interpolation - - Both plain-text and piped-text support interpolation, - which comes in two forms, escapes and non-escaped. The - following will output the _user.name_ in the paragraph - but HTML within it will be escaped to prevent XSS attacks: - - p Welcome #{user.name} - - The following syntax is identical however it will _not_ escape - HTML, and should only be used with strings that you trust: - - p Welcome !{user.name} - -## Inline HTML - - Sometimes constructing small inline snippets of HTML - in Jade can be annoying, luckily we can add plain - HTML as well: - - p Welcome #{user.name} - -## Code - - To buffer output with Jade simply use _=_ at the beginning - of a line or after a tag. This method escapes any HTML - present in the string. - - p= user.description - - To buffer output unescaped use the _!=_ variant, but again - be careful of XSS. - - p!= user.description - - The final way to mess with JavaScript code in Jade is the unbuffered - _-_, which can be used for conditionals, defining variables etc: - - - var user = { description: 'foo bar baz' } - #user - - if (user.description) { - h2 Description - p.description= user.description - - } - - When compiled blocks are wrapped in anonymous functions, so the - following is also valid, without braces: - - - var user = { description: 'foo bar baz' } - #user - - if (user.description) - h2 Description - p.description= user.description - - If you really want you could even use `.forEach()` and others: - - - users.forEach(function(user){ - .user - h2= user.name - p User #{user.name} is #{user.age} years old - - }) - - Taking this further Jade provides some syntax for conditionals, - iteration, switch statements etc. Let's look at those next! - -## Assignment - - Jade's first-class assignment is simple, simply use the _=_ - operator and Jade will _var_ it for you. The following are equivalent: - - - var user = { name: 'tobi' } - user = { name: 'tobi' } - -## Conditionals - - Jade's first-class conditional syntax allows for optional - parenthesis, and you may now omit the leading _-_ otherwise - it's identical, still just regular javascript: - - user = { description: 'foo bar baz' } - #user - if user.description - h2 Description - p.description= user.description - - Jade provides the negated version, _unless_ as well, the following - are equivalent: - - - if (!(user.isAnonymous)) - p You're logged in as #{user.name} - - unless user.isAnonymous - p You're logged in as #{user.name} - -## Iteration - - JavaScript's _for_ loops don't look very declarative, so Jade - also provides its own _for_ loop construct, aliased as _each_: - - for user in users - .user - h2= user.name - p user #{user.name} is #{user.age} year old - - As mentioned _each_ is identical: - - each user in users - .user - h2= user.name - - If necessary the index is available as well: - - for user, i in users - .user(class='user-#{i}') - h2= user.name - - Remember, it's just JavaScript: - - ul#letters - for letter in ['a', 'b', 'c'] - li= letter - -## Mixins - - Mixins provide a way to define jade "functions" which "mix in" - their contents when called. This is useful for abstracting - out large fragments of Jade. - - The simplest possible mixin which accepts no arguments might - look like this: - - mixin hello - p Hello - - You use a mixin by placing `+` before the name: - - +hello - - For something a little more dynamic, mixins can take - arguments, the mixin itself is converted to a javascript - function internally: - - mixin hello(user) - p Hello #{user} - - +hello('Tobi') - - Yields: - -

      Hello Tobi

      - - Mixins may optionally take blocks, when a block is passed - its contents becomes the implicit `block` argument. For - example here is a mixin passed a block, and also invoked - without passing a block: - - mixin article(title) - .article - .article-wrapper - h1= title - if block - block - else - p No content provided - - +article('Hello world') - - +article('Hello world') - p This is my - p Amazing article - - yields: - -
      -
      -

      Hello world

      -

      No content provided

      -
      -
      - -
      -
      -

      Hello world

      -

      This is my

      -

      Amazing article

      -
      -
      - - Mixins can even take attributes, just like a tag. When - attributes are passed they become the implicit `attributes` - argument. Individual attributes can be accessed just like - normal object properties: - - mixin centered - .centered(class=attributes.class) - block - - +centered.bold Hello world - - +centered.red - p This is my - p Amazing article - - yields: - -
      Hello world
      -
      -

      This is my

      -

      Amazing article

      -
      - - If you use `attributes` directly, *all* passed attributes - get used: - - mixin link - a.menu(attributes) - block - - +link.highlight(href='#top') Top - +link#sec1.plain(href='#section1') Section 1 - +link#sec2.plain(href='#section2') Section 2 - - yields: - - Top - Section 1 - Section 2 - - If you pass arguments, they must directly follow the mixin: - - mixin list(arr) - if block - .title - block - ul(attributes) - each item in arr - li= item - - +list(['foo', 'bar', 'baz'])(id='myList', class='bold') - - yields: - -
        -
      • foo
      • -
      • bar
      • -
      • baz
      • -
      diff --git a/node_modules/mocha/node_modules/jade/jade.min.js b/node_modules/mocha/node_modules/jade/jade.min.js deleted file mode 100644 index 72e4535..0000000 --- a/node_modules/mocha/node_modules/jade/jade.min.js +++ /dev/null @@ -1,2 +0,0 @@ -(function(){function require(p){var path=require.resolve(p),mod=require.modules[path];if(!mod)throw new Error('failed to require "'+p+'"');return mod.exports||(mod.exports={},mod.call(mod.exports,mod,mod.exports,require.relative(path))),mod.exports}require.modules={},require.resolve=function(path){var orig=path,reg=path+".js",index=path+"/index.js";return require.modules[reg]&®||require.modules[index]&&index||orig},require.register=function(path,fn){require.modules[path]=fn},require.relative=function(parent){return function(p){if("."!=p.charAt(0))return require(p);var path=parent.split("/"),segs=p.split("/");path.pop();for(var i=0;i",this.doctype=doctype,this.terse="5"==name||"html"==name,this.xml=0==this.doctype.indexOf("1&&!escape&&block.nodes[0].isText&&block.nodes[1].isText&&this.prettyIndent(1,!0);for(var i=0;i0&&!escape&&block.nodes[i].isText&&block.nodes[i-1].isText&&this.prettyIndent(1,!1),this.visit(block.nodes[i]),block.nodes[i+1]&&block.nodes[i].isText&&block.nodes[i+1].isText&&this.buffer("\\n")},visitDoctype:function(doctype){doctype&&(doctype.val||!this.doctype)&&this.setDoctype(doctype.val||"default"),this.doctype&&this.buffer(this.doctype),this.hasCompiledDoctype=!0},visitMixin:function(mixin){var name=mixin.name.replace(/-/g,"_")+"_mixin",args=mixin.args||"",block=mixin.block,attrs=mixin.attrs,pp=this.pp;if(mixin.call){pp&&this.buf.push("__indent.push('"+Array(this.indents+1).join(" ")+"');");if(block||attrs.length){this.buf.push(name+".call({");if(block){this.buf.push("block: function(){"),this.parentIndents++;var _indents=this.indents;this.indents=0,this.visit(mixin.block),this.indents=_indents,this.parentIndents--,attrs.length?this.buf.push("},"):this.buf.push("}")}if(attrs.length){var val=this.attrs(attrs);val.inherits?this.buf.push("attributes: merge({"+val.buf+"}, attributes), escaped: merge("+val.escaped+", escaped, true)"):this.buf.push("attributes: {"+val.buf+"}, escaped: "+val.escaped)}args?this.buf.push("}, "+args+");"):this.buf.push("});")}else this.buf.push(name+"("+args+");");pp&&this.buf.push("__indent.pop();")}else this.buf.push("var "+name+" = function("+args+"){"),this.buf.push("var block = this.block, attributes = this.attributes || {}, escaped = this.escaped || {};"),this.parentIndents++,this.visit(block),this.parentIndents--,this.buf.push("};")},visitTag:function(tag){this.indents++;var name=tag.name,pp=this.pp;tag.buffer&&(name="' + ("+name+") + '"),this.hasCompiledTag||(!this.hasCompiledDoctype&&"html"==name&&this.visitDoctype(),this.hasCompiledTag=!0),pp&&!tag.isInline()&&this.prettyIndent(0,!0),(~selfClosing.indexOf(name)||tag.selfClosing)&&!this.xml?(this.buffer("<"+name),this.visitAttributes(tag.attrs),this.terse?this.buffer(">"):this.buffer("/>")):(tag.attrs.length?(this.buffer("<"+name),tag.attrs.length&&this.visitAttributes(tag.attrs),this.buffer(">")):this.buffer("<"+name+">"),tag.code&&this.visitCode(tag.code),this.escape="pre"==tag.name,this.visit(tag.block),pp&&!tag.isInline()&&"pre"!=tag.name&&!tag.canInline()&&this.prettyIndent(0,!0),this.buffer("")),this.indents--},visitFilter:function(filter){var fn=filters[filter.name];if(!fn)throw filter.isASTFilter?new Error('unknown ast filter "'+filter.name+':"'):new Error('unknown filter ":'+filter.name+'"');if(filter.isASTFilter)this.buf.push(fn(filter.block,this,filter.attrs));else{var text=filter.block.nodes.map(function(node){return node.val}).join("\n");filter.attrs=filter.attrs||{},filter.attrs.filename=this.options.filename,this.buffer(utils.text(fn(text,filter.attrs)))}},visitText:function(text){text=utils.text(text.val.replace(/\\/g,"\\\\")),this.escape&&(text=escape(text)),this.buffer(text)},visitComment:function(comment){if(!comment.buffer)return;this.pp&&this.prettyIndent(1,!0),this.buffer("")},visitBlockComment:function(comment){if(!comment.buffer)return;0==comment.val.trim().indexOf("if")?(this.buffer("")):(this.buffer(""))},visitCode:function(code){if(code.buffer){var val=code.val.trimLeft();this.buf.push("var __val__ = "+val),val='null == __val__ ? "" : __val__',code.escape&&(val="escape("+val+")"),this.buf.push("buf.push("+val+");")}else this.buf.push(code.val);code.block&&(code.buffer||this.buf.push("{"),this.visit(code.block),code.buffer||this.buf.push("}"))},visitEach:function(each){this.buf.push("// iterate "+each.obj+"\n"+";(function(){\n"+" if ('number' == typeof "+each.obj+".length) {\n"+" for (var "+each.key+" = 0, $$l = "+each.obj+".length; "+each.key+" < $$l; "+each.key+"++) {\n"+" var "+each.val+" = "+each.obj+"["+each.key+"];\n"),this.visit(each.block),this.buf.push(" }\n } else {\n for (var "+each.key+" in "+each.obj+") {\n"+" if ("+each.obj+".hasOwnProperty("+each.key+")){"+" var "+each.val+" = "+each.obj+"["+each.key+"];\n"),this.visit(each.block),this.buf.push(" }\n"),this.buf.push(" }\n }\n}).call(this);\n")},visitAttributes:function(attrs){var val=this.attrs(attrs);val.inherits?this.buf.push("buf.push(attrs(merge({ "+val.buf+" }, attributes), merge("+val.escaped+", escaped, true)));"):val.constant?(eval("var buf={"+val.buf+"};"),this.buffer(runtime.attrs(buf,JSON.parse(val.escaped)),!0)):this.buf.push("buf.push(attrs({ "+val.buf+" }, "+val.escaped+"));")},attrs:function(attrs){var buf=[],classes=[],escaped={},constant=attrs.every(function(attr){return isConstant(attr.val)}),inherits=!1;return this.terse&&buf.push("terse: true"),attrs.forEach(function(attr){if(attr.name=="attributes")return inherits=!0;escaped[attr.name]=attr.escaped;if(attr.name=="class")classes.push("("+attr.val+")");else{var pair="'"+attr.name+"':("+attr.val+")";buf.push(pair)}}),classes.length&&(classes=classes.join(" + ' ' + "),buf.push("class: "+classes)),{buf:buf.join(", ").replace("class:",'"class":'),escaped:JSON.stringify(escaped),inherits:inherits,constant:constant}}};function isConstant(val){if(/^ *("([^"\\]*(\\.[^"\\]*)*)"|'([^'\\]*(\\.[^'\\]*)*)'|true|false|null|undefined) *$/i.test(val))return!0;if(!isNaN(Number(val)))return!0;var matches;return(matches=/^ *\[(.*)\] *$/.exec(val))?matches[1].split(",").every(isConstant):!1}function escape(html){return String(html).replace(/&(?!\w+;)/g,"&").replace(//g,">").replace(/"/g,""")}}),require.register("doctypes.js",function(module,exports,require){module.exports={5:"","default":"",xml:'',transitional:'',strict:'',frameset:'',1.1:'',basic:'',mobile:''}}),require.register("filters.js",function(module,exports,require){module.exports={cdata:function(str){return""},sass:function(str){str=str.replace(/\\n/g,"\n");var sass=require("sass").render(str).replace(/\n/g,"\\n");return'"},stylus:function(str,options){var ret;str=str.replace(/\\n/g,"\n");var stylus=require("stylus");return stylus(str,options).render(function(err,css){if(err)throw err;ret=css.replace(/\n/g,"\\n")}),'"},less:function(str){var ret;return str=str.replace(/\\n/g,"\n"),require("less").render(str,function(err,css){if(err)throw err;ret='"}),ret},markdown:function(str){var md;try{md=require("markdown")}catch(err){try{md=require("discount")}catch(err){try{md=require("markdown-js")}catch(err){try{md=require("marked")}catch(err){throw new Error("Cannot find markdown library, install markdown, discount, or marked.")}}}}return str=str.replace(/\\n/g,"\n"),md.parse(str).replace(/\n/g,"\\n").replace(/'/g,"'")},coffeescript:function(str){str=str.replace(/\\n/g,"\n");var js=require("coffee-script").compile(str).replace(/\\/g,"\\\\").replace(/\n/g,"\\n");return'"}}}),require.register("inline-tags.js",function(module,exports,require){module.exports=["a","abbr","acronym","b","br","code","em","font","i","img","ins","kbd","map","samp","small","span","strong","sub","sup"]}),require.register("jade.js",function(module,exports,require){var Parser=require("./parser"),Lexer=require("./lexer"),Compiler=require("./compiler"),runtime=require("./runtime");exports.version="0.26.1",exports.selfClosing=require("./self-closing"),exports.doctypes=require("./doctypes"),exports.filters=require("./filters"),exports.utils=require("./utils"),exports.Compiler=Compiler,exports.Parser=Parser,exports.Lexer=Lexer,exports.nodes=require("./nodes"),exports.runtime=runtime,exports.cache={};function parse(str,options){try{var parser=new Parser(str,options.filename,options),compiler=new(options.compiler||Compiler)(parser.parse(),options),js=compiler.compile();return options.debug&&console.error("\nCompiled Function:\n\n%s",js.replace(/^/gm," ")),"var buf = [];\n"+(options.self?"var self = locals || {};\n"+js:"with (locals || {}) {\n"+js+"\n}\n")+'return buf.join("");'}catch(err){parser=parser.context(),runtime.rethrow(err,parser.filename,parser.lexer.lineno)}}exports.compile=function(str,options){var options=options||{},client=options.client,filename=options.filename?JSON.stringify(options.filename):"undefined",fn;return options.compileDebug!==!1?fn=["var __jade = [{ lineno: 1, filename: "+filename+" }];","try {",parse(String(str),options),"} catch (err) {"," rethrow(err, __jade[0].filename, __jade[0].lineno);","}"].join("\n"):fn=parse(String(str),options),client&&(fn="attrs = attrs || jade.attrs; escape = escape || jade.escape; rethrow = rethrow || jade.rethrow; merge = merge || jade.merge;\n"+fn),fn=new Function("locals, attrs, escape, rethrow, merge",fn),client?fn:function(locals){return fn(locals,runtime.attrs,runtime.escape,runtime.rethrow,runtime.merge)}},exports.render=function(str,options,fn){"function"==typeof options&&(fn=options,options={});if(options.cache&&!options.filename)return fn(new Error('the "filename" option is required for caching'));try{var path=options.filename,tmpl=options.cache?exports.cache[path]||(exports.cache[path]=exports.compile(str,options)):exports.compile(str,options);fn(null,tmpl(options))}catch(err){fn(err)}},exports.renderFile=function(path,options,fn){var key=path+":string";"function"==typeof options&&(fn=options,options={});try{options.filename=path;var str=options.cache?exports.cache[key]||(exports.cache[key]=fs.readFileSync(path,"utf8")):fs.readFileSync(path,"utf8");exports.render(str,options,fn)}catch(err){fn(err)}},exports.__express=exports.renderFile}),require.register("lexer.js",function(module,exports,require){var Lexer=module.exports=function Lexer(str,options){options=options||{},this.input=str.replace(/\r\n|\r/g,"\n"),this.colons=options.colons,this.deferredTokens=[],this.lastIndents=0,this.lineno=1,this.stash=[],this.indentStack=[],this.indentRe=null,this.pipeless=!1};Lexer.prototype={tok:function(type,val){return{type:type,line:this.lineno,val:val}},consume:function(len){this.input=this.input.substr(len)},scan:function(regexp,type){var captures;if(captures=regexp.exec(this.input))return this.consume(captures[0].length),this.tok(type,captures[1])},defer:function(tok){this.deferredTokens.push(tok)},lookahead:function(n){var fetch=n-this.stash.length;while(fetch-->0)this.stash.push(this.next());return this.stash[--n]},indexOfDelimiters:function(start,end){var str=this.input,nstart=0,nend=0,pos=0;for(var i=0,len=str.length;iindents)this.stash.push(this.tok("outdent")),this.indentStack.shift();tok=this.stash.pop()}else indents&&indents!=this.indentStack[0]?(this.indentStack.unshift(indents),tok=this.tok("indent",indents)):tok=this.tok("newline");return tok}},pipelessText:function(){if(this.pipeless){if("\n"==this.input[0])return;var i=this.input.indexOf("\n");-1==i&&(i=this.input.length);var str=this.input.substr(0,i);return this.consume(str.length),this.tok("text",str)}},colon:function(){return this.scan(/^: */,":")},advance:function(){return this.stashed()||this.next()},next:function(){return this.deferred()||this.blank()||this.eos()||this.pipelessText()||this.yield()||this.doctype()||this.interpolation()||this["case"]()||this.when()||this["default"]()||this["extends"]()||this.append()||this.prepend()||this.block()||this.include()||this.mixin()||this.call()||this.conditional()||this.each()||this["while"]()||this.assignment()||this.tag()||this.filter()||this.code()||this.id()||this.className()||this.attrs()||this.indent()||this.comment()||this.colon()||this.text()}}}),require.register("nodes/attrs.js",function(module,exports,require){var Node=require("./node"),Block=require("./block"),Attrs=module.exports=function Attrs(){this.attrs=[]};Attrs.prototype=new Node,Attrs.prototype.constructor=Attrs,Attrs.prototype.setAttribute=function(name,val,escaped){return this.attrs.push({name:name,val:val,escaped:escaped}),this},Attrs.prototype.removeAttribute=function(name){for(var i=0,len=this.attrs.length;i/g,">").replace(/"/g,""")},exports.rethrow=function rethrow(err,filename,lineno){if(!filename)throw err;var context=3,str=require("fs").readFileSync(filename,"utf8"),lines=str.split("\n"),start=Math.max(lineno-context,0),end=Math.min(lines.length,lineno+context),context=lines.slice(start,end).map(function(line,i){var curr=i+start+1;return(curr==lineno?" > ":" ")+curr+"| "+line}).join("\n");throw err.path=filename,err.message=(filename||"Jade")+":"+lineno+"\n"+context+"\n\n"+err.message,err}}),require.register("self-closing.js",function(module,exports,require){module.exports=["meta","img","link","input","source","area","base","col","br","hr"]}),require.register("utils.js",function(module,exports,require){var interpolate=exports.interpolate=function(str){return str.replace(/(\\)?([#!]){(.*?)}/g,function(str,escape,flag,code){return escape?str:"' + "+("!"==flag?"":"escape")+"((interp = "+code.replace(/\\'/g,"'")+") == null ? '' : interp) + '"})},escape=exports.escape=function(str){return str.replace(/'/g,"\\'")};exports.text=function(str){return interpolate(escape(str))}}),window.jade=require("jade")})(); \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/compiler.js b/node_modules/mocha/node_modules/jade/lib/compiler.js deleted file mode 100644 index 516ac83..0000000 --- a/node_modules/mocha/node_modules/jade/lib/compiler.js +++ /dev/null @@ -1,642 +0,0 @@ - -/*! - * Jade - Compiler - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var nodes = require('./nodes') - , filters = require('./filters') - , doctypes = require('./doctypes') - , selfClosing = require('./self-closing') - , runtime = require('./runtime') - , utils = require('./utils'); - -// if browser -// -// if (!Object.keys) { -// Object.keys = function(obj){ -// var arr = []; -// for (var key in obj) { -// if (obj.hasOwnProperty(key)) { -// arr.push(key); -// } -// } -// return arr; -// } -// } -// -// if (!String.prototype.trimLeft) { -// String.prototype.trimLeft = function(){ -// return this.replace(/^\s+/, ''); -// } -// } -// -// end - - -/** - * Initialize `Compiler` with the given `node`. - * - * @param {Node} node - * @param {Object} options - * @api public - */ - -var Compiler = module.exports = function Compiler(node, options) { - this.options = options = options || {}; - this.node = node; - this.hasCompiledDoctype = false; - this.hasCompiledTag = false; - this.pp = options.pretty || false; - this.debug = false !== options.compileDebug; - this.indents = 0; - this.parentIndents = 0; - if (options.doctype) this.setDoctype(options.doctype); -}; - -/** - * Compiler prototype. - */ - -Compiler.prototype = { - - /** - * Compile parse tree to JavaScript. - * - * @api public - */ - - compile: function(){ - this.buf = ['var interp;']; - if (this.pp) this.buf.push("var __indent = [];"); - this.lastBufferedIdx = -1; - this.visit(this.node); - return this.buf.join('\n'); - }, - - /** - * Sets the default doctype `name`. Sets terse mode to `true` when - * html 5 is used, causing self-closing tags to end with ">" vs "/>", - * and boolean attributes are not mirrored. - * - * @param {string} name - * @api public - */ - - setDoctype: function(name){ - var doctype = doctypes[(name || 'default').toLowerCase()]; - doctype = doctype || ''; - this.doctype = doctype; - this.terse = '5' == name || 'html' == name; - this.xml = 0 == this.doctype.indexOf(' 1 && !escape && block.nodes[0].isText && block.nodes[1].isText) - this.prettyIndent(1, true); - - for (var i = 0; i < len; ++i) { - // Pretty print text - if (pp && i > 0 && !escape && block.nodes[i].isText && block.nodes[i-1].isText) - this.prettyIndent(1, false); - - this.visit(block.nodes[i]); - // Multiple text nodes are separated by newlines - if (block.nodes[i+1] && block.nodes[i].isText && block.nodes[i+1].isText) - this.buffer('\\n'); - } - }, - - /** - * Visit `doctype`. Sets terse mode to `true` when html 5 - * is used, causing self-closing tags to end with ">" vs "/>", - * and boolean attributes are not mirrored. - * - * @param {Doctype} doctype - * @api public - */ - - visitDoctype: function(doctype){ - if (doctype && (doctype.val || !this.doctype)) { - this.setDoctype(doctype.val || 'default'); - } - - if (this.doctype) this.buffer(this.doctype); - this.hasCompiledDoctype = true; - }, - - /** - * Visit `mixin`, generating a function that - * may be called within the template. - * - * @param {Mixin} mixin - * @api public - */ - - visitMixin: function(mixin){ - var name = mixin.name.replace(/-/g, '_') + '_mixin' - , args = mixin.args || '' - , block = mixin.block - , attrs = mixin.attrs - , pp = this.pp; - - if (mixin.call) { - if (pp) this.buf.push("__indent.push('" + Array(this.indents + 1).join(' ') + "');") - if (block || attrs.length) { - - this.buf.push(name + '.call({'); - - if (block) { - this.buf.push('block: function(){'); - - // Render block with no indents, dynamically added when rendered - this.parentIndents++; - var _indents = this.indents; - this.indents = 0; - this.visit(mixin.block); - this.indents = _indents; - this.parentIndents--; - - if (attrs.length) { - this.buf.push('},'); - } else { - this.buf.push('}'); - } - } - - if (attrs.length) { - var val = this.attrs(attrs); - if (val.inherits) { - this.buf.push('attributes: merge({' + val.buf - + '}, attributes), escaped: merge(' + val.escaped + ', escaped, true)'); - } else { - this.buf.push('attributes: {' + val.buf + '}, escaped: ' + val.escaped); - } - } - - if (args) { - this.buf.push('}, ' + args + ');'); - } else { - this.buf.push('});'); - } - - } else { - this.buf.push(name + '(' + args + ');'); - } - if (pp) this.buf.push("__indent.pop();") - } else { - this.buf.push('var ' + name + ' = function(' + args + '){'); - this.buf.push('var block = this.block, attributes = this.attributes || {}, escaped = this.escaped || {};'); - this.parentIndents++; - this.visit(block); - this.parentIndents--; - this.buf.push('};'); - } - }, - - /** - * Visit `tag` buffering tag markup, generating - * attributes, visiting the `tag`'s code and block. - * - * @param {Tag} tag - * @api public - */ - - visitTag: function(tag){ - this.indents++; - var name = tag.name - , pp = this.pp; - - if (tag.buffer) name = "' + (" + name + ") + '"; - - if (!this.hasCompiledTag) { - if (!this.hasCompiledDoctype && 'html' == name) { - this.visitDoctype(); - } - this.hasCompiledTag = true; - } - - // pretty print - if (pp && !tag.isInline()) - this.prettyIndent(0, true); - - if ((~selfClosing.indexOf(name) || tag.selfClosing) && !this.xml) { - this.buffer('<' + name); - this.visitAttributes(tag.attrs); - this.terse - ? this.buffer('>') - : this.buffer('/>'); - } else { - // Optimize attributes buffering - if (tag.attrs.length) { - this.buffer('<' + name); - if (tag.attrs.length) this.visitAttributes(tag.attrs); - this.buffer('>'); - } else { - this.buffer('<' + name + '>'); - } - if (tag.code) this.visitCode(tag.code); - this.escape = 'pre' == tag.name; - this.visit(tag.block); - - // pretty print - if (pp && !tag.isInline() && 'pre' != tag.name && !tag.canInline()) - this.prettyIndent(0, true); - - this.buffer(''); - } - this.indents--; - }, - - /** - * Visit `filter`, throwing when the filter does not exist. - * - * @param {Filter} filter - * @api public - */ - - visitFilter: function(filter){ - var fn = filters[filter.name]; - - // unknown filter - if (!fn) { - if (filter.isASTFilter) { - throw new Error('unknown ast filter "' + filter.name + ':"'); - } else { - throw new Error('unknown filter ":' + filter.name + '"'); - } - } - - if (filter.isASTFilter) { - this.buf.push(fn(filter.block, this, filter.attrs)); - } else { - var text = filter.block.nodes.map(function(node){ return node.val }).join('\n'); - filter.attrs = filter.attrs || {}; - filter.attrs.filename = this.options.filename; - this.buffer(utils.text(fn(text, filter.attrs))); - } - }, - - /** - * Visit `text` node. - * - * @param {Text} text - * @api public - */ - - visitText: function(text){ - text = utils.text(text.val.replace(/\\/g, '\\\\')); - if (this.escape) text = escape(text); - this.buffer(text); - }, - - /** - * Visit a `comment`, only buffering when the buffer flag is set. - * - * @param {Comment} comment - * @api public - */ - - visitComment: function(comment){ - if (!comment.buffer) return; - if (this.pp) this.prettyIndent(1, true); - this.buffer(''); - }, - - /** - * Visit a `BlockComment`. - * - * @param {Comment} comment - * @api public - */ - - visitBlockComment: function(comment){ - if (!comment.buffer) return; - if (0 == comment.val.trim().indexOf('if')) { - this.buffer(''); - } else { - this.buffer(''); - } - }, - - /** - * Visit `code`, respecting buffer / escape flags. - * If the code is followed by a block, wrap it in - * a self-calling function. - * - * @param {Code} code - * @api public - */ - - visitCode: function(code){ - // Wrap code blocks with {}. - // we only wrap unbuffered code blocks ATM - // since they are usually flow control - - // Buffer code - if (code.buffer) { - var val = code.val.trimLeft(); - this.buf.push('var __val__ = ' + val); - val = 'null == __val__ ? "" : __val__'; - if (code.escape) val = 'escape(' + val + ')'; - this.buf.push("buf.push(" + val + ");"); - } else { - this.buf.push(code.val); - } - - // Block support - if (code.block) { - if (!code.buffer) this.buf.push('{'); - this.visit(code.block); - if (!code.buffer) this.buf.push('}'); - } - }, - - /** - * Visit `each` block. - * - * @param {Each} each - * @api public - */ - - visitEach: function(each){ - this.buf.push('' - + '// iterate ' + each.obj + '\n' - + ';(function(){\n' - + ' if (\'number\' == typeof ' + each.obj + '.length) {\n' - + ' for (var ' + each.key + ' = 0, $$l = ' + each.obj + '.length; ' + each.key + ' < $$l; ' + each.key + '++) {\n' - + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); - - this.visit(each.block); - - this.buf.push('' - + ' }\n' - + ' } else {\n' - + ' for (var ' + each.key + ' in ' + each.obj + ') {\n' - // if browser - // + ' if (' + each.obj + '.hasOwnProperty(' + each.key + ')){' - // end - + ' var ' + each.val + ' = ' + each.obj + '[' + each.key + '];\n'); - - this.visit(each.block); - - // if browser - // this.buf.push(' }\n'); - // end - - this.buf.push(' }\n }\n}).call(this);\n'); - }, - - /** - * Visit `attrs`. - * - * @param {Array} attrs - * @api public - */ - - visitAttributes: function(attrs){ - var val = this.attrs(attrs); - if (val.inherits) { - this.buf.push("buf.push(attrs(merge({ " + val.buf + - " }, attributes), merge(" + val.escaped + ", escaped, true)));"); - } else if (val.constant) { - eval('var buf={' + val.buf + '};'); - this.buffer(runtime.attrs(buf, JSON.parse(val.escaped)), true); - } else { - this.buf.push("buf.push(attrs({ " + val.buf + " }, " + val.escaped + "));"); - } - }, - - /** - * Compile attributes. - */ - - attrs: function(attrs){ - var buf = [] - , classes = [] - , escaped = {} - , constant = attrs.every(function(attr){ return isConstant(attr.val) }) - , inherits = false; - - if (this.terse) buf.push('terse: true'); - - attrs.forEach(function(attr){ - if (attr.name == 'attributes') return inherits = true; - escaped[attr.name] = attr.escaped; - if (attr.name == 'class') { - classes.push('(' + attr.val + ')'); - } else { - var pair = "'" + attr.name + "':(" + attr.val + ')'; - buf.push(pair); - } - }); - - if (classes.length) { - classes = classes.join(" + ' ' + "); - buf.push("class: " + classes); - } - - return { - buf: buf.join(', ').replace('class:', '"class":'), - escaped: JSON.stringify(escaped), - inherits: inherits, - constant: constant - }; - } -}; - -/** - * Check if expression can be evaluated to a constant - * - * @param {String} expression - * @return {Boolean} - * @api private - */ - -function isConstant(val){ - // Check strings/literals - if (/^ *("([^"\\]*(\\.[^"\\]*)*)"|'([^'\\]*(\\.[^'\\]*)*)'|true|false|null|undefined) *$/i.test(val)) - return true; - - // Check numbers - if (!isNaN(Number(val))) - return true; - - // Check arrays - var matches; - if (matches = /^ *\[(.*)\] *$/.exec(val)) - return matches[1].split(',').every(isConstant); - - return false; -} - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -function escape(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -} \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/doctypes.js b/node_modules/mocha/node_modules/jade/lib/doctypes.js deleted file mode 100644 index e87ca1e..0000000 --- a/node_modules/mocha/node_modules/jade/lib/doctypes.js +++ /dev/null @@ -1,18 +0,0 @@ - -/*! - * Jade - doctypes - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = { - '5': '' - , 'default': '' - , 'xml': '' - , 'transitional': '' - , 'strict': '' - , 'frameset': '' - , '1.1': '' - , 'basic': '' - , 'mobile': '' -}; \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/filters.js b/node_modules/mocha/node_modules/jade/lib/filters.js deleted file mode 100644 index fdb634c..0000000 --- a/node_modules/mocha/node_modules/jade/lib/filters.js +++ /dev/null @@ -1,97 +0,0 @@ - -/*! - * Jade - filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = { - - /** - * Wrap text with CDATA block. - */ - - cdata: function(str){ - return ''; - }, - - /** - * Transform sass to css, wrapped in style tags. - */ - - sass: function(str){ - str = str.replace(/\\n/g, '\n'); - var sass = require('sass').render(str).replace(/\n/g, '\\n'); - return ''; - }, - - /** - * Transform stylus to css, wrapped in style tags. - */ - - stylus: function(str, options){ - var ret; - str = str.replace(/\\n/g, '\n'); - var stylus = require('stylus'); - stylus(str, options).render(function(err, css){ - if (err) throw err; - ret = css.replace(/\n/g, '\\n'); - }); - return ''; - }, - - /** - * Transform less to css, wrapped in style tags. - */ - - less: function(str){ - var ret; - str = str.replace(/\\n/g, '\n'); - require('less').render(str, function(err, css){ - if (err) throw err; - ret = ''; - }); - return ret; - }, - - /** - * Transform markdown to html. - */ - - markdown: function(str){ - var md; - - // support markdown / discount - try { - md = require('markdown'); - } catch (err){ - try { - md = require('discount'); - } catch (err) { - try { - md = require('markdown-js'); - } catch (err) { - try { - md = require('marked'); - } catch (err) { - throw new - Error('Cannot find markdown library, install markdown, discount, or marked.'); - } - } - } - } - - str = str.replace(/\\n/g, '\n'); - return md.parse(str).replace(/\n/g, '\\n').replace(/'/g,'''); - }, - - /** - * Transform coffeescript to javascript. - */ - - coffeescript: function(str){ - str = str.replace(/\\n/g, '\n'); - var js = require('coffee-script').compile(str).replace(/\\/g, '\\\\').replace(/\n/g, '\\n'); - return ''; - } -}; diff --git a/node_modules/mocha/node_modules/jade/lib/inline-tags.js b/node_modules/mocha/node_modules/jade/lib/inline-tags.js deleted file mode 100644 index 491de0b..0000000 --- a/node_modules/mocha/node_modules/jade/lib/inline-tags.js +++ /dev/null @@ -1,28 +0,0 @@ - -/*! - * Jade - inline tags - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = [ - 'a' - , 'abbr' - , 'acronym' - , 'b' - , 'br' - , 'code' - , 'em' - , 'font' - , 'i' - , 'img' - , 'ins' - , 'kbd' - , 'map' - , 'samp' - , 'small' - , 'span' - , 'strong' - , 'sub' - , 'sup' -]; \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/jade.js b/node_modules/mocha/node_modules/jade/lib/jade.js deleted file mode 100644 index 00f0abb..0000000 --- a/node_modules/mocha/node_modules/jade/lib/jade.js +++ /dev/null @@ -1,237 +0,0 @@ -/*! - * Jade - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Parser = require('./parser') - , Lexer = require('./lexer') - , Compiler = require('./compiler') - , runtime = require('./runtime') -// if node - , fs = require('fs'); -// end - -/** - * Library version. - */ - -exports.version = '0.26.3'; - -/** - * Expose self closing tags. - */ - -exports.selfClosing = require('./self-closing'); - -/** - * Default supported doctypes. - */ - -exports.doctypes = require('./doctypes'); - -/** - * Text filters. - */ - -exports.filters = require('./filters'); - -/** - * Utilities. - */ - -exports.utils = require('./utils'); - -/** - * Expose `Compiler`. - */ - -exports.Compiler = Compiler; - -/** - * Expose `Parser`. - */ - -exports.Parser = Parser; - -/** - * Expose `Lexer`. - */ - -exports.Lexer = Lexer; - -/** - * Nodes. - */ - -exports.nodes = require('./nodes'); - -/** - * Jade runtime helpers. - */ - -exports.runtime = runtime; - -/** - * Template function cache. - */ - -exports.cache = {}; - -/** - * Parse the given `str` of jade and return a function body. - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api private - */ - -function parse(str, options){ - try { - // Parse - var parser = new Parser(str, options.filename, options); - - // Compile - var compiler = new (options.compiler || Compiler)(parser.parse(), options) - , js = compiler.compile(); - - // Debug compiler - if (options.debug) { - console.error('\nCompiled Function:\n\n\033[90m%s\033[0m', js.replace(/^/gm, ' ')); - } - - return '' - + 'var buf = [];\n' - + (options.self - ? 'var self = locals || {};\n' + js - : 'with (locals || {}) {\n' + js + '\n}\n') - + 'return buf.join("");'; - } catch (err) { - parser = parser.context(); - runtime.rethrow(err, parser.filename, parser.lexer.lineno); - } -} - -/** - * Compile a `Function` representation of the given jade `str`. - * - * Options: - * - * - `compileDebug` when `false` debugging code is stripped from the compiled template - * - `client` when `true` the helper functions `escape()` etc will reference `jade.escape()` - * for use with the Jade client-side runtime.js - * - * @param {String} str - * @param {Options} options - * @return {Function} - * @api public - */ - -exports.compile = function(str, options){ - var options = options || {} - , client = options.client - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined' - , fn; - - if (options.compileDebug !== false) { - fn = [ - 'var __jade = [{ lineno: 1, filename: ' + filename + ' }];' - , 'try {' - , parse(String(str), options) - , '} catch (err) {' - , ' rethrow(err, __jade[0].filename, __jade[0].lineno);' - , '}' - ].join('\n'); - } else { - fn = parse(String(str), options); - } - - if (client) { - fn = 'attrs = attrs || jade.attrs; escape = escape || jade.escape; rethrow = rethrow || jade.rethrow; merge = merge || jade.merge;\n' + fn; - } - - fn = new Function('locals, attrs, escape, rethrow, merge', fn); - - if (client) return fn; - - return function(locals){ - return fn(locals, runtime.attrs, runtime.escape, runtime.rethrow, runtime.merge); - }; -}; - -/** - * Render the given `str` of jade and invoke - * the callback `fn(err, str)`. - * - * Options: - * - * - `cache` enable template caching - * - `filename` filename required for `include` / `extends` and caching - * - * @param {String} str - * @param {Object|Function} options or fn - * @param {Function} fn - * @api public - */ - -exports.render = function(str, options, fn){ - // swap args - if ('function' == typeof options) { - fn = options, options = {}; - } - - // cache requires .filename - if (options.cache && !options.filename) { - return fn(new Error('the "filename" option is required for caching')); - } - - try { - var path = options.filename; - var tmpl = options.cache - ? exports.cache[path] || (exports.cache[path] = exports.compile(str, options)) - : exports.compile(str, options); - fn(null, tmpl(options)); - } catch (err) { - fn(err); - } -}; - -/** - * Render a Jade file at the given `path` and callback `fn(err, str)`. - * - * @param {String} path - * @param {Object|Function} options or callback - * @param {Function} fn - * @api public - */ - -exports.renderFile = function(path, options, fn){ - var key = path + ':string'; - - if ('function' == typeof options) { - fn = options, options = {}; - } - - try { - options.filename = path; - var str = options.cache - ? exports.cache[key] || (exports.cache[key] = fs.readFileSync(path, 'utf8')) - : fs.readFileSync(path, 'utf8'); - exports.render(str, options, fn); - } catch (err) { - fn(err); - } -}; - -/** - * Express support. - */ - -exports.__express = exports.renderFile; diff --git a/node_modules/mocha/node_modules/jade/lib/lexer.js b/node_modules/mocha/node_modules/jade/lib/lexer.js deleted file mode 100644 index bca314a..0000000 --- a/node_modules/mocha/node_modules/jade/lib/lexer.js +++ /dev/null @@ -1,771 +0,0 @@ - -/*! - * Jade - Lexer - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Initialize `Lexer` with the given `str`. - * - * Options: - * - * - `colons` allow colons for attr delimiters - * - * @param {String} str - * @param {Object} options - * @api private - */ - -var Lexer = module.exports = function Lexer(str, options) { - options = options || {}; - this.input = str.replace(/\r\n|\r/g, '\n'); - this.colons = options.colons; - this.deferredTokens = []; - this.lastIndents = 0; - this.lineno = 1; - this.stash = []; - this.indentStack = []; - this.indentRe = null; - this.pipeless = false; -}; - -/** - * Lexer prototype. - */ - -Lexer.prototype = { - - /** - * Construct a token with the given `type` and `val`. - * - * @param {String} type - * @param {String} val - * @return {Object} - * @api private - */ - - tok: function(type, val){ - return { - type: type - , line: this.lineno - , val: val - } - }, - - /** - * Consume the given `len` of input. - * - * @param {Number} len - * @api private - */ - - consume: function(len){ - this.input = this.input.substr(len); - }, - - /** - * Scan for `type` with the given `regexp`. - * - * @param {String} type - * @param {RegExp} regexp - * @return {Object} - * @api private - */ - - scan: function(regexp, type){ - var captures; - if (captures = regexp.exec(this.input)) { - this.consume(captures[0].length); - return this.tok(type, captures[1]); - } - }, - - /** - * Defer the given `tok`. - * - * @param {Object} tok - * @api private - */ - - defer: function(tok){ - this.deferredTokens.push(tok); - }, - - /** - * Lookahead `n` tokens. - * - * @param {Number} n - * @return {Object} - * @api private - */ - - lookahead: function(n){ - var fetch = n - this.stash.length; - while (fetch-- > 0) this.stash.push(this.next()); - return this.stash[--n]; - }, - - /** - * Return the indexOf `start` / `end` delimiters. - * - * @param {String} start - * @param {String} end - * @return {Number} - * @api private - */ - - indexOfDelimiters: function(start, end){ - var str = this.input - , nstart = 0 - , nend = 0 - , pos = 0; - for (var i = 0, len = str.length; i < len; ++i) { - if (start == str.charAt(i)) { - ++nstart; - } else if (end == str.charAt(i)) { - if (++nend == nstart) { - pos = i; - break; - } - } - } - return pos; - }, - - /** - * Stashed token. - */ - - stashed: function() { - return this.stash.length - && this.stash.shift(); - }, - - /** - * Deferred token. - */ - - deferred: function() { - return this.deferredTokens.length - && this.deferredTokens.shift(); - }, - - /** - * end-of-source. - */ - - eos: function() { - if (this.input.length) return; - if (this.indentStack.length) { - this.indentStack.shift(); - return this.tok('outdent'); - } else { - return this.tok('eos'); - } - }, - - /** - * Blank line. - */ - - blank: function() { - var captures; - if (captures = /^\n *\n/.exec(this.input)) { - this.consume(captures[0].length - 1); - if (this.pipeless) return this.tok('text', ''); - return this.next(); - } - }, - - /** - * Comment. - */ - - comment: function() { - var captures; - if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('comment', captures[2]); - tok.buffer = '-' != captures[1]; - return tok; - } - }, - - /** - * Interpolated tag. - */ - - interpolation: function() { - var captures; - if (captures = /^#\{(.*?)\}/.exec(this.input)) { - this.consume(captures[0].length); - return this.tok('interpolation', captures[1]); - } - }, - - /** - * Tag. - */ - - tag: function() { - var captures; - if (captures = /^(\w[-:\w]*)(\/?)/.exec(this.input)) { - this.consume(captures[0].length); - var tok, name = captures[1]; - if (':' == name[name.length - 1]) { - name = name.slice(0, -1); - tok = this.tok('tag', name); - this.defer(this.tok(':')); - while (' ' == this.input[0]) this.input = this.input.substr(1); - } else { - tok = this.tok('tag', name); - } - tok.selfClosing = !! captures[2]; - return tok; - } - }, - - /** - * Filter. - */ - - filter: function() { - return this.scan(/^:(\w+)/, 'filter'); - }, - - /** - * Doctype. - */ - - doctype: function() { - return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype'); - }, - - /** - * Id. - */ - - id: function() { - return this.scan(/^#([\w-]+)/, 'id'); - }, - - /** - * Class. - */ - - className: function() { - return this.scan(/^\.([\w-]+)/, 'class'); - }, - - /** - * Text. - */ - - text: function() { - return this.scan(/^(?:\| ?| ?)?([^\n]+)/, 'text'); - }, - - /** - * Extends. - */ - - "extends": function() { - return this.scan(/^extends? +([^\n]+)/, 'extends'); - }, - - /** - * Block prepend. - */ - - prepend: function() { - var captures; - if (captures = /^prepend +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = 'prepend' - , name = captures[1] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Block append. - */ - - append: function() { - var captures; - if (captures = /^append +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = 'append' - , name = captures[1] - , tok = this.tok('block', name); - tok.mode = mode; - return tok; - } - }, - - /** - * Block. - */ - - block: function() { - var captures; - if (captures = /^block\b *(?:(prepend|append) +)?([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var mode = captures[1] || 'replace' - , name = captures[2] - , tok = this.tok('block', name); - - tok.mode = mode; - return tok; - } - }, - - /** - * Yield. - */ - - yield: function() { - return this.scan(/^yield */, 'yield'); - }, - - /** - * Include. - */ - - include: function() { - return this.scan(/^include +([^\n]+)/, 'include'); - }, - - /** - * Case. - */ - - "case": function() { - return this.scan(/^case +([^\n]+)/, 'case'); - }, - - /** - * When. - */ - - when: function() { - return this.scan(/^when +([^:\n]+)/, 'when'); - }, - - /** - * Default. - */ - - "default": function() { - return this.scan(/^default */, 'default'); - }, - - /** - * Assignment. - */ - - assignment: function() { - var captures; - if (captures = /^(\w+) += *([^;\n]+)( *;? *)/.exec(this.input)) { - this.consume(captures[0].length); - var name = captures[1] - , val = captures[2]; - return this.tok('code', 'var ' + name + ' = (' + val + ');'); - } - }, - - /** - * Call mixin. - */ - - call: function(){ - var captures; - if (captures = /^\+([-\w]+)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('call', captures[1]); - - // Check for args (not attributes) - if (captures = /^ *\((.*?)\)/.exec(this.input)) { - if (!/^ *[-\w]+ *=/.test(captures[1])) { - this.consume(captures[0].length); - tok.args = captures[1]; - } - } - - return tok; - } - }, - - /** - * Mixin. - */ - - mixin: function(){ - var captures; - if (captures = /^mixin +([-\w]+)(?: *\((.*)\))?/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('mixin', captures[1]); - tok.args = captures[2]; - return tok; - } - }, - - /** - * Conditional. - */ - - conditional: function() { - var captures; - if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) { - this.consume(captures[0].length); - var type = captures[1] - , js = captures[2]; - - switch (type) { - case 'if': js = 'if (' + js + ')'; break; - case 'unless': js = 'if (!(' + js + '))'; break; - case 'else if': js = 'else if (' + js + ')'; break; - case 'else': js = 'else'; break; - } - - return this.tok('code', js); - } - }, - - /** - * While. - */ - - "while": function() { - var captures; - if (captures = /^while +([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - return this.tok('code', 'while (' + captures[1] + ')'); - } - }, - - /** - * Each. - */ - - each: function() { - var captures; - if (captures = /^(?:- *)?(?:each|for) +(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var tok = this.tok('each', captures[1]); - tok.key = captures[2] || '$index'; - tok.code = captures[3]; - return tok; - } - }, - - /** - * Code. - */ - - code: function() { - var captures; - if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) { - this.consume(captures[0].length); - var flags = captures[1]; - captures[1] = captures[2]; - var tok = this.tok('code', captures[1]); - tok.escape = flags[0] === '='; - tok.buffer = flags[0] === '=' || flags[1] === '='; - return tok; - } - }, - - /** - * Attributes. - */ - - attrs: function() { - if ('(' == this.input.charAt(0)) { - var index = this.indexOfDelimiters('(', ')') - , str = this.input.substr(1, index-1) - , tok = this.tok('attrs') - , len = str.length - , colons = this.colons - , states = ['key'] - , escapedAttr - , key = '' - , val = '' - , quote - , c - , p; - - function state(){ - return states[states.length - 1]; - } - - function interpolate(attr) { - return attr.replace(/#\{([^}]+)\}/g, function(_, expr){ - return quote + " + (" + expr + ") + " + quote; - }); - } - - this.consume(index + 1); - tok.attrs = {}; - tok.escaped = {}; - - function parse(c) { - var real = c; - // TODO: remove when people fix ":" - if (colons && ':' == c) c = '='; - switch (c) { - case ',': - case '\n': - switch (state()) { - case 'expr': - case 'array': - case 'string': - case 'object': - val += c; - break; - default: - states.push('key'); - val = val.trim(); - key = key.trim(); - if ('' == key) return; - key = key.replace(/^['"]|['"]$/g, '').replace('!', ''); - tok.escaped[key] = escapedAttr; - tok.attrs[key] = '' == val - ? true - : interpolate(val); - key = val = ''; - } - break; - case '=': - switch (state()) { - case 'key char': - key += real; - break; - case 'val': - case 'expr': - case 'array': - case 'string': - case 'object': - val += real; - break; - default: - escapedAttr = '!' != p; - states.push('val'); - } - break; - case '(': - if ('val' == state() - || 'expr' == state()) states.push('expr'); - val += c; - break; - case ')': - if ('expr' == state() - || 'val' == state()) states.pop(); - val += c; - break; - case '{': - if ('val' == state()) states.push('object'); - val += c; - break; - case '}': - if ('object' == state()) states.pop(); - val += c; - break; - case '[': - if ('val' == state()) states.push('array'); - val += c; - break; - case ']': - if ('array' == state()) states.pop(); - val += c; - break; - case '"': - case "'": - switch (state()) { - case 'key': - states.push('key char'); - break; - case 'key char': - states.pop(); - break; - case 'string': - if (c == quote) states.pop(); - val += c; - break; - default: - states.push('string'); - val += c; - quote = c; - } - break; - case '': - break; - default: - switch (state()) { - case 'key': - case 'key char': - key += c; - break; - default: - val += c; - } - } - p = c; - } - - for (var i = 0; i < len; ++i) { - parse(str.charAt(i)); - } - - parse(','); - - if ('/' == this.input.charAt(0)) { - this.consume(1); - tok.selfClosing = true; - } - - return tok; - } - }, - - /** - * Indent | Outdent | Newline. - */ - - indent: function() { - var captures, re; - - // established regexp - if (this.indentRe) { - captures = this.indentRe.exec(this.input); - // determine regexp - } else { - // tabs - re = /^\n(\t*) */; - captures = re.exec(this.input); - - // spaces - if (captures && !captures[1].length) { - re = /^\n( *)/; - captures = re.exec(this.input); - } - - // established - if (captures && captures[1].length) this.indentRe = re; - } - - if (captures) { - var tok - , indents = captures[1].length; - - ++this.lineno; - this.consume(indents + 1); - - if (' ' == this.input[0] || '\t' == this.input[0]) { - throw new Error('Invalid indentation, you can use tabs or spaces but not both'); - } - - // blank line - if ('\n' == this.input[0]) return this.tok('newline'); - - // outdent - if (this.indentStack.length && indents < this.indentStack[0]) { - while (this.indentStack.length && this.indentStack[0] > indents) { - this.stash.push(this.tok('outdent')); - this.indentStack.shift(); - } - tok = this.stash.pop(); - // indent - } else if (indents && indents != this.indentStack[0]) { - this.indentStack.unshift(indents); - tok = this.tok('indent', indents); - // newline - } else { - tok = this.tok('newline'); - } - - return tok; - } - }, - - /** - * Pipe-less text consumed only when - * pipeless is true; - */ - - pipelessText: function() { - if (this.pipeless) { - if ('\n' == this.input[0]) return; - var i = this.input.indexOf('\n'); - if (-1 == i) i = this.input.length; - var str = this.input.substr(0, i); - this.consume(str.length); - return this.tok('text', str); - } - }, - - /** - * ':' - */ - - colon: function() { - return this.scan(/^: */, ':'); - }, - - /** - * Return the next token object, or those - * previously stashed by lookahead. - * - * @return {Object} - * @api private - */ - - advance: function(){ - return this.stashed() - || this.next(); - }, - - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ - - next: function() { - return this.deferred() - || this.blank() - || this.eos() - || this.pipelessText() - || this.yield() - || this.doctype() - || this.interpolation() - || this["case"]() - || this.when() - || this["default"]() - || this["extends"]() - || this.append() - || this.prepend() - || this.block() - || this.include() - || this.mixin() - || this.call() - || this.conditional() - || this.each() - || this["while"]() - || this.assignment() - || this.tag() - || this.filter() - || this.code() - || this.id() - || this.className() - || this.attrs() - || this.indent() - || this.comment() - || this.colon() - || this.text(); - } -}; diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/attrs.js b/node_modules/mocha/node_modules/jade/lib/nodes/attrs.js deleted file mode 100644 index 5de9b59..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/attrs.js +++ /dev/null @@ -1,77 +0,0 @@ - -/*! - * Jade - nodes - Attrs - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'), - Block = require('./block'); - -/** - * Initialize a `Attrs` node. - * - * @api public - */ - -var Attrs = module.exports = function Attrs() { - this.attrs = []; -}; - -/** - * Inherit from `Node`. - */ - -Attrs.prototype.__proto__ = Node.prototype; - -/** - * Set attribute `name` to `val`, keep in mind these become - * part of a raw js object literal, so to quote a value you must - * '"quote me"', otherwise or example 'user.name' is literal JavaScript. - * - * @param {String} name - * @param {String} val - * @param {Boolean} escaped - * @return {Tag} for chaining - * @api public - */ - -Attrs.prototype.setAttribute = function(name, val, escaped){ - this.attrs.push({ name: name, val: val, escaped: escaped }); - return this; -}; - -/** - * Remove attribute `name` when present. - * - * @param {String} name - * @api public - */ - -Attrs.prototype.removeAttribute = function(name){ - for (var i = 0, len = this.attrs.length; i < len; ++i) { - if (this.attrs[i] && this.attrs[i].name == name) { - delete this.attrs[i]; - } - } -}; - -/** - * Get attribute value by `name`. - * - * @param {String} name - * @return {String} - * @api public - */ - -Attrs.prototype.getAttribute = function(name){ - for (var i = 0, len = this.attrs.length; i < len; ++i) { - if (this.attrs[i] && this.attrs[i].name == name) { - return this.attrs[i].val; - } - } -}; diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/block-comment.js b/node_modules/mocha/node_modules/jade/lib/nodes/block-comment.js deleted file mode 100644 index 4f41e4a..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/block-comment.js +++ /dev/null @@ -1,33 +0,0 @@ - -/*! - * Jade - nodes - BlockComment - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `BlockComment` with the given `block`. - * - * @param {String} val - * @param {Block} block - * @param {Boolean} buffer - * @api public - */ - -var BlockComment = module.exports = function BlockComment(val, block, buffer) { - this.block = block; - this.val = val; - this.buffer = buffer; -}; - -/** - * Inherit from `Node`. - */ - -BlockComment.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/block.js b/node_modules/mocha/node_modules/jade/lib/nodes/block.js deleted file mode 100644 index bb00a1d..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/block.js +++ /dev/null @@ -1,121 +0,0 @@ - -/*! - * Jade - nodes - Block - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Block` with an optional `node`. - * - * @param {Node} node - * @api public - */ - -var Block = module.exports = function Block(node){ - this.nodes = []; - if (node) this.push(node); -}; - -/** - * Inherit from `Node`. - */ - -Block.prototype.__proto__ = Node.prototype; - -/** - * Block flag. - */ - -Block.prototype.isBlock = true; - -/** - * Replace the nodes in `other` with the nodes - * in `this` block. - * - * @param {Block} other - * @api private - */ - -Block.prototype.replace = function(other){ - other.nodes = this.nodes; -}; - -/** - * Pust the given `node`. - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Block.prototype.push = function(node){ - return this.nodes.push(node); -}; - -/** - * Check if this block is empty. - * - * @return {Boolean} - * @api public - */ - -Block.prototype.isEmpty = function(){ - return 0 == this.nodes.length; -}; - -/** - * Unshift the given `node`. - * - * @param {Node} node - * @return {Number} - * @api public - */ - -Block.prototype.unshift = function(node){ - return this.nodes.unshift(node); -}; - -/** - * Return the "last" block, or the first `yield` node. - * - * @return {Block} - * @api private - */ - -Block.prototype.includeBlock = function(){ - var ret = this - , node; - - for (var i = 0, len = this.nodes.length; i < len; ++i) { - node = this.nodes[i]; - if (node.yield) return node; - else if (node.textOnly) continue; - else if (node.includeBlock) ret = node.includeBlock(); - else if (node.block && !node.block.isEmpty()) ret = node.block.includeBlock(); - } - - return ret; -}; - -/** - * Return a clone of this block. - * - * @return {Block} - * @api private - */ - -Block.prototype.clone = function(){ - var clone = new Block; - for (var i = 0, len = this.nodes.length; i < len; ++i) { - clone.push(this.nodes[i].clone()); - } - return clone; -}; - diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/case.js b/node_modules/mocha/node_modules/jade/lib/nodes/case.js deleted file mode 100644 index 08ff033..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/case.js +++ /dev/null @@ -1,43 +0,0 @@ - -/*! - * Jade - nodes - Case - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a new `Case` with `expr`. - * - * @param {String} expr - * @api public - */ - -var Case = exports = module.exports = function Case(expr, block){ - this.expr = expr; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Case.prototype.__proto__ = Node.prototype; - -var When = exports.When = function When(expr, block){ - this.expr = expr; - this.block = block; - this.debug = false; -}; - -/** - * Inherit from `Node`. - */ - -When.prototype.__proto__ = Node.prototype; - diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/code.js b/node_modules/mocha/node_modules/jade/lib/nodes/code.js deleted file mode 100644 index babc675..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/code.js +++ /dev/null @@ -1,35 +0,0 @@ - -/*! - * Jade - nodes - Code - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Code` node with the given code `val`. - * Code may also be optionally buffered and escaped. - * - * @param {String} val - * @param {Boolean} buffer - * @param {Boolean} escape - * @api public - */ - -var Code = module.exports = function Code(val, buffer, escape) { - this.val = val; - this.buffer = buffer; - this.escape = escape; - if (val.match(/^ *else/)) this.debug = false; -}; - -/** - * Inherit from `Node`. - */ - -Code.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/comment.js b/node_modules/mocha/node_modules/jade/lib/nodes/comment.js deleted file mode 100644 index 2e1469e..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/comment.js +++ /dev/null @@ -1,32 +0,0 @@ - -/*! - * Jade - nodes - Comment - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Comment` with the given `val`, optionally `buffer`, - * otherwise the comment may render in the output. - * - * @param {String} val - * @param {Boolean} buffer - * @api public - */ - -var Comment = module.exports = function Comment(val, buffer) { - this.val = val; - this.buffer = buffer; -}; - -/** - * Inherit from `Node`. - */ - -Comment.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/doctype.js b/node_modules/mocha/node_modules/jade/lib/nodes/doctype.js deleted file mode 100644 index b8f33e5..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/doctype.js +++ /dev/null @@ -1,29 +0,0 @@ - -/*! - * Jade - nodes - Doctype - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Doctype` with the given `val`. - * - * @param {String} val - * @api public - */ - -var Doctype = module.exports = function Doctype(val) { - this.val = val; -}; - -/** - * Inherit from `Node`. - */ - -Doctype.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/each.js b/node_modules/mocha/node_modules/jade/lib/nodes/each.js deleted file mode 100644 index f54101f..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/each.js +++ /dev/null @@ -1,35 +0,0 @@ - -/*! - * Jade - nodes - Each - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize an `Each` node, representing iteration - * - * @param {String} obj - * @param {String} val - * @param {String} key - * @param {Block} block - * @api public - */ - -var Each = module.exports = function Each(obj, val, key, block) { - this.obj = obj; - this.val = val; - this.key = key; - this.block = block; -}; - -/** - * Inherit from `Node`. - */ - -Each.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/filter.js b/node_modules/mocha/node_modules/jade/lib/nodes/filter.js deleted file mode 100644 index 851a004..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/filter.js +++ /dev/null @@ -1,35 +0,0 @@ - -/*! - * Jade - nodes - Filter - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node') - , Block = require('./block'); - -/** - * Initialize a `Filter` node with the given - * filter `name` and `block`. - * - * @param {String} name - * @param {Block|Node} block - * @api public - */ - -var Filter = module.exports = function Filter(name, block, attrs) { - this.name = name; - this.block = block; - this.attrs = attrs; - this.isASTFilter = !block.nodes.every(function(node){ return node.isText }); -}; - -/** - * Inherit from `Node`. - */ - -Filter.prototype.__proto__ = Node.prototype; \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/index.js b/node_modules/mocha/node_modules/jade/lib/nodes/index.js deleted file mode 100644 index 386ad2f..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/index.js +++ /dev/null @@ -1,20 +0,0 @@ - -/*! - * Jade - nodes - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -exports.Node = require('./node'); -exports.Tag = require('./tag'); -exports.Code = require('./code'); -exports.Each = require('./each'); -exports.Case = require('./case'); -exports.Text = require('./text'); -exports.Block = require('./block'); -exports.Mixin = require('./mixin'); -exports.Filter = require('./filter'); -exports.Comment = require('./comment'); -exports.Literal = require('./literal'); -exports.BlockComment = require('./block-comment'); -exports.Doctype = require('./doctype'); diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/literal.js b/node_modules/mocha/node_modules/jade/lib/nodes/literal.js deleted file mode 100644 index fde586b..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/literal.js +++ /dev/null @@ -1,32 +0,0 @@ - -/*! - * Jade - nodes - Literal - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Literal` node with the given `str. - * - * @param {String} str - * @api public - */ - -var Literal = module.exports = function Literal(str) { - this.str = str - .replace(/\\/g, "\\\\") - .replace(/\n|\r\n/g, "\\n") - .replace(/'/g, "\\'"); -}; - -/** - * Inherit from `Node`. - */ - -Literal.prototype.__proto__ = Node.prototype; diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/mixin.js b/node_modules/mocha/node_modules/jade/lib/nodes/mixin.js deleted file mode 100644 index 8407bc7..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/mixin.js +++ /dev/null @@ -1,36 +0,0 @@ - -/*! - * Jade - nodes - Mixin - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Attrs = require('./attrs'); - -/** - * Initialize a new `Mixin` with `name` and `block`. - * - * @param {String} name - * @param {String} args - * @param {Block} block - * @api public - */ - -var Mixin = module.exports = function Mixin(name, args, block, call){ - this.name = name; - this.args = args; - this.block = block; - this.attrs = []; - this.call = call; -}; - -/** - * Inherit from `Attrs`. - */ - -Mixin.prototype.__proto__ = Attrs.prototype; - diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/node.js b/node_modules/mocha/node_modules/jade/lib/nodes/node.js deleted file mode 100644 index e98f042..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/node.js +++ /dev/null @@ -1,25 +0,0 @@ - -/*! - * Jade - nodes - Node - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Initialize a `Node`. - * - * @api public - */ - -var Node = module.exports = function Node(){}; - -/** - * Clone this node (return itself) - * - * @return {Node} - * @api private - */ - -Node.prototype.clone = function(){ - return this; -}; diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/tag.js b/node_modules/mocha/node_modules/jade/lib/nodes/tag.js deleted file mode 100644 index 4b6728a..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/tag.js +++ /dev/null @@ -1,95 +0,0 @@ - -/*! - * Jade - nodes - Tag - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Attrs = require('./attrs'), - Block = require('./block'), - inlineTags = require('../inline-tags'); - -/** - * Initialize a `Tag` node with the given tag `name` and optional `block`. - * - * @param {String} name - * @param {Block} block - * @api public - */ - -var Tag = module.exports = function Tag(name, block) { - this.name = name; - this.attrs = []; - this.block = block || new Block; -}; - -/** - * Inherit from `Attrs`. - */ - -Tag.prototype.__proto__ = Attrs.prototype; - -/** - * Clone this tag. - * - * @return {Tag} - * @api private - */ - -Tag.prototype.clone = function(){ - var clone = new Tag(this.name, this.block.clone()); - clone.line = this.line; - clone.attrs = this.attrs; - clone.textOnly = this.textOnly; - return clone; -}; - -/** - * Check if this tag is an inline tag. - * - * @return {Boolean} - * @api private - */ - -Tag.prototype.isInline = function(){ - return ~inlineTags.indexOf(this.name); -}; - -/** - * Check if this tag's contents can be inlined. Used for pretty printing. - * - * @return {Boolean} - * @api private - */ - -Tag.prototype.canInline = function(){ - var nodes = this.block.nodes; - - function isInline(node){ - // Recurse if the node is a block - if (node.isBlock) return node.nodes.every(isInline); - return node.isText || (node.isInline && node.isInline()); - } - - // Empty tag - if (!nodes.length) return true; - - // Text-only or inline-only tag - if (1 == nodes.length) return isInline(nodes[0]); - - // Multi-line inline-only tag - if (this.block.nodes.every(isInline)) { - for (var i = 1, len = nodes.length; i < len; ++i) { - if (nodes[i-1].isText && nodes[i].isText) - return false; - } - return true; - } - - // Mixed tag - return false; -}; \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/nodes/text.js b/node_modules/mocha/node_modules/jade/lib/nodes/text.js deleted file mode 100644 index 3b5dd55..0000000 --- a/node_modules/mocha/node_modules/jade/lib/nodes/text.js +++ /dev/null @@ -1,36 +0,0 @@ - -/*! - * Jade - nodes - Text - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Node = require('./node'); - -/** - * Initialize a `Text` node with optional `line`. - * - * @param {String} line - * @api public - */ - -var Text = module.exports = function Text(line) { - this.val = ''; - if ('string' == typeof line) this.val = line; -}; - -/** - * Inherit from `Node`. - */ - -Text.prototype.__proto__ = Node.prototype; - -/** - * Flag as text. - */ - -Text.prototype.isText = true; \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/parser.js b/node_modules/mocha/node_modules/jade/lib/parser.js deleted file mode 100644 index 92f2af0..0000000 --- a/node_modules/mocha/node_modules/jade/lib/parser.js +++ /dev/null @@ -1,710 +0,0 @@ - -/*! - * Jade - Parser - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var Lexer = require('./lexer') - , nodes = require('./nodes'); - -/** - * Initialize `Parser` with the given input `str` and `filename`. - * - * @param {String} str - * @param {String} filename - * @param {Object} options - * @api public - */ - -var Parser = exports = module.exports = function Parser(str, filename, options){ - this.input = str; - this.lexer = new Lexer(str, options); - this.filename = filename; - this.blocks = {}; - this.mixins = {}; - this.options = options; - this.contexts = [this]; -}; - -/** - * Tags that may not contain tags. - */ - -var textOnly = exports.textOnly = ['script', 'style']; - -/** - * Parser prototype. - */ - -Parser.prototype = { - - /** - * Push `parser` onto the context stack, - * or pop and return a `Parser`. - */ - - context: function(parser){ - if (parser) { - this.contexts.push(parser); - } else { - return this.contexts.pop(); - } - }, - - /** - * Return the next token object. - * - * @return {Object} - * @api private - */ - - advance: function(){ - return this.lexer.advance(); - }, - - /** - * Skip `n` tokens. - * - * @param {Number} n - * @api private - */ - - skip: function(n){ - while (n--) this.advance(); - }, - - /** - * Single token lookahead. - * - * @return {Object} - * @api private - */ - - peek: function() { - return this.lookahead(1); - }, - - /** - * Return lexer lineno. - * - * @return {Number} - * @api private - */ - - line: function() { - return this.lexer.lineno; - }, - - /** - * `n` token lookahead. - * - * @param {Number} n - * @return {Object} - * @api private - */ - - lookahead: function(n){ - return this.lexer.lookahead(n); - }, - - /** - * Parse input returning a string of js for evaluation. - * - * @return {String} - * @api public - */ - - parse: function(){ - var block = new nodes.Block, parser; - block.line = this.line(); - - while ('eos' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else { - block.push(this.parseExpr()); - } - } - - if (parser = this.extending) { - this.context(parser); - var ast = parser.parse(); - this.context(); - // hoist mixins - for (var name in this.mixins) - ast.unshift(this.mixins[name]); - return ast; - } - - return block; - }, - - /** - * Expect the given type, or throw an exception. - * - * @param {String} type - * @api private - */ - - expect: function(type){ - if (this.peek().type === type) { - return this.advance(); - } else { - throw new Error('expected "' + type + '", but got "' + this.peek().type + '"'); - } - }, - - /** - * Accept the given `type`. - * - * @param {String} type - * @api private - */ - - accept: function(type){ - if (this.peek().type === type) { - return this.advance(); - } - }, - - /** - * tag - * | doctype - * | mixin - * | include - * | filter - * | comment - * | text - * | each - * | code - * | yield - * | id - * | class - * | interpolation - */ - - parseExpr: function(){ - switch (this.peek().type) { - case 'tag': - return this.parseTag(); - case 'mixin': - return this.parseMixin(); - case 'block': - return this.parseBlock(); - case 'case': - return this.parseCase(); - case 'when': - return this.parseWhen(); - case 'default': - return this.parseDefault(); - case 'extends': - return this.parseExtends(); - case 'include': - return this.parseInclude(); - case 'doctype': - return this.parseDoctype(); - case 'filter': - return this.parseFilter(); - case 'comment': - return this.parseComment(); - case 'text': - return this.parseText(); - case 'each': - return this.parseEach(); - case 'code': - return this.parseCode(); - case 'call': - return this.parseCall(); - case 'interpolation': - return this.parseInterpolation(); - case 'yield': - this.advance(); - var block = new nodes.Block; - block.yield = true; - return block; - case 'id': - case 'class': - var tok = this.advance(); - this.lexer.defer(this.lexer.tok('tag', 'div')); - this.lexer.defer(tok); - return this.parseExpr(); - default: - throw new Error('unexpected token "' + this.peek().type + '"'); - } - }, - - /** - * Text - */ - - parseText: function(){ - var tok = this.expect('text') - , node = new nodes.Text(tok.val); - node.line = this.line(); - return node; - }, - - /** - * ':' expr - * | block - */ - - parseBlockExpansion: function(){ - if (':' == this.peek().type) { - this.advance(); - return new nodes.Block(this.parseExpr()); - } else { - return this.block(); - } - }, - - /** - * case - */ - - parseCase: function(){ - var val = this.expect('case').val - , node = new nodes.Case(val); - node.line = this.line(); - node.block = this.block(); - return node; - }, - - /** - * when - */ - - parseWhen: function(){ - var val = this.expect('when').val - return new nodes.Case.When(val, this.parseBlockExpansion()); - }, - - /** - * default - */ - - parseDefault: function(){ - this.expect('default'); - return new nodes.Case.When('default', this.parseBlockExpansion()); - }, - - /** - * code - */ - - parseCode: function(){ - var tok = this.expect('code') - , node = new nodes.Code(tok.val, tok.buffer, tok.escape) - , block - , i = 1; - node.line = this.line(); - while (this.lookahead(i) && 'newline' == this.lookahead(i).type) ++i; - block = 'indent' == this.lookahead(i).type; - if (block) { - this.skip(i-1); - node.block = this.block(); - } - return node; - }, - - /** - * comment - */ - - parseComment: function(){ - var tok = this.expect('comment') - , node; - - if ('indent' == this.peek().type) { - node = new nodes.BlockComment(tok.val, this.block(), tok.buffer); - } else { - node = new nodes.Comment(tok.val, tok.buffer); - } - - node.line = this.line(); - return node; - }, - - /** - * doctype - */ - - parseDoctype: function(){ - var tok = this.expect('doctype') - , node = new nodes.Doctype(tok.val); - node.line = this.line(); - return node; - }, - - /** - * filter attrs? text-block - */ - - parseFilter: function(){ - var block - , tok = this.expect('filter') - , attrs = this.accept('attrs'); - - this.lexer.pipeless = true; - block = this.parseTextBlock(); - this.lexer.pipeless = false; - - var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); - node.line = this.line(); - return node; - }, - - /** - * tag ':' attrs? block - */ - - parseASTFilter: function(){ - var block - , tok = this.expect('tag') - , attrs = this.accept('attrs'); - - this.expect(':'); - block = this.block(); - - var node = new nodes.Filter(tok.val, block, attrs && attrs.attrs); - node.line = this.line(); - return node; - }, - - /** - * each block - */ - - parseEach: function(){ - var tok = this.expect('each') - , node = new nodes.Each(tok.code, tok.val, tok.key); - node.line = this.line(); - node.block = this.block(); - return node; - }, - - /** - * 'extends' name - */ - - parseExtends: function(){ - var path = require('path') - , fs = require('fs') - , dirname = path.dirname - , basename = path.basename - , join = path.join; - - if (!this.filename) - throw new Error('the "filename" option is required to extend templates'); - - var path = this.expect('extends').val.trim() - , dir = dirname(this.filename); - - var path = join(dir, path + '.jade') - , str = fs.readFileSync(path, 'utf8') - , parser = new Parser(str, path, this.options); - - parser.blocks = this.blocks; - parser.contexts = this.contexts; - this.extending = parser; - - // TODO: null node - return new nodes.Literal(''); - }, - - /** - * 'block' name block - */ - - parseBlock: function(){ - var block = this.expect('block') - , mode = block.mode - , name = block.val.trim(); - - block = 'indent' == this.peek().type - ? this.block() - : new nodes.Block(new nodes.Literal('')); - - var prev = this.blocks[name]; - - if (prev) { - switch (prev.mode) { - case 'append': - block.nodes = block.nodes.concat(prev.nodes); - prev = block; - break; - case 'prepend': - block.nodes = prev.nodes.concat(block.nodes); - prev = block; - break; - } - } - - block.mode = mode; - return this.blocks[name] = prev || block; - }, - - /** - * include block? - */ - - parseInclude: function(){ - var path = require('path') - , fs = require('fs') - , dirname = path.dirname - , basename = path.basename - , join = path.join; - - var path = this.expect('include').val.trim() - , dir = dirname(this.filename); - - if (!this.filename) - throw new Error('the "filename" option is required to use includes'); - - // no extension - if (!~basename(path).indexOf('.')) { - path += '.jade'; - } - - // non-jade - if ('.jade' != path.substr(-5)) { - var path = join(dir, path) - , str = fs.readFileSync(path, 'utf8'); - return new nodes.Literal(str); - } - - var path = join(dir, path) - , str = fs.readFileSync(path, 'utf8') - , parser = new Parser(str, path, this.options); - parser.blocks = this.blocks; - parser.mixins = this.mixins; - - this.context(parser); - var ast = parser.parse(); - this.context(); - ast.filename = path; - - if ('indent' == this.peek().type) { - ast.includeBlock().push(this.block()); - } - - return ast; - }, - - /** - * call ident block - */ - - parseCall: function(){ - var tok = this.expect('call') - , name = tok.val - , args = tok.args - , mixin = new nodes.Mixin(name, args, new nodes.Block, true); - - this.tag(mixin); - if (mixin.block.isEmpty()) mixin.block = null; - return mixin; - }, - - /** - * mixin block - */ - - parseMixin: function(){ - var tok = this.expect('mixin') - , name = tok.val - , args = tok.args - , mixin; - - // definition - if ('indent' == this.peek().type) { - mixin = new nodes.Mixin(name, args, this.block(), false); - this.mixins[name] = mixin; - return mixin; - // call - } else { - return new nodes.Mixin(name, args, null, true); - } - }, - - /** - * indent (text | newline)* outdent - */ - - parseTextBlock: function(){ - var block = new nodes.Block; - block.line = this.line(); - var spaces = this.expect('indent').val; - if (null == this._spaces) this._spaces = spaces; - var indent = Array(spaces - this._spaces + 1).join(' '); - while ('outdent' != this.peek().type) { - switch (this.peek().type) { - case 'newline': - this.advance(); - break; - case 'indent': - this.parseTextBlock().nodes.forEach(function(node){ - block.push(node); - }); - break; - default: - var text = new nodes.Text(indent + this.advance().val); - text.line = this.line(); - block.push(text); - } - } - - if (spaces == this._spaces) this._spaces = null; - this.expect('outdent'); - return block; - }, - - /** - * indent expr* outdent - */ - - block: function(){ - var block = new nodes.Block; - block.line = this.line(); - this.expect('indent'); - while ('outdent' != this.peek().type) { - if ('newline' == this.peek().type) { - this.advance(); - } else { - block.push(this.parseExpr()); - } - } - this.expect('outdent'); - return block; - }, - - /** - * interpolation (attrs | class | id)* (text | code | ':')? newline* block? - */ - - parseInterpolation: function(){ - var tok = this.advance(); - var tag = new nodes.Tag(tok.val); - tag.buffer = true; - return this.tag(tag); - }, - - /** - * tag (attrs | class | id)* (text | code | ':')? newline* block? - */ - - parseTag: function(){ - // ast-filter look-ahead - var i = 2; - if ('attrs' == this.lookahead(i).type) ++i; - if (':' == this.lookahead(i).type) { - if ('indent' == this.lookahead(++i).type) { - return this.parseASTFilter(); - } - } - - var tok = this.advance() - , tag = new nodes.Tag(tok.val); - - tag.selfClosing = tok.selfClosing; - - return this.tag(tag); - }, - - /** - * Parse tag. - */ - - tag: function(tag){ - var dot; - - tag.line = this.line(); - - // (attrs | class | id)* - out: - while (true) { - switch (this.peek().type) { - case 'id': - case 'class': - var tok = this.advance(); - tag.setAttribute(tok.type, "'" + tok.val + "'"); - continue; - case 'attrs': - var tok = this.advance() - , obj = tok.attrs - , escaped = tok.escaped - , names = Object.keys(obj); - - if (tok.selfClosing) tag.selfClosing = true; - - for (var i = 0, len = names.length; i < len; ++i) { - var name = names[i] - , val = obj[name]; - tag.setAttribute(name, val, escaped[name]); - } - continue; - default: - break out; - } - } - - // check immediate '.' - if ('.' == this.peek().val) { - dot = tag.textOnly = true; - this.advance(); - } - - // (text | code | ':')? - switch (this.peek().type) { - case 'text': - tag.block.push(this.parseText()); - break; - case 'code': - tag.code = this.parseCode(); - break; - case ':': - this.advance(); - tag.block = new nodes.Block; - tag.block.push(this.parseExpr()); - break; - } - - // newline* - while ('newline' == this.peek().type) this.advance(); - - tag.textOnly = tag.textOnly || ~textOnly.indexOf(tag.name); - - // script special-case - if ('script' == tag.name) { - var type = tag.getAttribute('type'); - if (!dot && type && 'text/javascript' != type.replace(/^['"]|['"]$/g, '')) { - tag.textOnly = false; - } - } - - // block? - if ('indent' == this.peek().type) { - if (tag.textOnly) { - this.lexer.pipeless = true; - tag.block = this.parseTextBlock(); - this.lexer.pipeless = false; - } else { - var block = this.block(); - if (tag.block) { - for (var i = 0, len = block.nodes.length; i < len; ++i) { - tag.block.push(block.nodes[i]); - } - } else { - tag.block = block; - } - } - } - - return tag; - } -}; diff --git a/node_modules/mocha/node_modules/jade/lib/runtime.js b/node_modules/mocha/node_modules/jade/lib/runtime.js deleted file mode 100644 index fb711f5..0000000 --- a/node_modules/mocha/node_modules/jade/lib/runtime.js +++ /dev/null @@ -1,174 +0,0 @@ - -/*! - * Jade - runtime - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Lame Array.isArray() polyfill for now. - */ - -if (!Array.isArray) { - Array.isArray = function(arr){ - return '[object Array]' == Object.prototype.toString.call(arr); - }; -} - -/** - * Lame Object.keys() polyfill for now. - */ - -if (!Object.keys) { - Object.keys = function(obj){ - var arr = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - arr.push(key); - } - } - return arr; - } -} - -/** - * Merge two attribute objects giving precedence - * to values in object `b`. Classes are special-cased - * allowing for arrays and merging/joining appropriately - * resulting in a string. - * - * @param {Object} a - * @param {Object} b - * @return {Object} a - * @api private - */ - -exports.merge = function merge(a, b) { - var ac = a['class']; - var bc = b['class']; - - if (ac || bc) { - ac = ac || []; - bc = bc || []; - if (!Array.isArray(ac)) ac = [ac]; - if (!Array.isArray(bc)) bc = [bc]; - ac = ac.filter(nulls); - bc = bc.filter(nulls); - a['class'] = ac.concat(bc).join(' '); - } - - for (var key in b) { - if (key != 'class') { - a[key] = b[key]; - } - } - - return a; -}; - -/** - * Filter null `val`s. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function nulls(val) { - return val != null; -} - -/** - * Render the given attributes object. - * - * @param {Object} obj - * @param {Object} escaped - * @return {String} - * @api private - */ - -exports.attrs = function attrs(obj, escaped){ - var buf = [] - , terse = obj.terse; - - delete obj.terse; - var keys = Object.keys(obj) - , len = keys.length; - - if (len) { - buf.push(''); - for (var i = 0; i < len; ++i) { - var key = keys[i] - , val = obj[key]; - - if ('boolean' == typeof val || null == val) { - if (val) { - terse - ? buf.push(key) - : buf.push(key + '="' + key + '"'); - } - } else if (0 == key.indexOf('data') && 'string' != typeof val) { - buf.push(key + "='" + JSON.stringify(val) + "'"); - } else if ('class' == key && Array.isArray(val)) { - buf.push(key + '="' + exports.escape(val.join(' ')) + '"'); - } else if (escaped && escaped[key]) { - buf.push(key + '="' + exports.escape(val) + '"'); - } else { - buf.push(key + '="' + val + '"'); - } - } - } - - return buf.join(' '); -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function escape(html){ - return String(html) - .replace(/&(?!(\w+|\#\d+);)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -/** - * Re-throw the given `err` in context to the - * the jade in `filename` at the given `lineno`. - * - * @param {Error} err - * @param {String} filename - * @param {String} lineno - * @api private - */ - -exports.rethrow = function rethrow(err, filename, lineno){ - if (!filename) throw err; - - var context = 3 - , str = require('fs').readFileSync(filename, 'utf8') - , lines = str.split('\n') - , start = Math.max(lineno - context, 0) - , end = Math.min(lines.length, lineno + context); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' > ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'Jade') + ':' + lineno - + '\n' + context + '\n\n' + err.message; - throw err; -}; diff --git a/node_modules/mocha/node_modules/jade/lib/self-closing.js b/node_modules/mocha/node_modules/jade/lib/self-closing.js deleted file mode 100644 index 0548771..0000000 --- a/node_modules/mocha/node_modules/jade/lib/self-closing.js +++ /dev/null @@ -1,19 +0,0 @@ - -/*! - * Jade - self closing tags - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = [ - 'meta' - , 'img' - , 'link' - , 'input' - , 'source' - , 'area' - , 'base' - , 'col' - , 'br' - , 'hr' -]; \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/lib/utils.js b/node_modules/mocha/node_modules/jade/lib/utils.js deleted file mode 100644 index ff46d02..0000000 --- a/node_modules/mocha/node_modules/jade/lib/utils.js +++ /dev/null @@ -1,49 +0,0 @@ - -/*! - * Jade - utils - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Convert interpolation in the given string to JavaScript. - * - * @param {String} str - * @return {String} - * @api private - */ - -var interpolate = exports.interpolate = function(str){ - return str.replace(/(\\)?([#!]){(.*?)}/g, function(str, escape, flag, code){ - return escape - ? str - : "' + " - + ('!' == flag ? '' : 'escape') - + "((interp = " + code.replace(/\\'/g, "'") - + ") == null ? '' : interp) + '"; - }); -}; - -/** - * Escape single quotes in `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -var escape = exports.escape = function(str) { - return str.replace(/'/g, "\\'"); -}; - -/** - * Interpolate, and escape the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.text = function(str){ - return interpolate(escape(str)); -}; \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/node_modules/commander/.npmignore b/node_modules/mocha/node_modules/jade/node_modules/commander/.npmignore deleted file mode 100644 index f1250e5..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/commander/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -support -test -examples -*.sock diff --git a/node_modules/mocha/node_modules/jade/node_modules/commander/.travis.yml b/node_modules/mocha/node_modules/jade/node_modules/commander/.travis.yml deleted file mode 100644 index f1d0f13..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/commander/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node_modules/mocha/node_modules/jade/node_modules/commander/History.md b/node_modules/mocha/node_modules/jade/node_modules/commander/History.md deleted file mode 100644 index 4961d2e..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/commander/History.md +++ /dev/null @@ -1,107 +0,0 @@ - -0.6.1 / 2012-06-01 -================== - - * Added: append (yes or no) on confirmation - * Added: allow node.js v0.7.x - -0.6.0 / 2012-04-10 -================== - - * Added `.prompt(obj, callback)` support. Closes #49 - * Added default support to .choose(). Closes #41 - * Fixed the choice example - -0.5.1 / 2011-12-20 -================== - - * Fixed `password()` for recent nodes. Closes #36 - -0.5.0 / 2011-12-04 -================== - - * Added sub-command option support [itay] - -0.4.3 / 2011-12-04 -================== - - * Fixed custom help ordering. Closes #32 - -0.4.2 / 2011-11-24 -================== - - * Added travis support - * Fixed: line-buffered input automatically trimmed. Closes #31 - -0.4.1 / 2011-11-18 -================== - - * Removed listening for "close" on --help - -0.4.0 / 2011-11-15 -================== - - * Added support for `--`. Closes #24 - -0.3.3 / 2011-11-14 -================== - - * Fixed: wait for close event when writing help info [Jerry Hamlet] - -0.3.2 / 2011-11-01 -================== - - * Fixed long flag definitions with values [felixge] - -0.3.1 / 2011-10-31 -================== - - * Changed `--version` short flag to `-V` from `-v` - * Changed `.version()` so it's configurable [felixge] - -0.3.0 / 2011-10-31 -================== - - * Added support for long flags only. Closes #18 - -0.2.1 / 2011-10-24 -================== - - * "node": ">= 0.4.x < 0.7.0". Closes #20 - -0.2.0 / 2011-09-26 -================== - - * Allow for defaults that are not just boolean. Default peassignment only occurs for --no-*, optional, and required arguments. [Jim Isaacs] - -0.1.0 / 2011-08-24 -================== - - * Added support for custom `--help` output - -0.0.5 / 2011-08-18 -================== - - * Changed: when the user enters nothing prompt for password again - * Fixed issue with passwords beginning with numbers [NuckChorris] - -0.0.4 / 2011-08-15 -================== - - * Fixed `Commander#args` - -0.0.3 / 2011-08-15 -================== - - * Added default option value support - -0.0.2 / 2011-08-15 -================== - - * Added mask support to `Command#password(str[, mask], fn)` - * Added `Command#password(str, fn)` - -0.0.1 / 2010-01-03 -================== - - * Initial release diff --git a/node_modules/mocha/node_modules/jade/node_modules/commander/Makefile b/node_modules/mocha/node_modules/jade/node_modules/commander/Makefile deleted file mode 100644 index 0074625..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/commander/Makefile +++ /dev/null @@ -1,7 +0,0 @@ - -TESTS = $(shell find test/test.*.js) - -test: - @./test/run $(TESTS) - -.PHONY: test \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/node_modules/commander/Readme.md b/node_modules/mocha/node_modules/jade/node_modules/commander/Readme.md deleted file mode 100644 index b8328c3..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/commander/Readme.md +++ /dev/null @@ -1,262 +0,0 @@ -# Commander.js - - The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander). - - [![Build Status](https://secure.travis-ci.org/visionmedia/commander.js.png)](http://travis-ci.org/visionmedia/commander.js) - -## Installation - - $ npm install commander - -## Option parsing - - Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('commander'); - -program - .version('0.0.1') - .option('-p, --peppers', 'Add peppers') - .option('-P, --pineapple', 'Add pineapple') - .option('-b, --bbq', 'Add bbq sauce') - .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble') - .parse(process.argv); - -console.log('you ordered a pizza with:'); -if (program.peppers) console.log(' - peppers'); -if (program.pineapple) console.log(' - pineappe'); -if (program.bbq) console.log(' - bbq'); -console.log(' - %s cheese', program.cheese); -``` - - Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. - -## Automated --help - - The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free: - -``` - $ ./examples/pizza --help - - Usage: pizza [options] - - Options: - - -V, --version output the version number - -p, --peppers Add peppers - -P, --pineapple Add pineappe - -b, --bbq Add bbq sauce - -c, --cheese Add the specified type of cheese [marble] - -h, --help output usage information - -``` - -## Coercion - -```js -function range(val) { - return val.split('..').map(Number); -} - -function list(val) { - return val.split(','); -} - -program - .version('0.0.1') - .usage('[options] ') - .option('-i, --integer ', 'An integer argument', parseInt) - .option('-f, --float ', 'A float argument', parseFloat) - .option('-r, --range ..', 'A range', range) - .option('-l, --list ', 'A list', list) - .option('-o, --optional [value]', 'An optional value') - .parse(process.argv); - -console.log(' int: %j', program.integer); -console.log(' float: %j', program.float); -console.log(' optional: %j', program.optional); -program.range = program.range || []; -console.log(' range: %j..%j', program.range[0], program.range[1]); -console.log(' list: %j', program.list); -console.log(' args: %j', program.args); -``` - -## Custom help - - You can display arbitrary `-h, --help` information - by listening for "--help". Commander will automatically - exit once you are done so that the remainder of your program - does not execute causing undesired behaviours, for example - in the following executable "stuff" will not output when - `--help` is used. - -```js -#!/usr/bin/env node - -/** - * Module dependencies. - */ - -var program = require('../'); - -function list(val) { - return val.split(',').map(Number); -} - -program - .version('0.0.1') - .option('-f, --foo', 'enable some foo') - .option('-b, --bar', 'enable some bar') - .option('-B, --baz', 'enable some baz'); - -// must be before .parse() since -// node's emit() is immediate - -program.on('--help', function(){ - console.log(' Examples:'); - console.log(''); - console.log(' $ custom-help --help'); - console.log(' $ custom-help -h'); - console.log(''); -}); - -program.parse(process.argv); - -console.log('stuff'); -``` - -yielding the following help output: - -``` - -Usage: custom-help [options] - -Options: - - -h, --help output usage information - -V, --version output the version number - -f, --foo enable some foo - -b, --bar enable some bar - -B, --baz enable some baz - -Examples: - - $ custom-help --help - $ custom-help -h - -``` - -## .prompt(msg, fn) - - Single-line prompt: - -```js -program.prompt('name: ', function(name){ - console.log('hi %s', name); -}); -``` - - Multi-line prompt: - -```js -program.prompt('description:', function(name){ - console.log('hi %s', name); -}); -``` - - Coercion: - -```js -program.prompt('Age: ', Number, function(age){ - console.log('age: %j', age); -}); -``` - -```js -program.prompt('Birthdate: ', Date, function(date){ - console.log('date: %s', date); -}); -``` - -## .password(msg[, mask], fn) - -Prompt for password without echoing: - -```js -program.password('Password: ', function(pass){ - console.log('got "%s"', pass); - process.stdin.destroy(); -}); -``` - -Prompt for password with mask char "*": - -```js -program.password('Password: ', '*', function(pass){ - console.log('got "%s"', pass); - process.stdin.destroy(); -}); -``` - -## .confirm(msg, fn) - - Confirm with the given `msg`: - -```js -program.confirm('continue? ', function(ok){ - console.log(' got %j', ok); -}); -``` - -## .choose(list, fn) - - Let the user choose from a `list`: - -```js -var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; - -console.log('Choose the coolest pet:'); -program.choose(list, function(i){ - console.log('you chose %d "%s"', i, list[i]); -}); -``` - -## Links - - - [API documentation](http://visionmedia.github.com/commander.js/) - - [ascii tables](https://github.com/LearnBoost/cli-table) - - [progress bars](https://github.com/visionmedia/node-progress) - - [more progress bars](https://github.com/substack/node-multimeter) - - [examples](https://github.com/visionmedia/commander.js/tree/master/examples) - -## License - -(The MIT License) - -Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca> - -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. \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/node_modules/commander/index.js b/node_modules/mocha/node_modules/jade/node_modules/commander/index.js deleted file mode 100644 index 06ec1e4..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/commander/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/commander'); \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/node_modules/commander/lib/commander.js b/node_modules/mocha/node_modules/jade/node_modules/commander/lib/commander.js deleted file mode 100644 index 5ba87eb..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/commander/lib/commander.js +++ /dev/null @@ -1,1026 +0,0 @@ - -/*! - * commander - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var EventEmitter = require('events').EventEmitter - , path = require('path') - , tty = require('tty') - , basename = path.basename; - -/** - * Expose the root command. - */ - -exports = module.exports = new Command; - -/** - * Expose `Command`. - */ - -exports.Command = Command; - -/** - * Expose `Option`. - */ - -exports.Option = Option; - -/** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {String} flags - * @param {String} description - * @api public - */ - -function Option(flags, description) { - this.flags = flags; - this.required = ~flags.indexOf('<'); - this.optional = ~flags.indexOf('['); - this.bool = !~flags.indexOf('-no-'); - flags = flags.split(/[ ,|]+/); - if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift(); - this.long = flags.shift(); - this.description = description; -} - -/** - * Return option name. - * - * @return {String} - * @api private - */ - -Option.prototype.name = function(){ - return this.long - .replace('--', '') - .replace('no-', ''); -}; - -/** - * Check if `arg` matches the short or long flag. - * - * @param {String} arg - * @return {Boolean} - * @api private - */ - -Option.prototype.is = function(arg){ - return arg == this.short - || arg == this.long; -}; - -/** - * Initialize a new `Command`. - * - * @param {String} name - * @api public - */ - -function Command(name) { - this.commands = []; - this.options = []; - this.args = []; - this.name = name; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -Command.prototype.__proto__ = EventEmitter.prototype; - -/** - * Add command `name`. - * - * The `.action()` callback is invoked when the - * command `name` is specified via __ARGV__, - * and the remaining arguments are applied to the - * function for access. - * - * When the `name` is "*" an un-matched command - * will be passed as the first arg, followed by - * the rest of __ARGV__ remaining. - * - * Examples: - * - * program - * .version('0.0.1') - * .option('-C, --chdir ', 'change the working directory') - * .option('-c, --config ', 'set config path. defaults to ./deploy.conf') - * .option('-T, --no-tests', 'ignore test hook') - * - * program - * .command('setup') - * .description('run remote setup commands') - * .action(function(){ - * console.log('setup'); - * }); - * - * program - * .command('exec ') - * .description('run the given remote command') - * .action(function(cmd){ - * console.log('exec "%s"', cmd); - * }); - * - * program - * .command('*') - * .description('deploy the given env') - * .action(function(env){ - * console.log('deploying "%s"', env); - * }); - * - * program.parse(process.argv); - * - * @param {String} name - * @return {Command} the new command - * @api public - */ - -Command.prototype.command = function(name){ - var args = name.split(/ +/); - var cmd = new Command(args.shift()); - this.commands.push(cmd); - cmd.parseExpectedArgs(args); - cmd.parent = this; - return cmd; -}; - -/** - * Parse expected `args`. - * - * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. - * - * @param {Array} args - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parseExpectedArgs = function(args){ - if (!args.length) return; - var self = this; - args.forEach(function(arg){ - switch (arg[0]) { - case '<': - self.args.push({ required: true, name: arg.slice(1, -1) }); - break; - case '[': - self.args.push({ required: false, name: arg.slice(1, -1) }); - break; - } - }); - return this; -}; - -/** - * Register callback `fn` for the command. - * - * Examples: - * - * program - * .command('help') - * .description('display verbose help') - * .action(function(){ - * // output help here - * }); - * - * @param {Function} fn - * @return {Command} for chaining - * @api public - */ - -Command.prototype.action = function(fn){ - var self = this; - this.parent.on(this.name, function(args, unknown){ - // Parse any so-far unknown options - unknown = unknown || []; - var parsed = self.parseOptions(unknown); - - // Output help if necessary - outputHelpIfNecessary(self, parsed.unknown); - - // If there are still any unknown options, then we simply - // die, unless someone asked for help, in which case we give it - // to them, and then we die. - if (parsed.unknown.length > 0) { - self.unknownOption(parsed.unknown[0]); - } - - self.args.forEach(function(arg, i){ - if (arg.required && null == args[i]) { - self.missingArgument(arg.name); - } - }); - - // Always append ourselves to the end of the arguments, - // to make sure we match the number of arguments the user - // expects - if (self.args.length) { - args[self.args.length] = self; - } else { - args.push(self); - } - - fn.apply(this, args); - }); - return this; -}; - -/** - * Define option with `flags`, `description` and optional - * coercion `fn`. - * - * The `flags` string should contain both the short and long flags, - * separated by comma, a pipe or space. The following are all valid - * all will output this way when `--help` is used. - * - * "-p, --pepper" - * "-p|--pepper" - * "-p --pepper" - * - * Examples: - * - * // simple boolean defaulting to false - * program.option('-p, --pepper', 'add pepper'); - * - * --pepper - * program.pepper - * // => Boolean - * - * // simple boolean defaulting to false - * program.option('-C, --no-cheese', 'remove cheese'); - * - * program.cheese - * // => true - * - * --no-cheese - * program.cheese - * // => true - * - * // required argument - * program.option('-C, --chdir ', 'change the working directory'); - * - * --chdir /tmp - * program.chdir - * // => "/tmp" - * - * // optional argument - * program.option('-c, --cheese [type]', 'add cheese [marble]'); - * - * @param {String} flags - * @param {String} description - * @param {Function|Mixed} fn or default - * @param {Mixed} defaultValue - * @return {Command} for chaining - * @api public - */ - -Command.prototype.option = function(flags, description, fn, defaultValue){ - var self = this - , option = new Option(flags, description) - , oname = option.name() - , name = camelcase(oname); - - // default as 3rd arg - if ('function' != typeof fn) defaultValue = fn, fn = null; - - // preassign default value only for --no-*, [optional], or - if (false == option.bool || option.optional || option.required) { - // when --no-* we make sure default is true - if (false == option.bool) defaultValue = true; - // preassign only if we have a default - if (undefined !== defaultValue) self[name] = defaultValue; - } - - // register the option - this.options.push(option); - - // when it's passed assign the value - // and conditionally invoke the callback - this.on(oname, function(val){ - // coercion - if (null != val && fn) val = fn(val); - - // unassigned or bool - if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) { - // if no value, bool true, and we have a default, then use it! - if (null == val) { - self[name] = option.bool - ? defaultValue || true - : false; - } else { - self[name] = val; - } - } else if (null !== val) { - // reassign - self[name] = val; - } - }); - - return this; -}; - -/** - * Parse `argv`, settings options and invoking commands when defined. - * - * @param {Array} argv - * @return {Command} for chaining - * @api public - */ - -Command.prototype.parse = function(argv){ - // store raw args - this.rawArgs = argv; - - // guess name - if (!this.name) this.name = basename(argv[1]); - - // process argv - var parsed = this.parseOptions(this.normalize(argv.slice(2))); - this.args = parsed.args; - return this.parseArgs(this.args, parsed.unknown); -}; - -/** - * Normalize `args`, splitting joined short flags. For example - * the arg "-abc" is equivalent to "-a -b -c". - * - * @param {Array} args - * @return {Array} - * @api private - */ - -Command.prototype.normalize = function(args){ - var ret = [] - , arg; - - for (var i = 0, len = args.length; i < len; ++i) { - arg = args[i]; - if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) { - arg.slice(1).split('').forEach(function(c){ - ret.push('-' + c); - }); - } else { - ret.push(arg); - } - } - - return ret; -}; - -/** - * Parse command `args`. - * - * When listener(s) are available those - * callbacks are invoked, otherwise the "*" - * event is emitted and those actions are invoked. - * - * @param {Array} args - * @return {Command} for chaining - * @api private - */ - -Command.prototype.parseArgs = function(args, unknown){ - var cmds = this.commands - , len = cmds.length - , name; - - if (args.length) { - name = args[0]; - if (this.listeners(name).length) { - this.emit(args.shift(), args, unknown); - } else { - this.emit('*', args); - } - } else { - outputHelpIfNecessary(this, unknown); - - // If there were no args and we have unknown options, - // then they are extraneous and we need to error. - if (unknown.length > 0) { - this.unknownOption(unknown[0]); - } - } - - return this; -}; - -/** - * Return an option matching `arg` if any. - * - * @param {String} arg - * @return {Option} - * @api private - */ - -Command.prototype.optionFor = function(arg){ - for (var i = 0, len = this.options.length; i < len; ++i) { - if (this.options[i].is(arg)) { - return this.options[i]; - } - } -}; - -/** - * Parse options from `argv` returning `argv` - * void of these options. - * - * @param {Array} argv - * @return {Array} - * @api public - */ - -Command.prototype.parseOptions = function(argv){ - var args = [] - , len = argv.length - , literal - , option - , arg; - - var unknownOptions = []; - - // parse options - for (var i = 0; i < len; ++i) { - arg = argv[i]; - - // literal args after -- - if ('--' == arg) { - literal = true; - continue; - } - - if (literal) { - args.push(arg); - continue; - } - - // find matching Option - option = this.optionFor(arg); - - // option is defined - if (option) { - // requires arg - if (option.required) { - arg = argv[++i]; - if (null == arg) return this.optionMissingArgument(option); - if ('-' == arg[0]) return this.optionMissingArgument(option, arg); - this.emit(option.name(), arg); - // optional arg - } else if (option.optional) { - arg = argv[i+1]; - if (null == arg || '-' == arg[0]) { - arg = null; - } else { - ++i; - } - this.emit(option.name(), arg); - // bool - } else { - this.emit(option.name()); - } - continue; - } - - // looks like an option - if (arg.length > 1 && '-' == arg[0]) { - unknownOptions.push(arg); - - // If the next argument looks like it might be - // an argument for this option, we pass it on. - // If it isn't, then it'll simply be ignored - if (argv[i+1] && '-' != argv[i+1][0]) { - unknownOptions.push(argv[++i]); - } - continue; - } - - // arg - args.push(arg); - } - - return { args: args, unknown: unknownOptions }; -}; - -/** - * Argument `name` is missing. - * - * @param {String} name - * @api private - */ - -Command.prototype.missingArgument = function(name){ - console.error(); - console.error(" error: missing required argument `%s'", name); - console.error(); - process.exit(1); -}; - -/** - * `Option` is missing an argument, but received `flag` or nothing. - * - * @param {String} option - * @param {String} flag - * @api private - */ - -Command.prototype.optionMissingArgument = function(option, flag){ - console.error(); - if (flag) { - console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag); - } else { - console.error(" error: option `%s' argument missing", option.flags); - } - console.error(); - process.exit(1); -}; - -/** - * Unknown option `flag`. - * - * @param {String} flag - * @api private - */ - -Command.prototype.unknownOption = function(flag){ - console.error(); - console.error(" error: unknown option `%s'", flag); - console.error(); - process.exit(1); -}; - -/** - * Set the program version to `str`. - * - * This method auto-registers the "-V, --version" flag - * which will print the version number when passed. - * - * @param {String} str - * @param {String} flags - * @return {Command} for chaining - * @api public - */ - -Command.prototype.version = function(str, flags){ - if (0 == arguments.length) return this._version; - this._version = str; - flags = flags || '-V, --version'; - this.option(flags, 'output the version number'); - this.on('version', function(){ - console.log(str); - process.exit(0); - }); - return this; -}; - -/** - * Set the description `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.description = function(str){ - if (0 == arguments.length) return this._description; - this._description = str; - return this; -}; - -/** - * Set / get the command usage `str`. - * - * @param {String} str - * @return {String|Command} - * @api public - */ - -Command.prototype.usage = function(str){ - var args = this.args.map(function(arg){ - return arg.required - ? '<' + arg.name + '>' - : '[' + arg.name + ']'; - }); - - var usage = '[options' - + (this.commands.length ? '] [command' : '') - + ']' - + (this.args.length ? ' ' + args : ''); - if (0 == arguments.length) return this._usage || usage; - this._usage = str; - - return this; -}; - -/** - * Return the largest option length. - * - * @return {Number} - * @api private - */ - -Command.prototype.largestOptionLength = function(){ - return this.options.reduce(function(max, option){ - return Math.max(max, option.flags.length); - }, 0); -}; - -/** - * Return help for options. - * - * @return {String} - * @api private - */ - -Command.prototype.optionHelp = function(){ - var width = this.largestOptionLength(); - - // Prepend the help information - return [pad('-h, --help', width) + ' ' + 'output usage information'] - .concat(this.options.map(function(option){ - return pad(option.flags, width) - + ' ' + option.description; - })) - .join('\n'); -}; - -/** - * Return command help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.commandHelp = function(){ - if (!this.commands.length) return ''; - return [ - '' - , ' Commands:' - , '' - , this.commands.map(function(cmd){ - var args = cmd.args.map(function(arg){ - return arg.required - ? '<' + arg.name + '>' - : '[' + arg.name + ']'; - }).join(' '); - - return cmd.name - + (cmd.options.length - ? ' [options]' - : '') + ' ' + args - + (cmd.description() - ? '\n' + cmd.description() - : ''); - }).join('\n\n').replace(/^/gm, ' ') - , '' - ].join('\n'); -}; - -/** - * Return program help documentation. - * - * @return {String} - * @api private - */ - -Command.prototype.helpInformation = function(){ - return [ - '' - , ' Usage: ' + this.name + ' ' + this.usage() - , '' + this.commandHelp() - , ' Options:' - , '' - , '' + this.optionHelp().replace(/^/gm, ' ') - , '' - , '' - ].join('\n'); -}; - -/** - * Prompt for a `Number`. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForNumber = function(str, fn){ - var self = this; - this.promptSingleLine(str, function parseNumber(val){ - val = Number(val); - if (isNaN(val)) return self.promptSingleLine(str + '(must be a number) ', parseNumber); - fn(val); - }); -}; - -/** - * Prompt for a `Date`. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptForDate = function(str, fn){ - var self = this; - this.promptSingleLine(str, function parseDate(val){ - val = new Date(val); - if (isNaN(val.getTime())) return self.promptSingleLine(str + '(must be a date) ', parseDate); - fn(val); - }); -}; - -/** - * Single-line prompt. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptSingleLine = function(str, fn){ - if ('function' == typeof arguments[2]) { - return this['promptFor' + (fn.name || fn)](str, arguments[2]); - } - - process.stdout.write(str); - process.stdin.setEncoding('utf8'); - process.stdin.once('data', function(val){ - fn(val.trim()); - }).resume(); -}; - -/** - * Multi-line prompt. - * - * @param {String} str - * @param {Function} fn - * @api private - */ - -Command.prototype.promptMultiLine = function(str, fn){ - var buf = []; - console.log(str); - process.stdin.setEncoding('utf8'); - process.stdin.on('data', function(val){ - if ('\n' == val || '\r\n' == val) { - process.stdin.removeAllListeners('data'); - fn(buf.join('\n')); - } else { - buf.push(val.trimRight()); - } - }).resume(); -}; - -/** - * Prompt `str` and callback `fn(val)` - * - * Commander supports single-line and multi-line prompts. - * To issue a single-line prompt simply add white-space - * to the end of `str`, something like "name: ", whereas - * for a multi-line prompt omit this "description:". - * - * - * Examples: - * - * program.prompt('Username: ', function(name){ - * console.log('hi %s', name); - * }); - * - * program.prompt('Description:', function(desc){ - * console.log('description was "%s"', desc.trim()); - * }); - * - * @param {String|Object} str - * @param {Function} fn - * @api public - */ - -Command.prototype.prompt = function(str, fn){ - var self = this; - - if ('string' == typeof str) { - if (/ $/.test(str)) return this.promptSingleLine.apply(this, arguments); - this.promptMultiLine(str, fn); - } else { - var keys = Object.keys(str) - , obj = {}; - - function next() { - var key = keys.shift() - , label = str[key]; - - if (!key) return fn(obj); - self.prompt(label, function(val){ - obj[key] = val; - next(); - }); - } - - next(); - } -}; - -/** - * Prompt for password with `str`, `mask` char and callback `fn(val)`. - * - * The mask string defaults to '', aka no output is - * written while typing, you may want to use "*" etc. - * - * Examples: - * - * program.password('Password: ', function(pass){ - * console.log('got "%s"', pass); - * process.stdin.destroy(); - * }); - * - * program.password('Password: ', '*', function(pass){ - * console.log('got "%s"', pass); - * process.stdin.destroy(); - * }); - * - * @param {String} str - * @param {String} mask - * @param {Function} fn - * @api public - */ - -Command.prototype.password = function(str, mask, fn){ - var self = this - , buf = ''; - - // default mask - if ('function' == typeof mask) { - fn = mask; - mask = ''; - } - - process.stdin.resume(); - tty.setRawMode(true); - process.stdout.write(str); - - // keypress - process.stdin.on('keypress', function(c, key){ - if (key && 'enter' == key.name) { - console.log(); - process.stdin.removeAllListeners('keypress'); - tty.setRawMode(false); - if (!buf.trim().length) return self.password(str, mask, fn); - fn(buf); - return; - } - - if (key && key.ctrl && 'c' == key.name) { - console.log('%s', buf); - process.exit(); - } - - process.stdout.write(mask); - buf += c; - }).resume(); -}; - -/** - * Confirmation prompt with `str` and callback `fn(bool)` - * - * Examples: - * - * program.confirm('continue? ', function(ok){ - * console.log(' got %j', ok); - * process.stdin.destroy(); - * }); - * - * @param {String} str - * @param {Function} fn - * @api public - */ - - -Command.prototype.confirm = function(str, fn, verbose){ - var self = this; - this.prompt(str, function(ok){ - if (!ok.trim()) { - if (!verbose) str += '(yes or no) '; - return self.confirm(str, fn, true); - } - fn(parseBool(ok)); - }); -}; - -/** - * Choice prompt with `list` of items and callback `fn(index, item)` - * - * Examples: - * - * var list = ['tobi', 'loki', 'jane', 'manny', 'luna']; - * - * console.log('Choose the coolest pet:'); - * program.choose(list, function(i){ - * console.log('you chose %d "%s"', i, list[i]); - * process.stdin.destroy(); - * }); - * - * @param {Array} list - * @param {Number|Function} index or fn - * @param {Function} fn - * @api public - */ - -Command.prototype.choose = function(list, index, fn){ - var self = this - , hasDefault = 'number' == typeof index; - - if (!hasDefault) { - fn = index; - index = null; - } - - list.forEach(function(item, i){ - if (hasDefault && i == index) { - console.log('* %d) %s', i + 1, item); - } else { - console.log(' %d) %s', i + 1, item); - } - }); - - function again() { - self.prompt(' : ', function(val){ - val = parseInt(val, 10) - 1; - if (hasDefault && isNaN(val)) val = index; - - if (null == list[val]) { - again(); - } else { - fn(val, list[val]); - } - }); - } - - again(); -}; - -/** - * Camel-case the given `flag` - * - * @param {String} flag - * @return {String} - * @api private - */ - -function camelcase(flag) { - return flag.split('-').reduce(function(str, word){ - return str + word[0].toUpperCase() + word.slice(1); - }); -} - -/** - * Parse a boolean `str`. - * - * @param {String} str - * @return {Boolean} - * @api private - */ - -function parseBool(str) { - return /^y|yes|ok|true$/i.test(str); -} - -/** - * Pad `str` to `width`. - * - * @param {String} str - * @param {Number} width - * @return {String} - * @api private - */ - -function pad(str, width) { - var len = Math.max(0, width - str.length); - return str + Array(len + 1).join(' '); -} - -/** - * Output help information if necessary - * - * @param {Command} command to output help for - * @param {Array} array of options to search for -h or --help - * @api private - */ - -function outputHelpIfNecessary(cmd, options) { - options = options || []; - for (var i = 0; i < options.length; i++) { - if (options[i] == '--help' || options[i] == '-h') { - process.stdout.write(cmd.helpInformation()); - cmd.emit('--help'); - process.exit(0); - } - } -} diff --git a/node_modules/mocha/node_modules/jade/node_modules/commander/package.json b/node_modules/mocha/node_modules/jade/node_modules/commander/package.json deleted file mode 100644 index ab40add..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/commander/package.json +++ /dev/null @@ -1,61 +0,0 @@ -{ - "name": "commander", - "version": "0.6.1", - "description": "the complete solution for node.js command-line programs", - "keywords": [ - "command", - "option", - "parser", - "prompt", - "stdin" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/commander.js.git" - }, - "dependencies": {}, - "devDependencies": { - "should": ">= 0.0.1" - }, - "scripts": { - "test": "make test" - }, - "main": "index", - "engines": { - "node": ">= 0.4.x" - }, - "_npmUser": { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - "_id": "commander@0.6.1", - "optionalDependencies": {}, - "_engineSupported": true, - "_npmVersion": "1.1.0-3", - "_nodeVersion": "v0.6.12", - "_defaultsLoaded": true, - "dist": { - "shasum": "fa68a14f6a945d54dbbe50d8cdb3320e9e3b1a06", - "tarball": "http://registry.npmjs.org/commander/-/commander-0.6.1.tgz" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - } - ], - "directories": {}, - "_shasum": "fa68a14f6a945d54dbbe50d8cdb3320e9e3b1a06", - "_from": "commander@0.6.1", - "_resolved": "https://registry.npmjs.org/commander/-/commander-0.6.1.tgz", - "readme": "# Commander.js\n\n The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/visionmedia/commander).\n\n [![Build Status](https://secure.travis-ci.org/visionmedia/commander.js.png)](http://travis-ci.org/visionmedia/commander.js)\n\n## Installation\n\n $ npm install commander\n\n## Option parsing\n\n Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.\n\n```js\n#!/usr/bin/env node\n\n/**\n * Module dependencies.\n */\n\nvar program = require('commander');\n\nprogram\n .version('0.0.1')\n .option('-p, --peppers', 'Add peppers')\n .option('-P, --pineapple', 'Add pineapple')\n .option('-b, --bbq', 'Add bbq sauce')\n .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')\n .parse(process.argv);\n\nconsole.log('you ordered a pizza with:');\nif (program.peppers) console.log(' - peppers');\nif (program.pineapple) console.log(' - pineappe');\nif (program.bbq) console.log(' - bbq');\nconsole.log(' - %s cheese', program.cheese);\n```\n\n Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as \"--template-engine\" are camel-cased, becoming `program.templateEngine` etc.\n\n## Automated --help\n\n The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:\n\n``` \n $ ./examples/pizza --help\n\n Usage: pizza [options]\n\n Options:\n\n -V, --version output the version number\n -p, --peppers Add peppers\n -P, --pineapple Add pineappe\n -b, --bbq Add bbq sauce\n -c, --cheese Add the specified type of cheese [marble]\n -h, --help output usage information\n\n```\n\n## Coercion\n\n```js\nfunction range(val) {\n return val.split('..').map(Number);\n}\n\nfunction list(val) {\n return val.split(',');\n}\n\nprogram\n .version('0.0.1')\n .usage('[options] ')\n .option('-i, --integer ', 'An integer argument', parseInt)\n .option('-f, --float ', 'A float argument', parseFloat)\n .option('-r, --range ..', 'A range', range)\n .option('-l, --list ', 'A list', list)\n .option('-o, --optional [value]', 'An optional value')\n .parse(process.argv);\n\nconsole.log(' int: %j', program.integer);\nconsole.log(' float: %j', program.float);\nconsole.log(' optional: %j', program.optional);\nprogram.range = program.range || [];\nconsole.log(' range: %j..%j', program.range[0], program.range[1]);\nconsole.log(' list: %j', program.list);\nconsole.log(' args: %j', program.args);\n```\n\n## Custom help\n\n You can display arbitrary `-h, --help` information\n by listening for \"--help\". Commander will automatically\n exit once you are done so that the remainder of your program\n does not execute causing undesired behaviours, for example\n in the following executable \"stuff\" will not output when\n `--help` is used.\n\n```js\n#!/usr/bin/env node\n\n/**\n * Module dependencies.\n */\n\nvar program = require('../');\n\nfunction list(val) {\n return val.split(',').map(Number);\n}\n\nprogram\n .version('0.0.1')\n .option('-f, --foo', 'enable some foo')\n .option('-b, --bar', 'enable some bar')\n .option('-B, --baz', 'enable some baz');\n\n// must be before .parse() since\n// node's emit() is immediate\n\nprogram.on('--help', function(){\n console.log(' Examples:');\n console.log('');\n console.log(' $ custom-help --help');\n console.log(' $ custom-help -h');\n console.log('');\n});\n\nprogram.parse(process.argv);\n\nconsole.log('stuff');\n```\n\nyielding the following help output:\n\n```\n\nUsage: custom-help [options]\n\nOptions:\n\n -h, --help output usage information\n -V, --version output the version number\n -f, --foo enable some foo\n -b, --bar enable some bar\n -B, --baz enable some baz\n\nExamples:\n\n $ custom-help --help\n $ custom-help -h\n\n```\n\n## .prompt(msg, fn)\n\n Single-line prompt:\n\n```js\nprogram.prompt('name: ', function(name){\n console.log('hi %s', name);\n});\n```\n\n Multi-line prompt:\n\n```js\nprogram.prompt('description:', function(name){\n console.log('hi %s', name);\n});\n```\n\n Coercion:\n\n```js\nprogram.prompt('Age: ', Number, function(age){\n console.log('age: %j', age);\n});\n```\n\n```js\nprogram.prompt('Birthdate: ', Date, function(date){\n console.log('date: %s', date);\n});\n```\n\n## .password(msg[, mask], fn)\n\nPrompt for password without echoing:\n\n```js\nprogram.password('Password: ', function(pass){\n console.log('got \"%s\"', pass);\n process.stdin.destroy();\n});\n```\n\nPrompt for password with mask char \"*\":\n\n```js\nprogram.password('Password: ', '*', function(pass){\n console.log('got \"%s\"', pass);\n process.stdin.destroy();\n});\n```\n\n## .confirm(msg, fn)\n\n Confirm with the given `msg`:\n\n```js\nprogram.confirm('continue? ', function(ok){\n console.log(' got %j', ok);\n});\n```\n\n## .choose(list, fn)\n\n Let the user choose from a `list`:\n\n```js\nvar list = ['tobi', 'loki', 'jane', 'manny', 'luna'];\n\nconsole.log('Choose the coolest pet:');\nprogram.choose(list, function(i){\n console.log('you chose %d \"%s\"', i, list[i]);\n});\n```\n\n## Links\n\n - [API documentation](http://visionmedia.github.com/commander.js/)\n - [ascii tables](https://github.com/LearnBoost/cli-table)\n - [progress bars](https://github.com/visionmedia/node-progress)\n - [more progress bars](https://github.com/substack/node-multimeter)\n - [examples](https://github.com/visionmedia/commander.js/tree/master/examples)\n\n## License \n\n(The MIT License)\n\nCopyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/visionmedia/commander.js/issues" - }, - "homepage": "https://github.com/visionmedia/commander.js" -} diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/.gitignore.orig b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/.gitignore.orig deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/.gitignore.orig +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/.gitignore.rej b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/.gitignore.rej deleted file mode 100644 index 69244ff..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/.gitignore.rej +++ /dev/null @@ -1,5 +0,0 @@ ---- /dev/null -+++ .gitignore -@@ -0,0 +1,2 @@ -+node_modules/ -+npm-debug.log \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/.npmignore b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/.npmignore deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/LICENSE b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/LICENSE deleted file mode 100644 index 432d1ae..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: - -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/node_modules/mocha/node_modules/jade/node_modules/mkdirp/README.markdown b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/README.markdown deleted file mode 100644 index b4dd75f..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/README.markdown +++ /dev/null @@ -1,54 +0,0 @@ -mkdirp -====== - -Like `mkdir -p`, but in node.js! - -example -======= - -pow.js ------- - var mkdirp = require('mkdirp'); - - mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') - }); - -Output - pow! - -And now /tmp/foo/bar/baz exists, huzzah! - -methods -======= - -var mkdirp = require('mkdirp'); - -mkdirp(dir, mode, cb) ---------------------- - -Create a new directory and any necessary subdirectories at `dir` with octal -permission string `mode`. - -If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. - -mkdirp.sync(dir, mode) ----------------------- - -Synchronously create a new directory and any necessary subdirectories at `dir` -with octal permission string `mode`. - -If `mode` isn't specified, it defaults to `0777 & (~process.umask())`. - -install -======= - -With [npm](http://npmjs.org) do: - - npm install mkdirp - -license -======= - -MIT/X11 diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/examples/pow.js b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/examples/pow.js deleted file mode 100644 index e692421..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/examples/pow.js +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/examples/pow.js.orig b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/examples/pow.js.orig deleted file mode 100644 index 7741462..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/examples/pow.js.orig +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/examples/pow.js.rej b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/examples/pow.js.rej deleted file mode 100644 index 81e7f43..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/examples/pow.js.rej +++ /dev/null @@ -1,19 +0,0 @@ ---- examples/pow.js -+++ examples/pow.js -@@ -1,6 +1,15 @@ --var mkdirp = require('mkdirp').mkdirp; -+var mkdirp = require('../').mkdirp, -+ mkdirpSync = require('../').mkdirpSync; - - mkdirp('/tmp/foo/bar/baz', 0755, function (err) { - if (err) console.error(err) - else console.log('pow!') - }); -+ -+try { -+ mkdirpSync('/tmp/bar/foo/baz', 0755); -+ console.log('double pow!'); -+} -+catch (ex) { -+ console.log(ex); -+} \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/index.js b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/index.js deleted file mode 100644 index 25f43ad..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/index.js +++ /dev/null @@ -1,79 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, mode, f) { - if (typeof mode === 'function' || mode === undefined) { - f = mode; - mode = 0777 & (~process.umask()); - } - - var cb = f || function () {}; - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - fs.mkdir(p, mode, function (er) { - if (!er) return cb(); - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), mode, function (er) { - if (er) cb(er); - else mkdirP(p, mode, cb); - }); - break; - - case 'EEXIST': - fs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original EEXIST be the failure reason. - if (er2 || !stat.isDirectory()) cb(er) - else cb(); - }); - break; - - default: - cb(er); - break; - } - }); -} - -mkdirP.sync = function sync (p, mode) { - if (mode === undefined) { - mode = 0777 & (~process.umask()); - } - - if (typeof mode === 'string') mode = parseInt(mode, 8); - p = path.resolve(p); - - try { - fs.mkdirSync(p, mode) - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - var err1 = sync(path.dirname(p), mode) - if (err1) throw err1; - else return sync(p, mode); - break; - - case 'EEXIST' : - var stat; - try { - stat = fs.statSync(p); - } - catch (err1) { - throw err0 - } - if (!stat.isDirectory()) throw err0; - else return null; - break; - default : - throw err0 - break; - } - } - - return null; -}; diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/package.json b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/package.json deleted file mode 100644 index e40c3db..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/package.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "mkdirp", - "description": "Recursively mkdir, like `mkdir -p`", - "version": "0.3.0", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "main": "./index", - "keywords": [ - "mkdir", - "directory" - ], - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/substack/node-mkdirp.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "devDependencies": { - "tap": "0.0.x" - }, - "license": "MIT/X11", - "engines": { - "node": "*" - }, - "readme": "mkdirp\n======\n\nLike `mkdir -p`, but in node.js!\n\nexample\n=======\n\npow.js\n------\n var mkdirp = require('mkdirp');\n \n mkdirp('/tmp/foo/bar/baz', function (err) {\n if (err) console.error(err)\n else console.log('pow!')\n });\n\nOutput\n pow!\n\nAnd now /tmp/foo/bar/baz exists, huzzah!\n\nmethods\n=======\n\nvar mkdirp = require('mkdirp');\n\nmkdirp(dir, mode, cb)\n---------------------\n\nCreate a new directory and any necessary subdirectories at `dir` with octal\npermission string `mode`.\n\nIf `mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\nmkdirp.sync(dir, mode)\n----------------------\n\nSynchronously create a new directory and any necessary subdirectories at `dir`\nwith octal permission string `mode`.\n\nIf `mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) do:\n\n npm install mkdirp\n\nlicense\n=======\n\nMIT/X11\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/substack/node-mkdirp/issues" - }, - "homepage": "https://github.com/substack/node-mkdirp", - "_id": "mkdirp@0.3.0", - "_from": "mkdirp@0.3.0" -} diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/chmod.js b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/chmod.js deleted file mode 100644 index 520dcb8..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/chmod.js +++ /dev/null @@ -1,38 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -test('chmod-pre', function (t) { - var mode = 0744 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.equal(stat && stat.mode & 0777, mode, 'should be 0744'); - t.end(); - }); - }); -}); - -test('chmod', function (t) { - var mode = 0755 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.end(); - }); - }); -}); diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/clobber.js b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/clobber.js deleted file mode 100644 index 0eb7099..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/clobber.js +++ /dev/null @@ -1,37 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -// a file in the way -var itw = ps.slice(0, 3).join('/'); - - -test('clobber-pre', function (t) { - console.error("about to write to "+itw) - fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); - - fs.stat(itw, function (er, stat) { - t.ifError(er) - t.ok(stat && stat.isFile(), 'should be file') - t.end() - }) -}) - -test('clobber', function (t) { - t.plan(2); - mkdirp(file, 0755, function (err) { - t.ok(err); - t.equal(err.code, 'ENOTDIR'); - t.end(); - }); -}); diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/mkdirp.js b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/mkdirp.js deleted file mode 100644 index b07cd70..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/mkdirp.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('woo', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/perm.js b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/perm.js deleted file mode 100644 index 23a7abb..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/perm.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('async perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); - -test('async root perm', function (t) { - mkdirp('/tmp', 0755, function (err) { - if (err) t.fail(err); - t.end(); - }); - t.end(); -}); diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/perm_sync.js b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/perm_sync.js deleted file mode 100644 index f685f60..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/perm_sync.js +++ /dev/null @@ -1,39 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('sync perm', function (t) { - t.plan(2); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; - - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); - -test('sync root perm', function (t) { - t.plan(1); - - var file = '/tmp'; - mkdirp.sync(file, 0755); - path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }); -}); diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/race.js b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/race.js deleted file mode 100644 index 96a0447..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/race.js +++ /dev/null @@ -1,41 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('race', function (t) { - t.plan(4); - var ps = [ '', 'tmp' ]; - - for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); - } - var file = ps.join('/'); - - var res = 2; - mk(file, function () { - if (--res === 0) t.end(); - }); - - mk(file, function () { - if (--res === 0) t.end(); - }); - - function mk (file, cb) { - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - if (cb) cb(); - } - }) - }) - }); - } -}); diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/rel.js b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/rel.js deleted file mode 100644 index 7985824..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/rel.js +++ /dev/null @@ -1,32 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('rel', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var cwd = process.cwd(); - process.chdir('/tmp'); - - var file = [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - process.chdir(cwd); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/sync.js b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/sync.js deleted file mode 100644 index e0e389d..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/sync.js +++ /dev/null @@ -1,27 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('sync', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - var err = mkdirp.sync(file, 0755); - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) -}); diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/umask.js b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/umask.js deleted file mode 100644 index 64ccafe..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/umask.js +++ /dev/null @@ -1,28 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('implicit mode from umask', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, function (err) { - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, 0777 & (~process.umask())); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) - }); -}); diff --git a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/umask_sync.js b/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/umask_sync.js deleted file mode 100644 index 83cba56..0000000 --- a/node_modules/mocha/node_modules/jade/node_modules/mkdirp/test/umask_sync.js +++ /dev/null @@ -1,27 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('umask sync modes', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - var err = mkdirp.sync(file); - if (err) t.fail(err); - else path.exists(file, function (ex) { - if (!ex) t.fail('file not created') - else fs.stat(file, function (err, stat) { - if (err) t.fail(err) - else { - t.equal(stat.mode & 0777, (0777 & (~process.umask()))); - t.ok(stat.isDirectory(), 'target not a directory'); - t.end(); - } - }) - }) -}); diff --git a/node_modules/mocha/node_modules/jade/package.json b/node_modules/mocha/node_modules/jade/package.json deleted file mode 100644 index 14198af..0000000 --- a/node_modules/mocha/node_modules/jade/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "jade", - "description": "Jade template engine", - "version": "0.26.3", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/jade" - }, - "main": "./index.js", - "bin": { - "jade": "./bin/jade" - }, - "man": [ - "./jade.1" - ], - "dependencies": { - "commander": "0.6.1", - "mkdirp": "0.3.0" - }, - "devDependencies": { - "mocha": "*", - "markdown": "*", - "stylus": "*", - "uubench": "*", - "should": "*", - "less": "*", - "uglify-js": "*" - }, - "component": { - "scripts": { - "jade": "runtime.js" - } - }, - "scripts": { - "prepublish": "npm prune" - }, - "_id": "jade@0.26.3", - "dist": { - "shasum": "8f10d7977d8d79f2f6ff862a81b0513ccb25686c", - "tarball": "http://registry.npmjs.org/jade/-/jade-0.26.3.tgz" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - } - ], - "directories": {}, - "_shasum": "8f10d7977d8d79f2f6ff862a81b0513ccb25686c", - "_from": "jade@0.26.3", - "_resolved": "https://registry.npmjs.org/jade/-/jade-0.26.3.tgz" -} diff --git a/node_modules/mocha/node_modules/jade/runtime.js b/node_modules/mocha/node_modules/jade/runtime.js deleted file mode 100644 index 0f54907..0000000 --- a/node_modules/mocha/node_modules/jade/runtime.js +++ /dev/null @@ -1,179 +0,0 @@ - -jade = (function(exports){ -/*! - * Jade - runtime - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Lame Array.isArray() polyfill for now. - */ - -if (!Array.isArray) { - Array.isArray = function(arr){ - return '[object Array]' == Object.prototype.toString.call(arr); - }; -} - -/** - * Lame Object.keys() polyfill for now. - */ - -if (!Object.keys) { - Object.keys = function(obj){ - var arr = []; - for (var key in obj) { - if (obj.hasOwnProperty(key)) { - arr.push(key); - } - } - return arr; - } -} - -/** - * Merge two attribute objects giving precedence - * to values in object `b`. Classes are special-cased - * allowing for arrays and merging/joining appropriately - * resulting in a string. - * - * @param {Object} a - * @param {Object} b - * @return {Object} a - * @api private - */ - -exports.merge = function merge(a, b) { - var ac = a['class']; - var bc = b['class']; - - if (ac || bc) { - ac = ac || []; - bc = bc || []; - if (!Array.isArray(ac)) ac = [ac]; - if (!Array.isArray(bc)) bc = [bc]; - ac = ac.filter(nulls); - bc = bc.filter(nulls); - a['class'] = ac.concat(bc).join(' '); - } - - for (var key in b) { - if (key != 'class') { - a[key] = b[key]; - } - } - - return a; -}; - -/** - * Filter null `val`s. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function nulls(val) { - return val != null; -} - -/** - * Render the given attributes object. - * - * @param {Object} obj - * @param {Object} escaped - * @return {String} - * @api private - */ - -exports.attrs = function attrs(obj, escaped){ - var buf = [] - , terse = obj.terse; - - delete obj.terse; - var keys = Object.keys(obj) - , len = keys.length; - - if (len) { - buf.push(''); - for (var i = 0; i < len; ++i) { - var key = keys[i] - , val = obj[key]; - - if ('boolean' == typeof val || null == val) { - if (val) { - terse - ? buf.push(key) - : buf.push(key + '="' + key + '"'); - } - } else if (0 == key.indexOf('data') && 'string' != typeof val) { - buf.push(key + "='" + JSON.stringify(val) + "'"); - } else if ('class' == key && Array.isArray(val)) { - buf.push(key + '="' + exports.escape(val.join(' ')) + '"'); - } else if (escaped && escaped[key]) { - buf.push(key + '="' + exports.escape(val) + '"'); - } else { - buf.push(key + '="' + val + '"'); - } - } - } - - return buf.join(' '); -}; - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function escape(html){ - return String(html) - .replace(/&(?!(\w+|\#\d+);)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -/** - * Re-throw the given `err` in context to the - * the jade in `filename` at the given `lineno`. - * - * @param {Error} err - * @param {String} filename - * @param {String} lineno - * @api private - */ - -exports.rethrow = function rethrow(err, filename, lineno){ - if (!filename) throw err; - - var context = 3 - , str = require('fs').readFileSync(filename, 'utf8') - , lines = str.split('\n') - , start = Math.max(lineno - context, 0) - , end = Math.min(lines.length, lineno + context); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' > ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'Jade') + ':' + lineno - + '\n' + context + '\n\n' + err.message; - throw err; -}; - - return exports; - -})({}); diff --git a/node_modules/mocha/node_modules/jade/runtime.min.js b/node_modules/mocha/node_modules/jade/runtime.min.js deleted file mode 100644 index 1714efb..0000000 --- a/node_modules/mocha/node_modules/jade/runtime.min.js +++ /dev/null @@ -1 +0,0 @@ -jade=function(exports){Array.isArray||(Array.isArray=function(arr){return"[object Array]"==Object.prototype.toString.call(arr)}),Object.keys||(Object.keys=function(obj){var arr=[];for(var key in obj)obj.hasOwnProperty(key)&&arr.push(key);return arr}),exports.merge=function merge(a,b){var ac=a["class"],bc=b["class"];if(ac||bc)ac=ac||[],bc=bc||[],Array.isArray(ac)||(ac=[ac]),Array.isArray(bc)||(bc=[bc]),ac=ac.filter(nulls),bc=bc.filter(nulls),a["class"]=ac.concat(bc).join(" ");for(var key in b)key!="class"&&(a[key]=b[key]);return a};function nulls(val){return val!=null}return exports.attrs=function attrs(obj,escaped){var buf=[],terse=obj.terse;delete obj.terse;var keys=Object.keys(obj),len=keys.length;if(len){buf.push("");for(var i=0;i/g,">").replace(/"/g,""")},exports.rethrow=function rethrow(err,filename,lineno){if(!filename)throw err;var context=3,str=require("fs").readFileSync(filename,"utf8"),lines=str.split("\n"),start=Math.max(lineno-context,0),end=Math.min(lines.length,lineno+context),context=lines.slice(start,end).map(function(line,i){var curr=i+start+1;return(curr==lineno?" > ":" ")+curr+"| "+line}).join("\n");throw err.path=filename,err.message=(filename||"Jade")+":"+lineno+"\n"+context+"\n\n"+err.message,err},exports}({}); \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/test.jade b/node_modules/mocha/node_modules/jade/test.jade deleted file mode 100644 index b3a8988..0000000 --- a/node_modules/mocha/node_modules/jade/test.jade +++ /dev/null @@ -1,7 +0,0 @@ -p. - This is a large - body of text for - this tag. - - Nothing too - exciting. \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/testing/head.jade b/node_modules/mocha/node_modules/jade/testing/head.jade deleted file mode 100644 index 8515406..0000000 --- a/node_modules/mocha/node_modules/jade/testing/head.jade +++ /dev/null @@ -1,5 +0,0 @@ -head - script(src='/jquery.js') - yield - if false - script(src='/jquery.ui.js') diff --git a/node_modules/mocha/node_modules/jade/testing/index.jade b/node_modules/mocha/node_modules/jade/testing/index.jade deleted file mode 100644 index 1032c5f..0000000 --- a/node_modules/mocha/node_modules/jade/testing/index.jade +++ /dev/null @@ -1,22 +0,0 @@ - -tag = 'p' -foo = 'bar' - -#{tag} value -#{tag}(foo='bar') value -#{foo ? 'a' : 'li'}(something) here - -mixin item(icon) - li - if attributes.href - a(attributes) - img.icon(src=icon) - block - else - span(attributes) - img.icon(src=icon) - block - -ul - +item('contact') Contact - +item(href='/contact') Contact diff --git a/node_modules/mocha/node_modules/jade/testing/index.js b/node_modules/mocha/node_modules/jade/testing/index.js deleted file mode 100644 index 226e8c0..0000000 --- a/node_modules/mocha/node_modules/jade/testing/index.js +++ /dev/null @@ -1,11 +0,0 @@ - -/** - * Module dependencies. - */ - -var jade = require('../'); - -jade.renderFile('testing/index.jade', { pretty: true, debug: true, compileDebug: false }, function(err, str){ - if (err) throw err; - console.log(str); -}); \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/testing/layout.jade b/node_modules/mocha/node_modules/jade/testing/layout.jade deleted file mode 100644 index 6923cf1..0000000 --- a/node_modules/mocha/node_modules/jade/testing/layout.jade +++ /dev/null @@ -1,6 +0,0 @@ -html - include head - script(src='/caustic.js') - script(src='/app.js') - body - block content \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/testing/user.jade b/node_modules/mocha/node_modules/jade/testing/user.jade deleted file mode 100644 index 3c636b7..0000000 --- a/node_modules/mocha/node_modules/jade/testing/user.jade +++ /dev/null @@ -1,7 +0,0 @@ -h1 Tobi -p Is a ferret - -ul - li: a foo - li: a bar - li: a baz \ No newline at end of file diff --git a/node_modules/mocha/node_modules/jade/testing/user.js b/node_modules/mocha/node_modules/jade/testing/user.js deleted file mode 100644 index 2ecc45e..0000000 --- a/node_modules/mocha/node_modules/jade/testing/user.js +++ /dev/null @@ -1,27 +0,0 @@ -function anonymous(locals, attrs, escape, rethrow) { -var attrs = jade.attrs, escape = jade.escape, rethrow = jade.rethrow; -var __jade = [{ lineno: 1, filename: "testing/user.jade" }]; -try { -var buf = []; -with (locals || {}) { -var interp; -__jade.unshift({ lineno: 1, filename: __jade[0].filename }); -__jade.unshift({ lineno: 1, filename: __jade[0].filename }); -buf.push('

      Tobi'); -__jade.unshift({ lineno: undefined, filename: __jade[0].filename }); -__jade.shift(); -buf.push('

      '); -__jade.shift(); -__jade.unshift({ lineno: 2, filename: __jade[0].filename }); -buf.push('

      Is a ferret'); -__jade.unshift({ lineno: undefined, filename: __jade[0].filename }); -__jade.shift(); -buf.push('

      '); -__jade.shift(); -__jade.shift(); -} -return buf.join(""); -} catch (err) { - rethrow(err, __jade[0].filename, __jade[0].lineno); -} -} \ No newline at end of file diff --git a/node_modules/mocha/node_modules/mkdirp/.npmignore b/node_modules/mocha/node_modules/mkdirp/.npmignore deleted file mode 100644 index 9303c34..0000000 --- a/node_modules/mocha/node_modules/mkdirp/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node_modules/mocha/node_modules/mkdirp/.travis.yml b/node_modules/mocha/node_modules/mkdirp/.travis.yml deleted file mode 100644 index c693a93..0000000 --- a/node_modules/mocha/node_modules/mkdirp/.travis.yml +++ /dev/null @@ -1,5 +0,0 @@ -language: node_js -node_js: - - 0.6 - - 0.8 - - "0.10" diff --git a/node_modules/mocha/node_modules/mkdirp/LICENSE b/node_modules/mocha/node_modules/mkdirp/LICENSE deleted file mode 100644 index 432d1ae..0000000 --- a/node_modules/mocha/node_modules/mkdirp/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: - -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/node_modules/mocha/node_modules/mkdirp/bin/cmd.js b/node_modules/mocha/node_modules/mkdirp/bin/cmd.js deleted file mode 100755 index d95de15..0000000 --- a/node_modules/mocha/node_modules/mkdirp/bin/cmd.js +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env node - -var mkdirp = require('../'); -var minimist = require('minimist'); -var fs = require('fs'); - -var argv = minimist(process.argv.slice(2), { - alias: { m: 'mode', h: 'help' }, - string: [ 'mode' ] -}); -if (argv.help) { - fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout); - return; -} - -var paths = argv._.slice(); -var mode = argv.mode ? parseInt(argv.mode, 8) : undefined; - -(function next () { - if (paths.length === 0) return; - var p = paths.shift(); - - if (mode === undefined) mkdirp(p, cb) - else mkdirp(p, mode, cb) - - function cb (err) { - if (err) { - console.error(err.message); - process.exit(1); - } - else next(); - } -})(); diff --git a/node_modules/mocha/node_modules/mkdirp/bin/usage.txt b/node_modules/mocha/node_modules/mkdirp/bin/usage.txt deleted file mode 100644 index f952aa2..0000000 --- a/node_modules/mocha/node_modules/mkdirp/bin/usage.txt +++ /dev/null @@ -1,12 +0,0 @@ -usage: mkdirp [DIR1,DIR2..] {OPTIONS} - - Create each supplied directory including any necessary parent directories that - don't yet exist. - - If the directory already exists, do nothing. - -OPTIONS are: - - -m, --mode If a directory needs to be created, set the mode as an octal - permission string. - diff --git a/node_modules/mocha/node_modules/mkdirp/examples/pow.js b/node_modules/mocha/node_modules/mkdirp/examples/pow.js deleted file mode 100644 index e692421..0000000 --- a/node_modules/mocha/node_modules/mkdirp/examples/pow.js +++ /dev/null @@ -1,6 +0,0 @@ -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') -}); diff --git a/node_modules/mocha/node_modules/mkdirp/index.js b/node_modules/mocha/node_modules/mkdirp/index.js deleted file mode 100644 index a1742b2..0000000 --- a/node_modules/mocha/node_modules/mkdirp/index.js +++ /dev/null @@ -1,97 +0,0 @@ -var path = require('path'); -var fs = require('fs'); - -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = 0777 & (~process.umask()); - } - if (!made) made = null; - - var cb = f || function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - mkdirP(path.dirname(p), opts, function (er, made) { - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); -} - -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = 0777 & (~process.umask()); - } - if (!made) made = null; - - p = path.resolve(p); - - try { - xfs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) { - throw err0; - } - if (!stat.isDirectory()) throw err0; - break; - } - } - - return made; -}; diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/.travis.yml b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/.travis.yml deleted file mode 100644 index cc4dba2..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/LICENSE b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/LICENSE deleted file mode 100644 index ee27ba4..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -This software is released under the MIT license: - -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/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/example/parse.js b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/example/parse.js deleted file mode 100644 index abff3e8..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/example/parse.js +++ /dev/null @@ -1,2 +0,0 @@ -var argv = require('../')(process.argv.slice(2)); -console.dir(argv); diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/index.js b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/index.js deleted file mode 100644 index 584f551..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/index.js +++ /dev/null @@ -1,187 +0,0 @@ -module.exports = function (args, opts) { - if (!opts) opts = {}; - - var flags = { bools : {}, strings : {} }; - - [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { - flags.bools[key] = true; - }); - - [].concat(opts.string).filter(Boolean).forEach(function (key) { - flags.strings[key] = true; - }); - - var aliases = {}; - Object.keys(opts.alias || {}).forEach(function (key) { - aliases[key] = [].concat(opts.alias[key]); - aliases[key].forEach(function (x) { - aliases[x] = [key].concat(aliases[key].filter(function (y) { - return x !== y; - })); - }); - }); - - var defaults = opts['default'] || {}; - - var argv = { _ : [] }; - Object.keys(flags.bools).forEach(function (key) { - setArg(key, defaults[key] === undefined ? false : defaults[key]); - }); - - var notFlags = []; - - if (args.indexOf('--') !== -1) { - notFlags = args.slice(args.indexOf('--')+1); - args = args.slice(0, args.indexOf('--')); - } - - function setArg (key, val) { - var value = !flags.strings[key] && isNumber(val) - ? Number(val) : val - ; - setKey(argv, key.split('.'), value); - - (aliases[key] || []).forEach(function (x) { - setKey(argv, x.split('.'), value); - }); - } - - for (var i = 0; i < args.length; i++) { - var arg = args[i]; - - if (/^--.+=/.test(arg)) { - // Using [\s\S] instead of . because js doesn't support the - // 'dotall' regex modifier. See: - // http://stackoverflow.com/a/1068308/13216 - var m = arg.match(/^--([^=]+)=([\s\S]*)$/); - setArg(m[1], m[2]); - } - else if (/^--no-.+/.test(arg)) { - var key = arg.match(/^--no-(.+)/)[1]; - setArg(key, false); - } - else if (/^--.+/.test(arg)) { - var key = arg.match(/^--(.+)/)[1]; - var next = args[i + 1]; - if (next !== undefined && !/^-/.test(next) - && !flags.bools[key] - && (aliases[key] ? !flags.bools[aliases[key]] : true)) { - setArg(key, next); - i++; - } - else if (/^(true|false)$/.test(next)) { - setArg(key, next === 'true'); - i++; - } - else { - setArg(key, flags.strings[key] ? '' : true); - } - } - else if (/^-[^-]+/.test(arg)) { - var letters = arg.slice(1,-1).split(''); - - var broken = false; - for (var j = 0; j < letters.length; j++) { - var next = arg.slice(j+2); - - if (next === '-') { - setArg(letters[j], next) - continue; - } - - if (/[A-Za-z]/.test(letters[j]) - && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { - setArg(letters[j], next); - broken = true; - break; - } - - if (letters[j+1] && letters[j+1].match(/\W/)) { - setArg(letters[j], arg.slice(j+2)); - broken = true; - break; - } - else { - setArg(letters[j], flags.strings[letters[j]] ? '' : true); - } - } - - var key = arg.slice(-1)[0]; - if (!broken && key !== '-') { - if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1]) - && !flags.bools[key] - && (aliases[key] ? !flags.bools[aliases[key]] : true)) { - setArg(key, args[i+1]); - i++; - } - else if (args[i+1] && /true|false/.test(args[i+1])) { - setArg(key, args[i+1] === 'true'); - i++; - } - else { - setArg(key, flags.strings[key] ? '' : true); - } - } - } - else { - argv._.push( - flags.strings['_'] || !isNumber(arg) ? arg : Number(arg) - ); - } - } - - Object.keys(defaults).forEach(function (key) { - if (!hasKey(argv, key.split('.'))) { - setKey(argv, key.split('.'), defaults[key]); - - (aliases[key] || []).forEach(function (x) { - setKey(argv, x.split('.'), defaults[key]); - }); - } - }); - - notFlags.forEach(function(key) { - argv._.push(key); - }); - - return argv; -}; - -function hasKey (obj, keys) { - var o = obj; - keys.slice(0,-1).forEach(function (key) { - o = (o[key] || {}); - }); - - var key = keys[keys.length - 1]; - return key in o; -} - -function setKey (obj, keys, value) { - var o = obj; - keys.slice(0,-1).forEach(function (key) { - if (o[key] === undefined) o[key] = {}; - o = o[key]; - }); - - var key = keys[keys.length - 1]; - if (o[key] === undefined || typeof o[key] === 'boolean') { - o[key] = value; - } - else if (Array.isArray(o[key])) { - o[key].push(value); - } - else { - o[key] = [ o[key], value ]; - } -} - -function isNumber (x) { - if (typeof x === 'number') return true; - if (/^0x[0-9a-f]+$/i.test(x)) return true; - return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); -} - -function longest (xs) { - return Math.max.apply(null, xs.map(function (x) { return x.length })); -} diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/package.json b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/package.json deleted file mode 100644 index d181aaf..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/package.json +++ /dev/null @@ -1,68 +0,0 @@ -{ - "name": "minimist", - "version": "0.0.8", - "description": "parse argument options", - "main": "index.js", - "devDependencies": { - "tape": "~1.0.4", - "tap": "~0.4.0" - }, - "scripts": { - "test": "tap test/*.js" - }, - "testling": { - "files": "test/*.js", - "browsers": [ - "ie/6..latest", - "ff/5", - "firefox/latest", - "chrome/10", - "chrome/latest", - "safari/5.1", - "safari/latest", - "opera/12" - ] - }, - "repository": { - "type": "git", - "url": "git://github.com/substack/minimist.git" - }, - "homepage": "https://github.com/substack/minimist", - "keywords": [ - "argv", - "getopt", - "parser", - "optimist" - ], - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "license": "MIT", - "bugs": { - "url": "https://github.com/substack/minimist/issues" - }, - "_id": "minimist@0.0.8", - "dist": { - "shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d", - "tarball": "http://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz" - }, - "_from": "minimist@0.0.8", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "substack", - "email": "mail@substack.net" - }, - "maintainers": [ - { - "name": "substack", - "email": "mail@substack.net" - } - ], - "directories": {}, - "_shasum": "857fcabfc3397d2625b8228262e86aa7a011b05d", - "_resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", - "readme": "# minimist\n\nparse argument options\n\nThis module is the guts of optimist's argument parser without all the\nfanciful decoration.\n\n[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist)\n\n[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist)\n\n# example\n\n``` js\nvar argv = require('minimist')(process.argv.slice(2));\nconsole.dir(argv);\n```\n\n```\n$ node example/parse.js -a beep -b boop\n{ _: [], a: 'beep', b: 'boop' }\n```\n\n```\n$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz\n{ _: [ 'foo', 'bar', 'baz' ],\n x: 3,\n y: 4,\n n: 5,\n a: true,\n b: true,\n c: true,\n beep: 'boop' }\n```\n\n# methods\n\n``` js\nvar parseArgs = require('minimist')\n```\n\n## var argv = parseArgs(args, opts={})\n\nReturn an argument object `argv` populated with the array arguments from `args`.\n\n`argv._` contains all the arguments that didn't have an option associated with\nthem.\n\nNumeric-looking arguments will be returned as numbers unless `opts.string` or\n`opts.boolean` is set for that argument name.\n\nAny arguments after `'--'` will not be parsed and will end up in `argv._`.\n\noptions can be:\n\n* `opts.string` - a string or array of strings argument names to always treat as\nstrings\n* `opts.boolean` - a string or array of strings to always treat as booleans\n* `opts.alias` - an object mapping string names to strings or arrays of string\nargument names to use as aliases\n* `opts.default` - an object mapping string argument names to default values\n\n# install\n\nWith [npm](https://npmjs.org) do:\n\n```\nnpm install minimist\n```\n\n# license\n\nMIT\n", - "readmeFilename": "readme.markdown" -} diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/readme.markdown b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/readme.markdown deleted file mode 100644 index c256353..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/readme.markdown +++ /dev/null @@ -1,73 +0,0 @@ -# minimist - -parse argument options - -This module is the guts of optimist's argument parser without all the -fanciful decoration. - -[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist) - -[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist) - -# example - -``` js -var argv = require('minimist')(process.argv.slice(2)); -console.dir(argv); -``` - -``` -$ node example/parse.js -a beep -b boop -{ _: [], a: 'beep', b: 'boop' } -``` - -``` -$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz -{ _: [ 'foo', 'bar', 'baz' ], - x: 3, - y: 4, - n: 5, - a: true, - b: true, - c: true, - beep: 'boop' } -``` - -# methods - -``` js -var parseArgs = require('minimist') -``` - -## var argv = parseArgs(args, opts={}) - -Return an argument object `argv` populated with the array arguments from `args`. - -`argv._` contains all the arguments that didn't have an option associated with -them. - -Numeric-looking arguments will be returned as numbers unless `opts.string` or -`opts.boolean` is set for that argument name. - -Any arguments after `'--'` will not be parsed and will end up in `argv._`. - -options can be: - -* `opts.string` - a string or array of strings argument names to always treat as -strings -* `opts.boolean` - a string or array of strings to always treat as booleans -* `opts.alias` - an object mapping string names to strings or arrays of string -argument names to use as aliases -* `opts.default` - an object mapping string argument names to default values - -# install - -With [npm](https://npmjs.org) do: - -``` -npm install minimist -``` - -# license - -MIT diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/dash.js b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/dash.js deleted file mode 100644 index 8b034b9..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/dash.js +++ /dev/null @@ -1,24 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('-', function (t) { - t.plan(5); - t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] }); - t.deepEqual(parse([ '-' ]), { _: [ '-' ] }); - t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] }); - t.deepEqual( - parse([ '-b', '-' ], { boolean: 'b' }), - { b: true, _: [ '-' ] } - ); - t.deepEqual( - parse([ '-s', '-' ], { string: 's' }), - { s: '-', _: [] } - ); -}); - -test('-a -- b', function (t) { - t.plan(3); - t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] }); - t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); - t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/default_bool.js b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/default_bool.js deleted file mode 100644 index f0041ee..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/default_bool.js +++ /dev/null @@ -1,20 +0,0 @@ -var test = require('tape'); -var parse = require('../'); - -test('boolean default true', function (t) { - var argv = parse([], { - boolean: 'sometrue', - default: { sometrue: true } - }); - t.equal(argv.sometrue, true); - t.end(); -}); - -test('boolean default false', function (t) { - var argv = parse([], { - boolean: 'somefalse', - default: { somefalse: false } - }); - t.equal(argv.somefalse, false); - t.end(); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/dotted.js b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/dotted.js deleted file mode 100644 index ef0ae34..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/dotted.js +++ /dev/null @@ -1,16 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('dotted alias', function (t) { - var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); - t.equal(argv.a.b, 22); - t.equal(argv.aa.bb, 22); - t.end(); -}); - -test('dotted default', function (t) { - var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}}); - t.equal(argv.a.b, 11); - t.equal(argv.aa.bb, 11); - t.end(); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/long.js b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/long.js deleted file mode 100644 index 5d3a1e0..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/long.js +++ /dev/null @@ -1,31 +0,0 @@ -var test = require('tape'); -var parse = require('../'); - -test('long opts', function (t) { - t.deepEqual( - parse([ '--bool' ]), - { bool : true, _ : [] }, - 'long boolean' - ); - t.deepEqual( - parse([ '--pow', 'xixxle' ]), - { pow : 'xixxle', _ : [] }, - 'long capture sp' - ); - t.deepEqual( - parse([ '--pow=xixxle' ]), - { pow : 'xixxle', _ : [] }, - 'long capture eq' - ); - t.deepEqual( - parse([ '--host', 'localhost', '--port', '555' ]), - { host : 'localhost', port : 555, _ : [] }, - 'long captures sp' - ); - t.deepEqual( - parse([ '--host=localhost', '--port=555' ]), - { host : 'localhost', port : 555, _ : [] }, - 'long captures eq' - ); - t.end(); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/parse.js b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/parse.js deleted file mode 100644 index 8a90646..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/parse.js +++ /dev/null @@ -1,318 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('parse args', function (t) { - t.deepEqual( - parse([ '--no-moo' ]), - { moo : false, _ : [] }, - 'no' - ); - t.deepEqual( - parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]), - { v : ['a','b','c'], _ : [] }, - 'multi' - ); - t.end(); -}); - -test('comprehensive', function (t) { - t.deepEqual( - parse([ - '--name=meowmers', 'bare', '-cats', 'woo', - '-h', 'awesome', '--multi=quux', - '--key', 'value', - '-b', '--bool', '--no-meep', '--multi=baz', - '--', '--not-a-flag', 'eek' - ]), - { - c : true, - a : true, - t : true, - s : 'woo', - h : 'awesome', - b : true, - bool : true, - key : 'value', - multi : [ 'quux', 'baz' ], - meep : false, - name : 'meowmers', - _ : [ 'bare', '--not-a-flag', 'eek' ] - } - ); - t.end(); -}); - -test('nums', function (t) { - var argv = parse([ - '-x', '1234', - '-y', '5.67', - '-z', '1e7', - '-w', '10f', - '--hex', '0xdeadbeef', - '789' - ]); - t.deepEqual(argv, { - x : 1234, - y : 5.67, - z : 1e7, - w : '10f', - hex : 0xdeadbeef, - _ : [ 789 ] - }); - t.deepEqual(typeof argv.x, 'number'); - t.deepEqual(typeof argv.y, 'number'); - t.deepEqual(typeof argv.z, 'number'); - t.deepEqual(typeof argv.w, 'string'); - t.deepEqual(typeof argv.hex, 'number'); - t.deepEqual(typeof argv._[0], 'number'); - t.end(); -}); - -test('flag boolean', function (t) { - var argv = parse([ '-t', 'moo' ], { boolean: 't' }); - t.deepEqual(argv, { t : true, _ : [ 'moo' ] }); - t.deepEqual(typeof argv.t, 'boolean'); - t.end(); -}); - -test('flag boolean value', function (t) { - var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], { - boolean: [ 't', 'verbose' ], - default: { verbose: true } - }); - - t.deepEqual(argv, { - verbose: false, - t: true, - _: ['moo'] - }); - - t.deepEqual(typeof argv.verbose, 'boolean'); - t.deepEqual(typeof argv.t, 'boolean'); - t.end(); -}); - -test('flag boolean default false', function (t) { - var argv = parse(['moo'], { - boolean: ['t', 'verbose'], - default: { verbose: false, t: false } - }); - - t.deepEqual(argv, { - verbose: false, - t: false, - _: ['moo'] - }); - - t.deepEqual(typeof argv.verbose, 'boolean'); - t.deepEqual(typeof argv.t, 'boolean'); - t.end(); - -}); - -test('boolean groups', function (t) { - var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], { - boolean: ['x','y','z'] - }); - - t.deepEqual(argv, { - x : true, - y : false, - z : true, - _ : [ 'one', 'two', 'three' ] - }); - - t.deepEqual(typeof argv.x, 'boolean'); - t.deepEqual(typeof argv.y, 'boolean'); - t.deepEqual(typeof argv.z, 'boolean'); - t.end(); -}); - -test('newlines in params' , function (t) { - var args = parse([ '-s', "X\nX" ]) - t.deepEqual(args, { _ : [], s : "X\nX" }); - - // reproduce in bash: - // VALUE="new - // line" - // node program.js --s="$VALUE" - args = parse([ "--s=X\nX" ]) - t.deepEqual(args, { _ : [], s : "X\nX" }); - t.end(); -}); - -test('strings' , function (t) { - var s = parse([ '-s', '0001234' ], { string: 's' }).s; - t.equal(s, '0001234'); - t.equal(typeof s, 'string'); - - var x = parse([ '-x', '56' ], { string: 'x' }).x; - t.equal(x, '56'); - t.equal(typeof x, 'string'); - t.end(); -}); - -test('stringArgs', function (t) { - var s = parse([ ' ', ' ' ], { string: '_' })._; - t.same(s.length, 2); - t.same(typeof s[0], 'string'); - t.same(s[0], ' '); - t.same(typeof s[1], 'string'); - t.same(s[1], ' '); - t.end(); -}); - -test('empty strings', function(t) { - var s = parse([ '-s' ], { string: 's' }).s; - t.equal(s, ''); - t.equal(typeof s, 'string'); - - var str = parse([ '--str' ], { string: 'str' }).str; - t.equal(str, ''); - t.equal(typeof str, 'string'); - - var letters = parse([ '-art' ], { - string: [ 'a', 't' ] - }); - - t.equal(letters.a, ''); - t.equal(letters.r, true); - t.equal(letters.t, ''); - - t.end(); -}); - - -test('slashBreak', function (t) { - t.same( - parse([ '-I/foo/bar/baz' ]), - { I : '/foo/bar/baz', _ : [] } - ); - t.same( - parse([ '-xyz/foo/bar/baz' ]), - { x : true, y : true, z : '/foo/bar/baz', _ : [] } - ); - t.end(); -}); - -test('alias', function (t) { - var argv = parse([ '-f', '11', '--zoom', '55' ], { - alias: { z: 'zoom' } - }); - t.equal(argv.zoom, 55); - t.equal(argv.z, argv.zoom); - t.equal(argv.f, 11); - t.end(); -}); - -test('multiAlias', function (t) { - var argv = parse([ '-f', '11', '--zoom', '55' ], { - alias: { z: [ 'zm', 'zoom' ] } - }); - t.equal(argv.zoom, 55); - t.equal(argv.z, argv.zoom); - t.equal(argv.z, argv.zm); - t.equal(argv.f, 11); - t.end(); -}); - -test('nested dotted objects', function (t) { - var argv = parse([ - '--foo.bar', '3', '--foo.baz', '4', - '--foo.quux.quibble', '5', '--foo.quux.o_O', - '--beep.boop' - ]); - - t.same(argv.foo, { - bar : 3, - baz : 4, - quux : { - quibble : 5, - o_O : true - } - }); - t.same(argv.beep, { boop : true }); - t.end(); -}); - -test('boolean and alias with chainable api', function (t) { - var aliased = [ '-h', 'derp' ]; - var regular = [ '--herp', 'derp' ]; - var opts = { - herp: { alias: 'h', boolean: true } - }; - var aliasedArgv = parse(aliased, { - boolean: 'herp', - alias: { h: 'herp' } - }); - var propertyArgv = parse(regular, { - boolean: 'herp', - alias: { h: 'herp' } - }); - var expected = { - herp: true, - h: true, - '_': [ 'derp' ] - }; - - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -test('boolean and alias with options hash', function (t) { - var aliased = [ '-h', 'derp' ]; - var regular = [ '--herp', 'derp' ]; - var opts = { - alias: { 'h': 'herp' }, - boolean: 'herp' - }; - var aliasedArgv = parse(aliased, opts); - var propertyArgv = parse(regular, opts); - var expected = { - herp: true, - h: true, - '_': [ 'derp' ] - }; - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -test('boolean and alias using explicit true', function (t) { - var aliased = [ '-h', 'true' ]; - var regular = [ '--herp', 'true' ]; - var opts = { - alias: { h: 'herp' }, - boolean: 'h' - }; - var aliasedArgv = parse(aliased, opts); - var propertyArgv = parse(regular, opts); - var expected = { - herp: true, - h: true, - '_': [ ] - }; - - t.same(aliasedArgv, expected); - t.same(propertyArgv, expected); - t.end(); -}); - -// regression, see https://github.com/substack/node-optimist/issues/71 -test('boolean and --x=true', function(t) { - var parsed = parse(['--boool', '--other=true'], { - boolean: 'boool' - }); - - t.same(parsed.boool, true); - t.same(parsed.other, 'true'); - - parsed = parse(['--boool', '--other=false'], { - boolean: 'boool' - }); - - t.same(parsed.boool, true); - t.same(parsed.other, 'false'); - t.end(); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/parse_modified.js b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/parse_modified.js deleted file mode 100644 index 21851b0..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/parse_modified.js +++ /dev/null @@ -1,9 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('parse with modifier functions' , function (t) { - t.plan(1); - - var argv = parse([ '-b', '123' ], { boolean: 'b' }); - t.deepEqual(argv, { b: true, _: ['123'] }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/short.js b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/short.js deleted file mode 100644 index d513a1c..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/short.js +++ /dev/null @@ -1,67 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('numeric short args', function (t) { - t.plan(2); - t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] }); - t.deepEqual( - parse([ '-123', '456' ]), - { 1: true, 2: true, 3: 456, _: [] } - ); -}); - -test('short', function (t) { - t.deepEqual( - parse([ '-b' ]), - { b : true, _ : [] }, - 'short boolean' - ); - t.deepEqual( - parse([ 'foo', 'bar', 'baz' ]), - { _ : [ 'foo', 'bar', 'baz' ] }, - 'bare' - ); - t.deepEqual( - parse([ '-cats' ]), - { c : true, a : true, t : true, s : true, _ : [] }, - 'group' - ); - t.deepEqual( - parse([ '-cats', 'meow' ]), - { c : true, a : true, t : true, s : 'meow', _ : [] }, - 'short group next' - ); - t.deepEqual( - parse([ '-h', 'localhost' ]), - { h : 'localhost', _ : [] }, - 'short capture' - ); - t.deepEqual( - parse([ '-h', 'localhost', '-p', '555' ]), - { h : 'localhost', p : 555, _ : [] }, - 'short captures' - ); - t.end(); -}); - -test('mixed short bool and capture', function (t) { - t.same( - parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), - { - f : true, p : 555, h : 'localhost', - _ : [ 'script.js' ] - } - ); - t.end(); -}); - -test('short and long', function (t) { - t.deepEqual( - parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]), - { - f : true, p : 555, h : 'localhost', - _ : [ 'script.js' ] - } - ); - t.end(); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/whitespace.js b/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/whitespace.js deleted file mode 100644 index 8a52a58..0000000 --- a/node_modules/mocha/node_modules/mkdirp/node_modules/minimist/test/whitespace.js +++ /dev/null @@ -1,8 +0,0 @@ -var parse = require('../'); -var test = require('tape'); - -test('whitespace should be whitespace' , function (t) { - t.plan(1); - var x = parse([ '-x', '\t' ]).x; - t.equal(x, '\t'); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/package.json b/node_modules/mocha/node_modules/mkdirp/package.json deleted file mode 100644 index f209212..0000000 --- a/node_modules/mocha/node_modules/mkdirp/package.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "name": "mkdirp", - "description": "Recursively mkdir, like `mkdir -p`", - "version": "0.5.0", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "main": "./index", - "keywords": [ - "mkdir", - "directory" - ], - "repository": { - "type": "git", - "url": "https://github.com/substack/node-mkdirp.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "dependencies": { - "minimist": "0.0.8" - }, - "devDependencies": { - "tap": "~0.4.0", - "mock-fs": "~2.2.0" - }, - "bin": { - "mkdirp": "bin/cmd.js" - }, - "license": "MIT", - "bugs": { - "url": "https://github.com/substack/node-mkdirp/issues" - }, - "homepage": "https://github.com/substack/node-mkdirp", - "_id": "mkdirp@0.5.0", - "dist": { - "shasum": "1d73076a6df986cd9344e15e71fcc05a4c9abf12", - "tarball": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.0.tgz" - }, - "_from": "mkdirp@0.5.0", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "substack", - "email": "mail@substack.net" - }, - "maintainers": [ - { - "name": "substack", - "email": "mail@substack.net" - } - ], - "directories": {}, - "_shasum": "1d73076a6df986cd9344e15e71fcc05a4c9abf12", - "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.0.tgz", - "readme": "# mkdirp\n\nLike `mkdir -p`, but in node.js!\n\n[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp)\n\n# example\n\n## pow.js\n\n```js\nvar mkdirp = require('mkdirp');\n \nmkdirp('/tmp/foo/bar/baz', function (err) {\n if (err) console.error(err)\n else console.log('pow!')\n});\n```\n\nOutput\n\n```\npow!\n```\n\nAnd now /tmp/foo/bar/baz exists, huzzah!\n\n# methods\n\n```js\nvar mkdirp = require('mkdirp');\n```\n\n## mkdirp(dir, opts, cb)\n\nCreate a new directory and any necessary subdirectories at `dir` with octal\npermission string `opts.mode`. If `opts` is a non-object, it will be treated as\nthe `opts.mode`.\n\nIf `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\n`cb(err, made)` fires with the error or the first directory `made`\nthat had to be created, if any.\n\nYou can optionally pass in an alternate `fs` implementation by passing in\n`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and\n`opts.fs.stat(path, cb)`.\n\n## mkdirp.sync(dir, opts)\n\nSynchronously create a new directory and any necessary subdirectories at `dir`\nwith octal permission string `opts.mode`. If `opts` is a non-object, it will be\ntreated as the `opts.mode`.\n\nIf `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`.\n\nReturns the first directory that had to be created, if any.\n\nYou can optionally pass in an alternate `fs` implementation by passing in\n`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and\n`opts.fs.statSync(path)`.\n\n# usage\n\nThis package also ships with a `mkdirp` command.\n\n```\nusage: mkdirp [DIR1,DIR2..] {OPTIONS}\n\n Create each supplied directory including any necessary parent directories that\n don't yet exist.\n \n If the directory already exists, do nothing.\n\nOPTIONS are:\n\n -m, --mode If a directory needs to be created, set the mode as an octal\n permission string.\n\n```\n\n# install\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install mkdirp\n```\n\nto get the library, or\n\n```\nnpm install -g mkdirp\n```\n\nto get the command.\n\n# license\n\nMIT\n", - "readmeFilename": "readme.markdown" -} diff --git a/node_modules/mocha/node_modules/mkdirp/readme.markdown b/node_modules/mocha/node_modules/mkdirp/readme.markdown deleted file mode 100644 index 3cc1315..0000000 --- a/node_modules/mocha/node_modules/mkdirp/readme.markdown +++ /dev/null @@ -1,100 +0,0 @@ -# mkdirp - -Like `mkdir -p`, but in node.js! - -[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp) - -# example - -## pow.js - -```js -var mkdirp = require('mkdirp'); - -mkdirp('/tmp/foo/bar/baz', function (err) { - if (err) console.error(err) - else console.log('pow!') -}); -``` - -Output - -``` -pow! -``` - -And now /tmp/foo/bar/baz exists, huzzah! - -# methods - -```js -var mkdirp = require('mkdirp'); -``` - -## mkdirp(dir, opts, cb) - -Create a new directory and any necessary subdirectories at `dir` with octal -permission string `opts.mode`. If `opts` is a non-object, it will be treated as -the `opts.mode`. - -If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. - -`cb(err, made)` fires with the error or the first directory `made` -that had to be created, if any. - -You can optionally pass in an alternate `fs` implementation by passing in -`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and -`opts.fs.stat(path, cb)`. - -## mkdirp.sync(dir, opts) - -Synchronously create a new directory and any necessary subdirectories at `dir` -with octal permission string `opts.mode`. If `opts` is a non-object, it will be -treated as the `opts.mode`. - -If `opts.mode` isn't specified, it defaults to `0777 & (~process.umask())`. - -Returns the first directory that had to be created, if any. - -You can optionally pass in an alternate `fs` implementation by passing in -`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and -`opts.fs.statSync(path)`. - -# usage - -This package also ships with a `mkdirp` command. - -``` -usage: mkdirp [DIR1,DIR2..] {OPTIONS} - - Create each supplied directory including any necessary parent directories that - don't yet exist. - - If the directory already exists, do nothing. - -OPTIONS are: - - -m, --mode If a directory needs to be created, set the mode as an octal - permission string. - -``` - -# install - -With [npm](http://npmjs.org) do: - -``` -npm install mkdirp -``` - -to get the library, or - -``` -npm install -g mkdirp -``` - -to get the command. - -# license - -MIT diff --git a/node_modules/mocha/node_modules/mkdirp/test/chmod.js b/node_modules/mocha/node_modules/mkdirp/test/chmod.js deleted file mode 100644 index 520dcb8..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/chmod.js +++ /dev/null @@ -1,38 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -test('chmod-pre', function (t) { - var mode = 0744 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.equal(stat && stat.mode & 0777, mode, 'should be 0744'); - t.end(); - }); - }); -}); - -test('chmod', function (t) { - var mode = 0755 - mkdirp(file, mode, function (er) { - t.ifError(er, 'should not error'); - fs.stat(file, function (er, stat) { - t.ifError(er, 'should exist'); - t.ok(stat && stat.isDirectory(), 'should be directory'); - t.end(); - }); - }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/clobber.js b/node_modules/mocha/node_modules/mkdirp/test/clobber.js deleted file mode 100644 index 0eb7099..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/clobber.js +++ /dev/null @@ -1,37 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -var ps = [ '', 'tmp' ]; - -for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); -} - -var file = ps.join('/'); - -// a file in the way -var itw = ps.slice(0, 3).join('/'); - - -test('clobber-pre', function (t) { - console.error("about to write to "+itw) - fs.writeFileSync(itw, 'I AM IN THE WAY, THE TRUTH, AND THE LIGHT.'); - - fs.stat(itw, function (er, stat) { - t.ifError(er) - t.ok(stat && stat.isFile(), 'should be file') - t.end() - }) -}) - -test('clobber', function (t) { - t.plan(2); - mkdirp(file, 0755, function (err) { - t.ok(err); - t.equal(err.code, 'ENOTDIR'); - t.end(); - }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/mkdirp.js b/node_modules/mocha/node_modules/mkdirp/test/mkdirp.js deleted file mode 100644 index 3b624dd..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/mkdirp.js +++ /dev/null @@ -1,26 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; - -test('woo', function (t) { - t.plan(5); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - t.ifError(err); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }) - }) - }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/opts_fs.js b/node_modules/mocha/node_modules/mkdirp/test/opts_fs.js deleted file mode 100644 index f1fbeca..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/opts_fs.js +++ /dev/null @@ -1,27 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var test = require('tap').test; -var mockfs = require('mock-fs'); - -test('opts.fs', function (t) { - t.plan(5); - - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/beep/boop/' + [x,y,z].join('/'); - var xfs = mockfs.fs(); - - mkdirp(file, { fs: xfs, mode: 0755 }, function (err) { - t.ifError(err); - xfs.exists(file, function (ex) { - t.ok(ex, 'created file'); - xfs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }); - }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/opts_fs_sync.js b/node_modules/mocha/node_modules/mkdirp/test/opts_fs_sync.js deleted file mode 100644 index 224b506..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/opts_fs_sync.js +++ /dev/null @@ -1,25 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var test = require('tap').test; -var mockfs = require('mock-fs'); - -test('opts.fs sync', function (t) { - t.plan(4); - - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/beep/boop/' + [x,y,z].join('/'); - var xfs = mockfs.fs(); - - mkdirp.sync(file, { fs: xfs, mode: 0755 }); - xfs.exists(file, function (ex) { - t.ok(ex, 'created file'); - xfs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/perm.js b/node_modules/mocha/node_modules/mkdirp/test/perm.js deleted file mode 100644 index 2c97590..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/perm.js +++ /dev/null @@ -1,30 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; - -test('async perm', function (t) { - t.plan(5); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16); - - mkdirp(file, 0755, function (err) { - t.ifError(err); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }) - }) - }); -}); - -test('async root perm', function (t) { - mkdirp('/tmp', 0755, function (err) { - if (err) t.fail(err); - t.end(); - }); - t.end(); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/perm_sync.js b/node_modules/mocha/node_modules/mkdirp/test/perm_sync.js deleted file mode 100644 index 327e54b..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/perm_sync.js +++ /dev/null @@ -1,34 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; - -test('sync perm', function (t) { - t.plan(4); - var file = '/tmp/' + (Math.random() * (1<<30)).toString(16) + '.json'; - - mkdirp.sync(file, 0755); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }); -}); - -test('sync root perm', function (t) { - t.plan(3); - - var file = '/tmp'; - mkdirp.sync(file, 0755); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.ok(stat.isDirectory(), 'target not a directory'); - }) - }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/race.js b/node_modules/mocha/node_modules/mkdirp/test/race.js deleted file mode 100644 index 7c295f4..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/race.js +++ /dev/null @@ -1,40 +0,0 @@ -var mkdirp = require('../').mkdirp; -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; - -test('race', function (t) { - t.plan(6); - var ps = [ '', 'tmp' ]; - - for (var i = 0; i < 25; i++) { - var dir = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - ps.push(dir); - } - var file = ps.join('/'); - - var res = 2; - mk(file, function () { - if (--res === 0) t.end(); - }); - - mk(file, function () { - if (--res === 0) t.end(); - }); - - function mk (file, cb) { - mkdirp(file, 0755, function (err) { - t.ifError(err); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - if (cb) cb(); - }); - }) - }); - } -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/rel.js b/node_modules/mocha/node_modules/mkdirp/test/rel.js deleted file mode 100644 index d1f175c..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/rel.js +++ /dev/null @@ -1,30 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; - -test('rel', function (t) { - t.plan(5); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var cwd = process.cwd(); - process.chdir('/tmp'); - - var file = [x,y,z].join('/'); - - mkdirp(file, 0755, function (err) { - t.ifError(err); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - process.chdir(cwd); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }) - }) - }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/return.js b/node_modules/mocha/node_modules/mkdirp/test/return.js deleted file mode 100644 index bce68e5..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/return.js +++ /dev/null @@ -1,25 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('return value', function (t) { - t.plan(4); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - // should return the first dir created. - // By this point, it would be profoundly surprising if /tmp didn't - // already exist, since every other test makes things in there. - mkdirp(file, function (err, made) { - t.ifError(err); - t.equal(made, '/tmp/' + x); - mkdirp(file, function (err, made) { - t.ifError(err); - t.equal(made, null); - }); - }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/return_sync.js b/node_modules/mocha/node_modules/mkdirp/test/return_sync.js deleted file mode 100644 index 7c222d3..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/return_sync.js +++ /dev/null @@ -1,24 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('return value', function (t) { - t.plan(2); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - // should return the first dir created. - // By this point, it would be profoundly surprising if /tmp didn't - // already exist, since every other test makes things in there. - // Note that this will throw on failure, which will fail the test. - var made = mkdirp.sync(file); - t.equal(made, '/tmp/' + x); - - // making the same file again should have no effect. - made = mkdirp.sync(file); - t.equal(made, null); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/root.js b/node_modules/mocha/node_modules/mkdirp/test/root.js deleted file mode 100644 index 97ad7a2..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/root.js +++ /dev/null @@ -1,18 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var test = require('tap').test; - -test('root', function (t) { - // '/' on unix, 'c:/' on windows. - var file = path.resolve('/'); - - mkdirp(file, 0755, function (err) { - if (err) throw err - fs.stat(file, function (er, stat) { - if (er) throw er - t.ok(stat.isDirectory(), 'target is a directory'); - t.end(); - }) - }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/sync.js b/node_modules/mocha/node_modules/mkdirp/test/sync.js deleted file mode 100644 index 88fa432..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/sync.js +++ /dev/null @@ -1,30 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; - -test('sync', function (t) { - t.plan(4); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - try { - mkdirp.sync(file, 0755); - } catch (err) { - t.fail(err); - return t.end(); - } - - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & 0777, 0755); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/umask.js b/node_modules/mocha/node_modules/mkdirp/test/umask.js deleted file mode 100644 index 82c393a..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/umask.js +++ /dev/null @@ -1,26 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; - -test('implicit mode from umask', function (t) { - t.plan(5); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - mkdirp(file, function (err) { - t.ifError(err); - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & 0777, 0777 & (~process.umask())); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }) - }); -}); diff --git a/node_modules/mocha/node_modules/mkdirp/test/umask_sync.js b/node_modules/mocha/node_modules/mkdirp/test/umask_sync.js deleted file mode 100644 index e537fbe..0000000 --- a/node_modules/mocha/node_modules/mkdirp/test/umask_sync.js +++ /dev/null @@ -1,30 +0,0 @@ -var mkdirp = require('../'); -var path = require('path'); -var fs = require('fs'); -var exists = fs.exists || path.exists; -var test = require('tap').test; - -test('umask sync modes', function (t) { - t.plan(4); - var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16); - - var file = '/tmp/' + [x,y,z].join('/'); - - try { - mkdirp.sync(file); - } catch (err) { - t.fail(err); - return t.end(); - } - - exists(file, function (ex) { - t.ok(ex, 'file created'); - fs.stat(file, function (err, stat) { - t.ifError(err); - t.equal(stat.mode & 0777, (0777 & (~process.umask()))); - t.ok(stat.isDirectory(), 'target not a directory'); - }); - }); -}); diff --git a/node_modules/mocha/node_modules/supports-color/cli.js b/node_modules/mocha/node_modules/supports-color/cli.js deleted file mode 100755 index e746987..0000000 --- a/node_modules/mocha/node_modules/supports-color/cli.js +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env node -'use strict'; -var pkg = require('./package.json'); -var supportsColor = require('./'); -var argv = process.argv.slice(2); - -function help() { - console.log([ - '', - ' ' + pkg.description, - '', - ' Usage', - ' supports-color', - '', - ' Exits with code 0 if color is supported and 1 if not' - ].join('\n')); -} - -if (argv.indexOf('--help') !== -1) { - help(); - return; -} - -if (argv.indexOf('--version') !== -1) { - console.log(pkg.version); - return; -} - -process.exit(supportsColor ? 0 : 1); diff --git a/node_modules/mocha/node_modules/supports-color/index.js b/node_modules/mocha/node_modules/supports-color/index.js deleted file mode 100644 index a2b9784..0000000 --- a/node_modules/mocha/node_modules/supports-color/index.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; -var argv = process.argv; - -module.exports = (function () { - if (argv.indexOf('--no-color') !== -1 || - argv.indexOf('--no-colors') !== -1 || - argv.indexOf('--color=false') !== -1) { - return false; - } - - if (argv.indexOf('--color') !== -1 || - argv.indexOf('--colors') !== -1 || - argv.indexOf('--color=true') !== -1 || - argv.indexOf('--color=always') !== -1) { - return true; - } - - if (process.stdout && !process.stdout.isTTY) { - return false; - } - - if (process.platform === 'win32') { - return true; - } - - if ('COLORTERM' in process.env) { - return true; - } - - if (process.env.TERM === 'dumb') { - return false; - } - - if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) { - return true; - } - - return false; -})(); diff --git a/node_modules/mocha/node_modules/supports-color/license b/node_modules/mocha/node_modules/supports-color/license deleted file mode 100644 index 654d0bf..0000000 --- a/node_modules/mocha/node_modules/supports-color/license +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) Sindre Sorhus (sindresorhus.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/node_modules/mocha/node_modules/supports-color/package.json b/node_modules/mocha/node_modules/supports-color/package.json deleted file mode 100644 index bb327e3..0000000 --- a/node_modules/mocha/node_modules/supports-color/package.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "name": "supports-color", - "version": "1.2.1", - "description": "Detect whether a terminal supports color", - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/sindresorhus/supports-color" - }, - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "http://sindresorhus.com" - }, - "maintainers": [ - { - "name": "sindresorhus", - "email": "sindresorhus@gmail.com" - }, - { - "name": "jbnicolai", - "email": "jappelman@xebia.com" - } - ], - "bin": { - "supports-color": "cli.js" - }, - "engines": { - "node": ">=0.8.0" - }, - "scripts": { - "test": "mocha" - }, - "files": [ - "index.js", - "cli.js" - ], - "keywords": [ - "cli", - "bin", - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "ansi", - "styles", - "tty", - "rgb", - "256", - "shell", - "xterm", - "command-line", - "support", - "supports", - "capability", - "detect" - ], - "devDependencies": { - "mocha": "*", - "require-uncached": "^1.0.2" - }, - "gitHead": "ffe5e224bd24dc0410787b94e192d240be025aec", - "bugs": { - "url": "https://github.com/sindresorhus/supports-color/issues" - }, - "homepage": "https://github.com/sindresorhus/supports-color", - "_id": "supports-color@1.2.1", - "_shasum": "12ee21507086cd98c1058d9ec0f4ac476b7af3b2", - "_from": "supports-color@~1.2.0", - "_npmVersion": "2.1.16", - "_nodeVersion": "0.10.35", - "_npmUser": { - "name": "jbnicolai", - "email": "jappelman@xebia.com" - }, - "dist": { - "shasum": "12ee21507086cd98c1058d9ec0f4ac476b7af3b2", - "tarball": "http://registry.npmjs.org/supports-color/-/supports-color-1.2.1.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/supports-color/-/supports-color-1.2.1.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/node_modules/mocha/node_modules/supports-color/readme.md b/node_modules/mocha/node_modules/supports-color/readme.md deleted file mode 100644 index 32d4f46..0000000 --- a/node_modules/mocha/node_modules/supports-color/readme.md +++ /dev/null @@ -1,44 +0,0 @@ -# supports-color [![Build Status](https://travis-ci.org/sindresorhus/supports-color.svg?branch=master)](https://travis-ci.org/sindresorhus/supports-color) - -> Detect whether a terminal supports color - - -## Install - -```sh -$ npm install --save supports-color -``` - - -## Usage - -```js -var supportsColor = require('supports-color'); - -if (supportsColor) { - console.log('Terminal supports color'); -} -``` - -It obeys the `--color` and `--no-color` CLI flags. - - -## CLI - -```sh -$ npm install --global supports-color -``` - -``` -$ supports-color --help - - Usage - supports-color - - Exits with code 0 if color is supported and 1 if not -``` - - -## License - -MIT © [Sindre Sorhus](http://sindresorhus.com) diff --git a/node_modules/mocha/package.json b/node_modules/mocha/package.json deleted file mode 100644 index fd2104f..0000000 --- a/node_modules/mocha/package.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "name": "mocha", - "version": "2.2.5", - "description": "simple, flexible, fun test framework", - "keywords": [ - "mocha", - "test", - "bdd", - "tdd", - "tap" - ], - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "contributors": [ - { - "name": "Joshua Appelman", - "email": "joshua@jbna.nl" - }, - { - "name": "Christoffer Hallas", - "email": "christoffer.hallas@gmail.com" - }, - { - "name": "Christopher Hiller", - "email": "chiller@badwing.com" - }, - { - "name": "Travis Jeffery", - "email": "tj@travisjeffery.com" - }, - { - "name": "Daniel St. Jules", - "email": "danielst.jules@gmail.com" - }, - { - "name": "David da Silva Contín", - "email": "dasilvacontin@gmail.com" - }, - { - "name": "Ariel Mashraki", - "email": "ariel@mashraki.co.il" - }, - { - "name": "Pawel Kozlowski", - "email": "pkozlowski.opensource@gmail.com" - } - ], - "license": "MIT", - "repository": { - "type": "git", - "url": "git://github.com/mochajs/mocha.git" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "travisjeffery", - "email": "tj@travisjeffery.com" - }, - { - "name": "boneskull", - "email": "chiller@badwing.com" - } - ], - "main": "./index", - "browser": "./mocha.js", - "bin": { - "mocha": "./bin/mocha", - "_mocha": "./bin/_mocha" - }, - "engines": { - "node": ">= 0.8.x" - }, - "scripts": { - "test": "make test-all" - }, - "dependencies": { - "commander": "2.3.0", - "debug": "2.0.0", - "diff": "1.4.0", - "escape-string-regexp": "1.0.2", - "glob": "3.2.3", - "growl": "1.8.1", - "jade": "0.26.3", - "mkdirp": "0.5.0", - "supports-color": "~1.2.0" - }, - "devDependencies": { - "coffee-script": "~1.8.0", - "should": "~4.0.0" - }, - "files": [ - "bin", - "images", - "lib", - "index.js", - "mocha.css", - "mocha.js", - "LICENSE" - ], - "licenses": [ - { - "type": "MIT", - "url": "https://raw.github.com/mochajs/mocha/master/LICENSE" - } - ], - "bugs": { - "url": "https://github.com/mochajs/mocha/issues" - }, - "homepage": "https://github.com/mochajs/mocha", - "_id": "mocha@2.2.5", - "_shasum": "d3b72a4fe49ec9439353f1ac893dbc430d993140", - "_from": "mocha@*", - "_npmVersion": "1.4.9", - "_npmUser": { - "name": "travisjeffery", - "email": "tj@travisjeffery.com" - }, - "dist": { - "shasum": "d3b72a4fe49ec9439353f1ac893dbc430d993140", - "tarball": "http://registry.npmjs.org/mocha/-/mocha-2.2.5.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/mocha/-/mocha-2.2.5.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/node_modules/should/.npmignore b/node_modules/should/.npmignore deleted file mode 100644 index 3a32276..0000000 --- a/node_modules/should/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -examples -test \ No newline at end of file diff --git a/node_modules/should/CONTRIBUTING.md b/node_modules/should/CONTRIBUTING.md deleted file mode 100644 index e198247..0000000 --- a/node_modules/should/CONTRIBUTING.md +++ /dev/null @@ -1,9 +0,0 @@ -Before contribute something: - -1. Your code should look like all the other code - this project should look like it was written by one man, always. -2. If you want to propose something - just create an issue and describe your question with as much description as you can. -3. Please never send issues or pull requests about code style, jshint violations etc - I do not accept it (and you will spend your time for free). -4. If you think you have some general improvement, consider creating a pull request with it. -5. If you are not sure whether your improvement is general enough, just create your own plugin for should.js. (see should.use and Assertion.add usage). -6. If you add new code, it should be covered by tests. No tests - no code. -7. If you find a bug (or at least you think it is a bug), create an issue with the library version and test case that I can run and see what are you talking about, or at least full steps by which I can reproduce it. diff --git a/node_modules/should/History.md b/node_modules/should/History.md deleted file mode 100644 index 74fce97..0000000 --- a/node_modules/should/History.md +++ /dev/null @@ -1,256 +0,0 @@ -3.3.2 / 2014-05-23 -================== - - * Fix for should.format - -3.3.1 / 2014-04-16 -================== - - * Added aliases for es reserved words - * Fix bug with ownProperty alias - * Fix bug with not function alias - -3.3.0 / 2014-04-07 -================== - - * Added .enumerable(name, val) - -3.2.0 / 2014-03-29 -================== - - * Added first version of .any modifier that affect assertions with multiple parameters - * .header now have more nice message - * assertion can now override how to show object - -3.1.4 / 2014-03-18 -================== - - * .Error now do not throw assertion error for custom errors. - -3.1.3 / 2014-02-25 -================== - - * Fix TypeError in .containEql - -3.1.2 / 2014-01-28 -================== - - * Fix for adding .inspect for JQuery object only in case when it is exist - -3.1.1 / 2014-01-28 -================== - - * Fix for HTMLElement in DOM less environments - -3.1.0 / 2014-01-23 -================== - - * Added jquery based browser extension - -3.0.1 / 2014-01-17 -================== - - * Fix: .lengthOf() - -3.0.0 / 2014-01-17 -================== - - * Split everything to smaller files - * Added huge extension to .match and .matchEach. Thanks @alsotang for initial code and idea. - * Added .containDeep and .containEql - * Separate build for browser and node.js - * Basic plugin system - * Breaking change: .Object now do not fail on arrays - * Breaking change: Additional messages now replaces generated and do not added - * Breaking change: .keys now check as is - no keys in args means no keys in object - * Deprecated: assert extension - * Deprecated: .include and .includeEql - * Now all assertions define only positive cases, should.js take care about negations and chains - -2.1.1 / 2013-12-05 -================== - - * Move date formatting out of should.inspect - -2.1.0 / 2013-11-11 -================== - - * Override .inspect for Date's to convert them to ISOString - -2.0.2 / 2013-10-21 -================== - - * Add '#of' as getter for chaining. - * Exclude browser script for .npmignore. - -2.0.1 / 2013-10-10 -================== - - * Fix wrong path in .npmignore. - -2.0.0 / 2013-10-10 -================== - - * breaking change: #a now getter like #an. Was replaced with #type(str) - * breaking change: #empty does not check length for objects. Now it check if object do not have own properties. - * #properties check if object have some properties - * util.inspect now exposed as should.inspect - * assertions for NaN, Infinity, Array, Object, String, Boolean, Number, Error, Function - * #equal got alias #exactly - -1.3.0 / 2013-09-13 -================== - - * fix doc for .keys. Closes #108. - * add #endWith() - * add .startWith (#119) - -1.2.2 / 2013-02-19 -================== - - * fix should.be.instanceOf() failure on Date - -1.2.1 / 2012-11-02 -================== - - * add .showDiff - * Make instanceOf and throwError be aliased like others [alFReD-NSH] - * Fix should[.not].exist not having stack trace #84 [alFReD-NSH] - -1.2.0 / 2012-09-21 -================== - - * Added #approximately(value, delta, description) for doing assertions on results of operations with numbers. [titarenko] - -1.1.1 / 2012-09-19 -================== - - * add .type for eql()s assert - -1.1.0 / 2012-07-30 -================== - - * add enclosing of failure message functions. Closes #81 - * add mocha .actual / .expected string support for all assertion values - -0.7.0 / 2012-07-17 -================== - - * add `.throw(Constructor)` support [snakamura] - -0.6.3 / 2012-04-26 -================== - - * Added object inclusion support back - -0.6.2 / 2012-04-26 -================== - - * Added homepage to package.json - * Fixed .equal() with dates. Closes #63 - -0.6.1 / 2012-04-10 -================== - - * package: add "repository" section [TooTallNate] - * use valueOf() to get the reference the object [TooTallNate] - -0.6.0 / 2012-03-01 -================== - - * Added `err.actual` and `err.expected` for .{eql,equal}() - * Added 'return this;' to 'get json' and 'get html' in order to provide chaining for should.be.json and should.be.html - -0.5.1 / 2012-01-13 -================== - - * Added better `.json` - * Added better `.html` - -0.5.0 / 2012-01-12 -================== - - * Added string matching to `.throw()` [serby] - * Added regexp matching to `.throw()` [serby] - * Added `.includeEql()` [RubenVerborgh] - * Added `.should.be.html` - * Added `.should.be.json` - * Added optional description args to most matchers [Mike Swift] - -0.4.2 / 2011-12-17 -================== - - * Fixed .header() for realzzz - -0.4.1 / 2011-12-16 -================== - - * Fixed: chain .header() to retain negation - -0.4.0 / 2011-12-16 -================== - - * Added `.should.throw()` - * Added `.include()` support for strings - * Added `.include()` support for arrays - * Removed `keys()` `.include` modifier support - * Removed `.object()` - * Removed `.string()` - * Removed `.contain()` - * Removed `.respondTo()` rubyism - * expresso -> mocha - -0.3.2 / 2011-10-24 -================== - - * Fixed tests for 0.5.x - * Fixed sys warning - -0.3.1 / 2011-08-22 -================== - - * configurable - -0.3.0 / 2011-08-20 -================== - - * Added assertion for inclusion of an object: `foo.should.include.object({ foo: 'bar' })` - -0.2.1 / 2011-05-13 -================== - - * Fixed .status(code). Closes #18 - -0.2.0 / 2011-04-17 -================== - - * Added `res.should.have.status(code)` method - * Added `res.should.have.header(field, val)` method - -0.1.0 / 2011-04-06 -================== - - * Added `should.exist(obj)` [aseemk] - * Added `should.not.exist(obj)` [aseemk] - -0.0.4 / 2010-11-24 -================== - - * Added `.ok` to assert truthfulness - * Added `.arguments` - * Fixed double required bug. [thanks dominictarr] - -0.0.3 / 2010-11-19 -================== - - * Added `true` / `false` assertions - -0.0.2 / 2010-11-19 -================== - - * Added chaining support - -0.0.1 / 2010-11-19 -================== - - * Initial release diff --git a/node_modules/should/LICENSE b/node_modules/should/LICENSE deleted file mode 100644 index e3fcf59..0000000 --- a/node_modules/should/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010-2014 TJ Holowaychuk - -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. \ No newline at end of file diff --git a/node_modules/should/Makefile b/node_modules/should/Makefile deleted file mode 100644 index b9a2d8f..0000000 --- a/node_modules/should/Makefile +++ /dev/null @@ -1,8 +0,0 @@ -test: - @browserify lib/browser.js -s Should --dg false -o should.js.for-tests - @./node_modules/.bin/mocha --ui exports --reporter mocha-better-spec-reporter 'test/**/*.test.js' - -browser: - @browserify lib/browser.js -s Should --dg false -o should.js - -.PHONY: test browser diff --git a/node_modules/should/Readme.md b/node_modules/should/Readme.md deleted file mode 100644 index 9b983d4..0000000 --- a/node_modules/should/Readme.md +++ /dev/null @@ -1,671 +0,0 @@ -# should.js - -_should_ is an expressive, readable, test framework agnostic, assertion library. Main goals of this library __to be expressive__ and __to be helpful__. It keeps your test code clean, and your error messages helpful. - -It extends the `Object.prototype` with a single non-enumerable getter that allows you to express how that object should behave, also it returns itself when required with `require`. - -## Example -```javascript -var should = require('should'); - -var user = { - name: 'tj' - , pets: ['tobi', 'loki', 'jane', 'bandit'] -}; - -user.should.have.property('name', 'tj'); -user.should.have.property('pets').with.lengthOf(4); - -// if the object was created with Object.create(null) -// then it doesn't inherit `Object` and have the `should` getter -// so you can do: - -should(user).have.property('name', 'tj'); -should(true).ok; - -someAsyncTask(foo, function(err, result){ - should.not.exist(err); - should.exist(result); - result.bar.should.equal(foo); -}); -``` -## To begin - - 1. Install it: - - ```bash - $ npm install should --save-dev - ``` - - 2. Require it and use: - - ```js - var should = require('should'); - - (5).should.be.exactly(5).and.be.a.Number; - ``` - -## In browser - -Well, even when browsers by complains of authors has 100% es5 support, it does not mean it has not bugs. Please see [wiki](https://github.com/visionmedia/should.js/wiki/Known-Bugs) for known bugs. - -If you want to use _should_ in browser, use the `should.js` file in the root of this repository, or build it yourself. It is built with browserify (see [Makefile](https://github.com/visionmedia/should.js/blob/master/Makefile)). To build a fresh version: - -```bash -# you should have browserify -$ npm install -g browserify -$ make browser -``` - -The script is exported to `window.Should`. It is the same as using `should` statically: - -```js -Should(5).be.exactly(5) -``` - -Also, in the case of node.js, `Object.prototype` is extended with `should` (hence the capital S in `window.Should`): - -```js -window.should.be.exactly(window); -// the same -// window is host object -should.be.exactly(window); -// you should not really care about it - -(5).should.be.exactly(5); -``` - -*should.js* uses EcmaScript 5 very extensively so any browser that support ES5 is supported. (IE <=8 not supported). -See [kangax's compat table](http://kangax.github.io/es5-compat-table) to know which exactly. - -You can easy install it with npm or bower: -``` -npm install should --save-dev -# or -bower install visionmedia/should.js -``` - -## Static should and assert module - -For some rare cases should can be used statically, without `Object.prototype`. -It can be a replacement for the node assert module: - -```javascript -assert.fail(actual, expected, message, operator) // just write wrong should assertion -assert(value, message), assert.ok(value, [message]) // should(value).ok -assert.equal(actual, expected, [message]) // should(actual).eql(expected, [message]) -assert.notEqual(actual, expected, [message]) // should(actual).not.eql(expected, [message]) -assert.deepEqual(actual, expected, [message]) // should(actual).eql(expected, [message]) -assert.notDeepEqual(actual, expected, [message]) // should(actual).not.eql(expected, [message]) -assert.strictEqual(actual, expected, [message]) // should(actual).equal(expected, [message]) -assert.notStrictEqual(actual, expected, [message]) // should(actual).not.equal(expected, [message]) -assert.throws(block, [error], [message]) // should(block).throw([error]) -assert.doesNotThrow(block, [message]) // should(block).not.throw([error]) -assert.ifError(value) // should(value).Error (to check if it is error) or should(value).not.ok (to check that it is falsy) -``` - -## .not - -`.not` negate current assertion. - -## .any - -`.any` allow for assertions with multiple parameters to assert on any of parameters (not all) - -# Assertions -## chaining assertions - -Every assertion will return a `should.js`-wrapped Object, so assertions can be chained. -To help chained assertions read more clearly, you can use the following helpers anywhere in your chain: `.an`, `.of`, `.a`, `.and`, `.be`, `.have`, `.with`, `.is`, `.which`. Use them for better readability; they do nothing at all. -For example: -```js -user.should.be.an.instanceOf(Object).and.have.property('name', 'tj'); -user.pets.should.be.instanceof(Array).and.have.lengthOf(4); -``` -Almost all assertions return the same object - so you can easy chain them. But some (eg: `.length` and `.property`) move the assertion object to a property value, so be careful. - -## .ok - -Assert if chained object is truthy in javascript (ie: not '', null, undefined, 0 , NaN). - -Assert truthfulness: - -```javascript -true.should.be.ok; -'yay'.should.be.ok; -(1).should.be.ok; -({}).should.be.ok; -``` - -or negated: - -```javascript -false.should.not.be.ok; -''.should.not.be.ok; -(0).should.not.be.ok; -``` - -*Warning:* No assertions can be done on null and undefined. -e.g. -```js - undefined.should.not.be.ok; -``` -will give you `Uncaught TypeError: Cannot read property 'should' of undefined)`. - -In order to test for null use -```js -(err === null).should.be.true; -``` - -## .true - -Assert if chained object === true: - -```javascript -true.should.be.true; -'1'.should.not.be.true; -``` - -## .false - -Assert if chained object === false: - -```javascript -false.should.be.false; -(0).should.not.be.false; -``` - -## .eql(otherValue) - -Assert if chained object is *equal* to otherValue. The object is compared by its actual content, not just reference equality. - -```javascript -({ foo: 'bar' }).should.eql({ foo: 'bar' }); -[1,2,3].should.eql([1,2,3]); -// see next example it is correct, even if it is different types, but actual content the same -[1, 2, 3].should.eql({ '0': 1, '1': 2, '2': 3 }); -``` -## .equal(otherValue) and .exactly(otherValue) - -Assert if chained object is strictly equal to `otherValue` (using `===` - no type conversion for primitive types and reference equivalence for reference types). - -```javascript -(4).should.equal(4); -'test'.should.equal('test'); -[1,2,3].should.not.equal([1,2,3]); -(4).should.be.exactly(4); -``` - -## .startWith(str) - -Assert that a string starts with `str`. - -```javascript -'foobar'.should.startWith('foo'); -'foobar'.should.not.startWith('bar'); -``` -## .endWith(str) - -Assert that a string ends with `str`. - -```javascript -'foobar'.should.endWith('bar'); -'foobar'.should.not.endWith('foo'); -``` - -## .within(from, to) - -Assert inclusive numeric range (`<= to` and `>= from`): -```javascript -user.age.should.be.within(5, 50); -(5).should.be.within(5, 10).and.within(5, 5); -``` - -## .approximately(num, delta) - -Assert floating point number near `num` within `delta` margin: - -```javascript -(99.99).should.be.approximately(100, 0.1); -``` - -## .above(num) and .greaterThan(num) - -Assert numeric value above the given value (`> num`): - -```javascript -user.age.should.be.above(5); -user.age.should.not.be.above(100); -(5).should.be.above(0); -(5).should.not.be.above(5); -``` - -## .below(num) and .lessThan(num) - -Assert numeric value below the given value (`< num`): - -```javascript -user.age.should.be.below(100); -user.age.should.not.be.below(5); -(5).should.be.below(6); -(5).should.not.be.below(5); -``` - -## .NaN - -Assert numeric value is NaN: - -```javascript -(undefined + 0).should.be.NaN; -``` - -## .Infinity - -Assert numeric value is Infinity: - -```javascript -(1/0).should.be.Infinity; -``` - -## .type(str) - -Assert given object is of a particular type (using __typeof__ operator): -```javascript -user.should.be.type('object'); -'test'.should.be.type('string'); -``` - -## .instanceof(constructor) and .instanceOf(constructor) - -Assert given object is an instance of `constructor` (using __instanceof__ operator): - -```javascript -user.should.be.an.instanceof(User); -[].should.be.an.instanceOf(Array); -``` - -## .arguments - -Assert given object is an `Arguments`: - -```javascript -var args = (function(){ return arguments; })(1,2,3); -args.should.be.arguments; -[].should.not.be.arguments; -``` - -## .Object, .Number, .Array, .Boolean, .Function, .String, .Error - -Assert given object is instance of the given constructor (shortcut for `.instanceof` assertion). - -```javascript -({}).should.be.an.Object; -(1).should.be.a.Number; -[].should.be.an.Array.and.an.Object; -(true).should.be.a.Boolean; -''.should.be.a.String; -``` -## .enumerable(name[, value]) - -Assert a property exists, is enumerable, and has optional value (compare using `.eql`): -```javascript -'asd'.should.not.have.enumerable('0'); -user.should.have.enumerable('name'); -user.should.have.enumerable('age', 15); -user.should.not.have.enumerable('rawr'); -user.should.not.have.enumerable('age', 0); -[1, 2].should.have.enumerable('0', 1); -``` - -## .property(name[, value]) - -Assert property exists and has optional value (compare using `.eql`): -```javascript -user.should.have.property('name'); -user.should.have.property('age', 15); -user.should.not.have.property('rawr'); -user.should.not.have.property('age', 0); -[1, 2].should.have.property('0', 1); -``` - -__NB__ `.property` changes the chain's object to the given property's value, so be careful when chaining after `.property`! - -## .properties(propName1, propName2, ...) or .properties([propName1, propName2, ...]) or .properties(obj) - -`obj` should be an object that maps properties to their actual values. - -Assert all given properties exist and have given values (compare using `.eql`): - -```javascript -user.should.have.properties('name', 'age'); -user.should.have.properties(['name', 'age']); -user.should.have.properties({ - name: 'denis', - age: 24 -}); -``` - -## .length(number) and .lengthOf(number) - -Assert _length_ property exists and has a value of the given number (shortcut for `.property('length', number)`): -```javascript -user.pets.should.have.length(5); -user.pets.should.have.a.lengthOf(5); -({ length: 10}).should.have.length(10); -``` - -__NB__ `.length` and `.lengthOf` change the chain's object to the given length value, so be careful when chaining! - -## .ownProperty(str) and .hasOwnProperty(str) - -Assert given object has own property (using `.hasOwnProperty`): -```javascript -({ foo: 'bar' }).should.have.ownProperty('foo').equal('bar'); -``` - -__NB__ `.ownProperty` and `.hasOwnProperty` change the chain's object to the given property value, so be careful when chaining! - -## .empty - -Assert given value is empty. Strings, arrays, arguments with a length of 0, and objects without their own properties, are considered empty. - -```javascript -[].should.be.empty; -''.should.be.empty; -({}).should.be.empty; -(function() { - arguments.should.be.empty; -})(); -``` - -## .keys([key1, key2, ...]) and .keys(key1, key2, ...) and .key(key) - -Assert own object keys, which must match _exactly_, -and will fail if you omit a key or two: - -```javascript -var obj = { foo: 'bar', baz: 'raz' }; -obj.should.have.keys('foo', 'baz'); -obj.should.have.keys(['foo', 'baz']); -({}).should.have.keys(); -({}).should.have.keys('key'); //fail AssertionError: expected {} to have key 'key'missing keys: 'key' -``` - -## .containEql(otherValue) - -Assert given value to contain something *.eql* to otherValue. See examples to understand better: - -```javascript -'hello boy'.should.containEql('boy'); -[1,2,3].should.containEql(3); -[[1],[2],[3]].should.containEql([3]); -[[1],[2],[3, 4]].should.not.containEql([3]); - -({ b: 10 }).should.containEql({ b: 10 }); -([1, 2, { a: 10 }]).should.containEql({ a: 10 }); -[1, 2, 3].should.not.containEql({ a: 1 }); - -[{a: 'a'}, {b: 'b', c: 'c'}].should.containEql({a: 'a'}); -[{a: 'a'}, {b: 'b', c: 'c'}].should.not.containEql({b: 'b'}); -``` - -When `.containEql` check arrays it check elements to be in the same order in `otherValue` and object just to be presented. - -## .containDeep(otherValue) - -Assert given value to contain something *.eql* to otherValue within depth. -Again see examples: - -```javascript -'hello boy'.should.containDeep('boy'); -[1,2,3].should.containDeep([3]); -[1,2,3].should.containDeep([1, 3]); -//but not -[1,2,3].should.containDeep([3, 1]); - -({ a: { b: 10 }, b: { c: 10, d: 11, a: { b: 10, c: 11} }}).should - .containDeep({ a: { b: 10 }, b: { c: 10, a: { c: 11 }}}); - -[1, 2, 3, { a: { b: { d: 12 }}}].should.containDeep([{ a: { b: {d: 12}}}]); - -[[1],[2],[3]].should.containDeep([[3]]); -[[1],[2],[3, 4]].should.containDeep([[3]]); -[{a: 'a'}, {b: 'b', c: 'c'}].should.containDeep([{a: 'a'}]); -[{a: 'a'}, {b: 'b', c: 'c'}].should.containDeep([{b: 'b'}]); -``` - -It does not search somewhere in depth it check all pattern in depth. Objects are checked -by properties key and value; arrays are checked like sub sequences. Everyting is compared using `.eql`. -Main difference with `.containEql` is that this assertion requires full type chain - -if asserted value is an object, otherValue should be also an object (which is sub object of given). -The same is true for arrays, otherValue should be an array which compared to be subsequence of given object. - -When `.containDeep` check arrays it check elements to be in the same order (as arrays ordered collections) in `otherValue` and object just to be presented. - -## .match(otherValue) - -Assert given object matches `otherValue`. - -Given: String, otherValue: regexp. Uses `RegExp#exec(str)`: -```javascript -username.should.match(/^\w+$/) -``` - -Given: Array, otherValue: regexp - assert each value match to regexp. -```javascript -['a', 'b', 'c'].should.match(/[a-z]/); -['a', 'b', 'c'].should.not.match(/[d-z]/); -``` - -Given: Object, otherValue: regexp - assert own property's values to match regexp. -```javascript -({ a: 'foo', c: 'barfoo' }).should.match(/foo$/); -({ a: 'a' }).should.not.match(/^http/); -``` - -Given: Anything, otherValue: function - assert if given value matched to function. - -Function can use `.should` inside or return 'true' or 'false', in all other cases it do nothing. If you return value that return assertion, you will receive better error messages. - -```javascript -(5).should.match(function(n) { return n > 0; }); -(5).should.not.match(function(n) { return n < 0; }); -(5).should.not.match(function(it) { it.should.be.an.Array; }); -(5).should.match(function(it) { return it.should.be.a.Number; }); -``` - -Now compare messages: -```javascript -(5).should.not.match(function(it) { it.should.be.a.Number; }); -//AssertionError: expected 5 not to match [Function] -(5).should.not.match(function(it) { return it.should.be.a.Number; }); -//AssertionError: expected 5 not to match [Function] -// expected 5 to be a number -``` - -Given: object, otherValue: another object - assert that object properties match to properties of another object in meaning that describe above cases. See examples: - -```javascript -({ a: 10, b: 'abc', c: { d: 10 }, d: 0 }).should - .match({ a: 10, b: /c$/, c: function(it) { return it.should.have.property('d', 10); }}); - -[10, 'abc', { d: 10 }, 0].should - .match({ '0': 10, '1': /c$/, '2': function(it) { return it.should.have.property('d', 10); } }); - -[10, 'abc', { d: 10 }, 0].should - .match([10, /c$/, function(it) { return it.should.have.property('d', 10); }]); -``` - -## .matchEach(otherValue) - -Assert given property keys and values each match given check object. - -If `otherValue` is RegExp, then each property value checked to match it: -```javascript -(['a', 'b', 'c']).should.matchEach(/[a-c]/); -``` - -If `otherValue` is Function, then check each property value and key matched it: -```javascript -[10, 11, 12].should.matchEach(function(it) { return it >= 10; }); -[10, 11, 12].should.matchEach(function(it) { return it >= 10; }); -``` - -In other cases it checks that each property value is `.eql` to `otherValue`: -```javascript -[10, 10].should.matchEach(10); -``` -## .throw() and throwError() - -Assert an exception is thrown: - -```js -(function(){ - throw new Error('fail'); -}).should.throw(); -``` - -Assert an exception is not thrown: - -```js -(function(){ - -}).should.not.throw(); -``` -Assert exception message matches string: - -```js -(function(){ - throw new Error('fail'); -}).should.throw('fail'); -``` - -Assert exepection message matches regexp: - -```js -(function(){ - throw new Error('failed to foo'); -}).should.throw(/^fail/); -``` - -If you need to pass arguments and/or context to execute function use `Function#bind(context, arg1, ...)`: -```js -function isPositive(n) { - if(n <= 0) throw new Error('Given number is not positive') -} - -isPositive.bind(null, 10).should.not.throw(); -isPositive.bind(null, -10).should.throw(); -``` - -If you need to check something in an asynchronous function, you must do it in 2 steps: - -```js -// first we need to check that function is called -var called = false; -collection.findOne({ _id: 10 }, function(err, res) { - called = true; - - //second we test what you want - res.should.be.... -}); - -called.should.be.true; -``` - -In case you are using something like `Mocha`, you should use an asynchronous test, and call `done()` in the proper place to make sure that your asynchronous function is called before the test finishes. -```js -collection.findOne({ _id: 10 }, function(err, res) { - if(err) return done(err); - //second we test what you want - res.should.be.... - - done(); -}); -``` - -In general, if you need to check that something is executed, you are best using `spies`. A good example is [sinon](http://sinonjs.org/). - -## .status(code) - -Asserts that `.statusCode` is `code`: -```javascript -res.should.have.status(200); -``` - -Not included in browser build. - -## .header(field[, value]) - -Asserts that a `.headers` object with `field` and optional `value` are present: -```javascript -res.should.have.header('content-length'); -res.should.have.header('Content-Length', '123'); -``` - -Not included in browser build. - -## .json - -Assert that Content-Type is "application/json; charset=utf-8" - -```javascript -res.should.be.json -``` - -Not included in browser build. - -## .html - -Assert that Content-Type is "text/html; charset=utf-8" -```javascript -res.should.be.html -``` - -Not included in browser build. - -## Optional Error description - -As it can often be difficult to ascertain exactly where failed assertions are coming from in your tests, an optional description parameter can be passed to several should matchers. The description will follow the failed assertion in the error: - - (1).should.eql(0, 'some useful description') - - AssertionError: some useful description - at Object.eql (/Users/swift/code/should.js/node_modules/should/lib/should.js:280:10) - ... - -The methods that support this optional description are: `eql`, `equal`, `within`, `instanceof`, `above`, `below`, `match`, `length`, `property`, `ownProperty`. - -## Mocha example - -For example you can use should with the [Mocha test framework](http://visionmedia.github.io/mocha/) by simply including it: - -```javascript -var should = require('should'); -var mylib = require('mylib'); - - -describe('mylib', function() { - it('should have a version with the format #.#.#', function() { - lib.version.should.match(/^\d+\.\d+\.\d+$/); - }); -}); -``` - -## Contributions - -[Actual list of contributors](https://github.com/visionmedia/should.js/graphs/contributors) if you want to show it your friends. - -To run the tests for _should_ simply run: - - $ make test - -See also [CONTRIBUTING](./CONTRIBUTING.md). - -## OMG IT EXTENDS OBJECT???!?!@ - -Yes, yes it does, with a single getter _should_, and no it won't break your code, because it does this **properly** with a non-enumerable property. - -## License - -MIT © 2010-2014 TJ Holowaychuk diff --git a/node_modules/should/index.js b/node_modules/should/index.js deleted file mode 100644 index 2bb5c33..0000000 --- a/node_modules/should/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/node.js'); \ No newline at end of file diff --git a/node_modules/should/lib/browser.js b/node_modules/should/lib/browser.js deleted file mode 100644 index 4fdb15e..0000000 --- a/node_modules/should/lib/browser.js +++ /dev/null @@ -1,23 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var should = require('./should'); - -should - .use(require('./ext/assert')) - .use(require('./ext/chain')) - .use(require('./ext/bool')) - .use(require('./ext/number')) - .use(require('./ext/eql')) - .use(require('./ext/type')) - .use(require('./ext/string')) - .use(require('./ext/property')) - .use(require('./ext/error')) - .use(require('./ext/match')) - .use(require('./ext/browser/jquery')) - .use(require('./ext/deprecated')); - - module.exports = should; \ No newline at end of file diff --git a/node_modules/should/lib/eql.js b/node_modules/should/lib/eql.js deleted file mode 100644 index 17bd0fd..0000000 --- a/node_modules/should/lib/eql.js +++ /dev/null @@ -1,102 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -// Taken from node's assert module, because it sucks -// and exposes next to nothing useful. -var util = require('./util'); - -module.exports = _deepEqual; - -var pSlice = Array.prototype.slice; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - - -function objEquiv (a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) - return false; - // an identical 'prototype' property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (util.isArguments(a)) { - if (!util.isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try{ - var ka = Object.keys(a), - kb = Object.keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key])) return false; - } - return true; -} diff --git a/node_modules/should/lib/ext/assert.js b/node_modules/should/lib/ext/assert.js deleted file mode 100644 index 9bf436f..0000000 --- a/node_modules/should/lib/ext/assert.js +++ /dev/null @@ -1,57 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util') - , assert = require('assert') - , AssertionError = assert.AssertionError; - -module.exports = function(should) { - var i = should.format; - - /** - * Expose assert to should - * - * This allows you to do things like below - * without require()ing the assert module. - * - * should.equal(foo.bar, undefined); - * - */ - util.merge(should, assert); - - - /** - * Assert _obj_ exists, with optional message. - * - * @param {*} obj - * @param {String} [msg] - * @api public - */ - should.exist = should.exists = function(obj, msg) { - if(null == obj) { - throw new AssertionError({ - message: msg || ('expected ' + i(obj) + ' to exist'), stackStartFunction: should.exist - }); - } - }; - - /** - * Asserts _obj_ does not exist, with optional message. - * - * @param {*} obj - * @param {String} [msg] - * @api public - */ - - should.not = {}; - should.not.exist = should.not.exists = function(obj, msg) { - if(null != obj) { - throw new AssertionError({ - message: msg || ('expected ' + i(obj) + ' to not exist'), stackStartFunction: should.not.exist - }); - } - }; -}; \ No newline at end of file diff --git a/node_modules/should/lib/ext/bool.js b/node_modules/should/lib/ext/bool.js deleted file mode 100644 index c8ca67e..0000000 --- a/node_modules/should/lib/ext/bool.js +++ /dev/null @@ -1,25 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - Assertion.add('true', function() { - this.is.exactly(true); - }, true); - - Assertion.alias('true', 'True'); - - Assertion.add('false', function() { - this.is.exactly(false); - }, true); - - Assertion.alias('false', 'False'); - - Assertion.add('ok', function() { - this.params = { operator: 'to be truthy' }; - - this.assert(this.obj); - }, true); -}; \ No newline at end of file diff --git a/node_modules/should/lib/ext/browser/jquery.js b/node_modules/should/lib/ext/browser/jquery.js deleted file mode 100644 index cf58203..0000000 --- a/node_modules/should/lib/ext/browser/jquery.js +++ /dev/null @@ -1,229 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -/*! - * Portions copyright (c) 2010, 2011, 2012 Wojciech Zawistowski, Travis Jeffery - * From the jasmine-jquery project under the MIT License. - */ - -var util = require('../../util'); - -module.exports = function(should, Assertion) { - var i = should.format; - var $ = this.jQuery || this.$; - - /* Otherwise, node's util.inspect loops hangs */ - if (typeof HTMLElement !== "undefined" && HTMLElement && !HTMLElement.prototype.inspect) { - HTMLElement.prototype.inspect = function () { - return this.outerHTML; - }; - } - - if (typeof jQuery !== "undefined" && jQuery && !jQuery.prototype.inspect) { - jQuery.fn.inspect = function () { - var elementList = this.toArray().map(function (e) { - return util.inspect(e); - }).join(", "); - if (this.selector) { - return "SELECTOR(" + this.selector + ") matching " + this.length + " elements" + (elementList.length ? ": " + elementList : ""); - } else { - return elementList; - } - }; - } - - function jQueryAttributeTestHelper(method, singular, plural, nameOrHash, value) { - var keys = util.isObject(nameOrHash) ? Object.keys(nameOrHash) : [nameOrHash]; - var allRelevantAttributes = keys.reduce(function (memo, key) { - var value = $(this.obj)[method](key); - if (typeof value !== 'undefined') { - memo[key] = value; - } - return memo; - }.bind(this), {}); - - if (arguments.length === 4 && util.isObject(nameOrHash)) { - this.params = { operator: 'to have ' + plural + ' ' + i(nameOrHash) }; - allRelevantAttributes.should.have.properties(nameOrHash); - } else if (arguments.length === 4) { - this.params = { operator: 'to have ' + singular + ' ' + i(nameOrHash) }; - allRelevantAttributes.should.have.property(nameOrHash); - } else { - this.params = { operator: 'to have ' + singular + ' ' + i(nameOrHash) + ' with value ' + i(value) }; - allRelevantAttributes.should.have.property(nameOrHash, value); - } - } - - var browserTagCaseIndependentHtml = function (html) { - return $('
      ').append(html).html(); - }; - - var addJqPredicateAssertion = function (predicate, nameOverride, operatorOverride) { - Assertion.add(nameOverride || predicate, function() { - this.params = { operator: 'to be ' + (operatorOverride || predicate) }; - this.assert($(this.obj).is(':' + predicate)); - }, true); - } - - Assertion.add('className', function(className) { - this.params = { operator: 'to have class ' + className }; - this.assert($(this.obj).hasClass(className)); - }); - - Assertion.add('css', function(css) { - this.params = { operator: 'to have css ' + i(css) }; - for (var prop in css) { - var value = css[prop]; - if (value === 'auto' && $(this.obj).get(0).style[prop] === 'auto') { - continue; - } - $(this.obj).css(prop).should.eql(value); - } - }); - - addJqPredicateAssertion('visible'); - addJqPredicateAssertion('hidden'); - addJqPredicateAssertion('selected'); - addJqPredicateAssertion('checked'); - addJqPredicateAssertion('disabled'); - addJqPredicateAssertion('empty', 'emptyJq'); - addJqPredicateAssertion('focus', 'focused', 'focused'); - - Assertion.add('inDOM', function() { - this.params = { operator: 'to be in the DOM' }; - this.assert($.contains(document.documentElement, $(this.obj)[0])); - }, true); - - Assertion.add('exist', function() { - this.params = { operator: 'to exist' }; - $(this.obj).should.not.have.length(0); - }, true); - - Assertion.add('attr', function() { - var args = [ - 'attr', - 'attribute', - 'attributes' - ].concat(Array.prototype.slice.call(arguments, 0)); - jQueryAttributeTestHelper.apply(this, args); - }); - - Assertion.add('prop', function() { - var args = [ - 'prop', - 'property', - 'properties' - ].concat(Array.prototype.slice.call(arguments, 0)); - jQueryAttributeTestHelper.apply(this, args); - }); - - Assertion.add('elementId', function(id) { - this.params = { operator: 'to have ID ' + i(id) }; - this.obj.should.have.attr('id', id); - }); - - Assertion.add('html', function(html) { - this.params = { operator: 'to have HTML ' + i(html) }; - $(this.obj).html().should.eql(browserTagCaseIndependentHtml(html)); - }); - - Assertion.add('containHtml', function(html) { - this.params = { operator: 'to contain HTML ' + i(html) }; - $(this.obj).html().indexOf(browserTagCaseIndependentHtml(html)).should.be.above(-1); - }); - - Assertion.add('text', function(text) { - this.params = { operator: 'to have text ' + i(text) }; - var trimmedText = $.trim($(this.obj).text()); - - if (util.isRegExp(text)) { - trimmedText.should.match(text); - } else { - trimmedText.should.eql(text); - } - }); - - Assertion.add('containText', function(text) { - this.params = { operator: 'to contain text ' + i(text) }; - var trimmedText = $.trim($(this.obj).text()); - - if (util.isRegExp(text)) { - trimmedText.should.match(text); - } else { - trimmedText.indexOf(text).should.be.above(-1); - } - }); - - Assertion.add('value', function(val) { - this.params = { operator: 'to have value ' + i(val) }; - $(this.obj).val().should.eql(val); - }); - - Assertion.add('data', function() { - var args = [ - 'data', - 'data', - 'data' - ].concat(Array.prototype.slice.call(arguments, 0)); - jQueryAttributeTestHelper.apply(this, args); - }); - - Assertion.add('containElement', function(target) { - this.params = { operator: 'to contain ' + $(target).inspect() }; - $(this.obj).find(target).should.not.have.length(0); - }); - - Assertion.add('matchedBy', function(selector) { - this.params = { operator: 'to be matched by selector ' + selector }; - $(this.obj).filter(selector).should.not.have.length(0); - }); - - Assertion.add('handle', function(event) { - this.params = { operator: 'to handle ' + event }; - - var events = $._data($(this.obj).get(0), "events"); - - if (!events || !event || typeof event !== "string") { - return this.assert(false); - } - - var namespaces = event.split("."), - eventType = namespaces.shift(), - sortedNamespaces = namespaces.slice(0).sort(), - namespaceRegExp = new RegExp("(^|\\.)" + sortedNamespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); - - if (events[eventType] && namespaces.length) { - for (var i = 0; i < events[eventType].length; i++) { - var namespace = events[eventType][i].namespace; - - if (namespaceRegExp.test(namespace)) { - return; - } - } - } else { - events.should.have.property(eventType); - events[eventType].should.not.have.length(0); - return; - } - - this.assert(false); - }); - - Assertion.add('handleWith', function(eventName, eventHandler) { - this.params = { operator: 'to handle ' + eventName + ' with ' + eventHandler }; - - var normalizedEventName = eventName.split('.')[0], - stack = $._data($(this.obj).get(0), "events")[normalizedEventName]; - - for (var i = 0; i < stack.length; i++) { - if (stack[i].handler == eventHandler) { - return; - } - } - - this.assert(false); - }); -}; \ No newline at end of file diff --git a/node_modules/should/lib/ext/chain.js b/node_modules/should/lib/ext/chain.js deleted file mode 100644 index 9812131..0000000 --- a/node_modules/should/lib/ext/chain.js +++ /dev/null @@ -1,18 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - - function addLink(name) { - Object.defineProperty(Assertion.prototype, name, { - get: function() { - return this; - } - }); - } - - ['an', 'of', 'a', 'and', 'be', 'have', 'with', 'is', 'which', 'the'].forEach(addLink); -}; \ No newline at end of file diff --git a/node_modules/should/lib/ext/deprecated.js b/node_modules/should/lib/ext/deprecated.js deleted file mode 100644 index 3656d07..0000000 --- a/node_modules/should/lib/ext/deprecated.js +++ /dev/null @@ -1,33 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util'), - eql = require('../eql'); - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('include', function(obj, description) { - if(!Array.isArray(this.obj) && !util.isString(this.obj)) { - this.params = { operator: 'to include an object equal to ' + i(obj), message: description }; - var cmp = {}; - for(var key in obj) cmp[key] = this.obj[key]; - this.assert(eql(cmp, obj)); - } else { - this.params = { operator: 'to include ' + i(obj), message: description }; - - this.assert(~this.obj.indexOf(obj)); - } - }); - - Assertion.add('includeEql', function(obj, description) { - this.params = { operator: 'to include an object equal to ' + i(obj), message: description }; - - this.assert(this.obj.some(function(item) { - return eql(obj, item); - })); - }); -}; \ No newline at end of file diff --git a/node_modules/should/lib/ext/eql.js b/node_modules/should/lib/ext/eql.js deleted file mode 100644 index e3b03e5..0000000 --- a/node_modules/should/lib/ext/eql.js +++ /dev/null @@ -1,23 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var eql = require('../eql'); - -module.exports = function(should, Assertion) { - Assertion.add('eql', function(val, description) { - this.params = { operator: 'to equal', expected: val, showDiff: true, message: description }; - - this.assert(eql(val, this.obj)); - }); - - Assertion.add('equal', function(val, description) { - this.params = { operator: 'to be', expected: val, showDiff: true, message: description }; - - this.assert(val === this.obj); - }); - - Assertion.alias('equal', 'exactly'); -}; \ No newline at end of file diff --git a/node_modules/should/lib/ext/error.js b/node_modules/should/lib/ext/error.js deleted file mode 100644 index eac98e4..0000000 --- a/node_modules/should/lib/ext/error.js +++ /dev/null @@ -1,51 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('throw', function(message) { - var fn = this.obj - , err = {} - , errorInfo = '' - , ok = true; - - try { - fn(); - ok = false; - } catch(e) { - err = e; - } - - if(ok) { - if('string' == typeof message) { - ok = message == err.message; - } else if(message instanceof RegExp) { - ok = message.test(err.message); - } else if('function' == typeof message) { - ok = err instanceof message; - } - - if(message && !ok) { - if('string' == typeof message) { - errorInfo = " with a message matching '" + message + "', but got '" + err.message + "'"; - } else if(message instanceof RegExp) { - errorInfo = " with a message matching " + message + ", but got '" + err.message + "'"; - } else if('function' == typeof message) { - errorInfo = " of type " + message.name + ", but got " + err.constructor.name; - } - } else { - errorInfo = " (got " + i(err) + ")"; - } - } - - this.params = { operator: 'to throw exception' + errorInfo }; - - this.assert(ok); - }); - - Assertion.alias('throw', 'throwError'); -}; \ No newline at end of file diff --git a/node_modules/should/lib/ext/http.js b/node_modules/should/lib/ext/http.js deleted file mode 100644 index d7aad60..0000000 --- a/node_modules/should/lib/ext/http.js +++ /dev/null @@ -1,39 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ -var util = require('../util'); - -//var statusCodes = require('http').STATUS_CODES; - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('header', function(field, val) { - this.have.property('headers'); - this.params = { obj: '{ ..., headers: ' + i(this.obj) + ', ... }', operator: 'to have header ' + i(field) + (val !== undefined ? (':' + i(val)) : '') }; - if (val !== undefined) { - this.have.property(field.toLowerCase(), val); - } else { - this.have.property(field.toLowerCase()); - } - }); - - Assertion.add('status', function(code) { - //this.params = { operator: 'to have response code ' + code + ' ' + i(statusCodes[code]) - // + ', but got ' + this.obj.statusCode + ' ' + i(statusCodes[this.obj.statusCode]) } - - this.have.property('statusCode', code); - }); - - Assertion.add('json', function() { - this.have.property('headers') - .and.have.property('content-type').include('application/json'); - }, true); - - Assertion.add('html', function() { - this.have.property('headers') - .and.have.property('content-type').include('text/html'); - }, true); -}; \ No newline at end of file diff --git a/node_modules/should/lib/ext/match.js b/node_modules/should/lib/ext/match.js deleted file mode 100644 index f0322ae..0000000 --- a/node_modules/should/lib/ext/match.js +++ /dev/null @@ -1,112 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util'), - eql = require('../eql'); - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('match', function(other, description) { - this.params = { operator: 'to match ' + i(other), message: description }; - - if(!eql(this.obj, other)) { - if(util.isRegExp(other)) { // something - regex - - if(util.isString(this.obj)) { - - this.assert(other.exec(this.obj)); - } else if(Array.isArray(this.obj)) { - - this.obj.forEach(function(item) { - this.assert(other.exec(item));// should we try to convert to String and exec? - }, this); - } else if(util.isObject(this.obj)) { - - var notMatchedProps = [], matchedProps = []; - util.forOwn(this.obj, function(value, name) { - if(other.exec(value)) matchedProps.push(i(name)); - else notMatchedProps.push(i(name)); - }, this); - - if(notMatchedProps.length) - this.params.operator += '\n\tnot matched properties: ' + notMatchedProps.join(', '); - if(matchedProps.length) - this.params.operator += '\n\tmatched properties: ' + matchedProps.join(', '); - - this.assert(notMatchedProps.length == 0); - } // should we try to convert to String and exec? - } else if(util.isFunction(other)) { - var res; - try { - res = other(this.obj); - } catch(e) { - if(e instanceof should.AssertionError) { - this.params.operator += '\n\t' + e.message; - } - throw e; - } - - if(res instanceof Assertion) { - this.params.operator += '\n\t' + res.getMessage(); - } - - //if we throw exception ok - it is used .should inside - if(util.isBoolean(res)) { - this.assert(res); // if it is just boolean function assert on it - } - } else if(util.isObject(other)) { // try to match properties (for Object and Array) - notMatchedProps = []; matchedProps = []; - - util.forOwn(other, function(value, key) { - try { - this.obj[key].should.match(value); - matchedProps.push(key); - } catch(e) { - if(e instanceof should.AssertionError) { - notMatchedProps.push(key); - } else { - throw e; - } - } - }, this); - - if(notMatchedProps.length) - this.params.operator += '\n\tnot matched properties: ' + notMatchedProps.join(', '); - if(matchedProps.length) - this.params.operator += '\n\tmatched properties: ' + matchedProps.join(', '); - - this.assert(notMatchedProps.length == 0); - } else { - this.assert(false); - } - } - }); - - Assertion.add('matchEach', function(other, description) { - this.params = { operator: 'to match each ' + i(other), message: description }; - - var f = other; - - if(util.isRegExp(other)) - f = function(it) { - return !!other.exec(it); - }; - else if(!util.isFunction(other)) - f = function(it) { - return eql(it, other); - }; - - util.forOwn(this.obj, function(value, key) { - var res = f(value, key); - - //if we throw exception ok - it is used .should inside - if(util.isBoolean(res)) { - this.assert(res); // if it is just boolean function assert on it - } - }, this); - }); -}; \ No newline at end of file diff --git a/node_modules/should/lib/ext/number.js b/node_modules/should/lib/ext/number.js deleted file mode 100644 index de449a8..0000000 --- a/node_modules/should/lib/ext/number.js +++ /dev/null @@ -1,49 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - Assertion.add('NaN', function() { - this.params = { operator: 'to be NaN' }; - - this.assert(this.obj !== this.obj); - }, true); - - Assertion.add('Infinity', function() { - this.params = { operator: 'to be Infinity' }; - - this.is.a.Number - .and.not.a.NaN - .and.assert(!isFinite(this.obj)); - }, true); - - Assertion.add('within', function(start, finish, description) { - this.params = { operator: 'to be within ' + start + '..' + finish, message: description }; - - this.assert(this.obj >= start && this.obj <= finish); - }); - - Assertion.add('approximately', function(value, delta, description) { - this.params = { operator: 'to be approximately ' + value + " ±" + delta, message: description }; - - this.assert(Math.abs(this.obj - value) <= delta); - }); - - Assertion.add('above', function(n, description) { - this.params = { operator: 'to be above ' + n, message: description }; - - this.assert(this.obj > n); - }); - - Assertion.add('below', function(n, description) { - this.params = { operator: 'to be below ' + n, message: description }; - - this.assert(this.obj < n); - }); - - Assertion.alias('above', 'greaterThan'); - Assertion.alias('below', 'lessThan'); - -}; diff --git a/node_modules/should/lib/ext/property.js b/node_modules/should/lib/ext/property.js deleted file mode 100644 index 85f2e00..0000000 --- a/node_modules/should/lib/ext/property.js +++ /dev/null @@ -1,236 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util'), - eql = require('../eql'); - -var aSlice = Array.prototype.slice; - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('enumerable', function(name, val) { - this.params = { - operator:"to have enumerable property '"+name+"'" - }; - - this.assert(this.obj.propertyIsEnumerable(name)); - - if(arguments.length > 1){ - this.params.operator += " equal to '"+val+"'"; - this.assert(eql(val, this.obj[name])); - } - }); - - Assertion.add('property', function(name, val) { - if(arguments.length > 1) { - var p = {}; - p[name] = val; - this.have.properties(p); - } else { - this.have.properties(name); - } - this.obj = this.obj[name]; - }); - - Assertion.add('properties', function(names) { - var values = {}; - if(arguments.length > 1) { - names = aSlice.call(arguments); - } else if(!Array.isArray(names)) { - if(util.isString(names)) { - names = [names]; - } else { - values = names; - names = Object.keys(names); - } - } - - var obj = Object(this.obj), missingProperties = []; - - //just enumerate properties and check if they all present - names.forEach(function(name) { - if(!(name in obj)) missingProperties.push(i(name)); - }); - - var props = missingProperties; - if(props.length === 0) { - props = names.map(i); - } else if(this.one) { - props = names.filter(function(name) { - return missingProperties.indexOf(i(name)) < 0; - }).map(i); - } - - var operator = (props.length === 1 ? - 'to have property ' : 'to have '+(this.one? 'any of ' : '')+'properties ') + props.join(', '); - - this.params = { operator: operator }; - - //check that all properties presented - //or if we request one of them that at least one them presented - this.assert(missingProperties.length === 0 || (this.one && missingProperties.length != names.length)); - - // check if values in object matched expected - var valueCheckNames = Object.keys(values); - if(valueCheckNames.length) { - var wrongValues = []; - props = []; - - // now check values, as there we have all properties - valueCheckNames.forEach(function(name) { - var value = values[name]; - if(!eql(obj[name], value)) { - wrongValues.push(i(name) + ' of ' + i(value) + ' (got ' + i(obj[name]) + ')'); - } else { - props.push(i(name) + ' of ' + i(value)); - } - }); - - if((wrongValues.length !== 0 && !this.one) || (this.one && props.length === 0)) { - props = wrongValues; - } - - operator = (props.length === 1 ? - 'to have property ' : 'to have '+(this.one? 'any of ' : '')+'properties ') + props.join(', '); - - this.params = { operator: operator }; - - //if there is no not matched values - //or there is at least one matched - this.assert(wrongValues.length === 0 || (this.one && wrongValues.length != valueCheckNames.length)); - } - }); - - Assertion.add('length', function(n, description) { - this.have.property('length', n, description); - }); - - Assertion.alias('length', 'lengthOf'); - - var hasOwnProperty = Object.prototype.hasOwnProperty; - - Assertion.add('ownProperty', function(name, description) { - this.params = { operator: 'to have own property ' + i(name), message: description }; - - this.assert(hasOwnProperty.call(this.obj, name)); - - this.obj = this.obj[name]; - }); - - Assertion.alias('ownProperty', 'hasOwnProperty'); - - Assertion.add('empty', function() { - this.params = { operator: 'to be empty' }; - - if(util.isString(this.obj) || Array.isArray(this.obj) || util.isArguments(this.obj)) { - this.have.property('length', 0); - } else { - var obj = Object(this.obj); // wrap to reference for booleans and numbers - for(var prop in obj) { - this.have.not.ownProperty(prop); - } - } - }, true); - - Assertion.add('keys', function(keys) { - if(arguments.length > 1) keys = aSlice.call(arguments); - else if(arguments.length === 1 && util.isString(keys)) keys = [ keys ]; - else if(arguments.length === 0) keys = []; - - var obj = Object(this.obj); - - // first check if some keys are missing - var missingKeys = []; - keys.forEach(function(key) { - if(!hasOwnProperty.call(this.obj, key)) - missingKeys.push(i(key)); - }, this); - - // second check for extra keys - var extraKeys = []; - Object.keys(obj).forEach(function(key) { - if(keys.indexOf(key) < 0) { - extraKeys.push(i(key)); - } - }); - - var verb = keys.length === 0 ? 'to be empty' : - 'to have ' + (keys.length === 1 ? 'key ' : 'keys '); - - this.params = { operator: verb + keys.map(i).join(', ')}; - - if(missingKeys.length > 0) - this.params.operator += '\n\tmissing keys: ' + missingKeys.join(', '); - - if(extraKeys.length > 0) - this.params.operator += '\n\textra keys: ' + extraKeys.join(', '); - - this.assert(missingKeys.length === 0 && extraKeys.length === 0); - }); - - Assertion.alias("keys", "key"); - - Assertion.add('containEql', function(other) { - this.params = { operator: 'to contain ' + i(other) }; - var obj = this.obj; - if(Array.isArray(obj)) { - this.assert(obj.some(function(item) { - return eql(item, other); - })); - } else if(util.isString(obj)) { - // expect obj to be string - this.assert(obj.indexOf(String(other)) >= 0); - } else if(util.isObject(obj)) { - // object contains object case - util.forOwn(other, function(value, key) { - obj.should.have.property(key, value); - }); - } else { - //other uncovered cases - this.assert(false); - } - }); - - Assertion.add('containDeep', function(other) { - this.params = { operator: 'to contain ' + i(other) }; - - var obj = this.obj; - if(Array.isArray(obj)) { - if(Array.isArray(other)) { - var otherIdx = 0; - obj.forEach(function(item) { - try { - should(item).not.be.Null.and.containDeep(other[otherIdx]); - otherIdx++; - } catch(e) { - if(e instanceof should.AssertionError) { - return; - } - throw e; - } - }); - this.assert(otherIdx == other.length); - //search array contain other as sub sequence - } else { - this.assert(false); - } - } else if(util.isString(obj)) {// expect other to be string - this.assert(obj.indexOf(String(other)) >= 0); - } else if(util.isObject(obj)) {// object contains object case - if(util.isObject(other)) { - util.forOwn(other, function(value, key) { - should(obj[key]).not.be.Null.and.containDeep(value); - }); - } else {//one of the properties contain value - this.assert(false); - } - } else { - this.eql(other); - } - }); - -}; diff --git a/node_modules/should/lib/ext/string.js b/node_modules/should/lib/ext/string.js deleted file mode 100644 index c3c6fea..0000000 --- a/node_modules/should/lib/ext/string.js +++ /dev/null @@ -1,19 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - Assertion.add('startWith', function(str, description) { - this.params = { operator: 'to start with ' + should.format(str), message: description }; - - this.assert(0 === this.obj.indexOf(str)); - }); - - Assertion.add('endWith', function(str, description) { - this.params = { operator: 'to end with ' + should.format(str), message: description }; - - this.assert(this.obj.indexOf(str, this.obj.length - str.length) >= 0); - }); -}; \ No newline at end of file diff --git a/node_modules/should/lib/ext/type.js b/node_modules/should/lib/ext/type.js deleted file mode 100644 index 5286980..0000000 --- a/node_modules/should/lib/ext/type.js +++ /dev/null @@ -1,79 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util'); - -module.exports = function(should, Assertion) { - Assertion.add('Number', function() { - this.params = { operator: 'to be a number' }; - - this.assert(util.isNumber(this.obj)); - }, true); - - Assertion.add('arguments', function() { - this.params = { operator: 'to be arguments' }; - - this.assert(util.isArguments(this.obj)); - }, true); - - Assertion.add('type', function(type, description) { - this.params = { operator: 'to have type ' + type, message: description }; - - (typeof this.obj).should.be.exactly(type, description); - }); - - Assertion.add('instanceof', function(constructor, description) { - this.params = { operator: 'to be an instance of ' + constructor.name, message: description }; - - this.assert(Object(this.obj) instanceof constructor); - }); - - Assertion.add('Function', function() { - this.params = { operator: 'to be a function' }; - - this.assert(util.isFunction(this.obj)); - }, true); - - Assertion.add('Object', function() { - this.params = { operator: 'to be an object' }; - - this.assert(util.isObject(this.obj)); - }, true); - - Assertion.add('String', function() { - this.params = { operator: 'to be a string' }; - - this.assert(util.isString(this.obj)); - }, true); - - Assertion.add('Array', function() { - this.params = { operator: 'to be an array' }; - - this.assert(Array.isArray(this.obj)); - }, true); - - Assertion.add('Boolean', function() { - this.params = { operator: 'to be a boolean' }; - - this.assert(util.isBoolean(this.obj)); - }, true); - - Assertion.add('Error', function() { - this.params = { operator: 'to be an error' }; - - this.assert(util.isError(this.obj)); - }, true); - - Assertion.add('null', function() { - this.params = { operator: 'to be null' }; - - this.assert(this.obj === null); - }, true); - - Assertion.alias('null', 'Null'); - - Assertion.alias('instanceof', 'instanceOf'); -}; \ No newline at end of file diff --git a/node_modules/should/lib/node.js b/node_modules/should/lib/node.js deleted file mode 100644 index be2b5fb..0000000 --- a/node_modules/should/lib/node.js +++ /dev/null @@ -1,23 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var should = require('./should'); - -should - .use(require('./ext/assert')) - .use(require('./ext/chain')) - .use(require('./ext/bool')) - .use(require('./ext/number')) - .use(require('./ext/eql')) - .use(require('./ext/type')) - .use(require('./ext/string')) - .use(require('./ext/property')) - .use(require('./ext/http')) - .use(require('./ext/error')) - .use(require('./ext/match')) - .use(require('./ext/deprecated')); - - module.exports = should; \ No newline at end of file diff --git a/node_modules/should/lib/should.js b/node_modules/should/lib/should.js deleted file mode 100644 index a71e234..0000000 --- a/node_modules/should/lib/should.js +++ /dev/null @@ -1,182 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - - -var util = require('./util') - , AssertionError = util.AssertionError - , inspect = util.inspect; - -/** - * Our function should - * @param obj - * @returns {Assertion} - */ -var should = function(obj) { - return new Assertion(util.isWrapperType(obj) ? obj.valueOf(): obj); -}; - -/** - * Initialize a new `Assertion` with the given _obj_. - * - * @param {*} obj - * @api private - */ - -var Assertion = should.Assertion = function Assertion(obj) { - this.obj = obj; -}; - - -/** - Way to extend Assertion function. It uses some logic - to define only positive assertions and itself rule with negative assertion. - - All actions happen in subcontext and this method take care about negation. - Potentially we can add some more modifiers that does not depends from state of assertion. -*/ -Assertion.add = function(name, f, isGetter) { - var prop = {}; - prop[isGetter ? 'get' : 'value'] = function() { - var context = new Assertion(this.obj); - context.copy = context.copyIfMissing; - context.one = this.one; - - try { - f.apply(context, arguments); - } catch(e) { - //copy data from sub context to this - this.copy(context); - - //check for fail - if(e instanceof should.AssertionError) { - //negative fail - if(this.negate) { - this.obj = context.obj; - this.negate = false; - return this; - } - this.assert(false); - } - // throw if it is another exception - throw e; - } - //copy data from sub context to this - this.copy(context); - if(this.negate) { - this.assert(false); - } - - this.obj = context.obj; - this.negate = false; - return this; - }; - - Object.defineProperty(Assertion.prototype, name, prop); -}; - -Assertion.alias = function(from, to) { - var desc = Object.getOwnPropertyDescriptor(Assertion.prototype, from); - if(!desc) throw new Error('Alias ' + from + ' -> ' + to + ' could not be created as ' + from + ' not defined'); - Object.defineProperty(Assertion.prototype, to, desc); -}; - -should.AssertionError = AssertionError; -should.format = function (value) { - if(util.isDate(value) && typeof value.inspect !== 'function') return value.toISOString(); //show millis in dates - return inspect(value, { depth: null }); -}; - -should.use = function(f) { - f(this, Assertion); - return this; -}; - - -/** - * Expose should to external world. - */ -exports = module.exports = should; - - -/** - * Expose api via `Object#should`. - * - * @api public - */ - -Object.defineProperty(Object.prototype, 'should', { - set: function(){}, - get: function(){ - return should(this); - }, - configurable: true -}); - - -Assertion.prototype = { - constructor: Assertion, - - assert: function(expr) { - if(expr) return; - - var params = this.params; - - var msg = params.message, generatedMessage = false; - if(!msg) { - msg = this.getMessage(); - generatedMessage = true; - } - - var err = new AssertionError({ - message: msg - , actual: this.obj - , expected: params.expected - , stackStartFunction: this.assert - }); - - err.showDiff = params.showDiff; - err.operator = params.operator; - err.generatedMessage = generatedMessage; - - throw err; - }, - - getMessage: function() { - return 'expected ' + ('obj' in this.params ? this.params.obj: should.format(this.obj)) + (this.negate ? ' not ': ' ') + - this.params.operator + ('expected' in this.params ? ' ' + should.format(this.params.expected) : ''); - }, - - copy: function(other) { - this.params = other.params; - }, - - copyIfMissing: function(other) { - if(!this.params) this.params = other.params; - }, - - - /** - * Negation modifier. - * - * @api public - */ - - get not() { - this.negate = !this.negate; - return this; - }, - - /** - * Any modifier - it affect on execution of sequenced assertion to do not check all, but any of - * - * @api public - */ - get any() { - this.one = true; - return this; - } -}; - diff --git a/node_modules/should/lib/util.js b/node_modules/should/lib/util.js deleted file mode 100644 index 33bca93..0000000 --- a/node_modules/should/lib/util.js +++ /dev/null @@ -1,119 +0,0 @@ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Check if given obj just a primitive type wrapper - * @param {Object} obj - * @returns {boolean} - * @api private - */ -exports.isWrapperType = function(obj) { - return isNumber(obj) || isString(obj) || isBoolean(obj); -}; - -/** - * Merge object b with object a. - * - * var a = { foo: 'bar' } - * , b = { bar: 'baz' }; - * - * utils.merge(a, b); - * // => { foo: 'bar', bar: 'baz' } - * - * @param {Object} a - * @param {Object} b - * @return {Object} - * @api private - */ - -exports.merge = function(a, b){ - if (a && b) { - for (var key in b) { - a[key] = b[key]; - } - } - return a; -}; - -function isNumber(arg) { - return typeof arg === 'number' || arg instanceof Number; -} - -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string' || arg instanceof String; -} - -function isBoolean(arg) { - return typeof arg === 'boolean' || arg instanceof Boolean; -} -exports.isBoolean = isBoolean; - -exports.isString = isString; - -function isBuffer(arg) { - return typeof Buffer !== 'undefined' && arg instanceof Buffer; -} - -exports.isBuffer = isBuffer; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} - -exports.isDate = isDate; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -exports.isObject = isObject; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} - -exports.isRegExp = isRegExp; - -function isNullOrUndefined(arg) { - return arg == null; -} - -exports.isNullOrUndefined = isNullOrUndefined; - -function isArguments(object) { - return objectToString(object) === '[object Arguments]'; -} - -exports.isArguments = isArguments; - -exports.isFunction = function(arg) { - return typeof arg === 'function' || arg instanceof Function; -}; - -function isError(e) { - return (isObject(e) && objectToString(e) === '[object Error]') || (e instanceof Error); -} -exports.isError = isError; - -exports.inspect = require('util').inspect; - -exports.AssertionError = require('assert').AssertionError; - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -exports.forOwn = function(obj, f, context) { - for(var prop in obj) { - if(hasOwnProperty.call(obj, prop)) { - f.call(context, obj[prop], prop); - } - } -}; \ No newline at end of file diff --git a/node_modules/should/package.json b/node_modules/should/package.json deleted file mode 100644 index 6f581c2..0000000 --- a/node_modules/should/package.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "name": "should", - "description": "test framework agnostic BDD-style assertions", - "version": "3.3.2", - "author": { - "name": "TJ Holowaychuk", - "email": "tj@vision-media.ca" - }, - "repository": { - "type": "git", - "url": "git://github.com/visionmedia/should.js.git" - }, - "homepage": "https://github.com/visionmedia/should.js", - "scripts": { - "test": "make test" - }, - "devDependencies": { - "browserify": "*", - "mocha": "*", - "jsdom": "*", - "jquery": "*", - "mocha-better-spec-reporter": "0.0.2" - }, - "keywords": [ - "test", - "bdd", - "assert" - ], - "main": "./lib/node.js", - "bugs": { - "url": "https://github.com/visionmedia/should.js/issues" - }, - "_id": "should@3.3.2", - "dist": { - "shasum": "c883dd409b53bbdf1b55ec0d8fc3865f2b287e64", - "tarball": "http://registry.npmjs.org/should/-/should-3.3.2.tgz" - }, - "_from": "should@3.3.2", - "_npmVersion": "1.4.3", - "_npmUser": { - "name": "btd", - "email": "bardadymchik@gmail.com" - }, - "maintainers": [ - { - "name": "tjholowaychuk", - "email": "tj@vision-media.ca" - }, - { - "name": "gjohnson", - "email": "gjj391@gmail.com" - }, - { - "name": "travisjeffery", - "email": "tj@travisjeffery.com" - }, - { - "name": "btd", - "email": "bardadymchik@gmail.com" - } - ], - "directories": {}, - "_shasum": "c883dd409b53bbdf1b55ec0d8fc3865f2b287e64", - "_resolved": "https://registry.npmjs.org/should/-/should-3.3.2.tgz", - "readme": "# should.js\n\n_should_ is an expressive, readable, test framework agnostic, assertion library. Main goals of this library __to be expressive__ and __to be helpful__. It keeps your test code clean, and your error messages helpful.\n\nIt extends the `Object.prototype` with a single non-enumerable getter that allows you to express how that object should behave, also it returns itself when required with `require`.\n\n## Example\n```javascript\nvar should = require('should');\n\nvar user = {\n name: 'tj'\n , pets: ['tobi', 'loki', 'jane', 'bandit']\n};\n\nuser.should.have.property('name', 'tj');\nuser.should.have.property('pets').with.lengthOf(4);\n\n// if the object was created with Object.create(null)\n// then it doesn't inherit `Object` and have the `should` getter\n// so you can do:\n\nshould(user).have.property('name', 'tj');\nshould(true).ok;\n\nsomeAsyncTask(foo, function(err, result){\n should.not.exist(err);\n should.exist(result);\n result.bar.should.equal(foo);\n});\n```\n## To begin\n\n 1. Install it:\n\n ```bash\n $ npm install should --save-dev\n ```\n\n 2. Require it and use:\n\n ```js\n var should = require('should');\n\n (5).should.be.exactly(5).and.be.a.Number;\n ```\n\n## In browser\n\nWell, even when browsers by complains of authors has 100% es5 support, it does not mean it has not bugs. Please see [wiki](https://github.com/visionmedia/should.js/wiki/Known-Bugs) for known bugs.\n\nIf you want to use _should_ in browser, use the `should.js` file in the root of this repository, or build it yourself. It is built with browserify (see [Makefile](https://github.com/visionmedia/should.js/blob/master/Makefile)). To build a fresh version:\n\n```bash\n# you should have browserify\n$ npm install -g browserify\n$ make browser\n```\n\nThe script is exported to `window.Should`. It is the same as using `should` statically:\n\n```js\nShould(5).be.exactly(5)\n```\n\nAlso, in the case of node.js, `Object.prototype` is extended with `should` (hence the capital S in `window.Should`):\n\n```js\nwindow.should.be.exactly(window);\n// the same\n// window is host object\nshould.be.exactly(window);\n// you should not really care about it\n\n(5).should.be.exactly(5);\n```\n\n*should.js* uses EcmaScript 5 very extensively so any browser that support ES5 is supported. (IE <=8 not supported).\nSee [kangax's compat table](http://kangax.github.io/es5-compat-table) to know which exactly.\n\nYou can easy install it with npm or bower:\n```\nnpm install should --save-dev\n# or\nbower install visionmedia/should.js\n```\n\n## Static should and assert module\n\nFor some rare cases should can be used statically, without `Object.prototype`.\nIt can be a replacement for the node assert module:\n\n```javascript\nassert.fail(actual, expected, message, operator) // just write wrong should assertion\nassert(value, message), assert.ok(value, [message]) // should(value).ok\nassert.equal(actual, expected, [message]) // should(actual).eql(expected, [message])\nassert.notEqual(actual, expected, [message]) // should(actual).not.eql(expected, [message])\nassert.deepEqual(actual, expected, [message]) // should(actual).eql(expected, [message])\nassert.notDeepEqual(actual, expected, [message]) // should(actual).not.eql(expected, [message])\nassert.strictEqual(actual, expected, [message]) // should(actual).equal(expected, [message])\nassert.notStrictEqual(actual, expected, [message]) // should(actual).not.equal(expected, [message])\nassert.throws(block, [error], [message]) // should(block).throw([error])\nassert.doesNotThrow(block, [message]) // should(block).not.throw([error])\nassert.ifError(value) // should(value).Error (to check if it is error) or should(value).not.ok (to check that it is falsy)\n```\n\n## .not\n\n`.not` negate current assertion.\n\n## .any\n\n`.any` allow for assertions with multiple parameters to assert on any of parameters (not all)\n\n# Assertions\n## chaining assertions\n\nEvery assertion will return a `should.js`-wrapped Object, so assertions can be chained.\nTo help chained assertions read more clearly, you can use the following helpers anywhere in your chain: `.an`, `.of`, `.a`, `.and`, `.be`, `.have`, `.with`, `.is`, `.which`. Use them for better readability; they do nothing at all.\nFor example:\n```js\nuser.should.be.an.instanceOf(Object).and.have.property('name', 'tj');\nuser.pets.should.be.instanceof(Array).and.have.lengthOf(4);\n```\nAlmost all assertions return the same object - so you can easy chain them. But some (eg: `.length` and `.property`) move the assertion object to a property value, so be careful.\n\n## .ok\n\nAssert if chained object is truthy in javascript (ie: not '', null, undefined, 0 , NaN).\n\nAssert truthfulness:\n\n```javascript\ntrue.should.be.ok;\n'yay'.should.be.ok;\n(1).should.be.ok;\n({}).should.be.ok;\n```\n\nor negated:\n\n```javascript\nfalse.should.not.be.ok;\n''.should.not.be.ok;\n(0).should.not.be.ok;\n```\n\n*Warning:* No assertions can be done on null and undefined.\ne.g.\n```js\n undefined.should.not.be.ok;\n```\nwill give you `Uncaught TypeError: Cannot read property 'should' of undefined)`.\n\nIn order to test for null use\n```js\n(err === null).should.be.true;\n```\n\n## .true\n\nAssert if chained object === true:\n\n```javascript\ntrue.should.be.true;\n'1'.should.not.be.true;\n```\n\n## .false\n\nAssert if chained object === false:\n\n```javascript\nfalse.should.be.false;\n(0).should.not.be.false;\n```\n\n## .eql(otherValue)\n\nAssert if chained object is *equal* to otherValue. The object is compared by its actual content, not just reference equality.\n\n```javascript\n({ foo: 'bar' }).should.eql({ foo: 'bar' });\n[1,2,3].should.eql([1,2,3]);\n// see next example it is correct, even if it is different types, but actual content the same\n[1, 2, 3].should.eql({ '0': 1, '1': 2, '2': 3 });\n```\n## .equal(otherValue) and .exactly(otherValue)\n\nAssert if chained object is strictly equal to `otherValue` (using `===` - no type conversion for primitive types and reference equivalence for reference types).\n\n```javascript\n(4).should.equal(4);\n'test'.should.equal('test');\n[1,2,3].should.not.equal([1,2,3]);\n(4).should.be.exactly(4);\n```\n\n## .startWith(str)\n\nAssert that a string starts with `str`.\n\n```javascript\n'foobar'.should.startWith('foo');\n'foobar'.should.not.startWith('bar');\n```\n## .endWith(str)\n\nAssert that a string ends with `str`.\n\n```javascript\n'foobar'.should.endWith('bar');\n'foobar'.should.not.endWith('foo');\n```\n\n## .within(from, to)\n\nAssert inclusive numeric range (`<= to` and `>= from`):\n```javascript\nuser.age.should.be.within(5, 50);\n(5).should.be.within(5, 10).and.within(5, 5);\n```\n\n## .approximately(num, delta)\n\nAssert floating point number near `num` within `delta` margin:\n\n```javascript\n(99.99).should.be.approximately(100, 0.1);\n```\n\n## .above(num) and .greaterThan(num)\n\nAssert numeric value above the given value (`> num`):\n\n```javascript\nuser.age.should.be.above(5);\nuser.age.should.not.be.above(100);\n(5).should.be.above(0);\n(5).should.not.be.above(5);\n```\n\n## .below(num) and .lessThan(num)\n\nAssert numeric value below the given value (`< num`):\n\n```javascript\nuser.age.should.be.below(100);\nuser.age.should.not.be.below(5);\n(5).should.be.below(6);\n(5).should.not.be.below(5);\n```\n\n## .NaN\n\nAssert numeric value is NaN:\n\n```javascript\n(undefined + 0).should.be.NaN;\n```\n\n## .Infinity\n\nAssert numeric value is Infinity:\n\n```javascript\n(1/0).should.be.Infinity;\n```\n\n## .type(str)\n\nAssert given object is of a particular type (using __typeof__ operator):\n```javascript\nuser.should.be.type('object');\n'test'.should.be.type('string');\n```\n\n## .instanceof(constructor) and .instanceOf(constructor)\n\nAssert given object is an instance of `constructor` (using __instanceof__ operator):\n\n```javascript\nuser.should.be.an.instanceof(User);\n[].should.be.an.instanceOf(Array);\n```\n\n## .arguments\n\nAssert given object is an `Arguments`:\n\n```javascript\nvar args = (function(){ return arguments; })(1,2,3);\nargs.should.be.arguments;\n[].should.not.be.arguments;\n```\n\n## .Object, .Number, .Array, .Boolean, .Function, .String, .Error\n\nAssert given object is instance of the given constructor (shortcut for `.instanceof` assertion).\n\n```javascript\n({}).should.be.an.Object;\n(1).should.be.a.Number;\n[].should.be.an.Array.and.an.Object;\n(true).should.be.a.Boolean;\n''.should.be.a.String;\n```\n## .enumerable(name[, value])\n\nAssert a property exists, is enumerable, and has optional value (compare using `.eql`):\n```javascript\n'asd'.should.not.have.enumerable('0');\nuser.should.have.enumerable('name');\nuser.should.have.enumerable('age', 15);\nuser.should.not.have.enumerable('rawr');\nuser.should.not.have.enumerable('age', 0);\n[1, 2].should.have.enumerable('0', 1);\n```\n\n## .property(name[, value])\n\nAssert property exists and has optional value (compare using `.eql`):\n```javascript\nuser.should.have.property('name');\nuser.should.have.property('age', 15);\nuser.should.not.have.property('rawr');\nuser.should.not.have.property('age', 0);\n[1, 2].should.have.property('0', 1);\n```\n\n__NB__ `.property` changes the chain's object to the given property's value, so be careful when chaining after `.property`!\n\n## .properties(propName1, propName2, ...) or .properties([propName1, propName2, ...]) or .properties(obj)\n\n`obj` should be an object that maps properties to their actual values.\n\nAssert all given properties exist and have given values (compare using `.eql`):\n\n```javascript\nuser.should.have.properties('name', 'age');\nuser.should.have.properties(['name', 'age']);\nuser.should.have.properties({\n name: 'denis',\n age: 24\n});\n```\n\n## .length(number) and .lengthOf(number)\n\nAssert _length_ property exists and has a value of the given number (shortcut for `.property('length', number)`):\n```javascript\nuser.pets.should.have.length(5);\nuser.pets.should.have.a.lengthOf(5);\n({ length: 10}).should.have.length(10);\n```\n\n__NB__ `.length` and `.lengthOf` change the chain's object to the given length value, so be careful when chaining!\n\n## .ownProperty(str) and .hasOwnProperty(str)\n\nAssert given object has own property (using `.hasOwnProperty`):\n```javascript\n({ foo: 'bar' }).should.have.ownProperty('foo').equal('bar');\n```\n\n__NB__ `.ownProperty` and `.hasOwnProperty` change the chain's object to the given property value, so be careful when chaining!\n\n## .empty\n\nAssert given value is empty. Strings, arrays, arguments with a length of 0, and objects without their own properties, are considered empty.\n\n```javascript\n[].should.be.empty;\n''.should.be.empty;\n({}).should.be.empty;\n(function() {\n arguments.should.be.empty;\n})();\n```\n\n## .keys([key1, key2, ...]) and .keys(key1, key2, ...) and .key(key)\n\nAssert own object keys, which must match _exactly_,\nand will fail if you omit a key or two:\n\n```javascript\nvar obj = { foo: 'bar', baz: 'raz' };\nobj.should.have.keys('foo', 'baz');\nobj.should.have.keys(['foo', 'baz']);\n({}).should.have.keys();\n({}).should.have.keys('key'); //fail AssertionError: expected {} to have key 'key'missing keys: 'key'\n```\n\n## .containEql(otherValue)\n\nAssert given value to contain something *.eql* to otherValue. See examples to understand better:\n\n```javascript\n'hello boy'.should.containEql('boy');\n[1,2,3].should.containEql(3);\n[[1],[2],[3]].should.containEql([3]);\n[[1],[2],[3, 4]].should.not.containEql([3]);\n\n({ b: 10 }).should.containEql({ b: 10 });\n([1, 2, { a: 10 }]).should.containEql({ a: 10 });\n[1, 2, 3].should.not.containEql({ a: 1 });\n\n[{a: 'a'}, {b: 'b', c: 'c'}].should.containEql({a: 'a'});\n[{a: 'a'}, {b: 'b', c: 'c'}].should.not.containEql({b: 'b'});\n```\n\nWhen `.containEql` check arrays it check elements to be in the same order in `otherValue` and object just to be presented.\n\n## .containDeep(otherValue)\n\nAssert given value to contain something *.eql* to otherValue within depth.\nAgain see examples:\n\n```javascript\n'hello boy'.should.containDeep('boy');\n[1,2,3].should.containDeep([3]);\n[1,2,3].should.containDeep([1, 3]);\n//but not\n[1,2,3].should.containDeep([3, 1]);\n\n({ a: { b: 10 }, b: { c: 10, d: 11, a: { b: 10, c: 11} }}).should\n .containDeep({ a: { b: 10 }, b: { c: 10, a: { c: 11 }}});\n\n[1, 2, 3, { a: { b: { d: 12 }}}].should.containDeep([{ a: { b: {d: 12}}}]);\n\n[[1],[2],[3]].should.containDeep([[3]]);\n[[1],[2],[3, 4]].should.containDeep([[3]]);\n[{a: 'a'}, {b: 'b', c: 'c'}].should.containDeep([{a: 'a'}]);\n[{a: 'a'}, {b: 'b', c: 'c'}].should.containDeep([{b: 'b'}]);\n```\n\nIt does not search somewhere in depth it check all pattern in depth. Objects are checked\nby properties key and value; arrays are checked like sub sequences. Everyting is compared using `.eql`.\nMain difference with `.containEql` is that this assertion requires full type chain -\nif asserted value is an object, otherValue should be also an object (which is sub object of given).\nThe same is true for arrays, otherValue should be an array which compared to be subsequence of given object.\n\nWhen `.containDeep` check arrays it check elements to be in the same order (as arrays ordered collections) in `otherValue` and object just to be presented.\n\n## .match(otherValue)\n\nAssert given object matches `otherValue`.\n\nGiven: String, otherValue: regexp. Uses `RegExp#exec(str)`:\n```javascript\nusername.should.match(/^\\w+$/)\n```\n\nGiven: Array, otherValue: regexp - assert each value match to regexp.\n```javascript\n['a', 'b', 'c'].should.match(/[a-z]/);\n['a', 'b', 'c'].should.not.match(/[d-z]/);\n```\n\nGiven: Object, otherValue: regexp - assert own property's values to match regexp.\n```javascript\n({ a: 'foo', c: 'barfoo' }).should.match(/foo$/);\n({ a: 'a' }).should.not.match(/^http/);\n```\n\nGiven: Anything, otherValue: function - assert if given value matched to function.\n\nFunction can use `.should` inside or return 'true' or 'false', in all other cases it do nothing. If you return value that return assertion, you will receive better error messages.\n\n```javascript\n(5).should.match(function(n) { return n > 0; });\n(5).should.not.match(function(n) { return n < 0; });\n(5).should.not.match(function(it) { it.should.be.an.Array; });\n(5).should.match(function(it) { return it.should.be.a.Number; });\n```\n\nNow compare messages:\n```javascript\n(5).should.not.match(function(it) { it.should.be.a.Number; });\n//AssertionError: expected 5 not to match [Function]\n(5).should.not.match(function(it) { return it.should.be.a.Number; });\n//AssertionError: expected 5 not to match [Function]\n//\texpected 5 to be a number\n```\n\nGiven: object, otherValue: another object - assert that object properties match to properties of another object in meaning that describe above cases. See examples:\n\n```javascript\n({ a: 10, b: 'abc', c: { d: 10 }, d: 0 }).should\n .match({ a: 10, b: /c$/, c: function(it) { return it.should.have.property('d', 10); }});\n\n[10, 'abc', { d: 10 }, 0].should\n\t.match({ '0': 10, '1': /c$/, '2': function(it) { return it.should.have.property('d', 10); } });\n\n[10, 'abc', { d: 10 }, 0].should\n .match([10, /c$/, function(it) { return it.should.have.property('d', 10); }]);\n```\n\n## .matchEach(otherValue)\n\nAssert given property keys and values each match given check object.\n\nIf `otherValue` is RegExp, then each property value checked to match it:\n```javascript\n(['a', 'b', 'c']).should.matchEach(/[a-c]/);\n```\n\nIf `otherValue` is Function, then check each property value and key matched it:\n```javascript\n[10, 11, 12].should.matchEach(function(it) { return it >= 10; });\n[10, 11, 12].should.matchEach(function(it) { return it >= 10; });\n```\n\nIn other cases it checks that each property value is `.eql` to `otherValue`:\n```javascript\n[10, 10].should.matchEach(10);\n```\n## .throw() and throwError()\n\nAssert an exception is thrown:\n\n```js\n(function(){\n throw new Error('fail');\n}).should.throw();\n```\n\nAssert an exception is not thrown:\n\n```js\n(function(){\n\n}).should.not.throw();\n```\nAssert exception message matches string:\n\n```js\n(function(){\n throw new Error('fail');\n}).should.throw('fail');\n```\n\nAssert exepection message matches regexp:\n\n```js\n(function(){\n throw new Error('failed to foo');\n}).should.throw(/^fail/);\n```\n\nIf you need to pass arguments and/or context to execute function use `Function#bind(context, arg1, ...)`:\n```js\nfunction isPositive(n) {\n if(n <= 0) throw new Error('Given number is not positive')\n}\n\nisPositive.bind(null, 10).should.not.throw();\nisPositive.bind(null, -10).should.throw();\n```\n\nIf you need to check something in an asynchronous function, you must do it in 2 steps:\n\n```js\n// first we need to check that function is called\nvar called = false;\ncollection.findOne({ _id: 10 }, function(err, res) {\n called = true;\n\n //second we test what you want\n res.should.be....\n});\n\ncalled.should.be.true;\n```\n\nIn case you are using something like `Mocha`, you should use an asynchronous test, and call `done()` in the proper place to make sure that your asynchronous function is called before the test finishes.\n```js\ncollection.findOne({ _id: 10 }, function(err, res) {\n if(err) return done(err);\n //second we test what you want\n res.should.be....\n\n done();\n});\n```\n\nIn general, if you need to check that something is executed, you are best using `spies`. A good example is [sinon](http://sinonjs.org/).\n\n## .status(code)\n\nAsserts that `.statusCode` is `code`:\n```javascript\nres.should.have.status(200);\n```\n\nNot included in browser build.\n\n## .header(field[, value])\n\nAsserts that a `.headers` object with `field` and optional `value` are present:\n```javascript\nres.should.have.header('content-length');\nres.should.have.header('Content-Length', '123');\n```\n\nNot included in browser build.\n\n## .json\n\nAssert that Content-Type is \"application/json; charset=utf-8\"\n\n```javascript\nres.should.be.json\n```\n\nNot included in browser build.\n\n## .html\n\nAssert that Content-Type is \"text/html; charset=utf-8\"\n```javascript\nres.should.be.html\n```\n\nNot included in browser build.\n\n## Optional Error description\n\nAs it can often be difficult to ascertain exactly where failed assertions are coming from in your tests, an optional description parameter can be passed to several should matchers. The description will follow the failed assertion in the error:\n\n (1).should.eql(0, 'some useful description')\n\n AssertionError: some useful description\n at Object.eql (/Users/swift/code/should.js/node_modules/should/lib/should.js:280:10)\n ...\n\nThe methods that support this optional description are: `eql`, `equal`, `within`, `instanceof`, `above`, `below`, `match`, `length`, `property`, `ownProperty`.\n\n## Mocha example\n\nFor example you can use should with the [Mocha test framework](http://visionmedia.github.io/mocha/) by simply including it:\n\n```javascript\nvar should = require('should');\nvar mylib = require('mylib');\n\n\ndescribe('mylib', function() {\n it('should have a version with the format #.#.#', function() {\n lib.version.should.match(/^\\d+\\.\\d+\\.\\d+$/);\n });\n});\n```\n\n## Contributions\n\n[Actual list of contributors](https://github.com/visionmedia/should.js/graphs/contributors) if you want to show it your friends.\n\nTo run the tests for _should_ simply run:\n\n $ make test\n\nSee also [CONTRIBUTING](./CONTRIBUTING.md).\n\n## OMG IT EXTENDS OBJECT???!?!@\n\nYes, yes it does, with a single getter _should_, and no it won't break your code, because it does this **properly** with a non-enumerable property.\n\n## License\n\nMIT © 2010-2014 TJ Holowaychuk\n", - "readmeFilename": "Readme.md" -} diff --git a/node_modules/should/should.js b/node_modules/should/should.js deleted file mode 100644 index 525ce73..0000000 --- a/node_modules/should/should.js +++ /dev/null @@ -1,2362 +0,0 @@ -!function(e){if("object"==typeof exports)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.Should=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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o - * MIT Licensed - */ - -var should = require('./should'); - -should - .use(require('./ext/assert')) - .use(require('./ext/chain')) - .use(require('./ext/bool')) - .use(require('./ext/number')) - .use(require('./ext/eql')) - .use(require('./ext/type')) - .use(require('./ext/string')) - .use(require('./ext/property')) - .use(require('./ext/error')) - .use(require('./ext/match')) - .use(require('./ext/browser/jquery')) - .use(require('./ext/deprecated')); - - module.exports = should; -},{"./ext/assert":3,"./ext/bool":4,"./ext/browser/jquery":5,"./ext/chain":6,"./ext/deprecated":7,"./ext/eql":8,"./ext/error":9,"./ext/match":10,"./ext/number":11,"./ext/property":12,"./ext/string":13,"./ext/type":14,"./should":15}],2:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -// Taken from node's assert module, because it sucks -// and exposes next to nothing useful. -var util = require('./util'); - -module.exports = _deepEqual; - -var pSlice = Array.prototype.slice; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - - -function objEquiv (a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) - return false; - // an identical 'prototype' property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (util.isArguments(a)) { - if (!util.isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try{ - var ka = Object.keys(a), - kb = Object.keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key])) return false; - } - return true; -} - -},{"./util":16}],3:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util') - , assert = require('assert') - , AssertionError = assert.AssertionError; - -module.exports = function(should) { - var i = should.format; - - /** - * Expose assert to should - * - * This allows you to do things like below - * without require()ing the assert module. - * - * should.equal(foo.bar, undefined); - * - */ - util.merge(should, assert); - - - /** - * Assert _obj_ exists, with optional message. - * - * @param {*} obj - * @param {String} [msg] - * @api public - */ - should.exist = should.exists = function(obj, msg) { - if(null == obj) { - throw new AssertionError({ - message: msg || ('expected ' + i(obj) + ' to exist'), stackStartFunction: should.exist - }); - } - }; - - /** - * Asserts _obj_ does not exist, with optional message. - * - * @param {*} obj - * @param {String} [msg] - * @api public - */ - - should.not = {}; - should.not.exist = should.not.exists = function(obj, msg) { - if(null != obj) { - throw new AssertionError({ - message: msg || ('expected ' + i(obj) + ' to not exist'), stackStartFunction: should.not.exist - }); - } - }; -}; -},{"../util":16,"assert":17}],4:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - Assertion.add('true', function() { - this.is.exactly(true); - }, true); - - Assertion.alias('true', 'True'); - - Assertion.add('false', function() { - this.is.exactly(false); - }, true); - - Assertion.alias('false', 'False'); - - Assertion.add('ok', function() { - this.params = { operator: 'to be truthy' }; - - this.assert(this.obj); - }, true); -}; -},{}],5:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -/*! - * Portions copyright (c) 2010, 2011, 2012 Wojciech Zawistowski, Travis Jeffery - * From the jasmine-jquery project under the MIT License. - */ - -var util = require('../../util'); - -module.exports = function(should, Assertion) { - var i = should.format; - var $ = this.jQuery || this.$; - - /* Otherwise, node's util.inspect loops hangs */ - if (typeof HTMLElement !== "undefined" && HTMLElement && !HTMLElement.prototype.inspect) { - HTMLElement.prototype.inspect = function () { - return this.outerHTML; - }; - } - - if (typeof jQuery !== "undefined" && jQuery && !jQuery.prototype.inspect) { - jQuery.fn.inspect = function () { - var elementList = this.toArray().map(function (e) { - return util.inspect(e); - }).join(", "); - if (this.selector) { - return "SELECTOR(" + this.selector + ") matching " + this.length + " elements" + (elementList.length ? ": " + elementList : ""); - } else { - return elementList; - } - }; - } - - function jQueryAttributeTestHelper(method, singular, plural, nameOrHash, value) { - var keys = util.isObject(nameOrHash) ? Object.keys(nameOrHash) : [nameOrHash]; - var allRelevantAttributes = keys.reduce(function (memo, key) { - var value = $(this.obj)[method](key); - if (typeof value !== 'undefined') { - memo[key] = value; - } - return memo; - }.bind(this), {}); - - if (arguments.length === 4 && util.isObject(nameOrHash)) { - this.params = { operator: 'to have ' + plural + ' ' + i(nameOrHash) }; - allRelevantAttributes.should.have.properties(nameOrHash); - } else if (arguments.length === 4) { - this.params = { operator: 'to have ' + singular + ' ' + i(nameOrHash) }; - allRelevantAttributes.should.have.property(nameOrHash); - } else { - this.params = { operator: 'to have ' + singular + ' ' + i(nameOrHash) + ' with value ' + i(value) }; - allRelevantAttributes.should.have.property(nameOrHash, value); - } - } - - var browserTagCaseIndependentHtml = function (html) { - return $('
      ').append(html).html(); - }; - - var addJqPredicateAssertion = function (predicate, nameOverride, operatorOverride) { - Assertion.add(nameOverride || predicate, function() { - this.params = { operator: 'to be ' + (operatorOverride || predicate) }; - this.assert($(this.obj).is(':' + predicate)); - }, true); - } - - Assertion.add('className', function(className) { - this.params = { operator: 'to have class ' + className }; - this.assert($(this.obj).hasClass(className)); - }); - - Assertion.add('css', function(css) { - this.params = { operator: 'to have css ' + i(css) }; - for (var prop in css) { - var value = css[prop]; - if (value === 'auto' && $(this.obj).get(0).style[prop] === 'auto') { - continue; - } - $(this.obj).css(prop).should.eql(value); - } - }); - - addJqPredicateAssertion('visible'); - addJqPredicateAssertion('hidden'); - addJqPredicateAssertion('selected'); - addJqPredicateAssertion('checked'); - addJqPredicateAssertion('disabled'); - addJqPredicateAssertion('empty', 'emptyJq'); - addJqPredicateAssertion('focus', 'focused', 'focused'); - - Assertion.add('inDOM', function() { - this.params = { operator: 'to be in the DOM' }; - this.assert($.contains(document.documentElement, $(this.obj)[0])); - }, true); - - Assertion.add('exist', function() { - this.params = { operator: 'to exist' }; - $(this.obj).should.not.have.length(0); - }, true); - - Assertion.add('attr', function() { - var args = [ - 'attr', - 'attribute', - 'attributes' - ].concat(Array.prototype.slice.call(arguments, 0)); - jQueryAttributeTestHelper.apply(this, args); - }); - - Assertion.add('prop', function() { - var args = [ - 'prop', - 'property', - 'properties' - ].concat(Array.prototype.slice.call(arguments, 0)); - jQueryAttributeTestHelper.apply(this, args); - }); - - Assertion.add('elementId', function(id) { - this.params = { operator: 'to have ID ' + i(id) }; - this.obj.should.have.attr('id', id); - }); - - Assertion.add('html', function(html) { - this.params = { operator: 'to have HTML ' + i(html) }; - $(this.obj).html().should.eql(browserTagCaseIndependentHtml(html)); - }); - - Assertion.add('containHtml', function(html) { - this.params = { operator: 'to contain HTML ' + i(html) }; - $(this.obj).html().indexOf(browserTagCaseIndependentHtml(html)).should.be.above(-1); - }); - - Assertion.add('text', function(text) { - this.params = { operator: 'to have text ' + i(text) }; - var trimmedText = $.trim($(this.obj).text()); - - if (util.isRegExp(text)) { - trimmedText.should.match(text); - } else { - trimmedText.should.eql(text); - } - }); - - Assertion.add('containText', function(text) { - this.params = { operator: 'to contain text ' + i(text) }; - var trimmedText = $.trim($(this.obj).text()); - - if (util.isRegExp(text)) { - trimmedText.should.match(text); - } else { - trimmedText.indexOf(text).should.be.above(-1); - } - }); - - Assertion.add('value', function(val) { - this.params = { operator: 'to have value ' + i(val) }; - $(this.obj).val().should.eql(val); - }); - - Assertion.add('data', function() { - var args = [ - 'data', - 'data', - 'data' - ].concat(Array.prototype.slice.call(arguments, 0)); - jQueryAttributeTestHelper.apply(this, args); - }); - - Assertion.add('containElement', function(target) { - this.params = { operator: 'to contain ' + $(target).inspect() }; - $(this.obj).find(target).should.not.have.length(0); - }); - - Assertion.add('matchedBy', function(selector) { - this.params = { operator: 'to be matched by selector ' + selector }; - $(this.obj).filter(selector).should.not.have.length(0); - }); - - Assertion.add('handle', function(event) { - this.params = { operator: 'to handle ' + event }; - - var events = $._data($(this.obj).get(0), "events"); - - if (!events || !event || typeof event !== "string") { - return this.assert(false); - } - - var namespaces = event.split("."), - eventType = namespaces.shift(), - sortedNamespaces = namespaces.slice(0).sort(), - namespaceRegExp = new RegExp("(^|\\.)" + sortedNamespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); - - if (events[eventType] && namespaces.length) { - for (var i = 0; i < events[eventType].length; i++) { - var namespace = events[eventType][i].namespace; - - if (namespaceRegExp.test(namespace)) { - return; - } - } - } else { - events.should.have.property(eventType); - events[eventType].should.not.have.length(0); - return; - } - - this.assert(false); - }); - - Assertion.add('handleWith', function(eventName, eventHandler) { - this.params = { operator: 'to handle ' + eventName + ' with ' + eventHandler }; - - var normalizedEventName = eventName.split('.')[0], - stack = $._data($(this.obj).get(0), "events")[normalizedEventName]; - - for (var i = 0; i < stack.length; i++) { - if (stack[i].handler == eventHandler) { - return; - } - } - - this.assert(false); - }); -}; -},{"../../util":16}],6:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - - function addLink(name) { - Object.defineProperty(Assertion.prototype, name, { - get: function() { - return this; - } - }); - } - - ['an', 'of', 'a', 'and', 'be', 'have', 'with', 'is', 'which', 'the'].forEach(addLink); -}; -},{}],7:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util'), - eql = require('../eql'); - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('include', function(obj, description) { - if(!Array.isArray(this.obj) && !util.isString(this.obj)) { - this.params = { operator: 'to include an object equal to ' + i(obj), message: description }; - var cmp = {}; - for(var key in obj) cmp[key] = this.obj[key]; - this.assert(eql(cmp, obj)); - } else { - this.params = { operator: 'to include ' + i(obj), message: description }; - - this.assert(~this.obj.indexOf(obj)); - } - }); - - Assertion.add('includeEql', function(obj, description) { - this.params = { operator: 'to include an object equal to ' + i(obj), message: description }; - - this.assert(this.obj.some(function(item) { - return eql(obj, item); - })); - }); -}; -},{"../eql":2,"../util":16}],8:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var eql = require('../eql'); - -module.exports = function(should, Assertion) { - Assertion.add('eql', function(val, description) { - this.params = { operator: 'to equal', expected: val, showDiff: true, message: description }; - - this.assert(eql(val, this.obj)); - }); - - Assertion.add('equal', function(val, description) { - this.params = { operator: 'to be', expected: val, showDiff: true, message: description }; - - this.assert(val === this.obj); - }); - - Assertion.alias('equal', 'exactly'); -}; -},{"../eql":2}],9:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('throw', function(message) { - var fn = this.obj - , err = {} - , errorInfo = '' - , ok = true; - - try { - fn(); - ok = false; - } catch(e) { - err = e; - } - - if(ok) { - if('string' == typeof message) { - ok = message == err.message; - } else if(message instanceof RegExp) { - ok = message.test(err.message); - } else if('function' == typeof message) { - ok = err instanceof message; - } - - if(message && !ok) { - if('string' == typeof message) { - errorInfo = " with a message matching '" + message + "', but got '" + err.message + "'"; - } else if(message instanceof RegExp) { - errorInfo = " with a message matching " + message + ", but got '" + err.message + "'"; - } else if('function' == typeof message) { - errorInfo = " of type " + message.name + ", but got " + err.constructor.name; - } - } else { - errorInfo = " (got " + i(err) + ")"; - } - } - - this.params = { operator: 'to throw exception' + errorInfo }; - - this.assert(ok); - }); - - Assertion.alias('throw', 'throwError'); -}; -},{}],10:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util'), - eql = require('../eql'); - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('match', function(other, description) { - this.params = { operator: 'to match ' + i(other), message: description }; - - if(!eql(this.obj, other)) { - if(util.isRegExp(other)) { // something - regex - - if(util.isString(this.obj)) { - - this.assert(other.exec(this.obj)); - } else if(Array.isArray(this.obj)) { - - this.obj.forEach(function(item) { - this.assert(other.exec(item));// should we try to convert to String and exec? - }, this); - } else if(util.isObject(this.obj)) { - - var notMatchedProps = [], matchedProps = []; - util.forOwn(this.obj, function(value, name) { - if(other.exec(value)) matchedProps.push(i(name)); - else notMatchedProps.push(i(name)); - }, this); - - if(notMatchedProps.length) - this.params.operator += '\n\tnot matched properties: ' + notMatchedProps.join(', '); - if(matchedProps.length) - this.params.operator += '\n\tmatched properties: ' + matchedProps.join(', '); - - this.assert(notMatchedProps.length == 0); - } // should we try to convert to String and exec? - } else if(util.isFunction(other)) { - var res; - try { - res = other(this.obj); - } catch(e) { - if(e instanceof should.AssertionError) { - this.params.operator += '\n\t' + e.message; - } - throw e; - } - - if(res instanceof Assertion) { - this.params.operator += '\n\t' + res.getMessage(); - } - - //if we throw exception ok - it is used .should inside - if(util.isBoolean(res)) { - this.assert(res); // if it is just boolean function assert on it - } - } else if(util.isObject(other)) { // try to match properties (for Object and Array) - notMatchedProps = []; matchedProps = []; - - util.forOwn(other, function(value, key) { - try { - this.obj[key].should.match(value); - matchedProps.push(key); - } catch(e) { - if(e instanceof should.AssertionError) { - notMatchedProps.push(key); - } else { - throw e; - } - } - }, this); - - if(notMatchedProps.length) - this.params.operator += '\n\tnot matched properties: ' + notMatchedProps.join(', '); - if(matchedProps.length) - this.params.operator += '\n\tmatched properties: ' + matchedProps.join(', '); - - this.assert(notMatchedProps.length == 0); - } else { - this.assert(false); - } - } - }); - - Assertion.add('matchEach', function(other, description) { - this.params = { operator: 'to match each ' + i(other), message: description }; - - var f = other; - - if(util.isRegExp(other)) - f = function(it) { - return !!other.exec(it); - }; - else if(!util.isFunction(other)) - f = function(it) { - return eql(it, other); - }; - - util.forOwn(this.obj, function(value, key) { - var res = f(value, key); - - //if we throw exception ok - it is used .should inside - if(util.isBoolean(res)) { - this.assert(res); // if it is just boolean function assert on it - } - }, this); - }); -}; -},{"../eql":2,"../util":16}],11:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - Assertion.add('NaN', function() { - this.params = { operator: 'to be NaN' }; - - this.assert(this.obj !== this.obj); - }, true); - - Assertion.add('Infinity', function() { - this.params = { operator: 'to be Infinity' }; - - this.is.a.Number - .and.not.a.NaN - .and.assert(!isFinite(this.obj)); - }, true); - - Assertion.add('within', function(start, finish, description) { - this.params = { operator: 'to be within ' + start + '..' + finish, message: description }; - - this.assert(this.obj >= start && this.obj <= finish); - }); - - Assertion.add('approximately', function(value, delta, description) { - this.params = { operator: 'to be approximately ' + value + " ±" + delta, message: description }; - - this.assert(Math.abs(this.obj - value) <= delta); - }); - - Assertion.add('above', function(n, description) { - this.params = { operator: 'to be above ' + n, message: description }; - - this.assert(this.obj > n); - }); - - Assertion.add('below', function(n, description) { - this.params = { operator: 'to be below ' + n, message: description }; - - this.assert(this.obj < n); - }); - - Assertion.alias('above', 'greaterThan'); - Assertion.alias('below', 'lessThan'); - -}; - -},{}],12:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util'), - eql = require('../eql'); - -var aSlice = Array.prototype.slice; - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('enumerable', function(name, val) { - this.params = { - operator:"to have enumerable property '"+name+"'" - }; - - this.assert(this.obj.propertyIsEnumerable(name)); - - if(arguments.length > 1){ - this.params.operator += " equal to '"+val+"'"; - this.assert(eql(val, this.obj[name])); - } - }); - - Assertion.add('property', function(name, val) { - if(arguments.length > 1) { - var p = {}; - p[name] = val; - this.have.properties(p); - } else { - this.have.properties(name); - } - this.obj = this.obj[name]; - }); - - Assertion.add('properties', function(names) { - var values = {}; - if(arguments.length > 1) { - names = aSlice.call(arguments); - } else if(!Array.isArray(names)) { - if(util.isString(names)) { - names = [names]; - } else { - values = names; - names = Object.keys(names); - } - } - - var obj = Object(this.obj), missingProperties = []; - - //just enumerate properties and check if they all present - names.forEach(function(name) { - if(!(name in obj)) missingProperties.push(i(name)); - }); - - var props = missingProperties; - if(props.length === 0) { - props = names.map(i); - } else if(this.one) { - props = names.filter(function(name) { - return missingProperties.indexOf(i(name)) < 0; - }).map(i); - } - - var operator = (props.length === 1 ? - 'to have property ' : 'to have '+(this.one? 'any of ' : '')+'properties ') + props.join(', '); - - this.params = { operator: operator }; - - //check that all properties presented - //or if we request one of them that at least one them presented - this.assert(missingProperties.length === 0 || (this.one && missingProperties.length != names.length)); - - // check if values in object matched expected - var valueCheckNames = Object.keys(values); - if(valueCheckNames.length) { - var wrongValues = []; - props = []; - - // now check values, as there we have all properties - valueCheckNames.forEach(function(name) { - var value = values[name]; - if(!eql(obj[name], value)) { - wrongValues.push(i(name) + ' of ' + i(value) + ' (got ' + i(obj[name]) + ')'); - } else { - props.push(i(name) + ' of ' + i(value)); - } - }); - - if((wrongValues.length !== 0 && !this.one) || (this.one && props.length === 0)) { - props = wrongValues; - } - - operator = (props.length === 1 ? - 'to have property ' : 'to have '+(this.one? 'any of ' : '')+'properties ') + props.join(', '); - - this.params = { operator: operator }; - - //if there is no not matched values - //or there is at least one matched - this.assert(wrongValues.length === 0 || (this.one && wrongValues.length != valueCheckNames.length)); - } - }); - - Assertion.add('length', function(n, description) { - this.have.property('length', n, description); - }); - - Assertion.alias('length', 'lengthOf'); - - var hasOwnProperty = Object.prototype.hasOwnProperty; - - Assertion.add('ownProperty', function(name, description) { - this.params = { operator: 'to have own property ' + i(name), message: description }; - - this.assert(hasOwnProperty.call(this.obj, name)); - - this.obj = this.obj[name]; - }); - - Assertion.alias('ownProperty', 'hasOwnProperty'); - - Assertion.add('empty', function() { - this.params = { operator: 'to be empty' }; - - if(util.isString(this.obj) || Array.isArray(this.obj) || util.isArguments(this.obj)) { - this.have.property('length', 0); - } else { - var obj = Object(this.obj); // wrap to reference for booleans and numbers - for(var prop in obj) { - this.have.not.ownProperty(prop); - } - } - }, true); - - Assertion.add('keys', function(keys) { - if(arguments.length > 1) keys = aSlice.call(arguments); - else if(arguments.length === 1 && util.isString(keys)) keys = [ keys ]; - else if(arguments.length === 0) keys = []; - - var obj = Object(this.obj); - - // first check if some keys are missing - var missingKeys = []; - keys.forEach(function(key) { - if(!hasOwnProperty.call(this.obj, key)) - missingKeys.push(i(key)); - }, this); - - // second check for extra keys - var extraKeys = []; - Object.keys(obj).forEach(function(key) { - if(keys.indexOf(key) < 0) { - extraKeys.push(i(key)); - } - }); - - var verb = keys.length === 0 ? 'to be empty' : - 'to have ' + (keys.length === 1 ? 'key ' : 'keys '); - - this.params = { operator: verb + keys.map(i).join(', ')}; - - if(missingKeys.length > 0) - this.params.operator += '\n\tmissing keys: ' + missingKeys.join(', '); - - if(extraKeys.length > 0) - this.params.operator += '\n\textra keys: ' + extraKeys.join(', '); - - this.assert(missingKeys.length === 0 && extraKeys.length === 0); - }); - - Assertion.alias("keys", "key"); - - Assertion.add('containEql', function(other) { - this.params = { operator: 'to contain ' + i(other) }; - var obj = this.obj; - if(Array.isArray(obj)) { - this.assert(obj.some(function(item) { - return eql(item, other); - })); - } else if(util.isString(obj)) { - // expect obj to be string - this.assert(obj.indexOf(String(other)) >= 0); - } else if(util.isObject(obj)) { - // object contains object case - util.forOwn(other, function(value, key) { - obj.should.have.property(key, value); - }); - } else { - //other uncovered cases - this.assert(false); - } - }); - - Assertion.add('containDeep', function(other) { - this.params = { operator: 'to contain ' + i(other) }; - - var obj = this.obj; - if(Array.isArray(obj)) { - if(Array.isArray(other)) { - var otherIdx = 0; - obj.forEach(function(item) { - try { - should(item).not.be.Null.and.containDeep(other[otherIdx]); - otherIdx++; - } catch(e) { - if(e instanceof should.AssertionError) { - return; - } - throw e; - } - }); - this.assert(otherIdx == other.length); - //search array contain other as sub sequence - } else { - this.assert(false); - } - } else if(util.isString(obj)) {// expect other to be string - this.assert(obj.indexOf(String(other)) >= 0); - } else if(util.isObject(obj)) {// object contains object case - if(util.isObject(other)) { - util.forOwn(other, function(value, key) { - should(obj[key]).not.be.Null.and.containDeep(value); - }); - } else {//one of the properties contain value - this.assert(false); - } - } else { - this.eql(other); - } - }); - -}; - -},{"../eql":2,"../util":16}],13:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - Assertion.add('startWith', function(str, description) { - this.params = { operator: 'to start with ' + should.format(str), message: description }; - - this.assert(0 === this.obj.indexOf(str)); - }); - - Assertion.add('endWith', function(str, description) { - this.params = { operator: 'to end with ' + should.format(str), message: description }; - - this.assert(this.obj.indexOf(str, this.obj.length - str.length) >= 0); - }); -}; -},{}],14:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util'); - -module.exports = function(should, Assertion) { - Assertion.add('Number', function() { - this.params = { operator: 'to be a number' }; - - this.assert(util.isNumber(this.obj)); - }, true); - - Assertion.add('arguments', function() { - this.params = { operator: 'to be arguments' }; - - this.assert(util.isArguments(this.obj)); - }, true); - - Assertion.add('type', function(type, description) { - this.params = { operator: 'to have type ' + type, message: description }; - - (typeof this.obj).should.be.exactly(type, description); - }); - - Assertion.add('instanceof', function(constructor, description) { - this.params = { operator: 'to be an instance of ' + constructor.name, message: description }; - - this.assert(Object(this.obj) instanceof constructor); - }); - - Assertion.add('Function', function() { - this.params = { operator: 'to be a function' }; - - this.assert(util.isFunction(this.obj)); - }, true); - - Assertion.add('Object', function() { - this.params = { operator: 'to be an object' }; - - this.assert(util.isObject(this.obj)); - }, true); - - Assertion.add('String', function() { - this.params = { operator: 'to be a string' }; - - this.assert(util.isString(this.obj)); - }, true); - - Assertion.add('Array', function() { - this.params = { operator: 'to be an array' }; - - this.assert(Array.isArray(this.obj)); - }, true); - - Assertion.add('Boolean', function() { - this.params = { operator: 'to be a boolean' }; - - this.assert(util.isBoolean(this.obj)); - }, true); - - Assertion.add('Error', function() { - this.params = { operator: 'to be an error' }; - - this.assert(util.isError(this.obj)); - }, true); - - Assertion.add('null', function() { - this.params = { operator: 'to be null' }; - - this.assert(this.obj === null); - }, true); - - Assertion.alias('null', 'Null'); - - Assertion.alias('instanceof', 'instanceOf'); -}; -},{"../util":16}],15:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - - -var util = require('./util') - , AssertionError = util.AssertionError - , inspect = util.inspect; - -/** - * Our function should - * @param obj - * @returns {Assertion} - */ -var should = function(obj) { - return new Assertion(util.isWrapperType(obj) ? obj.valueOf(): obj); -}; - -/** - * Initialize a new `Assertion` with the given _obj_. - * - * @param {*} obj - * @api private - */ - -var Assertion = should.Assertion = function Assertion(obj) { - this.obj = obj; -}; - - -/** - Way to extend Assertion function. It uses some logic - to define only positive assertions and itself rule with negative assertion. - - All actions happen in subcontext and this method take care about negation. - Potentially we can add some more modifiers that does not depends from state of assertion. -*/ -Assertion.add = function(name, f, isGetter) { - var prop = {}; - prop[isGetter ? 'get' : 'value'] = function() { - var context = new Assertion(this.obj); - context.copy = context.copyIfMissing; - context.one = this.one; - - try { - f.apply(context, arguments); - } catch(e) { - //copy data from sub context to this - this.copy(context); - - //check for fail - if(e instanceof should.AssertionError) { - //negative fail - if(this.negate) { - this.obj = context.obj; - this.negate = false; - return this; - } - this.assert(false); - } - // throw if it is another exception - throw e; - } - //copy data from sub context to this - this.copy(context); - if(this.negate) { - this.assert(false); - } - - this.obj = context.obj; - this.negate = false; - return this; - }; - - Object.defineProperty(Assertion.prototype, name, prop); -}; - -Assertion.alias = function(from, to) { - var desc = Object.getOwnPropertyDescriptor(Assertion.prototype, from); - if(!desc) throw new Error('Alias ' + from + ' -> ' + to + ' could not be created as ' + from + ' not defined'); - Object.defineProperty(Assertion.prototype, to, desc); -}; - -should.AssertionError = AssertionError; -should.format = function (value) { - if(util.isDate(value) && typeof value.inspect !== 'function') return value.toISOString(); //show millis in dates - return inspect(value, { depth: null }); -}; - -should.use = function(f) { - f(this, Assertion); - return this; -}; - - -/** - * Expose should to external world. - */ -exports = module.exports = should; - - -/** - * Expose api via `Object#should`. - * - * @api public - */ - -Object.defineProperty(Object.prototype, 'should', { - set: function(){}, - get: function(){ - return should(this); - }, - configurable: true -}); - - -Assertion.prototype = { - constructor: Assertion, - - assert: function(expr) { - if(expr) return; - - var params = this.params; - - var msg = params.message, generatedMessage = false; - if(!msg) { - msg = this.getMessage(); - generatedMessage = true; - } - - var err = new AssertionError({ - message: msg - , actual: this.obj - , expected: params.expected - , stackStartFunction: this.assert - }); - - err.showDiff = params.showDiff; - err.operator = params.operator; - err.generatedMessage = generatedMessage; - - throw err; - }, - - getMessage: function() { - return 'expected ' + ('obj' in this.params ? this.params.obj: should.format(this.obj)) + (this.negate ? ' not ': ' ') + - this.params.operator + ('expected' in this.params ? ' ' + should.format(this.params.expected) : ''); - }, - - copy: function(other) { - this.params = other.params; - }, - - copyIfMissing: function(other) { - if(!this.params) this.params = other.params; - }, - - - /** - * Negation modifier. - * - * @api public - */ - - get not() { - this.negate = !this.negate; - return this; - }, - - /** - * Any modifier - it affect on execution of sequenced assertion to do not check all, but any of - * - * @api public - */ - get any() { - this.one = true; - return this; - } -}; - - -},{"./util":16}],16:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Check if given obj just a primitive type wrapper - * @param {Object} obj - * @returns {boolean} - * @api private - */ -exports.isWrapperType = function(obj) { - return isNumber(obj) || isString(obj) || isBoolean(obj); -}; - -/** - * Merge object b with object a. - * - * var a = { foo: 'bar' } - * , b = { bar: 'baz' }; - * - * utils.merge(a, b); - * // => { foo: 'bar', bar: 'baz' } - * - * @param {Object} a - * @param {Object} b - * @return {Object} - * @api private - */ - -exports.merge = function(a, b){ - if (a && b) { - for (var key in b) { - a[key] = b[key]; - } - } - return a; -}; - -function isNumber(arg) { - return typeof arg === 'number' || arg instanceof Number; -} - -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string' || arg instanceof String; -} - -function isBoolean(arg) { - return typeof arg === 'boolean' || arg instanceof Boolean; -} -exports.isBoolean = isBoolean; - -exports.isString = isString; - -function isBuffer(arg) { - return typeof Buffer !== 'undefined' && arg instanceof Buffer; -} - -exports.isBuffer = isBuffer; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} - -exports.isDate = isDate; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -exports.isObject = isObject; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} - -exports.isRegExp = isRegExp; - -function isNullOrUndefined(arg) { - return arg == null; -} - -exports.isNullOrUndefined = isNullOrUndefined; - -function isArguments(object) { - return objectToString(object) === '[object Arguments]'; -} - -exports.isArguments = isArguments; - -exports.isFunction = function(arg) { - return typeof arg === 'function' || arg instanceof Function; -}; - -function isError(e) { - return (isObject(e) && objectToString(e) === '[object Error]') || (e instanceof Error); -} -exports.isError = isError; - -exports.inspect = require('util').inspect; - -exports.AssertionError = require('assert').AssertionError; - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -exports.forOwn = function(obj, f, context) { - for(var prop in obj) { - if(hasOwnProperty.call(obj, prop)) { - f.call(context, obj[prop], prop); - } - } -}; -},{"assert":17,"util":20}],17:[function(require,module,exports){ -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.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 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. - -// when used in node, this will actually load the util module we depend on -// versus loading the builtin util module as happens otherwise -// this is a bug in node module loading as far as I am concerned -var util = require('util/'); - -var pSlice = Array.prototype.slice; -var hasOwn = Object.prototype.hasOwnProperty; - -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) - -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } - else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - // try to strip useless frames - var fn_name = stackStartFunction.name; - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - - this.stack = out; - } - } -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); - -function replacer(key, value) { - if (util.isUndefined(value)) { - return '' + value; - } - if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { - return value.toString(); - } - if (util.isFunction(value) || util.isRegExp(value)) { - return value.toString(); - } - return value; -} - -function truncate(s, n) { - if (util.isString(s)) { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} - -function getMessage(self) { - return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + - self.operator + ' ' + - truncate(JSON.stringify(self.expected, replacer), 128); -} - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) - return false; - // an identical 'prototype' property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try { - var ka = objectKeys(a), - kb = objectKeys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key])) return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; - -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } else if (actual instanceof expected) { - return true; - } else if (expected.call({}, actual) === true) { - return true; - } - - return false; -} - -function _throws(shouldThrow, block, expected, message) { - var actual; - - if (util.isString(expected)) { - message = expected; - expected = null; - } - - try { - block(); - } catch (e) { - actual = e; - } - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} - -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; - -assert.ifError = function(err) { if (err) {throw err;}}; - -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; -}; - -},{"util/":20}],18:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],19:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],20:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -},{"./support/isBuffer":19,"inherits":18}]},{},[1]) -(1) -}); \ No newline at end of file diff --git a/node_modules/should/should.js.for-tests b/node_modules/should/should.js.for-tests deleted file mode 100644 index 525ce73..0000000 --- a/node_modules/should/should.js.for-tests +++ /dev/null @@ -1,2362 +0,0 @@ -!function(e){if("object"==typeof exports)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.Should=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);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o - * MIT Licensed - */ - -var should = require('./should'); - -should - .use(require('./ext/assert')) - .use(require('./ext/chain')) - .use(require('./ext/bool')) - .use(require('./ext/number')) - .use(require('./ext/eql')) - .use(require('./ext/type')) - .use(require('./ext/string')) - .use(require('./ext/property')) - .use(require('./ext/error')) - .use(require('./ext/match')) - .use(require('./ext/browser/jquery')) - .use(require('./ext/deprecated')); - - module.exports = should; -},{"./ext/assert":3,"./ext/bool":4,"./ext/browser/jquery":5,"./ext/chain":6,"./ext/deprecated":7,"./ext/eql":8,"./ext/error":9,"./ext/match":10,"./ext/number":11,"./ext/property":12,"./ext/string":13,"./ext/type":14,"./should":15}],2:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -// Taken from node's assert module, because it sucks -// and exposes next to nothing useful. -var util = require('./util'); - -module.exports = _deepEqual; - -var pSlice = Array.prototype.slice; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - - -function objEquiv (a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) - return false; - // an identical 'prototype' property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (util.isArguments(a)) { - if (!util.isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try{ - var ka = Object.keys(a), - kb = Object.keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key])) return false; - } - return true; -} - -},{"./util":16}],3:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util') - , assert = require('assert') - , AssertionError = assert.AssertionError; - -module.exports = function(should) { - var i = should.format; - - /** - * Expose assert to should - * - * This allows you to do things like below - * without require()ing the assert module. - * - * should.equal(foo.bar, undefined); - * - */ - util.merge(should, assert); - - - /** - * Assert _obj_ exists, with optional message. - * - * @param {*} obj - * @param {String} [msg] - * @api public - */ - should.exist = should.exists = function(obj, msg) { - if(null == obj) { - throw new AssertionError({ - message: msg || ('expected ' + i(obj) + ' to exist'), stackStartFunction: should.exist - }); - } - }; - - /** - * Asserts _obj_ does not exist, with optional message. - * - * @param {*} obj - * @param {String} [msg] - * @api public - */ - - should.not = {}; - should.not.exist = should.not.exists = function(obj, msg) { - if(null != obj) { - throw new AssertionError({ - message: msg || ('expected ' + i(obj) + ' to not exist'), stackStartFunction: should.not.exist - }); - } - }; -}; -},{"../util":16,"assert":17}],4:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - Assertion.add('true', function() { - this.is.exactly(true); - }, true); - - Assertion.alias('true', 'True'); - - Assertion.add('false', function() { - this.is.exactly(false); - }, true); - - Assertion.alias('false', 'False'); - - Assertion.add('ok', function() { - this.params = { operator: 'to be truthy' }; - - this.assert(this.obj); - }, true); -}; -},{}],5:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -/*! - * Portions copyright (c) 2010, 2011, 2012 Wojciech Zawistowski, Travis Jeffery - * From the jasmine-jquery project under the MIT License. - */ - -var util = require('../../util'); - -module.exports = function(should, Assertion) { - var i = should.format; - var $ = this.jQuery || this.$; - - /* Otherwise, node's util.inspect loops hangs */ - if (typeof HTMLElement !== "undefined" && HTMLElement && !HTMLElement.prototype.inspect) { - HTMLElement.prototype.inspect = function () { - return this.outerHTML; - }; - } - - if (typeof jQuery !== "undefined" && jQuery && !jQuery.prototype.inspect) { - jQuery.fn.inspect = function () { - var elementList = this.toArray().map(function (e) { - return util.inspect(e); - }).join(", "); - if (this.selector) { - return "SELECTOR(" + this.selector + ") matching " + this.length + " elements" + (elementList.length ? ": " + elementList : ""); - } else { - return elementList; - } - }; - } - - function jQueryAttributeTestHelper(method, singular, plural, nameOrHash, value) { - var keys = util.isObject(nameOrHash) ? Object.keys(nameOrHash) : [nameOrHash]; - var allRelevantAttributes = keys.reduce(function (memo, key) { - var value = $(this.obj)[method](key); - if (typeof value !== 'undefined') { - memo[key] = value; - } - return memo; - }.bind(this), {}); - - if (arguments.length === 4 && util.isObject(nameOrHash)) { - this.params = { operator: 'to have ' + plural + ' ' + i(nameOrHash) }; - allRelevantAttributes.should.have.properties(nameOrHash); - } else if (arguments.length === 4) { - this.params = { operator: 'to have ' + singular + ' ' + i(nameOrHash) }; - allRelevantAttributes.should.have.property(nameOrHash); - } else { - this.params = { operator: 'to have ' + singular + ' ' + i(nameOrHash) + ' with value ' + i(value) }; - allRelevantAttributes.should.have.property(nameOrHash, value); - } - } - - var browserTagCaseIndependentHtml = function (html) { - return $('
      ').append(html).html(); - }; - - var addJqPredicateAssertion = function (predicate, nameOverride, operatorOverride) { - Assertion.add(nameOverride || predicate, function() { - this.params = { operator: 'to be ' + (operatorOverride || predicate) }; - this.assert($(this.obj).is(':' + predicate)); - }, true); - } - - Assertion.add('className', function(className) { - this.params = { operator: 'to have class ' + className }; - this.assert($(this.obj).hasClass(className)); - }); - - Assertion.add('css', function(css) { - this.params = { operator: 'to have css ' + i(css) }; - for (var prop in css) { - var value = css[prop]; - if (value === 'auto' && $(this.obj).get(0).style[prop] === 'auto') { - continue; - } - $(this.obj).css(prop).should.eql(value); - } - }); - - addJqPredicateAssertion('visible'); - addJqPredicateAssertion('hidden'); - addJqPredicateAssertion('selected'); - addJqPredicateAssertion('checked'); - addJqPredicateAssertion('disabled'); - addJqPredicateAssertion('empty', 'emptyJq'); - addJqPredicateAssertion('focus', 'focused', 'focused'); - - Assertion.add('inDOM', function() { - this.params = { operator: 'to be in the DOM' }; - this.assert($.contains(document.documentElement, $(this.obj)[0])); - }, true); - - Assertion.add('exist', function() { - this.params = { operator: 'to exist' }; - $(this.obj).should.not.have.length(0); - }, true); - - Assertion.add('attr', function() { - var args = [ - 'attr', - 'attribute', - 'attributes' - ].concat(Array.prototype.slice.call(arguments, 0)); - jQueryAttributeTestHelper.apply(this, args); - }); - - Assertion.add('prop', function() { - var args = [ - 'prop', - 'property', - 'properties' - ].concat(Array.prototype.slice.call(arguments, 0)); - jQueryAttributeTestHelper.apply(this, args); - }); - - Assertion.add('elementId', function(id) { - this.params = { operator: 'to have ID ' + i(id) }; - this.obj.should.have.attr('id', id); - }); - - Assertion.add('html', function(html) { - this.params = { operator: 'to have HTML ' + i(html) }; - $(this.obj).html().should.eql(browserTagCaseIndependentHtml(html)); - }); - - Assertion.add('containHtml', function(html) { - this.params = { operator: 'to contain HTML ' + i(html) }; - $(this.obj).html().indexOf(browserTagCaseIndependentHtml(html)).should.be.above(-1); - }); - - Assertion.add('text', function(text) { - this.params = { operator: 'to have text ' + i(text) }; - var trimmedText = $.trim($(this.obj).text()); - - if (util.isRegExp(text)) { - trimmedText.should.match(text); - } else { - trimmedText.should.eql(text); - } - }); - - Assertion.add('containText', function(text) { - this.params = { operator: 'to contain text ' + i(text) }; - var trimmedText = $.trim($(this.obj).text()); - - if (util.isRegExp(text)) { - trimmedText.should.match(text); - } else { - trimmedText.indexOf(text).should.be.above(-1); - } - }); - - Assertion.add('value', function(val) { - this.params = { operator: 'to have value ' + i(val) }; - $(this.obj).val().should.eql(val); - }); - - Assertion.add('data', function() { - var args = [ - 'data', - 'data', - 'data' - ].concat(Array.prototype.slice.call(arguments, 0)); - jQueryAttributeTestHelper.apply(this, args); - }); - - Assertion.add('containElement', function(target) { - this.params = { operator: 'to contain ' + $(target).inspect() }; - $(this.obj).find(target).should.not.have.length(0); - }); - - Assertion.add('matchedBy', function(selector) { - this.params = { operator: 'to be matched by selector ' + selector }; - $(this.obj).filter(selector).should.not.have.length(0); - }); - - Assertion.add('handle', function(event) { - this.params = { operator: 'to handle ' + event }; - - var events = $._data($(this.obj).get(0), "events"); - - if (!events || !event || typeof event !== "string") { - return this.assert(false); - } - - var namespaces = event.split("."), - eventType = namespaces.shift(), - sortedNamespaces = namespaces.slice(0).sort(), - namespaceRegExp = new RegExp("(^|\\.)" + sortedNamespaces.join("\\.(?:.*\\.)?") + "(\\.|$)"); - - if (events[eventType] && namespaces.length) { - for (var i = 0; i < events[eventType].length; i++) { - var namespace = events[eventType][i].namespace; - - if (namespaceRegExp.test(namespace)) { - return; - } - } - } else { - events.should.have.property(eventType); - events[eventType].should.not.have.length(0); - return; - } - - this.assert(false); - }); - - Assertion.add('handleWith', function(eventName, eventHandler) { - this.params = { operator: 'to handle ' + eventName + ' with ' + eventHandler }; - - var normalizedEventName = eventName.split('.')[0], - stack = $._data($(this.obj).get(0), "events")[normalizedEventName]; - - for (var i = 0; i < stack.length; i++) { - if (stack[i].handler == eventHandler) { - return; - } - } - - this.assert(false); - }); -}; -},{"../../util":16}],6:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - - function addLink(name) { - Object.defineProperty(Assertion.prototype, name, { - get: function() { - return this; - } - }); - } - - ['an', 'of', 'a', 'and', 'be', 'have', 'with', 'is', 'which', 'the'].forEach(addLink); -}; -},{}],7:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util'), - eql = require('../eql'); - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('include', function(obj, description) { - if(!Array.isArray(this.obj) && !util.isString(this.obj)) { - this.params = { operator: 'to include an object equal to ' + i(obj), message: description }; - var cmp = {}; - for(var key in obj) cmp[key] = this.obj[key]; - this.assert(eql(cmp, obj)); - } else { - this.params = { operator: 'to include ' + i(obj), message: description }; - - this.assert(~this.obj.indexOf(obj)); - } - }); - - Assertion.add('includeEql', function(obj, description) { - this.params = { operator: 'to include an object equal to ' + i(obj), message: description }; - - this.assert(this.obj.some(function(item) { - return eql(obj, item); - })); - }); -}; -},{"../eql":2,"../util":16}],8:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var eql = require('../eql'); - -module.exports = function(should, Assertion) { - Assertion.add('eql', function(val, description) { - this.params = { operator: 'to equal', expected: val, showDiff: true, message: description }; - - this.assert(eql(val, this.obj)); - }); - - Assertion.add('equal', function(val, description) { - this.params = { operator: 'to be', expected: val, showDiff: true, message: description }; - - this.assert(val === this.obj); - }); - - Assertion.alias('equal', 'exactly'); -}; -},{"../eql":2}],9:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('throw', function(message) { - var fn = this.obj - , err = {} - , errorInfo = '' - , ok = true; - - try { - fn(); - ok = false; - } catch(e) { - err = e; - } - - if(ok) { - if('string' == typeof message) { - ok = message == err.message; - } else if(message instanceof RegExp) { - ok = message.test(err.message); - } else if('function' == typeof message) { - ok = err instanceof message; - } - - if(message && !ok) { - if('string' == typeof message) { - errorInfo = " with a message matching '" + message + "', but got '" + err.message + "'"; - } else if(message instanceof RegExp) { - errorInfo = " with a message matching " + message + ", but got '" + err.message + "'"; - } else if('function' == typeof message) { - errorInfo = " of type " + message.name + ", but got " + err.constructor.name; - } - } else { - errorInfo = " (got " + i(err) + ")"; - } - } - - this.params = { operator: 'to throw exception' + errorInfo }; - - this.assert(ok); - }); - - Assertion.alias('throw', 'throwError'); -}; -},{}],10:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util'), - eql = require('../eql'); - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('match', function(other, description) { - this.params = { operator: 'to match ' + i(other), message: description }; - - if(!eql(this.obj, other)) { - if(util.isRegExp(other)) { // something - regex - - if(util.isString(this.obj)) { - - this.assert(other.exec(this.obj)); - } else if(Array.isArray(this.obj)) { - - this.obj.forEach(function(item) { - this.assert(other.exec(item));// should we try to convert to String and exec? - }, this); - } else if(util.isObject(this.obj)) { - - var notMatchedProps = [], matchedProps = []; - util.forOwn(this.obj, function(value, name) { - if(other.exec(value)) matchedProps.push(i(name)); - else notMatchedProps.push(i(name)); - }, this); - - if(notMatchedProps.length) - this.params.operator += '\n\tnot matched properties: ' + notMatchedProps.join(', '); - if(matchedProps.length) - this.params.operator += '\n\tmatched properties: ' + matchedProps.join(', '); - - this.assert(notMatchedProps.length == 0); - } // should we try to convert to String and exec? - } else if(util.isFunction(other)) { - var res; - try { - res = other(this.obj); - } catch(e) { - if(e instanceof should.AssertionError) { - this.params.operator += '\n\t' + e.message; - } - throw e; - } - - if(res instanceof Assertion) { - this.params.operator += '\n\t' + res.getMessage(); - } - - //if we throw exception ok - it is used .should inside - if(util.isBoolean(res)) { - this.assert(res); // if it is just boolean function assert on it - } - } else if(util.isObject(other)) { // try to match properties (for Object and Array) - notMatchedProps = []; matchedProps = []; - - util.forOwn(other, function(value, key) { - try { - this.obj[key].should.match(value); - matchedProps.push(key); - } catch(e) { - if(e instanceof should.AssertionError) { - notMatchedProps.push(key); - } else { - throw e; - } - } - }, this); - - if(notMatchedProps.length) - this.params.operator += '\n\tnot matched properties: ' + notMatchedProps.join(', '); - if(matchedProps.length) - this.params.operator += '\n\tmatched properties: ' + matchedProps.join(', '); - - this.assert(notMatchedProps.length == 0); - } else { - this.assert(false); - } - } - }); - - Assertion.add('matchEach', function(other, description) { - this.params = { operator: 'to match each ' + i(other), message: description }; - - var f = other; - - if(util.isRegExp(other)) - f = function(it) { - return !!other.exec(it); - }; - else if(!util.isFunction(other)) - f = function(it) { - return eql(it, other); - }; - - util.forOwn(this.obj, function(value, key) { - var res = f(value, key); - - //if we throw exception ok - it is used .should inside - if(util.isBoolean(res)) { - this.assert(res); // if it is just boolean function assert on it - } - }, this); - }); -}; -},{"../eql":2,"../util":16}],11:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - Assertion.add('NaN', function() { - this.params = { operator: 'to be NaN' }; - - this.assert(this.obj !== this.obj); - }, true); - - Assertion.add('Infinity', function() { - this.params = { operator: 'to be Infinity' }; - - this.is.a.Number - .and.not.a.NaN - .and.assert(!isFinite(this.obj)); - }, true); - - Assertion.add('within', function(start, finish, description) { - this.params = { operator: 'to be within ' + start + '..' + finish, message: description }; - - this.assert(this.obj >= start && this.obj <= finish); - }); - - Assertion.add('approximately', function(value, delta, description) { - this.params = { operator: 'to be approximately ' + value + " ±" + delta, message: description }; - - this.assert(Math.abs(this.obj - value) <= delta); - }); - - Assertion.add('above', function(n, description) { - this.params = { operator: 'to be above ' + n, message: description }; - - this.assert(this.obj > n); - }); - - Assertion.add('below', function(n, description) { - this.params = { operator: 'to be below ' + n, message: description }; - - this.assert(this.obj < n); - }); - - Assertion.alias('above', 'greaterThan'); - Assertion.alias('below', 'lessThan'); - -}; - -},{}],12:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util'), - eql = require('../eql'); - -var aSlice = Array.prototype.slice; - -module.exports = function(should, Assertion) { - var i = should.format; - - Assertion.add('enumerable', function(name, val) { - this.params = { - operator:"to have enumerable property '"+name+"'" - }; - - this.assert(this.obj.propertyIsEnumerable(name)); - - if(arguments.length > 1){ - this.params.operator += " equal to '"+val+"'"; - this.assert(eql(val, this.obj[name])); - } - }); - - Assertion.add('property', function(name, val) { - if(arguments.length > 1) { - var p = {}; - p[name] = val; - this.have.properties(p); - } else { - this.have.properties(name); - } - this.obj = this.obj[name]; - }); - - Assertion.add('properties', function(names) { - var values = {}; - if(arguments.length > 1) { - names = aSlice.call(arguments); - } else if(!Array.isArray(names)) { - if(util.isString(names)) { - names = [names]; - } else { - values = names; - names = Object.keys(names); - } - } - - var obj = Object(this.obj), missingProperties = []; - - //just enumerate properties and check if they all present - names.forEach(function(name) { - if(!(name in obj)) missingProperties.push(i(name)); - }); - - var props = missingProperties; - if(props.length === 0) { - props = names.map(i); - } else if(this.one) { - props = names.filter(function(name) { - return missingProperties.indexOf(i(name)) < 0; - }).map(i); - } - - var operator = (props.length === 1 ? - 'to have property ' : 'to have '+(this.one? 'any of ' : '')+'properties ') + props.join(', '); - - this.params = { operator: operator }; - - //check that all properties presented - //or if we request one of them that at least one them presented - this.assert(missingProperties.length === 0 || (this.one && missingProperties.length != names.length)); - - // check if values in object matched expected - var valueCheckNames = Object.keys(values); - if(valueCheckNames.length) { - var wrongValues = []; - props = []; - - // now check values, as there we have all properties - valueCheckNames.forEach(function(name) { - var value = values[name]; - if(!eql(obj[name], value)) { - wrongValues.push(i(name) + ' of ' + i(value) + ' (got ' + i(obj[name]) + ')'); - } else { - props.push(i(name) + ' of ' + i(value)); - } - }); - - if((wrongValues.length !== 0 && !this.one) || (this.one && props.length === 0)) { - props = wrongValues; - } - - operator = (props.length === 1 ? - 'to have property ' : 'to have '+(this.one? 'any of ' : '')+'properties ') + props.join(', '); - - this.params = { operator: operator }; - - //if there is no not matched values - //or there is at least one matched - this.assert(wrongValues.length === 0 || (this.one && wrongValues.length != valueCheckNames.length)); - } - }); - - Assertion.add('length', function(n, description) { - this.have.property('length', n, description); - }); - - Assertion.alias('length', 'lengthOf'); - - var hasOwnProperty = Object.prototype.hasOwnProperty; - - Assertion.add('ownProperty', function(name, description) { - this.params = { operator: 'to have own property ' + i(name), message: description }; - - this.assert(hasOwnProperty.call(this.obj, name)); - - this.obj = this.obj[name]; - }); - - Assertion.alias('ownProperty', 'hasOwnProperty'); - - Assertion.add('empty', function() { - this.params = { operator: 'to be empty' }; - - if(util.isString(this.obj) || Array.isArray(this.obj) || util.isArguments(this.obj)) { - this.have.property('length', 0); - } else { - var obj = Object(this.obj); // wrap to reference for booleans and numbers - for(var prop in obj) { - this.have.not.ownProperty(prop); - } - } - }, true); - - Assertion.add('keys', function(keys) { - if(arguments.length > 1) keys = aSlice.call(arguments); - else if(arguments.length === 1 && util.isString(keys)) keys = [ keys ]; - else if(arguments.length === 0) keys = []; - - var obj = Object(this.obj); - - // first check if some keys are missing - var missingKeys = []; - keys.forEach(function(key) { - if(!hasOwnProperty.call(this.obj, key)) - missingKeys.push(i(key)); - }, this); - - // second check for extra keys - var extraKeys = []; - Object.keys(obj).forEach(function(key) { - if(keys.indexOf(key) < 0) { - extraKeys.push(i(key)); - } - }); - - var verb = keys.length === 0 ? 'to be empty' : - 'to have ' + (keys.length === 1 ? 'key ' : 'keys '); - - this.params = { operator: verb + keys.map(i).join(', ')}; - - if(missingKeys.length > 0) - this.params.operator += '\n\tmissing keys: ' + missingKeys.join(', '); - - if(extraKeys.length > 0) - this.params.operator += '\n\textra keys: ' + extraKeys.join(', '); - - this.assert(missingKeys.length === 0 && extraKeys.length === 0); - }); - - Assertion.alias("keys", "key"); - - Assertion.add('containEql', function(other) { - this.params = { operator: 'to contain ' + i(other) }; - var obj = this.obj; - if(Array.isArray(obj)) { - this.assert(obj.some(function(item) { - return eql(item, other); - })); - } else if(util.isString(obj)) { - // expect obj to be string - this.assert(obj.indexOf(String(other)) >= 0); - } else if(util.isObject(obj)) { - // object contains object case - util.forOwn(other, function(value, key) { - obj.should.have.property(key, value); - }); - } else { - //other uncovered cases - this.assert(false); - } - }); - - Assertion.add('containDeep', function(other) { - this.params = { operator: 'to contain ' + i(other) }; - - var obj = this.obj; - if(Array.isArray(obj)) { - if(Array.isArray(other)) { - var otherIdx = 0; - obj.forEach(function(item) { - try { - should(item).not.be.Null.and.containDeep(other[otherIdx]); - otherIdx++; - } catch(e) { - if(e instanceof should.AssertionError) { - return; - } - throw e; - } - }); - this.assert(otherIdx == other.length); - //search array contain other as sub sequence - } else { - this.assert(false); - } - } else if(util.isString(obj)) {// expect other to be string - this.assert(obj.indexOf(String(other)) >= 0); - } else if(util.isObject(obj)) {// object contains object case - if(util.isObject(other)) { - util.forOwn(other, function(value, key) { - should(obj[key]).not.be.Null.and.containDeep(value); - }); - } else {//one of the properties contain value - this.assert(false); - } - } else { - this.eql(other); - } - }); - -}; - -},{"../eql":2,"../util":16}],13:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -module.exports = function(should, Assertion) { - Assertion.add('startWith', function(str, description) { - this.params = { operator: 'to start with ' + should.format(str), message: description }; - - this.assert(0 === this.obj.indexOf(str)); - }); - - Assertion.add('endWith', function(str, description) { - this.params = { operator: 'to end with ' + should.format(str), message: description }; - - this.assert(this.obj.indexOf(str, this.obj.length - str.length) >= 0); - }); -}; -},{}],14:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -var util = require('../util'); - -module.exports = function(should, Assertion) { - Assertion.add('Number', function() { - this.params = { operator: 'to be a number' }; - - this.assert(util.isNumber(this.obj)); - }, true); - - Assertion.add('arguments', function() { - this.params = { operator: 'to be arguments' }; - - this.assert(util.isArguments(this.obj)); - }, true); - - Assertion.add('type', function(type, description) { - this.params = { operator: 'to have type ' + type, message: description }; - - (typeof this.obj).should.be.exactly(type, description); - }); - - Assertion.add('instanceof', function(constructor, description) { - this.params = { operator: 'to be an instance of ' + constructor.name, message: description }; - - this.assert(Object(this.obj) instanceof constructor); - }); - - Assertion.add('Function', function() { - this.params = { operator: 'to be a function' }; - - this.assert(util.isFunction(this.obj)); - }, true); - - Assertion.add('Object', function() { - this.params = { operator: 'to be an object' }; - - this.assert(util.isObject(this.obj)); - }, true); - - Assertion.add('String', function() { - this.params = { operator: 'to be a string' }; - - this.assert(util.isString(this.obj)); - }, true); - - Assertion.add('Array', function() { - this.params = { operator: 'to be an array' }; - - this.assert(Array.isArray(this.obj)); - }, true); - - Assertion.add('Boolean', function() { - this.params = { operator: 'to be a boolean' }; - - this.assert(util.isBoolean(this.obj)); - }, true); - - Assertion.add('Error', function() { - this.params = { operator: 'to be an error' }; - - this.assert(util.isError(this.obj)); - }, true); - - Assertion.add('null', function() { - this.params = { operator: 'to be null' }; - - this.assert(this.obj === null); - }, true); - - Assertion.alias('null', 'Null'); - - Assertion.alias('instanceof', 'instanceOf'); -}; -},{"../util":16}],15:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - - -var util = require('./util') - , AssertionError = util.AssertionError - , inspect = util.inspect; - -/** - * Our function should - * @param obj - * @returns {Assertion} - */ -var should = function(obj) { - return new Assertion(util.isWrapperType(obj) ? obj.valueOf(): obj); -}; - -/** - * Initialize a new `Assertion` with the given _obj_. - * - * @param {*} obj - * @api private - */ - -var Assertion = should.Assertion = function Assertion(obj) { - this.obj = obj; -}; - - -/** - Way to extend Assertion function. It uses some logic - to define only positive assertions and itself rule with negative assertion. - - All actions happen in subcontext and this method take care about negation. - Potentially we can add some more modifiers that does not depends from state of assertion. -*/ -Assertion.add = function(name, f, isGetter) { - var prop = {}; - prop[isGetter ? 'get' : 'value'] = function() { - var context = new Assertion(this.obj); - context.copy = context.copyIfMissing; - context.one = this.one; - - try { - f.apply(context, arguments); - } catch(e) { - //copy data from sub context to this - this.copy(context); - - //check for fail - if(e instanceof should.AssertionError) { - //negative fail - if(this.negate) { - this.obj = context.obj; - this.negate = false; - return this; - } - this.assert(false); - } - // throw if it is another exception - throw e; - } - //copy data from sub context to this - this.copy(context); - if(this.negate) { - this.assert(false); - } - - this.obj = context.obj; - this.negate = false; - return this; - }; - - Object.defineProperty(Assertion.prototype, name, prop); -}; - -Assertion.alias = function(from, to) { - var desc = Object.getOwnPropertyDescriptor(Assertion.prototype, from); - if(!desc) throw new Error('Alias ' + from + ' -> ' + to + ' could not be created as ' + from + ' not defined'); - Object.defineProperty(Assertion.prototype, to, desc); -}; - -should.AssertionError = AssertionError; -should.format = function (value) { - if(util.isDate(value) && typeof value.inspect !== 'function') return value.toISOString(); //show millis in dates - return inspect(value, { depth: null }); -}; - -should.use = function(f) { - f(this, Assertion); - return this; -}; - - -/** - * Expose should to external world. - */ -exports = module.exports = should; - - -/** - * Expose api via `Object#should`. - * - * @api public - */ - -Object.defineProperty(Object.prototype, 'should', { - set: function(){}, - get: function(){ - return should(this); - }, - configurable: true -}); - - -Assertion.prototype = { - constructor: Assertion, - - assert: function(expr) { - if(expr) return; - - var params = this.params; - - var msg = params.message, generatedMessage = false; - if(!msg) { - msg = this.getMessage(); - generatedMessage = true; - } - - var err = new AssertionError({ - message: msg - , actual: this.obj - , expected: params.expected - , stackStartFunction: this.assert - }); - - err.showDiff = params.showDiff; - err.operator = params.operator; - err.generatedMessage = generatedMessage; - - throw err; - }, - - getMessage: function() { - return 'expected ' + ('obj' in this.params ? this.params.obj: should.format(this.obj)) + (this.negate ? ' not ': ' ') + - this.params.operator + ('expected' in this.params ? ' ' + should.format(this.params.expected) : ''); - }, - - copy: function(other) { - this.params = other.params; - }, - - copyIfMissing: function(other) { - if(!this.params) this.params = other.params; - }, - - - /** - * Negation modifier. - * - * @api public - */ - - get not() { - this.negate = !this.negate; - return this; - }, - - /** - * Any modifier - it affect on execution of sequenced assertion to do not check all, but any of - * - * @api public - */ - get any() { - this.one = true; - return this; - } -}; - - -},{"./util":16}],16:[function(require,module,exports){ -/*! - * Should - * Copyright(c) 2010-2014 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Check if given obj just a primitive type wrapper - * @param {Object} obj - * @returns {boolean} - * @api private - */ -exports.isWrapperType = function(obj) { - return isNumber(obj) || isString(obj) || isBoolean(obj); -}; - -/** - * Merge object b with object a. - * - * var a = { foo: 'bar' } - * , b = { bar: 'baz' }; - * - * utils.merge(a, b); - * // => { foo: 'bar', bar: 'baz' } - * - * @param {Object} a - * @param {Object} b - * @return {Object} - * @api private - */ - -exports.merge = function(a, b){ - if (a && b) { - for (var key in b) { - a[key] = b[key]; - } - } - return a; -}; - -function isNumber(arg) { - return typeof arg === 'number' || arg instanceof Number; -} - -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string' || arg instanceof String; -} - -function isBoolean(arg) { - return typeof arg === 'boolean' || arg instanceof Boolean; -} -exports.isBoolean = isBoolean; - -exports.isString = isString; - -function isBuffer(arg) { - return typeof Buffer !== 'undefined' && arg instanceof Buffer; -} - -exports.isBuffer = isBuffer; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} - -exports.isDate = isDate; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} - -exports.isObject = isObject; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} - -exports.isRegExp = isRegExp; - -function isNullOrUndefined(arg) { - return arg == null; -} - -exports.isNullOrUndefined = isNullOrUndefined; - -function isArguments(object) { - return objectToString(object) === '[object Arguments]'; -} - -exports.isArguments = isArguments; - -exports.isFunction = function(arg) { - return typeof arg === 'function' || arg instanceof Function; -}; - -function isError(e) { - return (isObject(e) && objectToString(e) === '[object Error]') || (e instanceof Error); -} -exports.isError = isError; - -exports.inspect = require('util').inspect; - -exports.AssertionError = require('assert').AssertionError; - -var hasOwnProperty = Object.prototype.hasOwnProperty; - -exports.forOwn = function(obj, f, context) { - for(var prop in obj) { - if(hasOwnProperty.call(obj, prop)) { - f.call(context, obj[prop], prop); - } - } -}; -},{"assert":17,"util":20}],17:[function(require,module,exports){ -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.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 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. - -// when used in node, this will actually load the util module we depend on -// versus loading the builtin util module as happens otherwise -// this is a bug in node module loading as far as I am concerned -var util = require('util/'); - -var pSlice = Array.prototype.slice; -var hasOwn = Object.prototype.hasOwnProperty; - -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) - -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } - else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - // try to strip useless frames - var fn_name = stackStartFunction.name; - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - - this.stack = out; - } - } -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); - -function replacer(key, value) { - if (util.isUndefined(value)) { - return '' + value; - } - if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { - return value.toString(); - } - if (util.isFunction(value) || util.isRegExp(value)) { - return value.toString(); - } - return value; -} - -function truncate(s, n) { - if (util.isString(s)) { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} - -function getMessage(self) { - return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + - self.operator + ' ' + - truncate(JSON.stringify(self.expected, replacer), 128); -} - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - return true; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) - return false; - // an identical 'prototype' property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try { - var ka = objectKeys(a), - kb = objectKeys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key])) return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; - -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } else if (actual instanceof expected) { - return true; - } else if (expected.call({}, actual) === true) { - return true; - } - - return false; -} - -function _throws(shouldThrow, block, expected, message) { - var actual; - - if (util.isString(expected)) { - message = expected; - expected = null; - } - - try { - block(); - } catch (e) { - actual = e; - } - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} - -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; - -assert.ifError = function(err) { if (err) {throw err;}}; - -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; -}; - -},{"util/":20}],18:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],19:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],20:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -},{"./support/isBuffer":19,"inherits":18}]},{},[1]) -(1) -}); \ No newline at end of file diff --git a/node_modules/should/should.min.js b/node_modules/should/should.min.js deleted file mode 100644 index b57e605..0000000 --- a/node_modules/should/should.min.js +++ /dev/null @@ -1,56 +0,0 @@ -!function(C){if("object"==typeof exports)module.exports=C();else if("function"==typeof define&&define.amd)define(C);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self);e.Should=C()}}(function(){return function e(l,d,g){function m(f,b){if(!d[f]){if(!l[f]){var a="function"==typeof require&&require;if(!b&&a)return a(f,!0);if(c)return c(f,!0);throw Error("Cannot find module '"+f+"'");}a=d[f]={exports:{}};l[f][0].call(a.exports,function(b){var h= -l[f][1][b];return m(h?h:b)},a,a.exports,e,l,d,g)}return d[f].exports}for(var c="function"==typeof require&&require,a=0;a").append(h).html()},k=function(h,k,a){c.add(k||h,function(){this.params={operator:"to be "+(a||h)};this.assert(b(this.obj).is(":"+h))},!0)};c.add("className",function(h){this.params={operator:"to have class "+ -h};this.assert(b(this.obj).hasClass(h))});c.add("css",function(h){this.params={operator:"to have css "+f(h)};for(var k in h){var a=h[k];"auto"===a&&"auto"===b(this.obj).get(0).style[k]||b(this.obj).css(k).should.eql(a)}});k("visible");k("hidden");k("selected");k("checked");k("disabled");k("empty","emptyJq");k("focus","focused","focused");c.add("inDOM",function(){this.params={operator:"to be in the DOM"};this.assert(b.contains(document.documentElement,b(this.obj)[0]))},!0);c.add("exist",function(){this.params= -{operator:"to exist"};b(this.obj).should.not.have.length(0)},!0);c.add("attr",function(){var b=["attr","attribute","attributes"].concat(Array.prototype.slice.call(arguments,0));a.apply(this,b)});c.add("prop",function(){var b=["prop","property","properties"].concat(Array.prototype.slice.call(arguments,0));a.apply(this,b)});c.add("elementId",function(b){this.params={operator:"to have ID "+f(b)};this.obj.should.have.attr("id",b)});c.add("html",function(h){this.params={operator:"to have HTML "+f(h)}; -b(this.obj).html().should.eql(e(h))});c.add("containHtml",function(h){this.params={operator:"to contain HTML "+f(h)};b(this.obj).html().indexOf(e(h)).should.be.above(-1)});c.add("text",function(h){this.params={operator:"to have text "+f(h)};var k=b.trim(b(this.obj).text());g.isRegExp(h)?k.should.match(h):k.should.eql(h)});c.add("containText",function(h){this.params={operator:"to contain text "+f(h)};var k=b.trim(b(this.obj).text());g.isRegExp(h)?k.should.match(h):k.indexOf(h).should.be.above(-1)}); -c.add("value",function(h){this.params={operator:"to have value "+f(h)};b(this.obj).val().should.eql(h)});c.add("data",function(){var b=["data","data","data"].concat(Array.prototype.slice.call(arguments,0));a.apply(this,b)});c.add("containElement",function(h){this.params={operator:"to contain "+b(h).inspect()};b(this.obj).find(h).should.not.have.length(0)});c.add("matchedBy",function(h){this.params={operator:"to be matched by selector "+h};b(this.obj).filter(h).should.not.have.length(0)});c.add("handle", -function(h){this.params={operator:"to handle "+h};var k=b._data(b(this.obj).get(0),"events");if(!k||!h||"string"!==typeof h)return this.assert(!1);var a=h.split(".");h=a.shift();var c=a.slice(0).sort(),c=new RegExp("(^|\\.)"+c.join("\\.(?:.*\\.)?")+"(\\.|$)");if(k[h]&&a.length){for(a=0;a=c&&this.obj<=a)});d.add("approximately",function(c,a,f){this.params={operator:"to be approximately "+c+" \u00b1"+a,message:f};this.assert(Math.abs(this.obj-c)<=a)});d.add("above",function(c,a){this.params={operator:"to be above "+c,message:a};this.assert(this.obj> -c)});d.add("below",function(c,a){this.params={operator:"to be below "+c,message:a};this.assert(this.objd.indexOf(b(a))}).map(b));var l=(1===e.length?"to have property ": -"to have "+(this.one?"any of ":"")+"properties ")+e.join(", ");this.params={operator:l};this.assert(0===d.length||this.one&&d.length!=a.length);var r=Object.keys(h);if(r.length){var q=[],e=[];r.forEach(function(a){var c=h[a];m(f[a],c)?e.push(b(a)+" of "+b(c)):q.push(b(a)+" of "+b(c)+" (got "+b(f[a])+")")});if(0!==q.length&&!this.one||this.one&&0===e.length)e=q;l=(1===e.length?"to have property ":"to have "+(this.one?"any of ":"")+"properties ")+e.join(", ");this.params={operator:l};this.assert(0=== -q.length||this.one&&q.length!=r.length)}});f.add("length",function(b,a){this.have.property("length",b,a)});f.alias("length","lengthOf");var d=Object.prototype.hasOwnProperty;f.add("ownProperty",function(a,c){this.params={operator:"to have own property "+b(a),message:c};this.assert(d.call(this.obj,a));this.obj=this.obj[a]});f.alias("ownProperty","hasOwnProperty");f.add("empty",function(){this.params={operator:"to be empty"};if(g.isString(this.obj)||Array.isArray(this.obj)||g.isArguments(this.obj))this.have.property("length", -0);else{var b=Object(this.obj),a;for(a in b)this.have.not.ownProperty(a)}},!0);f.add("keys",function(a){1a.indexOf(c)&&l.push(b(c))});this.params={operator:(0===a.length?"to be empty":"to have "+(1===a.length?"key ":"keys "))+a.map(b).join(", ")};0 "+a+" could not be created as "+b+" not defined");Object.defineProperty(f.prototype,a,c)};a.AssertionError=m;a.format=function(b){return g.isDate(b)&&"function"!==typeof b.inspect? -b.toISOString():c(b,{depth:null})};a.use=function(b){b(this,f);return this};l.exports=a;Object.defineProperty(Object.prototype,"should",{set:function(){},get:function(){return a(this)},configurable:!0});f.prototype={constructor:f,assert:function(b){if(!b){b=this.params;var a=b.message,c=!1;a||(a=this.getMessage(),c=!0);a=new m({message:a,actual:this.obj,expected:b.expected,stackStartFunction:this.assert});a.showDiff=b.showDiff;a.operator=b.operator;a.generatedMessage=c;throw a;}},getMessage:function(){return"expected "+ -("obj"in this.params?this.params.obj:a.format(this.obj))+(this.negate?" not ":" ")+this.params.operator+("expected"in this.params?" "+a.format(this.params.expected):"")},copy:function(b){this.params=b.params},copyIfMissing:function(b){this.params||(this.params=b.params)},get not(){this.negate=!this.negate;return this},get any(){this.one=!0;return this}}},{"./util":16}],16:[function(e,l,d){function g(b){return"number"===typeof b||b instanceof Number}function m(b){return"string"===typeof b||b instanceof -String}function c(b){return"boolean"===typeof b||b instanceof Boolean}function a(b){return"object"===typeof b&&null!==b}d.isWrapperType=function(b){return g(b)||m(b)||c(b)};d.merge=function(b,a){if(b&&a)for(var c in a)b[c]=a[c];return b};d.isNumber=g;d.isBoolean=c;d.isString=m;d.isBuffer=function(b){return"undefined"!==typeof Buffer&&b instanceof Buffer};d.isDate=function(b){return a(b)&&"[object Date]"===Object.prototype.toString.call(b)};d.isObject=a;d.isRegExp=function(b){return a(b)&&"[object RegExp]"=== -Object.prototype.toString.call(b)};d.isNullOrUndefined=function(b){return null==b};d.isArguments=function(b){return"[object Arguments]"===Object.prototype.toString.call(b)};d.isFunction=function(b){return"function"===typeof b||b instanceof Function};d.isError=function(b){return a(b)&&"[object Error]"===Object.prototype.toString.call(b)||b instanceof Error};d.inspect=e("util").inspect;d.AssertionError=e("assert").AssertionError;var f=Object.prototype.hasOwnProperty;d.forOwn=function(b,a,c){for(var d in b)f.call(b, -d)&&a.call(c,b[d],d)}},{assert:17,util:20}],17:[function(e,l,d){function g(b,a){return p.isUndefined(a)?""+a:p.isNumber(a)&&(isNaN(a)||!isFinite(a))||p.isFunction(a)||p.isRegExp(a)?a.toString():a}function m(a,b){return p.isString(a)?a.lengthg)return w(e)?c.stylize(RegExp.prototype.toString.call(e),"regexp"):c.stylize("[Object]","special");c.seen.push(e);m=z?k(c,e,g,n,m):m.map(function(a){return h(c, -e,g,n,a,z)});c.seen.pop();return p(m,l,A)}function b(a,b){if(q(b))return a.stylize("undefined","undefined");if(t(b)){var c="'"+JSON.stringify(b).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return a.stylize(c,"string")}if(n(b))return a.stylize(""+b,"number");if(v(b))return a.stylize(""+b,"boolean");if(null===b)return a.stylize("null","null")}function r(a){return"["+Error.prototype.toString.call(a)+"]"}function k(a,b,c,d,e){for(var f=[],g=0,k=b.length;ga.seen.indexOf(b.value)?(k=null===c?f(a,b.value,null):f(a,b.value,c-1),-1a?"0"+a.toString(10):a.toString(10)}function G(){var a=new Date,b=[E(a.getHours()),E(a.getMinutes()),E(a.getSeconds())].join(":");return[a.getDate(),H[a.getMonth()],b].join(" ")}var I=/%[sdj%]/g;d.format=function(a){if(!t(a)){for(var b=[],c=0;c=e)return a;switch(a){case "%s":return String(d[c++]);case "%d":return Number(d[c++]);case "%j":try{return JSON.stringify(d[c++])}catch(b){return"[Circular]"}default:return a}}),f=d[c];c Sinon version : -> Environment : -> Example URL : -> -> ##### Bug description - -Here's an example use of the template - -> Sinon version : 1.10.3 -> Environment : OSX Chrome 37.0.2062.94 -> Example URL : http://jsbin.com/iyebiWI/8/edit -> -> ##### Bug description -> -> If `respondWith` called with a URL including query parameter and a function , it doesn't work. -> This error reported in console. -> ``` -> `TypeError: requestUrl.match(...) is null` -> ``` - -## Contributing to the code base - -Pick [an issue](http://github.com/cjohansen/Sinon.JS/issues) to fix, or pitch -new features. To avoid wasting your time, please ask for feedback on feature -suggestions either with [an issue](http://github.com/cjohansen/Sinon.JS/issues/new) -or on [the mailing list](http://groups.google.com/group/sinonjs). - -### Making a pull request - -Please try to [write great commit messages](http://chris.beams.io/posts/git-commit/). - -There are numerous benefits to great commit messages - -* They allow Sinon.JS users to easily understand the consequences of updating to a newer version -* They help contributors understand what is going on with the codebase, allowing features and fixes to be developed faster -* They save maintainers time when compiling the changelog for a new release - -If you're already a few commits in by the time you read this, you can still [change your commit messages](https://help.github.com/articles/changing-a-commit-message/). - -Also, before making your pull request, consider if your commits make sense on their own (and potentially should be multiple pull requests) or if they can be squashed down to one commit (with a great message). There are no hard and fast rules about this, but being mindful of your readers greatly help you author good commits. - -### Use EditorConfig - -To save everyone some time, please use [EditorConfig](http://editorconfig.org), so your editor helps make -sure we all use the same encoding, indentation, line endings, etc. - -### Installation - -The Sinon.JS developer environment requires Node/NPM. Please make sure you have -Node installed, and install Sinon's dependencies: - - $ npm install - -#### PhantomJS - -In order to run the tests, you'll need a [PhantomJS](http://phantomjs.org) global. - -The test suite runs well with both `1.9.x` and `2.0.0` - -### Style - -Sinon.JS uses [JSCS](https://github.com/mdevils/node-jscs) to keep consistent style. You probably want to install one of their plugins for your editor. - -The JSCS test will be run before unit tests in the CI environment, your build will fail if it doesn't pass the style check. - -``` -$ npm run lint -``` - -To ensure consistent reporting of lint warnings, you should use the same version as CI environment (defined in `package.json`) - -### Run the tests - -This runs linting as well as unit tests in both PhantomJS and node - - $ npm test - -##### Testing in development - -Sinon.JS uses [Buster.JS](http://busterjs.org), please read those docs if you're unfamiliar with it. - -If you just want to run tests a few times - - $ npm run ci-test - -If you're doing more than a one line edit, you'll want to have finer control and less restarting of the Buster server and PhantomJS process - - # start a server - $ $(npm bin)/buster-server - - # capture a browser by pointing it to http://localhost:1111/capture - # run tests (in both browser and node) - $ $(npm bin)/buster-test - - # run tests only in browser - $ $(npm bin)/buster-test --config-group browser - - # run tests only in node - $ $(npm bin)/buster-test --config-group node - -If you install `Buster.JS` as a global, you can remove `$(npm-bin)/` from the lines above. - -##### Testing a built version - -To test against a built distribution, first -make sure you have a build (requires [Ruby][ruby] and [Juicer][juicer]): - - $ ./build - -[ruby]: https://www.ruby-lang.org/en/ -[juicer]: http://rubygems.org/gems/juicer - -If the build script is unable to find Juicer, try - - $ ruby -rubygems build - -Once built, you can run the tests against the packaged version as part of the `ci-test.sh` script. - - ./scripts/ci-test.sh - diff --git a/node_modules/sinon/Changelog.txt b/node_modules/sinon/Changelog.txt deleted file mode 100644 index a2114d9..0000000 --- a/node_modules/sinon/Changelog.txt +++ /dev/null @@ -1,499 +0,0 @@ -1.15.0 / 2015-05-30 -================== -* Fixed bug where assertions don't handle functions that have a property named proxy -* update license attribute -* Add test coverage report -* responseHeaders on abort are empty object -* Fix pre-existing style error -* Update documentation to cover testing built version -* Update CONTRIBUTING.md with section about "Making a pull request" -* Improve RELEASE.md to reduce effort when cutting a new release -* Deprecate mock -* Release.md -* Make `npm docs sinon` work. -* Run unit tests against packaged version in CI environment -* Remove unused Gruntfile -* Use Vanilla Buster.JS -* Use `files` in package.json -* Fix code style -* Don't stub getter properties -* Event listeners for `progress`, `load` and `readystatechange` in the `readyStateChange` function in `FakeXMLHttpRequest` are dispatched in a different order in comparison to a browser. Reorder the events dispatched to reflect general browser behaviour. -* Update linting instructions in CONTRIBUTING.md -* Lint all files with new linter -* Update JSCS to 1.11.3 and make npm lint task verify all files -* Cleanup .restore() - -== 1.14.1 / 2015-03-16 -* Fallback for .restore() native code functions on Chrome & PhantomJS (なつき) -* Restore support for sinon in IE<9 (Harry Wolff) - -== 1.14.0 / 2015-03-13 -* Stub & spy getters & setters (Simon Zack) -* Fix #702 async sinon.test using mocha interface (Mohayonao) -* Add respondImmediately to fake servers (Jonathan Freeman) - -== 1.13.0 / 2015-03-04 -* fix @depends-require mismatches (fixes AMD issues) (Ben Hockey) -* Fix spy.calledWith(undefined) to return false if it was called without args -* yieldsRight (Alexander Schmidt) -* stubs retain function arity (Charlie Rudolph) -* (AMD) use explicit define in built version -* spy().reset() returns this (Ali Shakiba) -* Add lengthComputable and download progress (Tamas Szebeni) -* Don't setContent-type when sending FormData (AJ Ortega) -* sinon.assert with spyCall (Alex Urbano) -* fakeXHR requests in Node. (Jmeas) -* Enhancement: run builds on docker (till@php.net) -* Use FakeXDomainRequest when XHR does not support CORS. Fixes #584 (Eric Wendelin) -* More lenient check for ActiveXObject -* aligned sandbox.useFakeXMLHttpRequest API to documentation (Phred) -* Fix #643. Returns supersedes previous throws (Adam Hull) -* Safely overwrite properties in IE - no more IE files! -* Add check for setInterval/clearInterval (kdpecker) -* Add safety check for document.createElement (kdpecker) -* Fix #633. Use a try/catch when deleting a property in IE8. (Garrick Cheung) - -== 1.12.1 / 2014-11-16 -* Fixed lolex issue on node - -== 1.12.0 / 2014-11-16 -* Fake timers are now extracted as lolex: http://github.com/sinonjs/lolex -* Improved setImmediate fake -* Proper AMD solution - -== 1.11.1 / 2014-10-27 - -* Expose match on returned sandbox (Duncan Beevers) -* Fix issue #586 (Antonio D'Ettole) -* Declare log_error dependency (Kurt Ruppel) - -== 1.11.0 / 2014-10-26 - -* Proper AMD support -* Don't call sinon.expectation.pass if there aren't any expectations (Jeffrey Falgout) -* Throw error when reset-ing while calling fake -* Added xhr.response property (Gyandeep Singh) -* Fixed premature sandbox destruction (Andrew Gurinovich) -* Add sandbox reset method (vitalets) -* A bunch of bug fixes (git log) -* Various source organizational improvements (Morgan Roderick and others) - -== 1.10.3 / 2014-07-11 - -* Fix loading in Web Workers (Victor Costan) -* Allow null as argument to clearTimeout and clearInterval (Lars Thorup) - -== 1.10.2 / 2014-06-02 - -* Fix `returnValue` and `exception` regression on spy calls (Maximilian Antoni) - -== 1.10.1 / 2014-05-30 - -* Improved mocha compatibility for async tests (Ming Liu) -* Make the fakeServer log function overloadable (Brian M Hunt) - -== 1.10.0 / 2014-05-19 - -* Ensure that spy createCallProperties is set before function invocation (James Barwell) -* XDomainRequest support (Søren Enemærke, Jonathan Sokolowski) -* Correct AMD behavior (Tim Branyen) -* Allow explicit naming of spies and stubs (Glen Mailer) -* deepEqual test for unequal objects in calledWithExactly (Bryan Donovan) -* Fix clearTimeout() for Node.js (Xiao Ma) -* fix fakeServer.respond() in IE8 (John Bernardo) -* Fix #448 (AMD require.amd) -* Fix wrapMethod error handling (Nikita Litvin) - -== 1.9.1 / 2014-04-03 - -* Fix an issue passing `NaN` to `calledWith` (Blake Israel) -* Explicate dependency on util package (Kris Kowal) -* Fake timers return an object with `ref` and `unref` properties on Node (Ben Fleis) - -== 1.9.0 / 2014-03-05 - -* Add sinon.assert.match (Robin Pedersen) -* Added ProgressEvent and CustomEvent. Fixes bug with progress events on IE. (Geries Handal) -* prevent setRequestHeaders from being called twice (Phred) -* Fix onload call, 'this' should be equal to XHR object (Niklas Andreasson) -* Remove sandbox injected values on restore (Marcus Hüsgen) -* Coerce matcher.or/and arguments into matchers (Glen Mailer) -* Don't use buster.format any more -* Fix comparison for regexp deepEqual (Matt Kern) - -== 1.8.2 / 2014-02-11 - -* Fixes an edge case with calledWithNew and spied native functions, and other - functions that lack a .prototype -* Add feature detection for the new ProgressEvent support - -== 1.8.1 / 2014-02-02 - -* Screwed up NPM release of 1.8.0, unable to replace it - -== 1.8.0 / 2014-02-02 - -* Add clearImmediate mocking support to the timers API (Tim Perry) -* Mirror custom Date properties when faking time -* Improved Weinre support -* Update call properties even if exceptions are thrown (Tim Perry) -* Update call properties even if exceptions are thrown (Tim Perry) -* Reverse matching order for fake server (Gordon L. Hempton) -* Fix restoring globals on another frame fails on Firefox (Burak Yiğit Kaya) -* Handle stubbing falsey properties (Tim Perry) -* Set returnValues correctly when the spied function is called as a constructor (Tim Perry) -* When creating a sandbox, do not overwrite existing properties when inject - properties into an object (Sergio Cinos) -* Added withCredentials property to fake xhr (Geries) -* Refine behavior withArgs error message (Tim Fischbach) -* Auto-respond to successive requests made with a single XHR object (Jan Suchý) -* Add the ability for mock to accept sinon.match matchers as expected arguments (Zcicala) -* Adding support for XMLHttpRequest.upload to FakeXMLHttpRequest (Benjamin Coe) -* Allow onCall to be combined with returns* and throwsException in stub behavior - sequences (Tim Fischbach) -* Fixed deepEqual to detect properties on array objects -* Fixed problem with chained timers with delay=0 (Ian Lewis) -* Use formatio in place of buster-format (Devin Weaver) - -== 1.7.3 / 2013-06-20 - -* Removed use of array forEach, breaks in older browsers (Martin Hansen) -* sinon.deepEqual(new Date(0), new Date()) returns true (G.Serebryanskyi) - -== 1.7.2 / 2013-05-08 - -* Sinon 1.7 has split calls out to a separate file. This caused some problems, - so 1.7.2 ships with spyCall as part of spy.js like it used to be. - -== 1.7.1 / 2013-05-07 - -* Fake XMLHttpRequest updated to call onerror and onsuccess callbacks, fixing - jQuery 2.0 problems (Roman Potashow) -* Implement XMLHttpRequest progress event api (Marten Lienen) -* Added sinon.restore() (Jonny Reeves) -* Fix bug where throwing a string was handled incorrectly by Sinon (Brandon Heyer) -* Web workers support (Victor Costan) - -== 1.7.0 - -* Failed release, see 1.7.1 - -== 1.6.0 / 2013-02-18 -* Add methods to spyCall interface: callArgOn, callArgOnWith, yieldOn, - yieldToOn (William Sears) -* sinon.createStubInstance creates a fully stubbed instance from a constructor - (Shawn Krisman) -* resetBehavior resets fakes created by withArgs (Martin Sander) -* The fake server now logs to sinon.log, if set (Luis Cardoso) -* Cleaner npm package that also includes pkg/sinon.js and - pkg/sinon-ie.js for cases where npm is used to install Sinon for - browser usage (Domenic Denicola) -* Improved spy formatter %C output (Farid Neshat) -* clock.tick returns clock.now (Michael Jackson) -* Fixed issue #248 with callOrder assertion - Did not fail if the last given spy was never called (Maximilian Antoni) -* Fixed issue with setResponseHeader for synchronous requests (goligo) -* Remove msSetImmediate; it only existed in IE10 previews (Domenic Denicola) -* Fix #231: not always picking up the latest calls to callsArgWith, etc. - (Domenic Denicola) -* Fix failing anonymous mock expectations - -== 1.5.2 / 2012-11-28 -* Revert stub.reset changes that caused existing tests to fail. - -== 1.5.1 / 2012-11-27 -* Ensure window.Image can be stubbed. (Adrian Phinney) -* Fix spy() in IE 8 (Scott Andrews) -* Fix sinon base in IE 8 (Scott Andrews) -* Format arguments ouput when mock excpetation is not met (kbackowski) -* Calling spy.reset directly from stub.reset (Thomas Meyer) - -== 1.5.0 / 2012-10-19 -* Don't force "use strict" on Sinon consumers -* Don't assume objects have hasOwnProperties. Fixes problem with e.g. - stubbing properties on process.env -* Preserve function length for spy (Maximilian Antoni) -* Add 'invokeCallback' alias for 'yield' on calls (Maximilian Antoni) -* Added matcher support for calledOn (Maximilian Antoni) -* Retain original expectation messages, for failed mocks under sinon.test - (Giorgos Giannoutsos) -* Allow yields* and callsArg* to create sequences of calls. (Domenic Denicola) -* sinon.js can catch itself in endless loop while filling stub prototype - with asynch methods (Jan Kopriva) - -== 1.4.2 / 2012-07-11 -* sinon.match for arrays (Maximilian Antoni) - -== 1.4.1 / 2012-07-11 -* Strengthen a Node.JS inference to avoid quirky behavior with Mocha - (which provides a shim process object) - -== 1.4.0 / 2012-07-09 -* Argument matchers (Maximillian Antoni) - sinon.match.{any, same, typeOf, instanceOf, has, hasOwn, defined, truthy, - falsy} as well as typeOf shortcuts for boolean, number, string, object, - function, array, regexp and date. The result of a call can be used with - spy.calledWith. -* spy.returned now works with matchers and compares objects deeply. -* Matcher assertions: calledWithMatch, alwaysCalledWithMatch and - neverCalledWithMatch -* calledWithNew and alwaysCalledWithNew for assert (Maximilian Antoni) -* Easier stubbed fluent interfaces: stub.returnsThis() (Glen Mailer) -* allow yields() and family to be used along with returns()/throws() and - family (Glen Mailer) -* Async versions `callsArg*` and `yields*` for stubs (TEHEK) -* Format args when doing `spy.printf("%*")` (Domenic Denicola) -* Add notCalled property to spies -* Fix: spy.reset did not reset fakes created by spy.withArgs (Maximilian Antoni) -* Properly restore stubs when stubbing entire objects through the sandbox - (Konrad Holowinski) -* Restore global methods properly - delete properties that where not own - properties (Keith Cirkel) -* setTimeout and setInterval pass arguments (Rodion Vynnychenko) -* Timer callbacks that contain a clock.tick no longer fails (Wesley Waser) -* spy(undefined, "property") now throws -* Prevent multiple restore for fake timers (Kevin Decker) -* Fix toString format under Node (Kevin Decker) -* Mock expectations emit success and failure events (Kevin Decker) -* Development improvement: Use Buster.JS to test Sinon -* Fix bug where expect.atLeast failed when minimum calls where received -* Make fake server safe to load on node.js -* Add support for no args on .withArgs and .withExactArgs (Tek Nynja) -* Avoid hasOwnProperty for host objects - -== 1.3.2 / 2012-03-11 -* Stronger Node inference in sandbox -* Fixed issue with sinon.useFakeTimers() and Rhino.js 1.7R3 -* Formatting brush-up -* FIX Internet Explorer misreporting the type of Function objects - originating in an external window as "object" instead of "function". -* New methods stub.callsArgOn, stub.callsArgOnWith, - stub.yieldsOn, stub.yieldsToOn -* Implemented -* Fixing `clearTimeout` to not throw when called for nonexistant IDs. -* Spys that are created using 'withArgs' now get initialized with previous - calls to the original spy. -* Minor bug fixes and docs cleanup. - -== 1.3.1 / 2012-01-04 -* Fix bug in core sinon: isNode was used for both a variable and a function, - causing load errors and lots of bugs. Should have never left the door. - -== 1.3.0 / 2012-01-01 -* Support using bare functions as fake server response handlers (< 1.3.0 - required URL and/or method matcher too) -* Log some internal errors to sinon.log (defaults to noop). Set sinon.log - to your logging utility of choice for better feedback when. -* White-list fake XHRs: Allows some fake requests and some that fall through to - the backend server (Tim Ruffles) -* Decide Date.now support at fake-time. Makes it possible to load something that - polyfills Date.now after Sinon loaded and still have Date.now on fake Dates. -* Mirror properties on replaced function properties -* New methods: spy.yield(), spy.yieldTo(), spy.callArg() and spy.callArgWith() - can be used to invoke callbacks passed to spies (while avoiding the mock-like - upfront yields() and friends). invokeCallback is available as an alias for - yield for people working with strict mode. (Maximilian Antoni) -* New properties: spy.firstCall, spy.secondCall, spy.thirdCall and spy.lastCall. - (Maximilian Antoni) -* New method: stub.returnsArg(), causes stub to return one of its arguments. - (Gavin Huang) -* Stubs now work for inherited methods. This was previously prohibited to avoid - stubbing not-yet-implemented methods. (Felix Geisendörfer) -* server.respond() can now accept the same arguments as server.respondWith() for - quick-and-dirty respondWith+respond. (Gavin Huang) -* Format objects with buster-format in the default bundle. Default to - util.inspect on node unless buster-format is available (not a hard dependency, - more like a 'preference'). - -* Bug fix: Make sure XHRs can complete even if onreadystatechange handler fails -* Bug fix: Mirror entire Date.prototype, including toUTCString when faking -* Bug fix: Default this object to global in exposed asserts -* Bug fix: sinon.test: use try/finally instead of catch and throw - preserves - stack traces (Kevin Turner) -* Bug fix: Fake `setTimeout` now returns ids greater than 0. (Domenic Denicola) -* Bug fix: NPM install warning (Felix Geisendörfer) -* Bug fix: Fake timers no longer swallows exceptions (Felix Geisendörfer) -* Bug fix: Properly expose all needed asserts for node -* Bug fix: wrapMethod on window property (i.e. when stubbing/spying on global - functions) -* Bug fix: Quote "yield" (Ben Hockey) -* Bug fix: callOrder works correctly when spies have been called multiple times - -== 1.2.0 / 2011-09-27 -* Bug fix: abort() switches state to DONE when OPENED and sent. Fix by - Tristan Koch. -* Bug fix: Mootools uses MSXML2.XMLHTTP as objectId, which Sinon matched with - different casing. Fix by Olmo Maldonado. -* Bug fix: When wrapping a non-owned property, restore now removes the wrapper - instead of replacing it. Fix by Will Butler. -* Bug fix: Make it possibly to stub Array.prototype.push by not using that - method directly inside Sinon. -* Bug fix: Don't assume that req.requestBody is a string in the fake server. -* Added spy.printf(format) to print a nicely formatted message with details - about a spy. -* Garbage collection: removing fakes from collections when restoring the - original methods. Fix by Tristan Koch. -* Add spy.calledWithNew to check if a function was used as a constructor -* Add spy.notCalledWith(), spy.neverCalledWith() and - sinon.assert.neverCalledWith. By Max Antoni -* Publicly expose sinon.expectation.fail to allow tools to integrate with mock - expectations. -* Fake XMLHttpRequests now support a minimal portion of the events API, making - them work seamlessly with e.g. SproutCode (which uses - xhr.addEventListener("readystatechange"). Partially by Sven Fuchs. - -== 1.1.1 / 2011-05-17 -* Fix broken mock verification in CommonJS when not including the full Sinon - package. - -== 1.1.0 / 2011-05-04 -* The fake server now has a autoRespond method which allows it to respond to - requests on the fly (asynchronously), making it a good fit for mockup - development -* Stubs and spies now has a withArgs method. Using it allows you to create - several spies/stubs for the same method, filtered by received arguments -* Stubs now has yields and yieldsTo methods for fuzzily invoking callbacks. - They work like callsArgAt only by inferring what callback to invoke, and - yieldsTo can invoke callbacks in object "options" arguments. -* Allow sandboxes/collections to stub any property so long as the object - has the property as an own property -* Significantly improve error reporting from failed mock expecations. Now prints - all met and unmet expectations with expected and received arguments -* Allow mock expectations to be consumed in any order -* Add pretty printing of all calls when assertions fail -* Fix bug: Stub exception message ended up as "undefined" (string) if not - specified -* Pass capture groups in URLs to fakeServer function handlers -* Pass through return value from test function in testCase -* typeof require is not enough to assume node, also use typeof module -* Don't use Object.create in sinon.create. In the off chance that someone stubs - it, sinon will fail mysteriously (Thanks to Espen Dalløkken) -* Catch exceptions when parsing DOM elements "on a hunch" - When responding to XHRs, Sinon acts like most browsers and try to parse the - response into responseXML if Content-Type indicates XML or HTML. However, it - also does this if the type is not set. Obviously, this may misfire and - should be caught. -* Fix fakeServer.respond() to not drop requests when they are queued during the - processing of an existing queue. (Sven Fuchs) -* Clean up module loading in CommonJS environments (Node.js still the only - tested such environment). No longer (temporarily) modifies require.paths, - always loads all modules. - -== 1.0.2 / 2011-02-22 -* Fix JSON bug in package.json -* Sandbox no longer tries to use a fake server if config says so, but - server is not loaded - -== 1.0.1 / 2010-12-20 -* Make sure sinon.sandbox is exposed in node.js (fix by Gord Tanner) - -== 1.0.0 / 2010-12-08 -* Switched indentation from 2 to 4 spaces :) -* Node.js compatibility improvements -* Remove magic booleans from sinon.assert.expose, replace with option object -* Put QUnit adapter in it's own repository -* Update build script to build standalone timers and server files -* Breaking change: thisObj -> thisValue - Change brings consistency to the code-base, always use thisValue -* Add sinon.assert.pass callback for successful assertions -* Extract sandbox configuration from sinon.test - - Refactored sinon.test to not do all the heavy lifting in creating sandbox - objects from sinon.config. Now sinon.sandbox.create accepts an optional - configuration that can be retrieved through sinon.getConfig({ ... }) - or, to - match previous behavior, through sinon.getConfig(sinon.config); - - The default configuration now lives in sinon.defaultConfig rather than the - previous sinon.test. - - This change enables external tools, such as test framework adapters, to easily - create configurable sandboxes without going through sinon.test -* Rewrite sinon.clock.tick to fix bug and make implementation clearer -* Test config load correct files -* Make timers and XHR truly standalone by splitting the IE work-around in two files -* Don't fail when comparing DOM elements in sinon.deepEqual (used in calledWith(...)) -* Should mirror properties on Date when faking it -* Added and updated configuration for both JsLint and JavaScript lint -* [August Lilleaas] The build script can optionally build a file without the - version name in it, by passing 'plain', i.e. './build plain'. - - Useful when using the build script to build and use sinon programatically, so - one can 'cp path/to/sinon/pkg/sinon.js my/scripts/' -* [August Lilleaas] Checking and warning if we got a load error and rubygems - isn't present. -* [August Lilleaas] Updating build script to be runnable from any - directory. Current working directory doesn't have to be repo root. - -== 0.8.0 / 2010-10-30 -* sinon.wrapMethod no longer accepts faking already faked methods -* sinon-qunit 'plugin' -* sinon.test / sinon.config can now expose the sandbox object - -== 0.7.2 / 2010-10-25 -* Add sinon.sandbox.create back in -* Fix bug where clock.tick would fire timeouts in intervals when - setInterval was also called - -== 0.7.1 / 2010-10-16 -* The fake server will now match paths against full URLs, meaning that - server.respondWith("/", "OK"); will match requests for - "http://currentHost/". -* Improved toString method for spies and stubs which leads to more - precise error messages from sinon.assert.* - -== 0.7.0 / 2010-09-19 -* sinon.useFakeTimers now fakes the Date constructor by default -* sinon.testCase now fakes XHR and timers by default -* sinon.config controls the behavior of sinon.testCase -* Fixed bug in clock.tick - now fires timers in correct order -* Added the ability to tick a clock string for longer ticks. - Passing a number causes the clock to tick the specified amount of - milliseconds, passing a string like "12:32" ticks 12 minutes and 32 - seconds. -* calledBefore and calledAfter for individual calls -* New assertions - sinon.assert.notCalled - sinon.assert.calledOnce - sinon.assert.calledTwice - sinon.assert.calledThrice -* sinon.test now throws if passed anything other than a function -* sinon.testCase now throws if passed anything other than an object -* sinon.{spy,stub}(obj, method) now throws if the property is not an - existing function - helps avoid perpetuating typo bugs -* Vastly improved error messages from assertions -* Spies/stubs/expectations can have their names resolved in many cases -* Removed feature where sinon.testCase allowed for nested test cases - (does not belong in Sinon.JS) -* Organizational change: src/ becomes lib/ Helps npm compatibility -* Thanks to Cory Flanigan for help on npm compatibility - -== 0.6.2 / 2010-08-12 -* Fixed another bug in sinon.fakeServerWithClock where consecutive - respond() calls did not trigger timeouts. - -== 0.6.1 / 2010-08-12 -* Fixed a bug in sinon.fakeServerWithClock where the clock was ticked - before the server had responded to all requests, resulting in - objects not having been responded to by the time the timeout ran. - -== 0.6.0 / 2010-08-10 -* FakeXMLHttpRequest -* sinon.useFakeXMLHttpRequest -* sinon.fakeServer -* sinon.fakeServerWithClock -* Improved fake timers implementation, made them work properly in IE 6-8 -* Improved sinon.sandbox - * Added useFakeServer - * Added inject method -* Improved sinon.test method - * Made configuration aware - * Now uses sinon.sandbox in place of sinon.collection -* Changed default configuration for sinon.test, breaking compatibility - with 0.5.0 - can be changed through sinon.config - -== 0.5.0 / 2010-06-09 -* Initial release -* Spies, stubs, mocks -* Assertions -* collections, test, testCase -* Fake timers (half-baked) diff --git a/node_modules/sinon/LICENSE b/node_modules/sinon/LICENSE deleted file mode 100644 index e7f50d1..0000000 --- a/node_modules/sinon/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -(The BSD License) - -Copyright (c) 2010-2014, Christian Johansen, christian@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. diff --git a/node_modules/sinon/README.md b/node_modules/sinon/README.md deleted file mode 100644 index 6eb68df..0000000 --- a/node_modules/sinon/README.md +++ /dev/null @@ -1,46 +0,0 @@ -# Sinon.JS - -[![Build status](https://secure.travis-ci.org/cjohansen/Sinon.JS.svg?branch=master)](http://travis-ci.org/cjohansen/Sinon.JS) - -Standalone and test framework agnostic JavaScript test spies, stubs and mocks. - -## Installation - -via [npm (node package manager)](http://github.com/isaacs/npm) - - $ npm install sinon - -via [NuGet (package manager for Microsoft development platform)](https://www.nuget.org/packages/SinonJS) - - Install-Package SinonJS - -or install via git by cloning the repository and including sinon.js -in your project, as you would any other third party library. - -Don't forget to include the parts of Sinon.JS that you want to use as well -(i.e. spy.js). - -## Usage - -See the [sinon project homepage](http://sinonjs.org/) for documentation on usage. - -If you have questions that are not covered by the documentation, please post them to the [Sinon.JS mailinglist](http://groups.google.com/group/sinonjs) or drop by #sinon.js on irc.freenode.net:6667 - -### Important: AMD needs pre-built version - -Sinon.JS *as source* **doesn't work with AMD loaders** (when they're asynchronous, like loading via script tags in the browser). For that you will have to use a pre-built version. You can either [build it yourself](CONTRIBUTING.md#testing-a-built-version) or get a numbered version from http://sinonjs.org. - -This might or might not change in future versions, depending of outcome of investigations. Please don't report this as a bug, just use pre-built versions. - -## Goals - -* No global pollution -* Easy to use -* Require minimal “integration” -* Easy to embed seamlessly with any testing framework -* Easily fake any interface -* Ship with ready-to-use fakes for XMLHttpRequest, timers and more - -## Contribute? - -See [CONTRIBUTING.md](CONTRIBUTING.md) for details on how you can contribute to Sinon.JS diff --git a/node_modules/sinon/lib/sinon.js b/node_modules/sinon/lib/sinon.js deleted file mode 100644 index 14fa07e..0000000 --- a/node_modules/sinon/lib/sinon.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Sinon core utilities. For internal use only. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -var sinon = (function () { - 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; -}()); diff --git a/node_modules/sinon/lib/sinon/assert.js b/node_modules/sinon/lib/sinon/assert.js deleted file mode 100644 index 2e7fb4a..0000000 --- a/node_modules/sinon/lib/sinon/assert.js +++ /dev/null @@ -1,215 +0,0 @@ -/** - * @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@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(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 && method.proxy.isSinonProxy) { - 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)); diff --git a/node_modules/sinon/lib/sinon/behavior.js b/node_modules/sinon/lib/sinon/behavior.js deleted file mode 100644 index 0f6e386..0000000 --- a/node_modules/sinon/lib/sinon/behavior.js +++ /dev/null @@ -1,359 +0,0 @@ -/** - * @depend util/core.js - * @depend extend.js - */ -/** - * Stub behavior - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Tim Fischbach (mail@timfischbach.de) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(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)); diff --git a/node_modules/sinon/lib/sinon/call.js b/node_modules/sinon/lib/sinon/call.js deleted file mode 100644 index 2c0d59b..0000000 --- a/node_modules/sinon/lib/sinon/call.js +++ /dev/null @@ -1,219 +0,0 @@ -/** - * @depend util/core.js - * @depend match.js - * @depend format.js - */ -/** - * Spy calls - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Maximilian Antoni (mail@maxantoni.de) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - * Copyright (c) 2013 Maximilian Antoni - */ -"use strict"; - -(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)); diff --git a/node_modules/sinon/lib/sinon/collection.js b/node_modules/sinon/lib/sinon/collection.js deleted file mode 100644 index 8781743..0000000 --- a/node_modules/sinon/lib/sinon/collection.js +++ /dev/null @@ -1,167 +0,0 @@ -/** - * @depend util/core.js - * @depend spy.js - * @depend stub.js - * @depend mock.js - */ -/** - * Collections of stubs, spies and mocks. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(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)); diff --git a/node_modules/sinon/lib/sinon/extend.js b/node_modules/sinon/lib/sinon/extend.js deleted file mode 100644 index 1a2442b..0000000 --- a/node_modules/sinon/lib/sinon/extend.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * @depend util/core.js - */ -"use strict"; - -(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)); diff --git a/node_modules/sinon/lib/sinon/format.js b/node_modules/sinon/lib/sinon/format.js deleted file mode 100644 index 8ae17dd..0000000 --- a/node_modules/sinon/lib/sinon/format.js +++ /dev/null @@ -1,88 +0,0 @@ -/** - * @depend util/core.js - */ -/** - * Format functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -(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) -)); diff --git a/node_modules/sinon/lib/sinon/log_error.js b/node_modules/sinon/lib/sinon/log_error.js deleted file mode 100644 index 94516ad..0000000 --- a/node_modules/sinon/lib/sinon/log_error.js +++ /dev/null @@ -1,68 +0,0 @@ -/** - * @depend util/core.js - */ -/** - * Logs errors - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -(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)); diff --git a/node_modules/sinon/lib/sinon/match.js b/node_modules/sinon/lib/sinon/match.js deleted file mode 100644 index 493a161..0000000 --- a/node_modules/sinon/lib/sinon/match.js +++ /dev/null @@ -1,254 +0,0 @@ -/** - * @depend util/core.js - * @depend typeOf.js - */ -/*jslint eqeqeq: false, onevar: false, plusplus: false*/ -/*global module, require, sinon*/ -/** - * Match functions - * - * @author Maximilian Antoni (mail@maxantoni.de) - * @license BSD - * - * Copyright (c) 2012 Maximilian Antoni - */ -"use strict"; - -(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)); diff --git a/node_modules/sinon/lib/sinon/mock.js b/node_modules/sinon/lib/sinon/mock.js deleted file mode 100644 index 30a479f..0000000 --- a/node_modules/sinon/lib/sinon/mock.js +++ /dev/null @@ -1,460 +0,0 @@ -/** - * @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@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - var push = [].push; - var match = sinon.match; - - function mock(object) { - // if (typeof console !== undefined && console.warn) { - // console.warn("mock will be removed from Sinon.JS v2.0"); - // } - - 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)); diff --git a/node_modules/sinon/lib/sinon/sandbox.js b/node_modules/sinon/lib/sinon/sandbox.js deleted file mode 100644 index 1b1523a..0000000 --- a/node_modules/sinon/lib/sinon/sandbox.js +++ /dev/null @@ -1,162 +0,0 @@ -/** - * @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@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(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); - } -}()); diff --git a/node_modules/sinon/lib/sinon/spy.js b/node_modules/sinon/lib/sinon/spy.js deleted file mode 100644 index a3bc8d7..0000000 --- a/node_modules/sinon/lib/sinon/spy.js +++ /dev/null @@ -1,457 +0,0 @@ -/** - * @depend times_in_words.js - * @depend util/core.js - * @depend extend.js - * @depend call.js - * @depend format.js - */ -/** - * Spy functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(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)); - }; - } - p.isSinonProxy = true; - 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)); diff --git a/node_modules/sinon/lib/sinon/stub.js b/node_modules/sinon/lib/sinon/stub.js deleted file mode 100644 index a88c8cb..0000000 --- a/node_modules/sinon/lib/sinon/stub.js +++ /dev/null @@ -1,180 +0,0 @@ -/** - * @depend util/core.js - * @depend extend.js - * @depend spy.js - * @depend behavior.js - */ -/** - * Stub functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(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 sinon.getPropertyDescriptor(object, prop).value === "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)); diff --git a/node_modules/sinon/lib/sinon/test.js b/node_modules/sinon/lib/sinon/test.js deleted file mode 100644 index 5c963d4..0000000 --- a/node_modules/sinon/lib/sinon/test.js +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @depend util/core.js - * @depend sandbox.js - */ -/** - * Test function, sandboxes fakes - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(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)); diff --git a/node_modules/sinon/lib/sinon/test_case.js b/node_modules/sinon/lib/sinon/test_case.js deleted file mode 100644 index d317928..0000000 --- a/node_modules/sinon/lib/sinon/test_case.js +++ /dev/null @@ -1,97 +0,0 @@ -/** - * @depend util/core.js - * @depend test.js - */ -/** - * Test case, sandboxes all test functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(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) { - if (!tests || typeof tests != "object") { - throw new TypeError("sinon.testCase needs an object with test functions"); - } - - 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) && !/^(setUp|tearDown)$/.test(testName)) { - property = tests[testName]; - - 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)); diff --git a/node_modules/sinon/lib/sinon/times_in_words.js b/node_modules/sinon/lib/sinon/times_in_words.js deleted file mode 100644 index 665e8eb..0000000 --- a/node_modules/sinon/lib/sinon/times_in_words.js +++ /dev/null @@ -1,43 +0,0 @@ -/** - * @depend util/core.js - */ -"use strict"; - -(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)); diff --git a/node_modules/sinon/lib/sinon/typeOf.js b/node_modules/sinon/lib/sinon/typeOf.js deleted file mode 100644 index 930ae1e..0000000 --- a/node_modules/sinon/lib/sinon/typeOf.js +++ /dev/null @@ -1,50 +0,0 @@ -/** - * @depend util/core.js - */ -/** - * Format functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -(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) -)); diff --git a/node_modules/sinon/lib/sinon/util/core.js b/node_modules/sinon/lib/sinon/util/core.js deleted file mode 100644 index 63a6889..0000000 --- a/node_modules/sinon/lib/sinon/util/core.js +++ /dev/null @@ -1,388 +0,0 @@ -/** - * @depend ../../sinon.js - */ -/** - * Sinon core utilities. For internal use only. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(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) { - // In some cases `delete` may throw an error - try { - delete object[property]; - } catch (e) {} - // For native code functions `delete` fails without throwing an error - // on Chrome < 43, PhantomJS, etc. - } else if (hasES5Support) { - Object.defineProperty(object, property, wrappedMethodDesc); - } - - // Use strict equality comparison to check failures then force a reset - // via direct assignment. - if (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)); diff --git a/node_modules/sinon/lib/sinon/util/event.js b/node_modules/sinon/lib/sinon/util/event.js deleted file mode 100644 index 4c9ef5f..0000000 --- a/node_modules/sinon/lib/sinon/util/event.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Minimal Event interface implementation - * - * Original implementation by Sven Fuchs: https://gist.github.com/995028 - * Modifications and tests by Christian Johansen. - * - * @author Sven Fuchs (svenfuchs@artweb-design.de) - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2011 Sven Fuchs, Christian Johansen - */ -"use strict"; - -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); - } -}()); diff --git a/node_modules/sinon/lib/sinon/util/fake_server.js b/node_modules/sinon/lib/sinon/util/fake_server.js deleted file mode 100644 index 37f2a56..0000000 --- a/node_modules/sinon/lib/sinon/util/fake_server.js +++ /dev/null @@ -1,242 +0,0 @@ -/** - * @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@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -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); - } -}()); diff --git a/node_modules/sinon/lib/sinon/util/fake_server_with_clock.js b/node_modules/sinon/lib/sinon/util/fake_server_with_clock.js deleted file mode 100644 index 8af8780..0000000 --- a/node_modules/sinon/lib/sinon/util/fake_server_with_clock.js +++ /dev/null @@ -1,101 +0,0 @@ -/** - * @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@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(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); - } -}()); diff --git a/node_modules/sinon/lib/sinon/util/fake_timers.js b/node_modules/sinon/lib/sinon/util/fake_timers.js deleted file mode 100644 index bfd3027..0000000 --- a/node_modules/sinon/lib/sinon/util/fake_timers.js +++ /dev/null @@ -1,77 +0,0 @@ -/*global lolex */ - -/** - * Fake timer API - * setTimeout - * setInterval - * clearTimeout - * clearInterval - * tick - * reset - * Date - * - * Inspired by jsUnitMockTimeOut from JsUnit - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -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)); diff --git a/node_modules/sinon/lib/sinon/util/fake_xdomain_request.js b/node_modules/sinon/lib/sinon/util/fake_xdomain_request.js deleted file mode 100644 index b4561bf..0000000 --- a/node_modules/sinon/lib/sinon/util/fake_xdomain_request.js +++ /dev/null @@ -1,223 +0,0 @@ -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XDomainRequest object - */ -"use strict"; - -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); - } -})(typeof global !== "undefined" ? global : self); diff --git a/node_modules/sinon/lib/sinon/util/fake_xml_http_request.js b/node_modules/sinon/lib/sinon/util/fake_xml_http_request.js deleted file mode 100644 index ad5ebb5..0000000 --- a/node_modules/sinon/lib/sinon/util/fake_xml_http_request.js +++ /dev/null @@ -1,634 +0,0 @@ -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XMLHttpRequest object - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (global) { - - var supportsProgress = typeof ProgressEvent !== "undefined"; - var supportsCustomEvent = typeof CustomEvent !== "undefined"; - var supportsFormData = typeof FormData !== "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*/ - - // Note that for FakeXMLHttpRequest to work pre ES5 - // we lose some of the alignment with the spec. - // To ensure as close a match as possible, - // set responseType before calling open, send or respond; - function FakeXMLHttpRequest() { - this.readyState = FakeXMLHttpRequest.UNSENT; - this.requestHeaders = {}; - this.requestBody = null; - this.status = 0; - this.statusText = ""; - this.upload = new UploadProgress(); - this.responseType = ""; - this.response = ""; - 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.response = this.responseType === "json" ? 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); - } - } - - switch (this.readyState) { - case FakeXMLHttpRequest.DONE: - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - } - this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("loadend", false, false, this)); - break; - } - - this.dispatchEvent(new sinon.Event("readystatechange")); - }, - - 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 (supportsFormData && !(data instanceof FormData)) { - this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; - } - - this.requestBody = data; - } - - this.errorFlag = false; - this.sendFlag = this.async; - this.response = this.responseType === "json" ? null : ""; - 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.response = this.responseType === "json" ? null : ""; - this.errorFlag = true; - this.requestHeaders = {}; - this.responseHeaders = {}; - - 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.response = this.responseType === "json" ? JSON.parse(this.responseText) : this.responseText; - 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 : self); diff --git a/node_modules/sinon/lib/sinon/util/timers_ie.js b/node_modules/sinon/lib/sinon/util/timers_ie.js deleted file mode 100644 index 7fca222..0000000 --- a/node_modules/sinon/lib/sinon/util/timers_ie.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * Helps IE run the fake timers. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake timers to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function setTimeout() {} - function clearTimeout() {} - function setImmediate() {} - function clearImmediate() {} - function setInterval() {} - function clearInterval() {} - function Date() {} - - // Reassign the original functions. Now their writable attribute - // should be true. Hackish, I know, but it works. - setTimeout = sinon.timers.setTimeout; - clearTimeout = sinon.timers.clearTimeout; - setImmediate = sinon.timers.setImmediate; - clearImmediate = sinon.timers.clearImmediate; - setInterval = sinon.timers.setInterval; - clearInterval = sinon.timers.clearInterval; - Date = sinon.timers.Date; -} diff --git a/node_modules/sinon/lib/sinon/util/xdr_ie.js b/node_modules/sinon/lib/sinon/util/xdr_ie.js deleted file mode 100644 index 05a5f6b..0000000 --- a/node_modules/sinon/lib/sinon/util/xdr_ie.js +++ /dev/null @@ -1,15 +0,0 @@ -/** - * Helps IE run the fake XDomainRequest. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake XDR to work in IE, don't include this file. - */ -if (typeof window !== "undefined") { - function XDomainRequest() {} - - // Reassign the original function. Now its writable attribute - // should be true. Hackish, I know, but it works. - XDomainRequest = sinon.xdr.XDomainRequest || undefined; -} diff --git a/node_modules/sinon/lib/sinon/util/xhr_ie.js b/node_modules/sinon/lib/sinon/util/xhr_ie.js deleted file mode 100644 index 3a5561d..0000000 --- a/node_modules/sinon/lib/sinon/util/xhr_ie.js +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Helps IE run the fake XMLHttpRequest. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake XHR to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function XMLHttpRequest() {} - - // Reassign the original function. Now its writable attribute - // should be true. Hackish, I know, but it works. - XMLHttpRequest = sinon.xhr.XMLHttpRequest || undefined; -} diff --git a/node_modules/sinon/node_modules/formatio/.travis.yml b/node_modules/sinon/node_modules/formatio/.travis.yml deleted file mode 100644 index 20fd86b..0000000 --- a/node_modules/sinon/node_modules/formatio/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: node_js -node_js: - - 0.10 diff --git a/node_modules/sinon/node_modules/formatio/AUTHORS b/node_modules/sinon/node_modules/formatio/AUTHORS deleted file mode 100644 index 103c176..0000000 --- a/node_modules/sinon/node_modules/formatio/AUTHORS +++ /dev/null @@ -1,6 +0,0 @@ -Buster.JS Format was written by -Christian Johansen, christian@cjohansen.no -August Lilleaas, august.lilleaas@gmail.com -Dave Geddes, davidcgeddes@gmail.com -Stein Magnus Jodal, stein.magnus@jodal.no -Tek Nynja, github@teknynja.com diff --git a/node_modules/sinon/node_modules/formatio/LICENSE b/node_modules/sinon/node_modules/formatio/LICENSE deleted file mode 100644 index d5908f3..0000000 --- a/node_modules/sinon/node_modules/formatio/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -(The BSD License) - -Copyright (c) 2010-2012, Christian Johansen (christian@cjohansen.no) and -August Lilleaas (august.lilleaas@gmail.com). 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. diff --git a/node_modules/sinon/node_modules/formatio/Readme.md b/node_modules/sinon/node_modules/formatio/Readme.md deleted file mode 100644 index 91cdf7b..0000000 --- a/node_modules/sinon/node_modules/formatio/Readme.md +++ /dev/null @@ -1,244 +0,0 @@ -# formatio - -[![Build status](https://secure.travis-ci.org/busterjs/formatio.png?branch=master)](http://travis-ci.org/busterjs/formatio) - -> The cheesy object formatter - -Pretty formatting of arbitrary JavaScript values. Currently only supports ascii -formatting, suitable for command-line utilities. Like `JSON.stringify`, it -formats objects recursively, but unlike `JSON.stringify`, it can handle -regular expressions, functions, circular objects and more. - -`formatio` is a general-purpose library. It works in browsers (including old -and rowdy ones, like IE6) and Node. It will define itself as an AMD module if -you want it to (i.e. if there's a `define` function available). - - -## Running tests - -``` -npm test -``` - -Or use Buster.JS manually: - -``` -node_modules/buster/bin/buster-test --help -``` - - -## `formatio.ascii` API - -`formatio.ascii` can take any JavaScript object and format it nicely as plain -text. It uses the helper functions described below to format different types of -objects. - - -### `formatio.ascii(object)` - -`object` can be any kind of object, including DOM elements. - - -**Simple object** - -```javascript -var formatio = require("formatio"); - -var object = { name: "Christian" }; -console.log(formatio.ascii(object)); - -// Outputs: -// { name: "Christian" } -``` - - -**Complex object** - -```javascript -var formatio = require("formatio"); - -var developer = { - name: "Christian", - interests: ["Programming", "Guitar", "TV"], - - location: { - language: "Norway", - city: "Oslo", - - getLatLon: function getLatLon(callback) { - // ... - }, - - distanceTo: function distanceTo(location) { - } - }, - - speak: function () { - return "Oh hi!"; - } -}; - -console.log(formatio.ascii(developer)); - -// Outputs: -// { -// interests: ["Programming", "Guitar", "TV"], -// location: { -// city: "Oslo", -// distanceTo: function distanceTo() {}, -// getLatLon: function getLatLon() {}, -// language: "Norway" -// }, -// name: "Christian", -// speak: function () {} -// } -``` - - -**Custom constructor** - -If the object to format is not a generic `Object` object, **formatio** -displays the type of object (i.e. name of constructor). Set the -`excludeConstructors` (see below) property to control what constructors to -include in formatted output. - -```javascript -var formatio = require("formatio"); - -function Person(name) { this.name = name; } - -var dude = new Person("Dude"); -console.log(format.ascii(dude)); - -// Outputs: -// [Person] { name: "Dude" } -``` - - -**DOM elements** - -DOM elements are formatted as abbreviated HTML source. 20 characters of -`innerHTML` is included, and if the content is longer, it is truncated with -`"[...]"`. Future editions will add the possibility to format nested markup -structures. - -```javascript -var p = document.createElement("p"); -p.id = "sample"; -p.className = "notice"; -p.setAttribute("data-custom", "42"); -p.innerHTML = "Hey there, here's some text for ya there buddy"; - -console.log(formatio.ascii(p)); - -// Outputs -// <p id="sample" class="notice" data-custom="42">Hey there, here's so[...]</p> -``` - - -### `formatio.ascii.func(func)` - -Formats a function like `"function [name]() {}"`. The name is retrieved from -`formatio.functionName`. - - -### `formatio.ascii.array(array)` - -Formats an array as `"[item1, item2, item3]"` where each item is formatted -with `formatio.ascii`. Circular references are represented in the resulting -string as `"[Circular]"`. - - -### `formatio.ascii.object(object)` - -Formats all properties of the object with `formatio.ascii`. If the object can -be fully represented in 80 characters, it's formatted in one line. Otherwise, -it's nicely indented over as many lines as necessary. Circular references are -represented by `"[Circular]"`. - -Objects created with custom constructors will be formatted as -`"[ConstructorName] { ... }"`. Set the `excludeConstructors` property to -control what constructors are included in the output like this. - - -### `formatio.ascii.element(element)` - -Formats a DOM element as HTML source. The tag name is represented in lower-case -and all attributes and their values are included. The element's content is -included, up to 20 characters. If the length exceeds 20 characters, it's -truncated with a `"[...]"`. - - -### `formatio.functionName(func)` - -Guesses a function's name. If the function defines the `displayName` property -(used by `some debugging tools `_) it is -preferred. If it is not found, the `name` property is tried. If no name can be -found this way, an attempt is made to find the function name by looking at the -function's `toString()` representation. - - -### `formatio.constructorName(object)` - -Attempts to guess the name of the constructor that created the object. It does -so by getting the name of `object.constructor` using `functionName`. If a -name is found, `excludeConstructors` is consulted. If the constructor name -matches any of these elements, an empty string is returned, otherwise the name -is returned. - - -## `formatio.ascii` properties - -### `quoteStrings(true)` - -Whether or not to quote simple strings. When set to `false`, simple strings -are not quoted. Strings in arrays and objects will still be quoted, but -`ascii("Some string")` will not gain additional quotes. - -### `limitChildrenCount(number)` - -This property allows to limit the number of printed array elements or object -properties. When set to 0, all elements will be included in output, any number -greater than zero will set the limit to that number. - -### `excludeConstructors (["Object", /^.$/])` - -An array of strings and/or regular expressions naming constructors that should -be stripped from the formatted output. The default value skips objects created -by `Object` and constructors that have one character names (which are -typically used in `Object.create` shims). - -While you can set this property directly on `formatio.ascii`, it is -recommended to create an instance of `formatio.ascii` and override the -property on that object. - -**Strings** represent constructor names that should not be represented in the -formatted output. **Regular expressions** are tested against constructor names -when formatting. If the expression is a match, the constructor name is not -included in the formatted output. - -```javascript -function Person(name) { - this.name = name; -} - -var person = new Person("Chris"); -console.log(formatio.ascii(person)); - -// Outputs -// [Person] { name: "Chris" } - -var formatter = Object.create(formatio); -formatter.excludeConstructors = ["Object", /^.$/, "Person"]; -console.log(formatter.ascii(person)); - -// Outputs -// { name: "Chris" } - -// Global overwrite, generally not recommended -formatio.excludeConstructors = ["Object", /^.$/, "Person"]; -console.log(formatio.ascii(person)); - -// Outputs -// { name: "Chris" } -``` diff --git a/node_modules/sinon/node_modules/formatio/autolint.js b/node_modules/sinon/node_modules/formatio/autolint.js deleted file mode 100644 index 62ded41..0000000 --- a/node_modules/sinon/node_modules/formatio/autolint.js +++ /dev/null @@ -1,23 +0,0 @@ -module.exports = { - paths: [ - "lib/*.js", - "test/*.js" - ], - linterOptions: { - node: true, - browser: true, - plusplus: true, - vars: true, - nomen: true, - forin: true, - sloppy: true, - regexp: true, - predef: [ - "samsam", - "define", - "assert", - "refute", - "buster" - ] - } -}; diff --git a/node_modules/sinon/node_modules/formatio/buster.js b/node_modules/sinon/node_modules/formatio/buster.js deleted file mode 100644 index 697bab1..0000000 --- a/node_modules/sinon/node_modules/formatio/buster.js +++ /dev/null @@ -1,14 +0,0 @@ -exports["Browser"] = { - // TODO: Needs fixing - environment: "browser", - libs: [ - "node_modules/samsam/lib/samsam.js" - ], - sources: ["lib/*.js"], - tests: ["test/*-test.js"] -}; - -exports["Node"] = { - extends: "Browser", - environment: "node" -}; diff --git a/node_modules/sinon/node_modules/formatio/lib/formatio.js b/node_modules/sinon/node_modules/formatio/lib/formatio.js deleted file mode 100644 index ffe234a..0000000 --- a/node_modules/sinon/node_modules/formatio/lib/formatio.js +++ /dev/null @@ -1,213 +0,0 @@ -((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) { - "use strict"; - - 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 + - ""; - - 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; -}); diff --git a/node_modules/sinon/node_modules/formatio/package.json b/node_modules/sinon/node_modules/formatio/package.json deleted file mode 100644 index ec95478..0000000 --- a/node_modules/sinon/node_modules/formatio/package.json +++ /dev/null @@ -1,81 +0,0 @@ -{ - "name": "formatio", - "version": "1.1.1", - "description": "Human-readable object formatting", - "homepage": "http://busterjs.org/docs/formatio/", - "author": { - "name": "Christian Johansen" - }, - "contributors": [ - { - "name": "Christian Johansen", - "email": "christian@cjohansen.no", - "url": "http://cjohansen.no" - }, - { - "name": "August Lilleaas", - "email": "august.lilleaas@gmail.com", - "url": "http://augustl.com" - }, - { - "name": "Dave Geddes", - "email": "davidcgeddes@gmail.com" - }, - { - "name": "Stein Magnus Jodal", - "email": "stein.magnus@jodal.no" - }, - { - "name": "Tek Nynja", - "email": "github@teknynja.com" - } - ], - "main": "./lib/formatio", - "repository": { - "type": "git", - "url": "git+https://github.com/busterjs/formatio.git" - }, - "scripts": { - "test": "node node_modules/buster/bin/buster-test --node", - "test-debug": "node --debug-brk node_modules/buster/bin/buster-test --node" - }, - "dependencies": { - "samsam": "~1.1" - }, - "devDependencies": { - "buster": "*" - }, - "bugs": { - "url": "https://github.com/busterjs/formatio/issues" - }, - "_id": "formatio@1.1.1", - "dist": { - "shasum": "5ed3ccd636551097383465d996199100e86161e9", - "tarball": "http://registry.npmjs.org/formatio/-/formatio-1.1.1.tgz" - }, - "_from": "formatio@1.1.1", - "_npmVersion": "1.3.21", - "_npmUser": { - "name": "cjohansen", - "email": "christian@cjohansen.no" - }, - "maintainers": [ - { - "name": "cjohansen", - "email": "christian@cjohansen.no" - }, - { - "name": "augustl", - "email": "august@augustl.com" - }, - { - "name": "dwittner", - "email": "d.wittner@gmx.de" - } - ], - "directories": {}, - "_shasum": "5ed3ccd636551097383465d996199100e86161e9", - "_resolved": "https://registry.npmjs.org/formatio/-/formatio-1.1.1.tgz", - "readme": "# formatio\n\n[![Build status](https://secure.travis-ci.org/busterjs/formatio.png?branch=master)](http://travis-ci.org/busterjs/formatio)\n\n> The cheesy object formatter\n\nPretty formatting of arbitrary JavaScript values. Currently only supports ascii\nformatting, suitable for command-line utilities. Like `JSON.stringify`, it\nformats objects recursively, but unlike `JSON.stringify`, it can handle\nregular expressions, functions, circular objects and more.\n\n`formatio` is a general-purpose library. It works in browsers (including old\nand rowdy ones, like IE6) and Node. It will define itself as an AMD module if\nyou want it to (i.e. if there's a `define` function available).\n\n\n## Running tests\n\n```\nnpm test\n```\n\nOr use Buster.JS manually:\n\n```\nnode_modules/buster/bin/buster-test --help\n```\n\n\n## `formatio.ascii` API\n\n`formatio.ascii` can take any JavaScript object and format it nicely as plain\ntext. It uses the helper functions described below to format different types of\nobjects.\n\n\n### `formatio.ascii(object)`\n\n`object` can be any kind of object, including DOM elements.\n\n\n**Simple object**\n\n```javascript\nvar formatio = require(\"formatio\");\n\nvar object = { name: \"Christian\" };\nconsole.log(formatio.ascii(object));\n\n// Outputs:\n// { name: \"Christian\" }\n```\n\n\n**Complex object**\n\n```javascript\nvar formatio = require(\"formatio\");\n\nvar developer = {\n name: \"Christian\",\n interests: [\"Programming\", \"Guitar\", \"TV\"],\n\n location: {\n language: \"Norway\",\n city: \"Oslo\",\n\n getLatLon: function getLatLon(callback) {\n // ...\n },\n\n distanceTo: function distanceTo(location) {\n }\n },\n\n speak: function () {\n return \"Oh hi!\";\n }\n};\n\nconsole.log(formatio.ascii(developer));\n\n// Outputs:\n// {\n// interests: [\"Programming\", \"Guitar\", \"TV\"],\n// location: {\n// city: \"Oslo\",\n// distanceTo: function distanceTo() {},\n// getLatLon: function getLatLon() {},\n// language: \"Norway\"\n// },\n// name: \"Christian\",\n// speak: function () {}\n// }\n```\n\n\n**Custom constructor**\n\nIf the object to format is not a generic `Object` object, **formatio**\ndisplays the type of object (i.e. name of constructor). Set the\n`excludeConstructors` (see below) property to control what constructors to\ninclude in formatted output.\n\n```javascript\nvar formatio = require(\"formatio\");\n\nfunction Person(name) { this.name = name; }\n\nvar dude = new Person(\"Dude\");\nconsole.log(format.ascii(dude));\n\n// Outputs:\n// [Person] { name: \"Dude\" }\n```\n\n\n**DOM elements**\n\nDOM elements are formatted as abbreviated HTML source. 20 characters of\n`innerHTML` is included, and if the content is longer, it is truncated with\n`\"[...]\"`. Future editions will add the possibility to format nested markup\nstructures.\n\n```javascript\nvar p = document.createElement(\"p\");\np.id = \"sample\";\np.className = \"notice\";\np.setAttribute(\"data-custom\", \"42\");\np.innerHTML = \"Hey there, here's some text for ya there buddy\";\n\nconsole.log(formatio.ascii(p));\n\n// Outputs\n// <p id=\"sample\" class=\"notice\" data-custom=\"42\">Hey there, here's so[...]</p>\n```\n\n\n### `formatio.ascii.func(func)`\n\nFormats a function like `\"function [name]() {}\"`. The name is retrieved from\n`formatio.functionName`.\n\n\n### `formatio.ascii.array(array)`\n\nFormats an array as `\"[item1, item2, item3]\"` where each item is formatted\nwith `formatio.ascii`. Circular references are represented in the resulting\nstring as `\"[Circular]\"`.\n\n\n### `formatio.ascii.object(object)`\n\nFormats all properties of the object with `formatio.ascii`. If the object can\nbe fully represented in 80 characters, it's formatted in one line. Otherwise,\nit's nicely indented over as many lines as necessary. Circular references are\nrepresented by `\"[Circular]\"`.\n\nObjects created with custom constructors will be formatted as\n`\"[ConstructorName] { ... }\"`. Set the `excludeConstructors` property to\ncontrol what constructors are included in the output like this.\n\n\n### `formatio.ascii.element(element)`\n\nFormats a DOM element as HTML source. The tag name is represented in lower-case\nand all attributes and their values are included. The element's content is\nincluded, up to 20 characters. If the length exceeds 20 characters, it's\ntruncated with a `\"[...]\"`.\n\n\n### `formatio.functionName(func)`\n\nGuesses a function's name. If the function defines the `displayName` property\n(used by `some debugging tools `_) it is\npreferred. If it is not found, the `name` property is tried. If no name can be\nfound this way, an attempt is made to find the function name by looking at the\nfunction's `toString()` representation.\n\n\n### `formatio.constructorName(object)`\n\nAttempts to guess the name of the constructor that created the object. It does\nso by getting the name of `object.constructor` using `functionName`. If a\nname is found, `excludeConstructors` is consulted. If the constructor name\nmatches any of these elements, an empty string is returned, otherwise the name\nis returned.\n\n\n## `formatio.ascii` properties\n\n### `quoteStrings(true)`\n\nWhether or not to quote simple strings. When set to `false`, simple strings\nare not quoted. Strings in arrays and objects will still be quoted, but\n`ascii(\"Some string\")` will not gain additional quotes.\n\n### `limitChildrenCount(number)`\n\nThis property allows to limit the number of printed array elements or object \nproperties. When set to 0, all elements will be included in output, any number\ngreater than zero will set the limit to that number.\n\n### `excludeConstructors ([\"Object\", /^.$/])`\n\nAn array of strings and/or regular expressions naming constructors that should\nbe stripped from the formatted output. The default value skips objects created\nby `Object` and constructors that have one character names (which are\ntypically used in `Object.create` shims).\n\nWhile you can set this property directly on `formatio.ascii`, it is\nrecommended to create an instance of `formatio.ascii` and override the\nproperty on that object.\n\n**Strings** represent constructor names that should not be represented in the\nformatted output. **Regular expressions** are tested against constructor names\nwhen formatting. If the expression is a match, the constructor name is not\nincluded in the formatted output.\n\n```javascript\nfunction Person(name) {\n this.name = name;\n}\n\nvar person = new Person(\"Chris\");\nconsole.log(formatio.ascii(person));\n\n// Outputs\n// [Person] { name: \"Chris\" }\n\nvar formatter = Object.create(formatio);\nformatter.excludeConstructors = [\"Object\", /^.$/, \"Person\"];\nconsole.log(formatter.ascii(person));\n\n// Outputs\n// { name: \"Chris\" }\n\n// Global overwrite, generally not recommended\nformatio.excludeConstructors = [\"Object\", /^.$/, \"Person\"];\nconsole.log(formatio.ascii(person));\n\n// Outputs\n// { name: \"Chris\" }\n```\n", - "readmeFilename": "Readme.md" -} diff --git a/node_modules/sinon/node_modules/formatio/test/formatio-test.js b/node_modules/sinon/node_modules/formatio/test/formatio-test.js deleted file mode 100644 index 5edb20e..0000000 --- a/node_modules/sinon/node_modules/formatio/test/formatio-test.js +++ /dev/null @@ -1,476 +0,0 @@ -/*global formatio*/ -((typeof module === "object" && typeof require === "function" && function (t) { - t(require("buster"), require("../lib/formatio")); -}) || function (t) { - t(buster, formatio); -})(function (buster, formatio) { - - var assert = buster.referee.assert; - var refute = buster.referee.refute; - - function getArrayOfNumbers(size){ - var array = new Array(), - i; - - for (i = 0; i < size; i++){ - array[i] = i; - } - - return array - } - - function getObjectWithManyProperties(size){ - var object = {}; - - for (i = 0; i < size; i++) { - object[i.toString()] = i; - } - - return object; - } - - buster.testCase("formatio.ascii", { - "formats strings with quotes": function () { - assert.equals(formatio.ascii("A string"), '"A string"'); - }, - - "formats booleans without quotes": function () { - assert.equals(formatio.ascii(true), "true"); - assert.equals(formatio.ascii(false), "false"); - }, - - "formats null and undefined without quotes": function () { - assert.equals(formatio.ascii(null), "null"); - assert.equals(formatio.ascii(undefined), "undefined"); - }, - - "formats numbers without quotes": function () { - assert.equals(formatio.ascii(3), "3"); - assert.equals(formatio.ascii(3987.56), "3987.56"); - assert.equals(formatio.ascii(-980.0), "-980"); - assert.equals(formatio.ascii(NaN), "NaN"); - assert.equals(formatio.ascii(Infinity), "Infinity"); - assert.equals(formatio.ascii(-Infinity), "-Infinity"); - assert.equals(formatio.ascii(-0), "-0"); - }, - - "formats regexp using toString": function () { - assert.equals(formatio.ascii(/[a-zA-Z0-9]+\.?/), - "/[a-zA-Z0-9]+\\.?/"); - }, - - "formats functions with name": function () { - var fn = function doIt() {}; - assert.equals(formatio.ascii(fn), "function doIt() {}"); - }, - - "formats functions without name": function () { - assert.equals(formatio.ascii(function () {}), "function () {}"); - }, - - "formats functions with display name": function () { - function doIt() {} - doIt.displayName = "ohHai"; - - assert.equals(formatio.ascii(doIt), "function ohHai() {}"); - }, - - "shortens functions with long bodies": function () { - function doIt() { - var i; - function hey() {} - for (i = 0; i < 10; i++) { console.log(i); } - } - - assert.equals(formatio.ascii(doIt), "function doIt() {}"); - }, - - "formats functions with no name or display name": function () { - function doIt() {} - doIt.name = ""; - - assert.equals(formatio.ascii(doIt), "function doIt() {}"); - }, - - "formats arrays": function () { - function ohNo() { return "Oh yes!"; } - - var array = ["String", 123, /a-z/, null]; - - var str = formatio.ascii(array); - assert.equals(str, '["String", 123, /a-z/, null]'); - - str = formatio.ascii([ohNo, array]); - assert.equals(str, - '[function ohNo() {}, ["String", 123, /a-z/, null]]'); - }, - - "does not trip on circular arrays": function () { - var array = ["String", 123, /a-z/]; - array.push(array); - - var str = formatio.ascii(array); - assert.equals(str, '["String", 123, /a-z/, [Circular]]'); - }, - - "limit formatted array length": { - "should stop at given limit" : function () { - var array = getArrayOfNumbers(300); - var configuredFormatio = formatio.configure({ - limitChildrenCount : 30 - }); - var str = configuredFormatio.ascii(array); - - refute.contains(str, "30"); - assert.contains(str, "29"); - assert.contains(str, "[... 270 more elements]"); - }, - - "should only format as many elements as exists" : function(){ - var array = getArrayOfNumbers(10); - configuredFormatio = formatio.configure({ - limitChildrenCount : 30 - }); - var str = configuredFormatio.ascii(array); - - refute.contains(str, "10"); - assert.contains(str, "9"); - refute.contains(str, "undefined"); - refute.contains(str, "[..."); - }, - - "should format all array elements if no config is used" : function () { - var array = getArrayOfNumbers(300); - var str = formatio.ascii(array); - - assert.contains(str, "100"); - assert.contains(str, "299]"); - refute.contains(str, "[..."); - }, - }, - - "limit count of formated object properties": { - setUp: function() { - this.testobject = {}; - for (i = 0; i < 300; i++) { - this.testobject[i.toString()] = i; - } - }, - - "should stop at given limit" : function () { - var object = getObjectWithManyProperties(300); - configuredFormatio = formatio.configure({ - limitChildrenCount : 30 - }); - var str = configuredFormatio.ascii(object); - - // returned formation may not be in the original order - assert.equals(30 + 3, str.split("\n").length); - assert.contains(str, "[... 270 more elements]"); - }, - - "should only format as many properties as exists" : function(){ - var object = getObjectWithManyProperties(10); - configuredFormatio = formatio.configure({ - limitChildrenCount : 30 - }); - var str = configuredFormatio.ascii(object); - - refute.contains(str, "10"); - assert.contains(str, "9"); - refute.contains(str, "undefined"); - refute.contains(str, "[..."); - }, - - "should format all properties if no config is used" : function () { - var object = getObjectWithManyProperties(300); - var str = formatio.ascii(object); - - assert.equals(300 + 2, str.split("\n").length); - }, - }, - - "formats object": function () { - var object = { - id: 42, - hello: function () {}, - prop: "Some", - more: "properties", - please: "Gimme some more", - "oh hi": 42, - seriously: "many properties" - }; - - var expected = "{\n hello: function () {},\n id: 42,\n " + - "more: \"properties\",\n \"oh hi\": 42,\n please: " + - "\"Gimme some more\",\n prop: \"Some\"," + - "\n seriously: \"many properties\"\n}"; - - assert.equals(formatio.ascii(object), expected); - }, - - "formats short object on one line": function () { - var object = { - id: 42, - hello: function () {}, - prop: "Some" - }; - - var expected = "{ hello: function () {}, id: 42, prop: \"Some\" }"; - assert.equals(formatio.ascii(object), expected); - }, - - "formats object with a non-function toString": function () { - var object = { toString: 42 }; - assert.equals(formatio.ascii(object), "{ toString: 42 }"); - }, - - "formats nested object": function () { - var object = { - id: 42, - hello: function () {}, - prop: "Some", - obj: { - num: 23, - string: "Here you go you little mister" - } - }; - - var expected = "{\n hello: function () {},\n id: 42,\n obj" + - ": { num: 23, string: \"Here you go you little mister\"" + - " },\n prop: \"Some\"\n}"; - - assert.equals(formatio.ascii(object), expected); - }, - - "includes constructor if known and not Object": function () { - function Person(name) { - this.name = name; - } - - var person = new Person("Christian"); - - assert.equals(formatio.ascii(person), - "[Person] { name: \"Christian\" }"); - }, - - "does not include one letter constructors": function () { - function F(name) { - this.name = name; - } - - var person = new F("Christian"); - - assert.equals(formatio.ascii(person), "{ name: \"Christian\" }"); - }, - - "includes one letter constructors when configured so": function () { - function C(name) { - this.name = name; - } - - var person = new C("Christian"); - var formatter = formatio.configure({ excludeConstructors: [] }); - - assert.equals(formatter.ascii(person), - "[C] { name: \"Christian\" }"); - }, - - "excludes constructors when configured to do so": function () { - function Person(name) { - this.name = name; - } - - var person = new Person("Christian"); - var formatter = formatio.configure({ excludeConstructors: ["Person"] }); - - assert.equals(formatter.ascii(person), "{ name: \"Christian\" }"); - }, - - "excludes constructors by pattern when configured so": function () { - function Person(name) { this.name = name; } - function Ninja(name) { this.name = name; } - function Pervert(name) { this.name = name; } - - var person = new Person("Christian"); - var ninja = new Ninja("Haruhachi"); - var pervert = new Pervert("Mr. Garrison"); - var formatter = formatio.configure({ excludeConstructors: [/^Per/] }); - - assert.equals(formatter.ascii(person), "{ name: \"Christian\" }"); - assert.equals(formatter.ascii(ninja), - "[Ninja] { name: \"Haruhachi\" }"); - assert.equals(formatter.ascii(pervert), - "{ name: \"Mr. Garrison\" }"); - }, - - "excludes constructors when run on other objects": function () { - function Person(name) { this.name = name; } - - var person = new Person("Christian"); - var formatter = { ascii: formatio.ascii }; - formatter.excludeConstructors = ["Person"]; - - assert.equals(formatter.ascii(person), "{ name: \"Christian\" }"); - }, - - "excludes default constructors when run on other objects": function () { - var person = { name: "Christian" }; - var formatter = { ascii: formatio.ascii }; - - assert.equals(formatter.ascii(person), "{ name: \"Christian\" }"); - }, - - "does not trip on circular formatting": function () { - var object = {}; - object.foo = object; - - assert.equals(formatio.ascii(object), "{ foo: [Circular] }"); - }, - - "does not trip on indirect circular formatting": function () { - var object = { someProp: {} }; - object.someProp.foo = object; - - assert.equals(formatio.ascii(object), - "{ someProp: { foo: [Circular] } }"); - }, - - "formats nested array nicely": function () { - var object = { people: ["Chris", "August"] }; - - assert.equals(formatio.ascii(object), - "{ people: [\"Chris\", \"August\"] }"); - }, - - "does not rely on object's hasOwnProperty": function () { - // Create object with no "own" properties to get past - // Object.keys test and no .hasOwnProperty() function - var Obj = function () {}; - Obj.prototype = { hasOwnProperty: undefined }; - var object = new Obj(); - - assert.equals(formatio.ascii(object), "{ }"); - }, - - "handles cyclic structures": function () { - var obj = {}; - obj.list1 = [obj]; - obj.list2 = [obj]; - obj.list3 = [{ prop: obj }]; - - refute.exception(function () { - formatio.ascii(obj); - }); - }, - - "unquoted strings": { - setUp: function () { - this.formatter = formatio.configure({ quoteStrings: false }); - }, - - "does not quote strings": function () { - assert.equals(this.formatter.ascii("Hey there"), "Hey there"); - }, - - "quotes string properties": function () { - var obj = { hey: "Mister" }; - assert.equals(this.formatter.ascii(obj), "{ hey: \"Mister\" }"); - } - }, - - "numbers": { - "formats object with 0": function () { - var str = formatio.ascii({ me: 0 }); - refute.match(str, "-0"); - }, - - "formats object with -0": function () { - var str = formatio.ascii({ me: -0 }); - assert.match(str, "-0"); - } - }, - - "DOM elements": { - requiresSupportFor: { "DOM": typeof document !== "undefined" }, - - "formats dom element": function () { - var element = document.createElement("div"); - - assert.equals(formatio.ascii(element), "
      "); - }, - - "formats dom element with attributes": function () { - var element = document.createElement("div"); - element.className = "hey there"; - element.id = "ohyeah"; - var str = formatio.ascii(element); - - assert.match(str, /
      <\/div>/); - assert.match(str, /class="hey there"/); - assert.match(str, /id="ohyeah"/); - }, - - "formats dom element with content": function () { - var element = document.createElement("div"); - element.innerHTML = "Oh hi!"; - - assert.equals(formatio.ascii(element), "
      Oh hi!
      "); - }, - - "truncates dom element content": function () { - var element = document.createElement("div"); - element.innerHTML = "Oh hi! I'm Christian, and this " + - "is a lot of content"; - - assert.equals(formatio.ascii(element), - "
      Oh hi! I'm Christian[...]
      "); - }, - - "includes attributes and truncated content": function () { - var element = document.createElement("div"); - element.id = "anid"; - element.lang = "en"; - element.innerHTML = "Oh hi! I'm Christian, and this " + - "is a lot of content"; - var str = formatio.ascii(element); - - assert.match(str, - /
      Oh hi! I'm Christian\[\.\.\.\]<\/div>/); - assert.match(str, /lang="en"/); - assert.match(str, /id="anid"/); - }, - - "formats document object as toString": function () { - var str; - buster.assertions.refute.exception(function () { - str = formatio.ascii(document); - }); - - assert.equals(str, "[object HTMLDocument]"); - }, - - "formats window object as toString": function () { - var str; - buster.assertions.refute.exception(function () { - str = formatio.ascii(window); - }); - - assert.equals(str, "[object Window]"); - } - }, - - "global object": { - requiresSupportFor: { "global": typeof global !== "undefined" }, - - "formats global object as toString": function () { - var str; - buster.assertions.refute.exception(function () { - str = formatio.ascii(global); - }); - - assert.equals(str, "[object global]"); - } - } - }); -}); diff --git a/node_modules/sinon/node_modules/lolex/.min-wd b/node_modules/sinon/node_modules/lolex/.min-wd deleted file mode 100644 index 40f963f..0000000 --- a/node_modules/sinon/node_modules/lolex/.min-wd +++ /dev/null @@ -1,13 +0,0 @@ -{ - "sauceLabs": true, - "browsers": [{ - "name": "chrome" - }, { - "name": "internet explorer", - "version": "9", - "url": "http://maxantoni.de/doctype.html" - }, { - "name": "internet explorer", - "version": "10" - }] -} diff --git a/node_modules/sinon/node_modules/lolex/.npmignore b/node_modules/sinon/node_modules/lolex/.npmignore deleted file mode 100644 index 07e6e47..0000000 --- a/node_modules/sinon/node_modules/lolex/.npmignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules diff --git a/node_modules/sinon/node_modules/lolex/LICENSE b/node_modules/sinon/node_modules/lolex/LICENSE deleted file mode 100644 index e7f50d1..0000000 --- a/node_modules/sinon/node_modules/lolex/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -(The BSD License) - -Copyright (c) 2010-2014, Christian Johansen, christian@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. diff --git a/node_modules/sinon/node_modules/lolex/Readme.md b/node_modules/sinon/node_modules/lolex/Readme.md deleted file mode 100644 index ab6b88a..0000000 --- a/node_modules/sinon/node_modules/lolex/Readme.md +++ /dev/null @@ -1,161 +0,0 @@ -# Lolex [![Build Status](https://secure.travis-ci.org/sinonjs/lolex.png)](http://travis-ci.org/sinonjs/lolex) - -JavaScript implementation of the timer APIs; `setTimeout`, `clearTimeout`, -`setImmediate`, `clearImmediate`, `setInterval`, `clearInterval`, and -`requestAnimationFrame`, along with a clock instance that controls the flow of -time. Lolex also provides a `Date` implementation that gets its time from the -clock. - -Lolex can be used to simulate passing time in automated tests and other -situations where you want the scheduling semantics, but don't want to actually -wait. Lolex is extracted from [Sinon.JS](https://github.com/sinonjs/sinon.js). - -## Installation - -Lolex can be installed using `npm`: - -```sh -npm install lolex -``` - -If you want to use Lolex in a browser, you have a few options. Releases are -hosted on the [sinonjs.org](http://sinonjs.org/download/) website. You can also -get the node module and build a file for the browser using browserify: - -```sh -npm install lolex -npm install browserify # If you don't already have it globally installed -browserify node_modules/lolex/lolex.js -``` - -## Usage - -To use lolex, create a new clock, schedule events on it using the timer -functions and pass time using the `tick` method. - -```js -// In the browser distribution, a global `lolex` is already available -var lolex = require("lolex"); -var clock = lolex.createClock(); - -clock.setTimeout(function () { - console.log("The poblano is a mild chili pepper originating in the state of Puebla, Mexico."); -}, 15); - -// ... - -clock.tick(15); -``` - -Upon executing the last line, an interesting fact about the -[Poblano](http://en.wikipedia.org/wiki/Poblano) will be printed synchronously to -the screen. If you want to simulate asynchronous behavior, you have to use your -imagination when calling the various functions. - -### Faking the native timers - -When using lolex to test timers, you will most likely want to replace the native -timers such that calling `setTimeout` actually schedules a callback with your -clock instance, not the browser's internals. - -To hijack timers in another context, use the `install` method. You can then call -`uninstall` later to restore things as they were again. - -```js -var lolex = require("lolex"); -var clock = lolex.install(window); - -window.setTimeout(fn, 15); // Schedules with clock.setTimeout - -clock.uninstall(); - -// window.setTimeout is restored to the native implementation -``` - -In 90% av the times, you want to install the timers onto the global object. -Calling `install` with no arguments achieves this: - -```js -var clock = lolex.install(); - -// Equivalent to -// var clock = lolex.install(typeof global !== "undefined" ? global : window); -``` - -## API Reference - -### `var clock = lolex.createClock([now])` - -### `var clock = lolex.install([context[, now[, toFake]]])` - -### `var clock = lolex.install([now[, toFake]])` - -### `var id = clock.setTimeout(callback, timeout)` - -### `clock.clearTimeout(id)` - -### `var id = clock.setInterval(callback, timeout)` - -### `clock.clearInterval(id)` - -### `var id = clock.setImmediate(callback)` - -### `clock.clearImmediate(id)` - -### `clock.tick(time)` - -### `clock.uninstall()` - -### `Date` - -## Running tests - -Lolex has a comprehensive test suite. If you're thinking of contributing bug -fixes or suggest new features, you need to make sure you have not broken any -tests. You are also expected to add tests for any new behavior. - -### On node: - -```sh -npm test -``` - -Or, if you prefer slightly less verbose output: - -``` -node run-tests.js -``` - -### In the browser - - - -## License - -(The BSD License) - -Copyright (c) 2010-2014, Christian Johansen (christian@cjohansen.no) and -contributors. 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. diff --git a/node_modules/sinon/node_modules/lolex/lolex.js b/node_modules/sinon/node_modules/lolex/lolex.js deleted file mode 100644 index 758ed9f..0000000 --- a/node_modules/sinon/node_modules/lolex/lolex.js +++ /dev/null @@ -1,428 +0,0 @@ -!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 module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 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) -}); \ No newline at end of file diff --git a/node_modules/sinon/node_modules/lolex/package.json b/node_modules/sinon/node_modules/lolex/package.json deleted file mode 100644 index 78b89c1..0000000 --- a/node_modules/sinon/node_modules/lolex/package.json +++ /dev/null @@ -1,59 +0,0 @@ -{ - "name": "lolex", - "description": "Fake JavaScript timers", - "version": "1.1.0", - "homepage": "http://github.com/sinonjs/lolex", - "author": { - "name": "Christian Johansen" - }, - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/sinonjs/lolex.git" - }, - "bugs": { - "url": "http://github.com/sinonjs/lolex/issues" - }, - "licenses": [ - { - "type": "BSD", - "url": "http://github.com/sinonjs/lolex/blob/master/LICENSE" - } - ], - "scripts": { - "test-node": "mocha -R dot", - "test-headless": "mochify", - "test-cloud": "mochify --wd", - "test": "npm run test-node && npm run test-headless && npm run test-cloud", - "bundle": "browserify -s lolex -o lolex.js src/lolex.js" - }, - "devDependencies": { - "mocha": ">=1.21 <2", - "mochify": ">=1.0 <2", - "browserify": ">=5.9 <6", - "referee": "~1.0", - "sinon": "~1.10" - }, - "main": "./src/lolex.js", - "_id": "lolex@1.1.0", - "dist": { - "shasum": "5dbbbc850395e7523c74b3586f7fbd2626d25b1b", - "tarball": "http://registry.npmjs.org/lolex/-/lolex-1.1.0.tgz" - }, - "_from": "lolex@1.1.0", - "_npmVersion": "1.3.21", - "_npmUser": { - "name": "cjohansen", - "email": "christian@cjohansen.no" - }, - "maintainers": [ - { - "name": "cjohansen", - "email": "christian@cjohansen.no" - } - ], - "directories": {}, - "_shasum": "5dbbbc850395e7523c74b3586f7fbd2626d25b1b", - "_resolved": "https://registry.npmjs.org/lolex/-/lolex-1.1.0.tgz", - "readme": "# Lolex [![Build Status](https://secure.travis-ci.org/sinonjs/lolex.png)](http://travis-ci.org/sinonjs/lolex)\n\nJavaScript implementation of the timer APIs; `setTimeout`, `clearTimeout`,\n`setImmediate`, `clearImmediate`, `setInterval`, `clearInterval`, and\n`requestAnimationFrame`, along with a clock instance that controls the flow of\ntime. Lolex also provides a `Date` implementation that gets its time from the\nclock.\n\nLolex can be used to simulate passing time in automated tests and other\nsituations where you want the scheduling semantics, but don't want to actually\nwait. Lolex is extracted from [Sinon.JS](https://github.com/sinonjs/sinon.js).\n\n## Installation\n\nLolex can be installed using `npm`:\n\n```sh\nnpm install lolex\n```\n\nIf you want to use Lolex in a browser, you have a few options. Releases are\nhosted on the [sinonjs.org](http://sinonjs.org/download/) website. You can also\nget the node module and build a file for the browser using browserify:\n\n```sh\nnpm install lolex\nnpm install browserify # If you don't already have it globally installed\nbrowserify node_modules/lolex/lolex.js\n```\n\n## Usage\n\nTo use lolex, create a new clock, schedule events on it using the timer\nfunctions and pass time using the `tick` method.\n\n```js\n// In the browser distribution, a global `lolex` is already available\nvar lolex = require(\"lolex\");\nvar clock = lolex.createClock();\n\nclock.setTimeout(function () {\n console.log(\"The poblano is a mild chili pepper originating in the state of Puebla, Mexico.\");\n}, 15);\n\n// ...\n\nclock.tick(15);\n```\n\nUpon executing the last line, an interesting fact about the\n[Poblano](http://en.wikipedia.org/wiki/Poblano) will be printed synchronously to\nthe screen. If you want to simulate asynchronous behavior, you have to use your\nimagination when calling the various functions.\n\n### Faking the native timers\n\nWhen using lolex to test timers, you will most likely want to replace the native\ntimers such that calling `setTimeout` actually schedules a callback with your\nclock instance, not the browser's internals.\n\nTo hijack timers in another context, use the `install` method. You can then call\n`uninstall` later to restore things as they were again.\n\n```js\nvar lolex = require(\"lolex\");\nvar clock = lolex.install(window);\n\nwindow.setTimeout(fn, 15); // Schedules with clock.setTimeout\n\nclock.uninstall();\n\n// window.setTimeout is restored to the native implementation\n```\n\nIn 90% av the times, you want to install the timers onto the global object.\nCalling `install` with no arguments achieves this:\n\n```js\nvar clock = lolex.install();\n\n// Equivalent to\n// var clock = lolex.install(typeof global !== \"undefined\" ? global : window);\n```\n\n## API Reference\n\n### `var clock = lolex.createClock([now])`\n\n### `var clock = lolex.install([context[, now[, toFake]]])`\n\n### `var clock = lolex.install([now[, toFake]])`\n\n### `var id = clock.setTimeout(callback, timeout)`\n\n### `clock.clearTimeout(id)`\n\n### `var id = clock.setInterval(callback, timeout)`\n\n### `clock.clearInterval(id)`\n\n### `var id = clock.setImmediate(callback)`\n\n### `clock.clearImmediate(id)`\n\n### `clock.tick(time)`\n\n### `clock.uninstall()`\n\n### `Date`\n\n## Running tests\n\nLolex has a comprehensive test suite. If you're thinking of contributing bug\nfixes or suggest new features, you need to make sure you have not broken any\ntests. You are also expected to add tests for any new behavior.\n\n### On node:\n\n```sh\nnpm test\n```\n\nOr, if you prefer slightly less verbose output:\n\n```\nnode run-tests.js\n```\n\n### In the browser\n\n\n\n## License\n\n(The BSD License)\n\nCopyright (c) 2010-2014, Christian Johansen (christian@cjohansen.no) and\ncontributors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n * Neither the name of Christian Johansen nor the names of his contributors\n may be used to endorse or promote products derived from this software\n without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\nTHIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n", - "readmeFilename": "Readme.md" -} diff --git a/node_modules/sinon/node_modules/lolex/src/lolex.js b/node_modules/sinon/node_modules/lolex/src/lolex.js deleted file mode 100644 index beb54a0..0000000 --- a/node_modules/sinon/node_modules/lolex/src/lolex.js +++ /dev/null @@ -1,422 +0,0 @@ -/*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/ -/*global global*/ -/** - * @author Christian Johansen (christian@cjohansen.no) and contributors - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -// 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; -}; diff --git a/node_modules/sinon/node_modules/lolex/test/lolex-test.js b/node_modules/sinon/node_modules/lolex/test/lolex-test.js deleted file mode 100644 index c2659a7..0000000 --- a/node_modules/sinon/node_modules/lolex/test/lolex-test.js +++ /dev/null @@ -1,1089 +0,0 @@ -/*jslint onevar: false, eqeqeq: false, plusplus: false*/ -/** - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -if (typeof require == "function" && typeof module == "object") { - var referee = require("referee"); - var lolex = require("../src/lolex"); - var sinon = require("sinon"); - - global.lolex = lolex; // For testing eval -} - -var assert = referee.assert; -var refute = referee.refute; -var globalDate = Date; - -describe("lolex", function () { - - describe("setTimeout", function () { - - beforeEach(function () { - this.clock = lolex.createClock(); - lolex.evalCalled = false; - }); - - afterEach(function () { - delete lolex.evalCalled; - }); - - it("throws if no arguments", function () { - var clock = this.clock; - - assert.exception(function () { clock.setTimeout(); }); - }); - - it("returns numeric id or object with numeric id", function () { - var result = this.clock.setTimeout(""); - - if (typeof result === 'object') - assert.isNumber(result.id); - else - assert.isNumber(result); - }); - - it("returns unique id", function () { - var id1 = this.clock.setTimeout(""); - var id2 = this.clock.setTimeout(""); - - refute.equals(id2, id1); - }); - - it("sets timers on instance", function () { - var clock1 = lolex.createClock(); - var clock2 = lolex.createClock(); - var stubs = [sinon.stub(), sinon.stub()]; - - clock1.setTimeout(stubs[0], 100); - clock2.setTimeout(stubs[1], 100); - clock2.tick(200); - - assert.isFalse(stubs[0].called); - assert(stubs[1].called); - }); - - it("evals non-function callbacks", function () { - this.clock.setTimeout("lolex.evalCalled = true", 10); - this.clock.tick(10); - - assert(lolex.evalCalled); - }); - - it("passes setTimeout parameters", function() { - var clock = lolex.createClock(); - var stub = sinon.stub(); - - clock.setTimeout(stub, 2, "the first", "the second"); - - clock.tick(3); - - assert.isTrue(stub.calledWithExactly("the first", "the second")); - }); - - it("calls correct timeout on recursive tick", function() { - var clock = lolex.createClock(); - var stub = sinon.stub(); - var recurseCallback = function () { clock.tick(100); }; - - clock.setTimeout(recurseCallback, 50); - clock.setTimeout(stub, 100); - - clock.tick(50); - assert(stub.called); - }); - - it("does not depend on this", function () { - var clock = lolex.createClock(); - var stub = sinon.stub(); - var setTimeout = clock.setTimeout; - - setTimeout(stub, 100); - - clock.tick(100); - assert(stub.called); - }); - }); - - describe("setImmediate", function () { - - beforeEach(function () { - this.clock = lolex.createClock(); - }); - - it("returns numeric id or object with numeric id", function () { - var result = this.clock.setImmediate(function () { }); - - if (typeof result === 'object') - assert.isNumber(result.id); - else - assert.isNumber(result); - }); - - it("calls the given callback immediately", function () { - var stub = sinon.stub(); - - this.clock.setImmediate(stub); - this.clock.tick(0); - - assert(stub.called); - }); - - it("throws if no arguments", function () { - var clock = this.clock; - - assert.exception(function () { - clock.setImmediate(); - }); - }); - - it("manages separate timers per clock instance", function () { - var clock1 = lolex.createClock(); - var clock2 = lolex.createClock(); - var stubs = [sinon.stub(), sinon.stub()]; - - clock1.setImmediate(stubs[0]); - clock2.setImmediate(stubs[1]); - clock2.tick(0); - - assert.isFalse(stubs[0].called); - assert(stubs[1].called); - }); - - it("passes extra parameters through to the callback", function () { - var stub = sinon.stub(); - - this.clock.setImmediate(stub, 'value1', 2); - this.clock.tick(1); - - assert(stub.calledWithExactly('value1', 2)); - }); - - it("calls the given callback before setTimeout", function () { - var stub1 = sinon.stub.create(); - var stub2 = sinon.stub.create(); - - this.clock.setTimeout(stub1, 0); - this.clock.setImmediate(stub2); - this.clock.tick(0); - - assert(stub1.calledOnce); - assert(stub2.calledOnce); - assert(stub2.calledBefore(stub1)); - }); - }); - - describe("clearImmediate", function () { - - beforeEach(function () { - this.clock = lolex.createClock(); - }); - - it("removes immediate callbacks", function () { - var callback = sinon.stub(); - - var id = this.clock.setImmediate(callback); - this.clock.clearImmediate(id); - this.clock.tick(1); - - assert.isFalse(callback.called); - }); - }); - - describe("tick", function () { - - beforeEach(function () { - this.clock = lolex.install(0); - }); - - afterEach(function () { - this.clock.uninstall(); - }); - - it("triggers immediately without specified delay", function () { - var stub = sinon.stub(); - this.clock.setTimeout(stub); - - this.clock.tick(0); - - assert(stub.called); - }); - - it("does not trigger without sufficient delay", function () { - var stub = sinon.stub(); - this.clock.setTimeout(stub, 100); - this.clock.tick(10); - - assert.isFalse(stub.called); - }); - - it("triggers after sufficient delay", function () { - var stub = sinon.stub(); - this.clock.setTimeout(stub, 100); - this.clock.tick(100); - - assert(stub.called); - }); - - it("triggers simultaneous timers", function () { - var spies = [sinon.spy(), sinon.spy()]; - this.clock.setTimeout(spies[0], 100); - this.clock.setTimeout(spies[1], 100); - - this.clock.tick(100); - - assert(spies[0].called); - assert(spies[1].called); - }); - - it("triggers multiple simultaneous timers", function () { - var spies = [sinon.spy(), sinon.spy(), sinon.spy(), sinon.spy()]; - this.clock.setTimeout(spies[0], 100); - this.clock.setTimeout(spies[1], 100); - this.clock.setTimeout(spies[2], 99); - this.clock.setTimeout(spies[3], 100); - - this.clock.tick(100); - - assert(spies[0].called); - assert(spies[1].called); - assert(spies[2].called); - assert(spies[3].called); - }); - - it("triggers multiple simultaneous timers with zero callAt", function () { - var test = this; - var spies = [ - sinon.spy(function() { - test.clock.setTimeout(spies[1], 0) - }), - sinon.spy(), - sinon.spy() - ]; - - // First spy calls another setTimeout with delay=0 - this.clock.setTimeout(spies[0], 0); - this.clock.setTimeout(spies[2], 10); - - this.clock.tick(10); - - assert(spies[0].called); - assert(spies[1].called); - assert(spies[2].called); - }); - - it("waits after setTimeout was called", function () { - this.clock.tick(100); - var stub = sinon.stub(); - this.clock.setTimeout(stub, 150); - this.clock.tick(50); - - assert.isFalse(stub.called); - this.clock.tick(100); - assert(stub.called); - }); - - it("mini integration test", function () { - var stubs = [sinon.stub(), sinon.stub(), sinon.stub()]; - this.clock.setTimeout(stubs[0], 100); - this.clock.setTimeout(stubs[1], 120); - this.clock.tick(10); - this.clock.tick(89); - assert.isFalse(stubs[0].called); - assert.isFalse(stubs[1].called); - this.clock.setTimeout(stubs[2], 20); - this.clock.tick(1); - assert(stubs[0].called); - assert.isFalse(stubs[1].called); - assert.isFalse(stubs[2].called); - this.clock.tick(19); - assert.isFalse(stubs[1].called); - assert(stubs[2].called); - this.clock.tick(1); - assert(stubs[1].called); - }); - - it("triggers even when some throw", function () { - var clock = this.clock; - var stubs = [sinon.stub().throws(), sinon.stub()]; - - clock.setTimeout(stubs[0], 100); - clock.setTimeout(stubs[1], 120); - - assert.exception(function() { - clock.tick(120); - }); - - assert(stubs[0].called); - assert(stubs[1].called); - }); - - it("calls function with global object or null (strict mode) as this", function () { - var clock = this.clock; - var stub = sinon.stub().throws(); - clock.setTimeout(stub, 100); - - assert.exception(function() { - clock.tick(100); - }); - - assert(stub.calledOn(global) || stub.calledOn(null)); - }); - - it("triggers in the order scheduled", function () { - var spies = [sinon.spy(), sinon.spy()]; - this.clock.setTimeout(spies[0], 13); - this.clock.setTimeout(spies[1], 11); - - this.clock.tick(15); - - assert(spies[1].calledBefore(spies[0])); - }); - - it("creates updated Date while ticking", function () { - var spy = sinon.spy(); - - this.clock.setInterval(function () { - spy(new Date().getTime()); - }, 10); - - this.clock.tick(100); - - assert.equals(spy.callCount, 10); - assert(spy.calledWith(10)); - assert(spy.calledWith(20)); - assert(spy.calledWith(30)); - assert(spy.calledWith(40)); - assert(spy.calledWith(50)); - assert(spy.calledWith(60)); - assert(spy.calledWith(70)); - assert(spy.calledWith(80)); - assert(spy.calledWith(90)); - assert(spy.calledWith(100)); - }); - - it("fires timer in intervals of 13", function () { - var spy = sinon.spy(); - this.clock.setInterval(spy, 13); - - this.clock.tick(500); - - assert.equals(spy.callCount, 38); - }); - - it("fires timers in correct order", function () { - var spy13 = sinon.spy(); - var spy10 = sinon.spy(); - - this.clock.setInterval(function () { - spy13(new Date().getTime()); - }, 13); - - this.clock.setInterval(function () { - spy10(new Date().getTime()); - }, 10); - - this.clock.tick(500); - - assert.equals(spy13.callCount, 38); - assert.equals(spy10.callCount, 50); - - assert(spy13.calledWith(416)); - assert(spy10.calledWith(320)); - - assert(spy10.getCall(0).calledBefore(spy13.getCall(0))); - assert(spy10.getCall(4).calledBefore(spy13.getCall(3))); - }); - - it("triggers timeouts and intervals in the order scheduled", function () { - var spies = [sinon.spy(), sinon.spy()]; - this.clock.setInterval(spies[0], 10); - this.clock.setTimeout(spies[1], 50); - - this.clock.tick(100); - - assert(spies[0].calledBefore(spies[1])); - assert.equals(spies[0].callCount, 10); - assert.equals(spies[1].callCount, 1); - }); - - it("does not fire canceled intervals", function () { - var id; - var callback = sinon.spy(function () { - if (callback.callCount == 3) { - clearTimeout(id); - } - }); - - id = this.clock.setInterval(callback, 10); - this.clock.tick(100); - - assert.equals(callback.callCount, 3); - }); - - it("passes 6 seconds", function () { - var spy = sinon.spy(); - this.clock.setInterval(spy, 4000); - - this.clock.tick("08"); - - assert.equals(spy.callCount, 2); - }); - - it("passes 1 minute", function () { - var spy = sinon.spy(); - this.clock.setInterval(spy, 6000); - - this.clock.tick("01:00"); - - assert.equals(spy.callCount, 10); - }); - - it("passes 2 hours, 34 minutes and 12 seconds", function () { - var spy = sinon.spy(); - this.clock.setInterval(spy, 10000); - - this.clock.tick("02:34:10"); - - assert.equals(spy.callCount, 925); - }); - - it("throws for invalid format", function () { - var spy = sinon.spy(); - this.clock.setInterval(spy, 10000); - var test = this; - - assert.exception(function () { - test.clock.tick("12:02:34:10"); - }); - - assert.equals(spy.callCount, 0); - }); - - it("throws for invalid minutes", function () { - var spy = sinon.spy(); - this.clock.setInterval(spy, 10000); - var test = this; - - assert.exception(function () { - test.clock.tick("67:10"); - }); - - assert.equals(spy.callCount, 0); - }); - - it("throws for negative minutes", function () { - var spy = sinon.spy(); - this.clock.setInterval(spy, 10000); - var test = this; - - assert.exception(function () { - test.clock.tick("-7:10"); - }); - - assert.equals(spy.callCount, 0); - }); - - it("treats missing argument as 0", function () { - this.clock.tick(); - - assert.equals(this.clock.now, 0); - }); - - it("fires nested setTimeout calls properly", function () { - var i = 0; - var clock = this.clock; - - var callback = function () { - ++i; - clock.setTimeout(function () { - callback(); - }, 100); - }; - - callback(); - - clock.tick(1000); - - assert.equals(i, 11); - }); - - it("does not silently catch exceptions", function () { - var clock = this.clock; - - clock.setTimeout(function() { - throw new Exception("oh no!"); - }, 1000); - - assert.exception(function() { - clock.tick(1000); - }); - }); - - it("returns the current now value", function () { - var clock = this.clock; - var value = clock.tick(200); - assert.equals(clock.now, value); - }); - }); - - describe("clearTimeout", function () { - - beforeEach(function () { - this.clock = lolex.createClock(); - }); - - it("removes timeout", function () { - var stub = sinon.stub(); - var id = this.clock.setTimeout(stub, 50); - this.clock.clearTimeout(id); - this.clock.tick(50); - - assert.isFalse(stub.called); - }); - - it("ignores null argument", function () { - this.clock.clearTimeout(null); - assert(true); // doesn't fail - }); - }); - - describe("reset", function () { - - beforeEach(function () { - this.clock = lolex.createClock(); - }); - - it("empties timeouts queue", function () { - var stub = sinon.stub(); - this.clock.setTimeout(stub); - this.clock.reset(); - this.clock.tick(0); - - assert.isFalse(stub.called); - }); - }); - - describe("setInterval", function () { - - beforeEach(function () { - this.clock = lolex.createClock(); - }); - - it("throws if no arguments", function () { - var clock = this.clock; - - assert.exception(function () { - clock.setInterval(); - }); - }); - - it("returns numeric id or object with numeric id", function () { - var result = this.clock.setInterval(""); - - if (typeof result === 'object') - assert.isNumber(result.id); - else - assert.isNumber(result); - }); - - it("returns unique id", function () { - var id1 = this.clock.setInterval(""); - var id2 = this.clock.setInterval(""); - - refute.equals(id2, id1); - }); - - it("schedules recurring timeout", function () { - var stub = sinon.stub(); - this.clock.setInterval(stub, 10); - this.clock.tick(99); - - assert.equals(stub.callCount, 9); - }); - - it("does not schedule recurring timeout when cleared", function () { - var clock = this.clock; - var id; - var stub = sinon.spy(function () { - if (stub.callCount == 3) { - clock.clearInterval(id); - } - }); - - id = this.clock.setInterval(stub, 10); - this.clock.tick(100); - - assert.equals(stub.callCount, 3); - }); - - it("passes setTimeout parameters", function() { - var clock = lolex.createClock(); - var stub = sinon.stub(); - - clock.setInterval(stub, 2, "the first", "the second"); - - clock.tick(3); - - assert.isTrue(stub.calledWithExactly("the first", "the second")); - }); - }); - - describe("date", function () { - - beforeEach(function () { - this.now = new globalDate().getTime() - 3000; - this.clock = lolex.createClock(this.now); - this.Date = global.Date; - }); - - afterEach(function () { - global.Date = this.Date; - }); - - it("provides date constructor", function () { - assert.isFunction(this.clock.Date); - }); - - it("creates real Date objects", function () { - var date = new this.clock.Date(); - - assert(Date.prototype.isPrototypeOf(date)); - }); - - it("creates real Date objects when called as function", function () { - var date = this.clock.Date(); - - assert(Date.prototype.isPrototypeOf(date)); - }); - - it("creates real Date objects when Date constructor is gone", function () { - var realDate = new Date(); - Date = function () {}; - global.Date = function () {}; - - var date = new this.clock.Date(); - - assert.same(date.constructor.prototype, realDate.constructor.prototype); - }); - - it("creates Date objects representing clock time", function () { - var date = new this.clock.Date(); - - assert.equals(date.getTime(), new Date(this.now).getTime()); - }); - - it("returns Date object representing clock time", function () { - var date = this.clock.Date(); - - assert.equals(date.getTime(), new Date(this.now).getTime()); - }); - - it("listens to ticking clock", function () { - var date1 = new this.clock.Date(); - this.clock.tick(3); - var date2 = new this.clock.Date(); - - assert.equals(date2.getTime() - date1.getTime(), 3); - }); - - it("creates regular date when passing timestamp", function () { - var date = new Date(); - var fakeDate = new this.clock.Date(date.getTime()); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("returns regular date when calling with timestamp", function () { - var date = new Date(); - var fakeDate = this.clock.Date(date.getTime()); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("creates regular date when passing year, month", function () { - var date = new Date(2010, 4); - var fakeDate = new this.clock.Date(2010, 4); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("returns regular date when calling with year, month", function () { - var date = new Date(2010, 4); - var fakeDate = this.clock.Date(2010, 4); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("creates regular date when passing y, m, d", function () { - var date = new Date(2010, 4, 2); - var fakeDate = new this.clock.Date(2010, 4, 2); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("returns regular date when calling with y, m, d", function () { - var date = new Date(2010, 4, 2); - var fakeDate = this.clock.Date(2010, 4, 2); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("creates regular date when passing y, m, d, h", function () { - var date = new Date(2010, 4, 2, 12); - var fakeDate = new this.clock.Date(2010, 4, 2, 12); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("returns regular date when calling with y, m, d, h", function () { - var date = new Date(2010, 4, 2, 12); - var fakeDate = this.clock.Date(2010, 4, 2, 12); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("creates regular date when passing y, m, d, h, m", function () { - var date = new Date(2010, 4, 2, 12, 42); - var fakeDate = new this.clock.Date(2010, 4, 2, 12, 42); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("returns regular date when calling with y, m, d, h, m", function () { - var date = new Date(2010, 4, 2, 12, 42); - var fakeDate = this.clock.Date(2010, 4, 2, 12, 42); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("creates regular date when passing y, m, d, h, m, s", function () { - var date = new Date(2010, 4, 2, 12, 42, 53); - var fakeDate = new this.clock.Date(2010, 4, 2, 12, 42, 53); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("returns regular date when calling with y, m, d, h, m, s", function () { - var date = new Date(2010, 4, 2, 12, 42, 53); - var fakeDate = this.clock.Date(2010, 4, 2, 12, 42, 53); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("creates regular date when passing y, m, d, h, m, s, ms", function () { - var date = new Date(2010, 4, 2, 12, 42, 53, 498); - var fakeDate = new this.clock.Date(2010, 4, 2, 12, 42, 53, 498); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("returns regular date when calling with y, m, d, h, m, s, ms", function () { - var date = new Date(2010, 4, 2, 12, 42, 53, 498); - var fakeDate = this.clock.Date(2010, 4, 2, 12, 42, 53, 498); - - assert.equals(fakeDate.getTime(), date.getTime()); - }); - - it("mirrors native Date.prototype", function () { - assert.same(this.clock.Date.prototype, Date.prototype); - }); - - it("supports now method if present", function () { - assert.same(typeof this.clock.Date.now, typeof Date.now); - }); - - if (Date.now) { - describe("now", function () { - it("returns clock.now", function () { - assert.equals(this.clock.Date.now(), this.now); - }); - }); - } else { - describe("unsupported now", function () { - it("is undefined", function () { - refute.defined(this.clock.Date.now); - }); - }); - } - - it("mirrors parse method", function () { - assert.same(this.clock.Date.parse, Date.parse); - }); - - it("mirrors UTC method", function () { - assert.same(this.clock.Date.UTC, Date.UTC); - }); - - it("mirrors toUTCString method", function () { - assert.same(this.clock.Date.prototype.toUTCString, Date.prototype.toUTCString); - }); - - if (Date.toSource) { - describe("toSource", function () { - - it("is mirrored", function () { - assert.same(this.clock.Date.toSource(), Date.toSource()); - }); - - }); - } else { - describe("unsupported toSource", function () { - - it("is undefined", function () { - refute.defined(this.clock.Date.toSource); - }); - - }); - } - - it("mirrors toString", function () { - assert.same(this.clock.Date.toString(), Date.toString()); - }); - }); - - describe("stubTimers", function () { - - beforeEach(function () { - this.dateNow = global.Date.now; - }); - - afterEach(function () { - if (this.clock) { - this.clock.uninstall(); - } - - clearTimeout(this.timer); - if (typeof this.dateNow == "undefined") { - delete global.Date.now; - } else { - global.Date.now = this.dateNow; - } - }); - - it("returns clock object", function () { - this.clock = lolex.install(); - - assert.isObject(this.clock); - assert.isFunction(this.clock.tick); - }); - - it("has clock property", function () { - this.clock = lolex.install(); - - assert.same(setTimeout.clock, this.clock); - assert.same(clearTimeout.clock, this.clock); - assert.same(setInterval.clock, this.clock); - assert.same(clearInterval.clock, this.clock); - assert.same(Date.clock, this.clock); - }); - - it("sets initial timestamp", function () { - this.clock = lolex.install(1400); - - assert.equals(this.clock.now, 1400); - }); - - it("replaces global setTimeout", function () { - this.clock = lolex.install(); - var stub = sinon.stub(); - - setTimeout(stub, 1000); - this.clock.tick(1000); - - assert(stub.called); - }); - - it("global fake setTimeout should return id", function () { - this.clock = lolex.install(); - var stub = sinon.stub(); - - var to = setTimeout(stub, 1000); - - if (typeof (setTimeout(function() {}, 0)) === 'object') { - assert.isNumber(to.id); - assert.isFunction(to.ref); - assert.isFunction(to.unref); - } - else { - assert.isNumber(to); - } - }); - - it("replaces global clearTimeout", function () { - this.clock = lolex.install(); - var stub = sinon.stub(); - - clearTimeout(setTimeout(stub, 1000)); - this.clock.tick(1000); - - assert.isFalse(stub.called); - }); - - it("uninstalls global setTimeout", function () { - this.clock = lolex.install(); - var stub = sinon.stub(); - this.clock.uninstall(); - - this.timer = setTimeout(stub, 1000); - this.clock.tick(1000); - - assert.isFalse(stub.called); - assert.same(setTimeout, lolex.timers.setTimeout); - }); - - it("uninstalls global clearTimeout", function () { - this.clock = lolex.install(); - sinon.stub(); - this.clock.uninstall(); - - assert.same(clearTimeout, lolex.timers.clearTimeout); - }); - - it("replaces global setInterval", function () { - this.clock = lolex.install(); - var stub = sinon.stub(); - - setInterval(stub, 500); - this.clock.tick(1000); - - assert(stub.calledTwice); - }); - - it("replaces global clearInterval", function () { - this.clock = lolex.install(); - var stub = sinon.stub(); - - clearInterval(setInterval(stub, 500)); - this.clock.tick(1000); - - assert.isFalse(stub.called); - }); - - it("uninstalls global setInterval", function () { - this.clock = lolex.install(); - var stub = sinon.stub(); - this.clock.uninstall(); - - this.timer = setInterval(stub, 1000); - this.clock.tick(1000); - - assert.isFalse(stub.called); - assert.same(setInterval, lolex.timers.setInterval); - }); - - it("uninstalls global clearInterval", function () { - this.clock = lolex.install(); - sinon.stub(); - this.clock.uninstall(); - - assert.same(clearInterval, lolex.timers.clearInterval); - }); - - if (global.__proto__) { - it("deletes global property on uninstall if it was inherited onto the global object", function () { - // Give the global object an inherited 'tick' method - delete global.tick; - global.__proto__.tick = function() { }; - - this.clock = lolex.install(0, ['tick']); - assert.isTrue(global.hasOwnProperty("tick")); - this.clock.uninstall(); - - assert.isFalse(global.hasOwnProperty("tick")); - delete global.__proto__.tick; - }); - } - - it("uninstalls global property on uninstall if it is present on the global object itself", function () { - // Directly give the global object a tick method - global.tick = function () { }; - - this.clock = lolex.install(0, ['tick']); - assert.isTrue(global.hasOwnProperty("tick")); - this.clock.uninstall(); - - assert.isTrue(global.hasOwnProperty("tick")); - delete global.tick; - }); - - it("fakes Date constructor", function () { - this.clock = lolex.install(0); - var now = new Date(); - - refute.same(Date, lolex.timers.Date); - assert.equals(now.getTime(), 0); - }); - - it("fake Date constructor should mirror Date's properties", function () { - this.clock = lolex.install(0); - - assert(!!Date.parse); - assert(!!Date.UTC); - }); - - it("decide on Date.now support at call-time when supported", function () { - global.Date.now = function () {}; - this.clock = lolex.install(0); - - assert.equals(typeof Date.now, "function"); - }); - - it("decide on Date.now support at call-time when unsupported", function () { - global.Date.now = null; - this.clock = lolex.install(0); - - refute.defined(Date.now); - }); - - // TODO: The following tests causes test suite instability - - // "mirrors custom Date properties": function () { - // var f = function () { }; - // global.Date.format = f; - // lolex.install(); - - // assert.equals(Date.format, f); - // }, - - // "uninstalls Date constructor": function () { - // this.clock = lolex.install(0); - // this.clock.uninstall(); - - // assert.same(globalDate, lolex.timers.Date); - // }, - - // "fakes provided methods": function () { - // this.clock = lolex.install(0, ["setTimeout", "Date"]); - - // refute.same(setTimeout, lolex.timers.setTimeout); - // refute.same(Date, lolex.timers.Date); - // }, - - // "resets faked methods": function () { - // this.clock = lolex.install(0, ["setTimeout", "Date"]); - // this.clock.uninstall(); - - // assert.same(setTimeout, lolex.timers.setTimeout); - // assert.same(Date, lolex.timers.Date); - // }, - - // "does not fake methods not provided": function () { - // this.clock = lolex.install(0, ["setTimeout", "Date"]); - - // assert.same(clearTimeout, lolex.timers.clearTimeout); - // assert.same(setInterval, lolex.timers.setInterval); - // assert.same(clearInterval, lolex.timers.clearInterval); - // }, - - // "does not be able to use date object for now": function () { - // assert.exception(function () { - // lolex.install(new Date(2011, 9, 1)); - // }); - // } - }); -}); diff --git a/node_modules/sinon/node_modules/samsam/.npmignore b/node_modules/sinon/node_modules/samsam/.npmignore deleted file mode 100644 index 07e6e47..0000000 --- a/node_modules/sinon/node_modules/samsam/.npmignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules diff --git a/node_modules/sinon/node_modules/samsam/.travis.yml b/node_modules/sinon/node_modules/samsam/.travis.yml deleted file mode 100644 index 587bd3e..0000000 --- a/node_modules/sinon/node_modules/samsam/.travis.yml +++ /dev/null @@ -1 +0,0 @@ -language: node_js diff --git a/node_modules/sinon/node_modules/samsam/AUTHORS b/node_modules/sinon/node_modules/samsam/AUTHORS deleted file mode 100644 index 13df013..0000000 --- a/node_modules/sinon/node_modules/samsam/AUTHORS +++ /dev/null @@ -1,2 +0,0 @@ -Christian Johansen (christian@cjohansen.no) -August Lilleaas (august@augustl.com) diff --git a/node_modules/sinon/node_modules/samsam/LICENSE b/node_modules/sinon/node_modules/samsam/LICENSE deleted file mode 100644 index f00310b..0000000 --- a/node_modules/sinon/node_modules/samsam/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -(The BSD License) - -Copyright (c) 2010-2012, Christian Johansen, christian@cjohansen.no and -August Lilleaas, august.lilleaas@gmail.com. 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. diff --git a/node_modules/sinon/node_modules/samsam/Readme.md b/node_modules/sinon/node_modules/samsam/Readme.md deleted file mode 100644 index a2a56c3..0000000 --- a/node_modules/sinon/node_modules/samsam/Readme.md +++ /dev/null @@ -1,226 +0,0 @@ -# samsam - -[![Build status](https://secure.travis-ci.org/busterjs/samsam.png?branch=master)](http://travis-ci.org/busterjs/samsam) - -> Same same, but different - -`samsam` is a collection of predicate and comparison functions useful for -identifiying the type of values and to compare values with varying degrees of -strictness. - -`samsam` is a general-purpose library with no dependencies. It works in browsers -(including old and rowdy ones, like IE6) and Node. It will define itself as an -AMD module if you want it to (i.e. if there's a `define` function available). - -`samsam` was originally extracted from the -`referee `_ assertion library, which -ships with the Buster.JS testing framework. - - -## Predicate functions - - -### `isArguments(object)` - -Returns `true` if `object` is an `arguments` object, `false` otherwise. - - -### `isNegZero(value)` - -Returns `true` if `value` is `-0`. - - -## `isElement(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`. - - -###`isDate(object)` - -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`. - - -## Comparison functions - - -###`identical(x, y)` - -Strict equality check according to `EcmaScript Harmony's `egal`. - -**From the Harmony wiki:** - -> An egal function simply makes available the internal `SameValue` function -from section 9.12 of the ES5 spec. If two values are egal, then they are not -observably distinguishable. - -`identical` returns `true` when `===` is `true`, except for `-0` and -`+0`, where it returns `false`. Additionally, it returns `true` when -`NaN` is compared to itself. - - -### `deepEqual(obj1, obj2)` - -Deep equal comparison. Two values are "deep equal" if: - -* They are 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` - - -### `match(object, matcher)` - -Partial equality check. Compares `object` with matcher according a wide set of -rules: - - -**String matcher** - -In its simplest form, `match` performs a case insensitive substring match. -When the matcher is a string, `object` is converted to a string, and the -function returns `true` if the matcher is a case-insensitive substring of -`object` as a string. - -```javascript -samsam.match("Give me something", "Give"); //true -samsam.match("Give me something", "sumptn"); // false -samsam.match({ toString: function () { return "yeah"; } }, "Yeah!"); // true -``` - -The last example is not symmetric. When the matcher is a string, the `object` -is coerced to a string - in this case using `toString`. Changing the order of -the arguments would cause the matcher to be an object, in which case different -rules apply (see below). - - -**Boolean matcher** - -Performs a strict (i.e. `===`) match with the object. So, only `true` -matches `true`, and only `false` matches `false`. - - -**Regular expression matcher** - -When the matcher is a regular expression, the function will pass if -`object.test(matcher)` is `true`. `match` is written in a generic way, so -any object with a `test` method will be used as a matcher this way. - -```javascript -samsam.match("Give me something", /^[a-z\s]$/i); // true -samsam.match("Give me something", /[0-9]/); // false -samsam.match({ toString: function () { return "yeah!"; } }, /yeah/); // true -samsam.match(234, /[a-z]/); // false -``` - - -**Number matcher** - -When the matcher is a number, the assertion will pass if `object == matcher`. - -```javascript -samsam.match("123", 123); // true -samsam.match("Give me something", 425); // false -samsam.match({ toString: function () { return "42"; } }, 42); // true -samsam.match(234, 1234); // false -``` - - -**Function matcher** - -When the matcher is a function, it is called with `object` as its only -argument. `match` returns `true` if the function returns `true`. A strict -match is performed against the return value, so a boolean `true` is required, -truthy is not enough. - -```javascript -// true -samsam.match("123", function (exp) { - return exp == "123"; -}); - -// false -samsam.match("Give me something", function () { - return "ok"; -}); - -// true -samsam.match({ - toString: function () { - return "42"; - } -}, function () { return true; }); - -// false -samsam.match(234, function () {}); -``` - - -**Object matcher** - -As mentioned above, if an object matcher defines a `test` method, `match` -will return `true` if `matcher.test(object)` returns truthy. - -If the matcher does not have a test method, a recursive match is performed. If -all properties of `matcher` matches corresponding properties in `object`, -`match` returns `true`. Note that the object matcher does not care if the -number of properties in the two objects are the same - only if all properties in -the matcher recursively matches ones in `object`. - -```javascript -// true -samsam.match("123", { - test: function (arg) { - return arg == 123; - } -}); - -// false -samsam.match({}, { prop: 42 }); - -// true -samsam.match({ - name: "Chris", - profession: "Programmer" -}, { - name: "Chris" -}); - -// false -samsam.match(234, { name: "Chris" }); -``` - - -**DOM elements** - -`match` can be very helpful when comparing DOM elements, because it allows -you to compare several properties with one call: - -```javascript -var el = document.getElementById("myEl"); - -samsam.match(el, { - tagName: "h2", - className: "item", - innerHTML: "Howdy" -}); -``` - - -## Changelog - -**1.1.2** (11.12.2014) - -* Fix for issue [#359 - `assert.match` does not support objects with `null` properties`](https://github.com/busterjs/buster/issues/359) -* Implementation of feature request [#64 - assert.match and parentNode](https://github.com/busterjs/buster/issues/64) - -**1.1.1** (26.03.2014) - -* [Make `isArguments` work with arguments from `"strict mode"` functions](https://github.com/busterjs/samsam/commit/72903613af90f39474f8388ed8957eaea4cf46ae) -* [Fix type error for nested object in function `match`](https://github.com/busterjs/samsam/commit/9d3420a11e9b3c65559945e60ca56980820db20f) -* Fix for issue [#366 - Assertion match fails with data attribute](https://github.com/busterjs/buster/issues/366) diff --git a/node_modules/sinon/node_modules/samsam/autolint.js b/node_modules/sinon/node_modules/samsam/autolint.js deleted file mode 100644 index 4f9755e..0000000 --- a/node_modules/sinon/node_modules/samsam/autolint.js +++ /dev/null @@ -1,23 +0,0 @@ -module.exports = { - paths: [ - "lib/*.js", - "test/*.js" - ], - linterOptions: { - node: true, - browser: true, - plusplus: true, - vars: true, - nomen: true, - forin: true, - sloppy: true, - eqeq: true, - predef: [ - "_", - "define", - "assert", - "refute", - "buster" - ] - } -}; diff --git a/node_modules/sinon/node_modules/samsam/jsTestDriver.conf b/node_modules/sinon/node_modules/samsam/jsTestDriver.conf deleted file mode 100644 index ee91c70..0000000 --- a/node_modules/sinon/node_modules/samsam/jsTestDriver.conf +++ /dev/null @@ -1,9 +0,0 @@ -server: http://localhost:4224 - -load: - - node_modules/sinon/lib/sinon.js - - node_modules/sinon/lib/sinon/spy.js - - lib/samsam.js - - node_modules/buster-util/lib/buster-util/test-case.js - - node_modules/buster-util/lib/buster-util/jstestdriver-shim.js - - test/samsam-test.js diff --git a/node_modules/sinon/node_modules/samsam/lib/samsam.js b/node_modules/sinon/node_modules/samsam/lib/samsam.js deleted file mode 100644 index c451e68..0000000 --- a/node_modules/sinon/node_modules/samsam/lib/samsam.js +++ /dev/null @@ -1,399 +0,0 @@ -((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 - }; -}); diff --git a/node_modules/sinon/node_modules/samsam/package.json b/node_modules/sinon/node_modules/samsam/package.json deleted file mode 100644 index b9947f1..0000000 --- a/node_modules/sinon/node_modules/samsam/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "name": "samsam", - "version": "1.1.2", - "description": "Value identification and comparison functions", - "homepage": "http://busterjs.org/docs/buster-assertions", - "author": { - "name": "Christian Johansen" - }, - "contributors": [ - { - "name": "Christian Johansen", - "email": "christian@cjohansen.no", - "url": "http://cjohansen.no" - }, - { - "name": "August Lilleaas", - "email": "august.lilleaas@gmail.com", - "url": "http://augustl.com" - }, - { - "name": "Daniel Wittner", - "email": "d.wittner@gmx.de", - "url": "https://github.com/dwittner" - } - ], - "main": "./lib/samsam", - "repository": { - "type": "git", - "url": "git+https://github.com/busterjs/samsam.git" - }, - "scripts": { - "test": "node test/samsam-test.js", - "test-debug": "node --debug-brk test/samsam-test.js" - }, - "devDependencies": { - "buster": "0.6.11" - }, - "bugs": { - "url": "https://github.com/busterjs/samsam/issues" - }, - "_id": "samsam@1.1.2", - "_shasum": "bec11fdc83a9fda063401210e40176c3024d1567", - "_from": "samsam@1.1.2", - "_npmVersion": "1.4.9", - "_npmUser": { - "name": "dwittner", - "email": "d.wittner@gmx.de" - }, - "maintainers": [ - { - "name": "cjohansen", - "email": "christian@cjohansen.no" - }, - { - "name": "augustl", - "email": "august@augustl.com" - }, - { - "name": "dwittner", - "email": "d.wittner@gmx.de" - } - ], - "dist": { - "shasum": "bec11fdc83a9fda063401210e40176c3024d1567", - "tarball": "http://registry.npmjs.org/samsam/-/samsam-1.1.2.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/samsam/-/samsam-1.1.2.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/node_modules/sinon/node_modules/samsam/test/samsam-test.js b/node_modules/sinon/node_modules/samsam/test/samsam-test.js deleted file mode 100644 index a55f9a2..0000000 --- a/node_modules/sinon/node_modules/samsam/test/samsam-test.js +++ /dev/null @@ -1,386 +0,0 @@ -if (typeof module === "object" && typeof require === "function") { - var buster = require("buster"); - var samsam = require("../lib/samsam"); -} - -(function () { - - var assert = buster.assert; - - function tests(method, body) { - var tc = {}; - - function pass(name) { - var args = Array.prototype.slice.call(arguments, 1); - tc["should return true for " + name] = function () { - assert(samsam[method].apply(samsam, args)); - }; - } - - function fail(name) { - var args = Array.prototype.slice.call(arguments, 1); - tc["should return false for " + name] = function () { - assert(!samsam[method].apply(samsam, args)); - }; - } - - function shouldThrow(name) { - var args = Array.prototype.slice.call(arguments, 1); - try { - samsam[method].apply(samsam, args); - buster.assertion.fail("Expected to throw"); - } catch (e) { - assert(true); - } - } - - function add(name, func) { - tc[name] = func; - } - - body(pass, fail, shouldThrow, add); - buster.testCase(method, tc); - } - - tests("isElement", function (pass, fail) { - if (typeof document !== "undefined") { - pass("DOM element node", document.createElement("div")); - fail("DOM text node", document.createTextNode("Hello")); - } - - fail("primitive", 42); - fail("object", {}); - fail("node-like object", { nodeType: 1 }); - }); - - tests("isNegZero", function (pass, fail) { - pass("-0", -0); - fail("0", 0); - fail("object", {}); - }); - - tests("identical", function (pass, fail) { - var object = { id: 42 }; - pass("same object", object, object); - pass("same primitive", 42, 42); - fail("-0 and 0", -0, 0); - pass("NaN and NaN", NaN, NaN); - }); - - tests("deepEqual", function (pass, fail) { - var func = function () {}; - var obj = {}; - var arr = []; - var date = new Date(); - var sameDate = new Date(date.getTime()); - var anotherDate = new Date(date.getTime() - 10); - var sameDateWithProp = new Date(date.getTime()); - sameDateWithProp.prop = 42; - - pass("object to itself", obj, obj); - pass("strings", "Hey", "Hey"); - pass("numbers", 32, 32); - pass("booleans", false, false); - pass("null", null, null); - pass("undefined", undefined, undefined); - pass("function to itself", func, func); - fail("functions", function () {}, function () {}); - pass("array to itself", arr, arr); - pass("date objects with same date", date, sameDate); - fail("date objects with different dates", date, anotherDate); - fail("date objects to null", date, null); - fail("date with different custom properties", date, sameDateWithProp); - fail("strings and numbers with coercion", "4", 4); - fail("numbers and strings with coercion", 4, "4"); - fail("number object with coercion", 32, new Number(32)); - fail("number object reverse with coercion", new Number(32), 32); - fail("falsy values with coercion", 0, ""); - fail("falsy values reverse with coercion", "", 0); - fail("string boxing with coercion", "4", new String("4")); - fail("string boxing reverse with coercion", new String("4"), "4"); - pass("NaN to NaN", NaN, NaN); - fail("-0 to +0", -0, +0); - fail("-0 to 0", -0, 0); - fail("objects with different own properties", - { id: 42 }, { id: 42, di: 24 }); - fail("objects with different own properties #2", - { id: undefined }, { di: 24 }); - fail("objects with different own properties #3", - { id: 24 }, { di: undefined }); - pass("objects with one property", { id: 42 }, { id: 42 }); - pass("objects with one object property", - { obj: { id: 42 } }, { obj: { id: 42 } }); - fail("objects with one property with different values", - { id: 42 }, { id: 24 }); - - var deepObject = { - id: 42, - name: "Hey", - sayIt: function () { - return this.name; - }, - - child: { - speaking: function () {} - } - }; - - pass("complex objects", deepObject, { - sayIt: deepObject.sayIt, - child: { speaking: deepObject.child.speaking }, - id: 42, - name: "Hey" - }); - - pass("arrays", - [1, 2, "Hey there", func, { id: 42, prop: [2, 3] }], - [1, 2, "Hey there", func, { id: 42, prop: [2, 3] }]); - - fail("nested array with shallow array", [["hey"]], ["hey"]); - - var arr1 = [1, 2, 3]; - var arr2 = [1, 2, 3]; - arr1.prop = 42; - fail("arrays with different custom properties", arr1, arr2); - - pass("regexp literals", /a/, /a/); - pass("regexp objects", new RegExp("[a-z]+"), new RegExp("[a-z]+")); - - var re1 = new RegExp("[a-z]+"); - var re2 = new RegExp("[a-z]+"); - re2.id = 42; - - fail("regexp objects with custom properties", re1, re2); - fail("different objects", { id: 42 }, {}); - fail("object to null", {}, null); - fail("object to undefined", {}, undefined); - fail("object to false", {}, false); - fail("false to object", false, {}); - fail("object to true", {}, true); - fail("true to object", true, {}); - fail("'empty' object to date", {}, new Date()); - fail("'empty' object to string object", {}, String()); - fail("'empty' object to number object", {}, Number()); - fail("'empty' object to empty array", {}, []); - - function gather() { return arguments; } - var arrayLike = { length: 4, "0": 1, "1": 2, "2": {}, "3": [] }; - - pass("arguments to array", [1, 2, {}, []], gather(1, 2, {}, [])); - pass("array to arguments", gather(), []); - - pass("arguments to array like object", - arrayLike, gather(1, 2, {}, [])); - }); - - /** - * Tests for cyclic objects. - */ - tests("deepEqual", function (pass, fail) { - - (function () { - var cyclic1 = {}, cyclic2 = {}; - cyclic1.ref = cyclic1; - cyclic2.ref = cyclic2; - pass("equal cyclic objects (cycle on 2nd level)", cyclic1, cyclic2); - }()); - - (function () { - var cyclic1 = {}, cyclic2 = {}; - cyclic1.ref = cyclic1; - cyclic2.ref = cyclic2; - cyclic2.ref2 = cyclic2; - fail("different cyclic objects (cycle on 2nd level)", - cyclic1, cyclic2); - }()); - - (function () { - var cyclic1 = {}, cyclic2 = {}; - cyclic1.ref = {}; - cyclic1.ref.ref = cyclic1; - cyclic2.ref = {}; - cyclic2.ref.ref = cyclic2; - pass("equal cyclic objects (cycle on 3rd level)", cyclic1, cyclic2); - }()); - - (function () { - var cyclic1 = {}, cyclic2 = {}; - cyclic1.ref = {}; - cyclic1.ref.ref = cyclic1; - cyclic2.ref = {}; - cyclic2.ref.ref = cyclic2; - cyclic2.ref.ref2 = cyclic2; - fail("different cyclic objects (cycle on 3rd level)", - cyclic1, cyclic2); - }()); - - (function () { - var cyclic1 = {}, cyclic2 = {}; - cyclic1.ref = cyclic1; - cyclic2.ref = cyclic1; - pass("equal objects even though only one object is cyclic", - cyclic1, cyclic2); - }()); - - (function () { - var cyclic1 = {}, cyclic2 = {}; - cyclic1.ref = { - ref: cyclic1 - }; - cyclic2.ref = {}; - cyclic2.ref.ref = cyclic2.ref; - pass("referencing different but equal cyclic objects", - cyclic1, cyclic2); - }()); - - (function () { - var cyclic1 = {a: "a"}, cyclic2 = {a: "a"}; - cyclic1.ref = { - b: "b", - ref: cyclic1 - }; - cyclic2.ref = { - b: "b" - }; - cyclic2.ref.ref = cyclic2.ref; - fail("referencing different and unequal cyclic objects", - cyclic1, cyclic2); - }()); - }); - - tests("match", function (pass, fail, shouldThrow, add) { - pass("matching regexp", "Assertions", /[a-z]/); - pass("generic object and test method returning true", "Assertions", { - test: function () { return true; } - }); - fail("non-matching regexp", "Assertions 123", /^[a-z]$/); - pass("matching boolean", true, true); - fail("mismatching boolean", true, false); - fail("generic object with test method returning false", "Assertions", { - test: function () { return false; } - }); - shouldThrow("match object === null", "Assertions 123", null); - fail("match object === false", "Assertions 123", false); - fail("matching number against string", "Assertions 123", 23); - fail("matching number against similar string", "23", 23); - pass("matching number against itself", 23, 23); - pass("matcher function returns true", - "Assertions 123", function (obj) { return true; }); - fail("matcher function returns false", - "Assertions 123", function (obj) { return false; }); - fail("matcher function returns falsy", - "Assertions 123", function () {}); - fail("matcher does not return explicit true", - "Assertions 123", function () { return "Hey"; }); - - add("should call matcher with object", function () { - var spy = this.spy(); - samsam.match("Assertions 123", spy); - assert.calledWith(spy, "Assertions 123"); - }); - - pass("matcher is substring of matchee", "Diskord", "or"); - pass("matcher is string equal to matchee", "Diskord", "Diskord"); - pass("strings ignoring case", "Look ma, case-insensitive", - "LoOk Ma, CaSe-InSenSiTiVe"); - fail("match string is not substring of matchee", "Vim", "Emacs"); - fail("match string is not substring of object", {}, "Emacs"); - fail("matcher is not substring of object.toString", { - toString: function () { return "Vim"; } - }, "Emacs"); - fail("null and empty string", null, ""); - fail("undefined and empty string", undefined, ""); - fail("false and empty string", false, ""); - fail("0 and empty string", 0, ""); - fail("NaN and empty string", NaN, ""); - - var object = { - id: 42, - name: "Christian", - doIt: "yes", - - speak: function () { - return this.name; - } - }; - - pass("object containing all properties in matcher", object, { - id: 42, - doIt: "yes" - }); - - var object2 = { - id: 42, - name: "Christian", - doIt: "yes", - owner: { - someDude: "Yes", - hello: "ok" - }, - - speak: function () { - return this.name; - } - }; - - pass("nested matcher", object2, { - owner: { - someDude: "Yes", - hello: function (value) { - return value == "ok"; - } - } - }); - - pass("empty strings", "", ""); - pass("empty strings as object properties", { foo: "" }, { foo: "" }); - pass("similar arrays", [1, 2, 3], [1, 2, 3]); - pass("array subset", [1, 2, 3], [2, 3]); - pass("single-element array subset", [1, 2, 3], [1]); - pass("matching array subset", [1, 2, 3, { id: 42 }], [{ id: 42 }]); - fail("mis-matching array 'subset'", [1, 2, 3], [2, 3, 4]); - fail("mis-ordered array 'subset'", [1, 2, 3], [1, 3]); - pass("empty arrays", [], []); - pass("objects with empty arrays", { xs: [] }, { xs: [] }); - fail("nested objects with different depth", { a: 1 }, { b: { c: 2 } }); - pass("dom elements with matching data attributes", { - getAttribute: function (name) { - if (name === "data-path") { - return "foo.bar"; - } - } - }, { "data-path": "foo.bar" }); - fail("dom elements with not matching data attributes", { - getAttribute: function (name) { - if (name === "data-path") { - return "foo.foo"; - } - } - }, { "data-path": "foo.bar" }); - - pass("equal null properties", { foo: null }, { foo: null }); - fail("unmatched null property", {}, { foo: null }); - fail("matcher with unmatched null property", { foo: 'arbitrary' }, { foo: null }); - pass("equal undefined properties", { foo: undefined }, { foo: undefined }); - fail("matcher with unmatched undefined property", { foo: 'arbitrary' }, { foo: undefined }); - pass('unmatched undefined property', {}, { foo: undefined }); - - var obj = { foo: undefined }; - pass("same object matches self", obj, obj); - - pass("null matches null", null, null); - fail("null does not match undefined", null, undefined); - - pass("undefined matches undefined", undefined, undefined); - fail("undefined does not match null", undefined, null); - - }); - - tests("isArguments", function (pass, fail) { - pass("arguments object", arguments); - fail("primitive", 42); - fail("object", {}); - pass("arguments object from strict-mode function", - (function () { "use strict"; return arguments; }())); - }); -}()); diff --git a/node_modules/sinon/node_modules/util/.npmignore b/node_modules/sinon/node_modules/util/.npmignore deleted file mode 100644 index 3c3629e..0000000 --- a/node_modules/sinon/node_modules/util/.npmignore +++ /dev/null @@ -1 +0,0 @@ -node_modules diff --git a/node_modules/sinon/node_modules/util/.travis.yml b/node_modules/sinon/node_modules/util/.travis.yml deleted file mode 100644 index ded625c..0000000 --- a/node_modules/sinon/node_modules/util/.travis.yml +++ /dev/null @@ -1,8 +0,0 @@ -language: node_js -node_js: -- '0.8' -- '0.10' -env: - global: - - secure: AdUubswCR68/eGD+WWjwTHgFbelwQGnNo81j1IOaUxKw+zgFPzSnFEEtDw7z98pWgg7p9DpCnyzzSnSllP40wq6AG19OwyUJjSLoZK57fp+r8zwTQwWiSqUgMu2YSMmKJPIO/aoSGpRQXT+L1nRrHoUJXgFodyIZgz40qzJeZjc= - - secure: heQuxPVsQ7jBbssoVKimXDpqGjQFiucm6W5spoujmspjDG7oEcHD9ANo9++LoRPrsAmNx56SpMK5fNfVmYediw6SvhXm4Mxt56/fYCrLDBtgGG+1neCeffAi8z1rO8x48m77hcQ6YhbUL5R9uBimUjMX92fZcygAt8Rg804zjFo= diff --git a/node_modules/sinon/node_modules/util/.zuul.yml b/node_modules/sinon/node_modules/util/.zuul.yml deleted file mode 100644 index 2105010..0000000 --- a/node_modules/sinon/node_modules/util/.zuul.yml +++ /dev/null @@ -1,10 +0,0 @@ -ui: mocha-qunit -browsers: - - name: chrome - version: 27..latest - - name: firefox - version: latest - - name: safari - version: latest - - name: ie - version: 9..latest diff --git a/node_modules/sinon/node_modules/util/LICENSE b/node_modules/sinon/node_modules/util/LICENSE deleted file mode 100644 index e3d4e69..0000000 --- a/node_modules/sinon/node_modules/util/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. All rights reserved. -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/node_modules/sinon/node_modules/util/README.md b/node_modules/sinon/node_modules/util/README.md deleted file mode 100644 index 1c473d2..0000000 --- a/node_modules/sinon/node_modules/util/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# util - -[![Build Status](https://travis-ci.org/defunctzombie/node-util.png?branch=master)](https://travis-ci.org/defunctzombie/node-util) - -node.js [util](http://nodejs.org/api/util.html) module as a module - -## install via [npm](npmjs.org) - -```shell -npm install util -``` - -## browser support - -This module also works in modern browsers. If you need legacy browser support you will need to polyfill ES5 features. diff --git a/node_modules/sinon/node_modules/util/node_modules/inherits/LICENSE b/node_modules/sinon/node_modules/util/node_modules/inherits/LICENSE deleted file mode 100644 index dea3013..0000000 --- a/node_modules/sinon/node_modules/util/node_modules/inherits/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. - diff --git a/node_modules/sinon/node_modules/util/node_modules/inherits/README.md b/node_modules/sinon/node_modules/util/node_modules/inherits/README.md deleted file mode 100644 index b1c5665..0000000 --- a/node_modules/sinon/node_modules/util/node_modules/inherits/README.md +++ /dev/null @@ -1,42 +0,0 @@ -Browser-friendly inheritance fully compatible with standard node.js -[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). - -This package exports standard `inherits` from node.js `util` module in -node environment, but also provides alternative browser-friendly -implementation through [browser -field](https://gist.github.com/shtylman/4339901). Alternative -implementation is a literal copy of standard one located in standalone -module to avoid requiring of `util`. It also has a shim for old -browsers with no `Object.create` support. - -While keeping you sure you are using standard `inherits` -implementation in node.js environment, it allows bundlers such as -[browserify](https://github.com/substack/node-browserify) to not -include full `util` package to your client code if all you need is -just `inherits` function. It worth, because browser shim for `util` -package is large and `inherits` is often the single function you need -from it. - -It's recommended to use this package instead of -`require('util').inherits` for any code that has chances to be used -not only in node.js but in browser too. - -## usage - -```js -var inherits = require('inherits'); -// then use exactly as the standard one -``` - -## note on version ~1.0 - -Version ~1.0 had completely different motivation and is not compatible -neither with 2.0 nor with standard node.js `inherits`. - -If you are using version ~1.0 and planning to switch to ~2.0, be -careful: - -* new version uses `super_` instead of `super` for referencing - superclass -* new version overwrites current prototype while old one preserves any - existing fields on it diff --git a/node_modules/sinon/node_modules/util/node_modules/inherits/inherits.js b/node_modules/sinon/node_modules/util/node_modules/inherits/inherits.js deleted file mode 100644 index 29f5e24..0000000 --- a/node_modules/sinon/node_modules/util/node_modules/inherits/inherits.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('util').inherits diff --git a/node_modules/sinon/node_modules/util/node_modules/inherits/inherits_browser.js b/node_modules/sinon/node_modules/util/node_modules/inherits/inherits_browser.js deleted file mode 100644 index c1e78a7..0000000 --- a/node_modules/sinon/node_modules/util/node_modules/inherits/inherits_browser.js +++ /dev/null @@ -1,23 +0,0 @@ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} diff --git a/node_modules/sinon/node_modules/util/node_modules/inherits/package.json b/node_modules/sinon/node_modules/util/node_modules/inherits/package.json deleted file mode 100644 index 79068a6..0000000 --- a/node_modules/sinon/node_modules/util/node_modules/inherits/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "inherits", - "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", - "version": "2.0.1", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented", - "inherits", - "browser", - "browserify" - ], - "main": "./inherits.js", - "browser": "./inherits_browser.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/inherits" - }, - "license": "ISC", - "scripts": { - "test": "node test" - }, - "bugs": { - "url": "https://github.com/isaacs/inherits/issues" - }, - "_id": "inherits@2.0.1", - "dist": { - "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", - "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" - }, - "_from": "inherits@2", - "_npmVersion": "1.3.8", - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "directories": {}, - "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", - "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" -} diff --git a/node_modules/sinon/node_modules/util/node_modules/inherits/test.js b/node_modules/sinon/node_modules/util/node_modules/inherits/test.js deleted file mode 100644 index fc53012..0000000 --- a/node_modules/sinon/node_modules/util/node_modules/inherits/test.js +++ /dev/null @@ -1,25 +0,0 @@ -var inherits = require('./inherits.js') -var assert = require('assert') - -function test(c) { - assert(c.constructor === Child) - assert(c.constructor.super_ === Parent) - assert(Object.getPrototypeOf(c) === Child.prototype) - assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) - assert(c instanceof Child) - assert(c instanceof Parent) -} - -function Child() { - Parent.call(this) - test(this) -} - -function Parent() {} - -inherits(Child, Parent) - -var c = new Child -test(c) - -console.log('ok') diff --git a/node_modules/sinon/node_modules/util/package.json b/node_modules/sinon/node_modules/util/package.json deleted file mode 100644 index ee896c1..0000000 --- a/node_modules/sinon/node_modules/util/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "author": { - "name": "Joyent", - "url": "http://www.joyent.com" - }, - "name": "util", - "description": "Node.JS util module", - "keywords": [ - "util" - ], - "version": "0.10.3", - "homepage": "https://github.com/defunctzombie/node-util", - "repository": { - "type": "git", - "url": "git://github.com/defunctzombie/node-util.git" - }, - "main": "./util.js", - "scripts": { - "test": "node test/node/*.js && zuul test/browser/*.js" - }, - "dependencies": { - "inherits": "2.0.1" - }, - "license": "MIT", - "devDependencies": { - "zuul": "~1.0.9" - }, - "browser": { - "./support/isBuffer.js": "./support/isBufferBrowser.js" - }, - "bugs": { - "url": "https://github.com/defunctzombie/node-util/issues" - }, - "_id": "util@0.10.3", - "dist": { - "shasum": "7afb1afe50805246489e3db7fe0ed379336ac0f9", - "tarball": "http://registry.npmjs.org/util/-/util-0.10.3.tgz" - }, - "_from": "util@>=0.10.3 <1", - "_npmVersion": "1.3.24", - "_npmUser": { - "name": "shtylman", - "email": "shtylman@gmail.com" - }, - "maintainers": [ - { - "name": "shtylman", - "email": "shtylman@gmail.com" - } - ], - "directories": {}, - "_shasum": "7afb1afe50805246489e3db7fe0ed379336ac0f9", - "_resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/node_modules/sinon/node_modules/util/support/isBuffer.js b/node_modules/sinon/node_modules/util/support/isBuffer.js deleted file mode 100644 index ace9ac0..0000000 --- a/node_modules/sinon/node_modules/util/support/isBuffer.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = function isBuffer(arg) { - return arg instanceof Buffer; -} diff --git a/node_modules/sinon/node_modules/util/support/isBufferBrowser.js b/node_modules/sinon/node_modules/util/support/isBufferBrowser.js deleted file mode 100644 index 0e1bee1..0000000 --- a/node_modules/sinon/node_modules/util/support/isBufferBrowser.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} \ No newline at end of file diff --git a/node_modules/sinon/node_modules/util/test/browser/inspect.js b/node_modules/sinon/node_modules/util/test/browser/inspect.js deleted file mode 100644 index 91af3b0..0000000 --- a/node_modules/sinon/node_modules/util/test/browser/inspect.js +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -var assert = require('assert'); -var util = require('../../'); - -suite('inspect'); - -test('util.inspect - test for sparse array', function () { - var a = ['foo', 'bar', 'baz']; - assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); - delete a[1]; - assert.equal(util.inspect(a), '[ \'foo\', , \'baz\' ]'); - assert.equal(util.inspect(a, true), '[ \'foo\', , \'baz\', [length]: 3 ]'); - assert.equal(util.inspect(new Array(5)), '[ , , , , ]'); -}); - -test('util.inspect - exceptions should print the error message, not \'{}\'', function () { - assert.equal(util.inspect(new Error()), '[Error]'); - assert.equal(util.inspect(new Error('FAIL')), '[Error: FAIL]'); - assert.equal(util.inspect(new TypeError('FAIL')), '[TypeError: FAIL]'); - assert.equal(util.inspect(new SyntaxError('FAIL')), '[SyntaxError: FAIL]'); -}); diff --git a/node_modules/sinon/node_modules/util/test/browser/is.js b/node_modules/sinon/node_modules/util/test/browser/is.js deleted file mode 100644 index f63bff9..0000000 --- a/node_modules/sinon/node_modules/util/test/browser/is.js +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -var assert = require('assert'); - -var util = require('../../'); - -suite('is'); - -test('util.isArray', function () { - assert.equal(true, util.isArray([])); - assert.equal(true, util.isArray(Array())); - assert.equal(true, util.isArray(new Array())); - assert.equal(true, util.isArray(new Array(5))); - assert.equal(true, util.isArray(new Array('with', 'some', 'entries'))); - assert.equal(false, util.isArray({})); - assert.equal(false, util.isArray({ push: function() {} })); - assert.equal(false, util.isArray(/regexp/)); - assert.equal(false, util.isArray(new Error())); - assert.equal(false, util.isArray(Object.create(Array.prototype))); -}); - -test('util.isRegExp', function () { - assert.equal(true, util.isRegExp(/regexp/)); - assert.equal(true, util.isRegExp(RegExp())); - assert.equal(true, util.isRegExp(new RegExp())); - assert.equal(false, util.isRegExp({})); - assert.equal(false, util.isRegExp([])); - assert.equal(false, util.isRegExp(new Date())); - assert.equal(false, util.isRegExp(Object.create(RegExp.prototype))); -}); - -test('util.isDate', function () { - assert.equal(true, util.isDate(new Date())); - assert.equal(true, util.isDate(new Date(0))); - assert.equal(false, util.isDate(Date())); - assert.equal(false, util.isDate({})); - assert.equal(false, util.isDate([])); - assert.equal(false, util.isDate(new Error())); - assert.equal(false, util.isDate(Object.create(Date.prototype))); -}); - -test('util.isError', function () { - assert.equal(true, util.isError(new Error())); - assert.equal(true, util.isError(new TypeError())); - assert.equal(true, util.isError(new SyntaxError())); - assert.equal(false, util.isError({})); - assert.equal(false, util.isError({ name: 'Error', message: '' })); - assert.equal(false, util.isError([])); - assert.equal(true, util.isError(Object.create(Error.prototype))); -}); - -test('util._extend', function () { - assert.deepEqual(util._extend({a:1}), {a:1}); - assert.deepEqual(util._extend({a:1}, []), {a:1}); - assert.deepEqual(util._extend({a:1}, null), {a:1}); - assert.deepEqual(util._extend({a:1}, true), {a:1}); - assert.deepEqual(util._extend({a:1}, false), {a:1}); - assert.deepEqual(util._extend({a:1}, {b:2}), {a:1, b:2}); - assert.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); -}); - -test('util.isBuffer', function () { - assert.equal(true, util.isBuffer(new Buffer(4))); - assert.equal(true, util.isBuffer(Buffer(4))); - assert.equal(true, util.isBuffer(new Buffer(4))); - assert.equal(true, util.isBuffer(new Buffer([1, 2, 3, 4]))); - assert.equal(false, util.isBuffer({})); - assert.equal(false, util.isBuffer([])); - assert.equal(false, util.isBuffer(new Error())); - assert.equal(false, util.isRegExp(new Date())); - assert.equal(true, util.isBuffer(Object.create(Buffer.prototype))); -}); diff --git a/node_modules/sinon/node_modules/util/test/node/debug.js b/node_modules/sinon/node_modules/util/test/node/debug.js deleted file mode 100644 index ef5f69f..0000000 --- a/node_modules/sinon/node_modules/util/test/node/debug.js +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -var assert = require('assert'); -var util = require('../../'); - -if (process.argv[2] === 'child') - child(); -else - parent(); - -function parent() { - test('foo,tud,bar', true); - test('foo,tud', true); - test('tud,bar', true); - test('tud', true); - test('foo,bar', false); - test('', false); -} - -function test(environ, shouldWrite) { - var expectErr = ''; - if (shouldWrite) { - expectErr = 'TUD %PID%: this { is: \'a\' } /debugging/\n' + - 'TUD %PID%: number=1234 string=asdf obj={"foo":"bar"}\n'; - } - var expectOut = 'ok\n'; - var didTest = false; - - var spawn = require('child_process').spawn; - var child = spawn(process.execPath, [__filename, 'child'], { - env: { NODE_DEBUG: environ } - }); - - expectErr = expectErr.split('%PID%').join(child.pid); - - var err = ''; - child.stderr.setEncoding('utf8'); - child.stderr.on('data', function(c) { - err += c; - }); - - var out = ''; - child.stdout.setEncoding('utf8'); - child.stdout.on('data', function(c) { - out += c; - }); - - child.on('close', function(c) { - assert(!c); - assert.equal(err, expectErr); - assert.equal(out, expectOut); - didTest = true; - console.log('ok %j %j', environ, shouldWrite); - }); - - process.on('exit', function() { - assert(didTest); - }); -} - - -function child() { - var debug = util.debuglog('tud'); - debug('this', { is: 'a' }, /debugging/); - debug('number=%d string=%s obj=%j', 1234, 'asdf', { foo: 'bar' }); - console.log('ok'); -} diff --git a/node_modules/sinon/node_modules/util/test/node/format.js b/node_modules/sinon/node_modules/util/test/node/format.js deleted file mode 100644 index f2d1862..0000000 --- a/node_modules/sinon/node_modules/util/test/node/format.js +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - - - - -var assert = require('assert'); -var util = require('../../'); - -assert.equal(util.format(), ''); -assert.equal(util.format(''), ''); -assert.equal(util.format([]), '[]'); -assert.equal(util.format({}), '{}'); -assert.equal(util.format(null), 'null'); -assert.equal(util.format(true), 'true'); -assert.equal(util.format(false), 'false'); -assert.equal(util.format('test'), 'test'); - -// CHECKME this is for console.log() compatibility - but is it *right*? -assert.equal(util.format('foo', 'bar', 'baz'), 'foo bar baz'); - -assert.equal(util.format('%d', 42.0), '42'); -assert.equal(util.format('%d', 42), '42'); -assert.equal(util.format('%s', 42), '42'); -assert.equal(util.format('%j', 42), '42'); - -assert.equal(util.format('%d', '42.0'), '42'); -assert.equal(util.format('%d', '42'), '42'); -assert.equal(util.format('%s', '42'), '42'); -assert.equal(util.format('%j', '42'), '"42"'); - -assert.equal(util.format('%%s%s', 'foo'), '%sfoo'); - -assert.equal(util.format('%s'), '%s'); -assert.equal(util.format('%s', undefined), 'undefined'); -assert.equal(util.format('%s', 'foo'), 'foo'); -assert.equal(util.format('%s:%s'), '%s:%s'); -assert.equal(util.format('%s:%s', undefined), 'undefined:%s'); -assert.equal(util.format('%s:%s', 'foo'), 'foo:%s'); -assert.equal(util.format('%s:%s', 'foo', 'bar'), 'foo:bar'); -assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz'); -assert.equal(util.format('%%%s%%', 'hi'), '%hi%'); -assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%'); - -(function() { - var o = {}; - o.o = o; - assert.equal(util.format('%j', o), '[Circular]'); -})(); - -// Errors -assert.equal(util.format(new Error('foo')), '[Error: foo]'); -function CustomError(msg) { - Error.call(this); - Object.defineProperty(this, 'message', { value: msg, enumerable: false }); - Object.defineProperty(this, 'name', { value: 'CustomError', enumerable: false }); -} -util.inherits(CustomError, Error); -assert.equal(util.format(new CustomError('bar')), '[CustomError: bar]'); diff --git a/node_modules/sinon/node_modules/util/test/node/inspect.js b/node_modules/sinon/node_modules/util/test/node/inspect.js deleted file mode 100644 index f766d11..0000000 --- a/node_modules/sinon/node_modules/util/test/node/inspect.js +++ /dev/null @@ -1,195 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - - - - -var assert = require('assert'); -var util = require('../../'); - -// test the internal isDate implementation -var Date2 = require('vm').runInNewContext('Date'); -var d = new Date2(); -var orig = util.inspect(d); -Date2.prototype.foo = 'bar'; -var after = util.inspect(d); -assert.equal(orig, after); - -// test for sparse array -var a = ['foo', 'bar', 'baz']; -assert.equal(util.inspect(a), '[ \'foo\', \'bar\', \'baz\' ]'); -delete a[1]; -assert.equal(util.inspect(a), '[ \'foo\', , \'baz\' ]'); -assert.equal(util.inspect(a, true), '[ \'foo\', , \'baz\', [length]: 3 ]'); -assert.equal(util.inspect(new Array(5)), '[ , , , , ]'); - -// test for property descriptors -var getter = Object.create(null, { - a: { - get: function() { return 'aaa'; } - } -}); -var setter = Object.create(null, { - b: { - set: function() {} - } -}); -var getterAndSetter = Object.create(null, { - c: { - get: function() { return 'ccc'; }, - set: function() {} - } -}); -assert.equal(util.inspect(getter, true), '{ [a]: [Getter] }'); -assert.equal(util.inspect(setter, true), '{ [b]: [Setter] }'); -assert.equal(util.inspect(getterAndSetter, true), '{ [c]: [Getter/Setter] }'); - -// exceptions should print the error message, not '{}' -assert.equal(util.inspect(new Error()), '[Error]'); -assert.equal(util.inspect(new Error('FAIL')), '[Error: FAIL]'); -assert.equal(util.inspect(new TypeError('FAIL')), '[TypeError: FAIL]'); -assert.equal(util.inspect(new SyntaxError('FAIL')), '[SyntaxError: FAIL]'); -try { - undef(); -} catch (e) { - assert.equal(util.inspect(e), '[ReferenceError: undef is not defined]'); -} -var ex = util.inspect(new Error('FAIL'), true); -assert.ok(ex.indexOf('[Error: FAIL]') != -1); -assert.ok(ex.indexOf('[stack]') != -1); -assert.ok(ex.indexOf('[message]') != -1); - -// GH-1941 -// should not throw: -assert.equal(util.inspect(Object.create(Date.prototype)), '{}'); - -// GH-1944 -assert.doesNotThrow(function() { - var d = new Date(); - d.toUTCString = null; - util.inspect(d); -}); - -assert.doesNotThrow(function() { - var r = /regexp/; - r.toString = null; - util.inspect(r); -}); - -// bug with user-supplied inspect function returns non-string -assert.doesNotThrow(function() { - util.inspect([{ - inspect: function() { return 123; } - }]); -}); - -// GH-2225 -var x = { inspect: util.inspect }; -assert.ok(util.inspect(x).indexOf('inspect') != -1); - -// util.inspect.styles and util.inspect.colors -function test_color_style(style, input, implicit) { - var color_name = util.inspect.styles[style]; - var color = ['', '']; - if(util.inspect.colors[color_name]) - color = util.inspect.colors[color_name]; - - var without_color = util.inspect(input, false, 0, false); - var with_color = util.inspect(input, false, 0, true); - var expect = '\u001b[' + color[0] + 'm' + without_color + - '\u001b[' + color[1] + 'm'; - assert.equal(with_color, expect, 'util.inspect color for style '+style); -} - -test_color_style('special', function(){}); -test_color_style('number', 123.456); -test_color_style('boolean', true); -test_color_style('undefined', undefined); -test_color_style('null', null); -test_color_style('string', 'test string'); -test_color_style('date', new Date); -test_color_style('regexp', /regexp/); - -// an object with "hasOwnProperty" overwritten should not throw -assert.doesNotThrow(function() { - util.inspect({ - hasOwnProperty: null - }); -}); - -// new API, accepts an "options" object -var subject = { foo: 'bar', hello: 31, a: { b: { c: { d: 0 } } } }; -Object.defineProperty(subject, 'hidden', { enumerable: false, value: null }); - -assert(util.inspect(subject, { showHidden: false }).indexOf('hidden') === -1); -assert(util.inspect(subject, { showHidden: true }).indexOf('hidden') !== -1); -assert(util.inspect(subject, { colors: false }).indexOf('\u001b[32m') === -1); -assert(util.inspect(subject, { colors: true }).indexOf('\u001b[32m') !== -1); -assert(util.inspect(subject, { depth: 2 }).indexOf('c: [Object]') !== -1); -assert(util.inspect(subject, { depth: 0 }).indexOf('a: [Object]') !== -1); -assert(util.inspect(subject, { depth: null }).indexOf('{ d: 0 }') !== -1); - -// "customInspect" option can enable/disable calling inspect() on objects -subject = { inspect: function() { return 123; } }; - -assert(util.inspect(subject, { customInspect: true }).indexOf('123') !== -1); -assert(util.inspect(subject, { customInspect: true }).indexOf('inspect') === -1); -assert(util.inspect(subject, { customInspect: false }).indexOf('123') === -1); -assert(util.inspect(subject, { customInspect: false }).indexOf('inspect') !== -1); - -// custom inspect() functions should be able to return other Objects -subject.inspect = function() { return { foo: 'bar' }; }; - -assert.equal(util.inspect(subject), '{ foo: \'bar\' }'); - -subject.inspect = function(depth, opts) { - assert.strictEqual(opts.customInspectOptions, true); -}; - -util.inspect(subject, { customInspectOptions: true }); - -// util.inspect with "colors" option should produce as many lines as without it -function test_lines(input) { - var count_lines = function(str) { - return (str.match(/\n/g) || []).length; - } - - var without_color = util.inspect(input); - var with_color = util.inspect(input, {colors: true}); - assert.equal(count_lines(without_color), count_lines(with_color)); -} - -test_lines([1, 2, 3, 4, 5, 6, 7]); -test_lines(function() { - var big_array = []; - for (var i = 0; i < 100; i++) { - big_array.push(i); - } - return big_array; -}()); -test_lines({foo: 'bar', baz: 35, b: {a: 35}}); -test_lines({ - foo: 'bar', - baz: 35, - b: {a: 35}, - very_long_key: 'very_long_value', - even_longer_key: ['with even longer value in array'] -}); diff --git a/node_modules/sinon/node_modules/util/test/node/log.js b/node_modules/sinon/node_modules/util/test/node/log.js deleted file mode 100644 index 6bd96d1..0000000 --- a/node_modules/sinon/node_modules/util/test/node/log.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - - -var assert = require('assert'); -var util = require('../../'); - -assert.ok(process.stdout.writable); -assert.ok(process.stderr.writable); - -var stdout_write = global.process.stdout.write; -var strings = []; -global.process.stdout.write = function(string) { - strings.push(string); -}; -console._stderr = process.stdout; - -var tests = [ - {input: 'foo', output: 'foo'}, - {input: undefined, output: 'undefined'}, - {input: null, output: 'null'}, - {input: false, output: 'false'}, - {input: 42, output: '42'}, - {input: function(){}, output: '[Function]'}, - {input: parseInt('not a number', 10), output: 'NaN'}, - {input: {answer: 42}, output: '{ answer: 42 }'}, - {input: [1,2,3], output: '[ 1, 2, 3 ]'} -]; - -// test util.log() -tests.forEach(function(test) { - util.log(test.input); - var result = strings.shift().trim(), - re = (/[0-9]{1,2} [A-Z][a-z]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} - (.+)$/), - match = re.exec(result); - assert.ok(match); - assert.equal(match[1], test.output); -}); - -global.process.stdout.write = stdout_write; diff --git a/node_modules/sinon/node_modules/util/test/node/util.js b/node_modules/sinon/node_modules/util/test/node/util.js deleted file mode 100644 index 633ba69..0000000 --- a/node_modules/sinon/node_modules/util/test/node/util.js +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - - -var assert = require('assert'); -var context = require('vm').runInNewContext; - -var util = require('../../'); - -// isArray -assert.equal(true, util.isArray([])); -assert.equal(true, util.isArray(Array())); -assert.equal(true, util.isArray(new Array())); -assert.equal(true, util.isArray(new Array(5))); -assert.equal(true, util.isArray(new Array('with', 'some', 'entries'))); -assert.equal(true, util.isArray(context('Array')())); -assert.equal(false, util.isArray({})); -assert.equal(false, util.isArray({ push: function() {} })); -assert.equal(false, util.isArray(/regexp/)); -assert.equal(false, util.isArray(new Error)); -assert.equal(false, util.isArray(Object.create(Array.prototype))); - -// isRegExp -assert.equal(true, util.isRegExp(/regexp/)); -assert.equal(true, util.isRegExp(RegExp())); -assert.equal(true, util.isRegExp(new RegExp())); -assert.equal(true, util.isRegExp(context('RegExp')())); -assert.equal(false, util.isRegExp({})); -assert.equal(false, util.isRegExp([])); -assert.equal(false, util.isRegExp(new Date())); -assert.equal(false, util.isRegExp(Object.create(RegExp.prototype))); - -// isDate -assert.equal(true, util.isDate(new Date())); -assert.equal(true, util.isDate(new Date(0))); -assert.equal(true, util.isDate(new (context('Date')))); -assert.equal(false, util.isDate(Date())); -assert.equal(false, util.isDate({})); -assert.equal(false, util.isDate([])); -assert.equal(false, util.isDate(new Error)); -assert.equal(false, util.isDate(Object.create(Date.prototype))); - -// isError -assert.equal(true, util.isError(new Error)); -assert.equal(true, util.isError(new TypeError)); -assert.equal(true, util.isError(new SyntaxError)); -assert.equal(true, util.isError(new (context('Error')))); -assert.equal(true, util.isError(new (context('TypeError')))); -assert.equal(true, util.isError(new (context('SyntaxError')))); -assert.equal(false, util.isError({})); -assert.equal(false, util.isError({ name: 'Error', message: '' })); -assert.equal(false, util.isError([])); -assert.equal(true, util.isError(Object.create(Error.prototype))); - -// isObject -assert.ok(util.isObject({}) === true); - -// _extend -assert.deepEqual(util._extend({a:1}), {a:1}); -assert.deepEqual(util._extend({a:1}, []), {a:1}); -assert.deepEqual(util._extend({a:1}, null), {a:1}); -assert.deepEqual(util._extend({a:1}, true), {a:1}); -assert.deepEqual(util._extend({a:1}, false), {a:1}); -assert.deepEqual(util._extend({a:1}, {b:2}), {a:1, b:2}); -assert.deepEqual(util._extend({a:1, b:2}, {b:3}), {a:1, b:3}); diff --git a/node_modules/sinon/node_modules/util/util.js b/node_modules/sinon/node_modules/util/util.js deleted file mode 100644 index e0ea321..0000000 --- a/node_modules/sinon/node_modules/util/util.js +++ /dev/null @@ -1,586 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// 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. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} diff --git a/node_modules/sinon/package.json b/node_modules/sinon/package.json deleted file mode 100644 index 1c21ad2..0000000 --- a/node_modules/sinon/package.json +++ /dev/null @@ -1,428 +0,0 @@ -{ - "name": "sinon", - "description": "JavaScript test spies, stubs and mocks.", - "version": "1.15.4", - "homepage": "http://sinonjs.org/", - "author": { - "name": "Christian Johansen" - }, - "repository": { - "type": "git", - "url": "http://github.com/cjohansen/Sinon.JS.git" - }, - "bugs": { - "url": "http://github.com/cjohansen/Sinon.JS/issues" - }, - "license": "BSD-3-Clause", - "scripts": { - "ci-test": "./scripts/ci-test.sh", - "test": "npm run lint && ./scripts/ci-test.sh", - "lint": "jscs .", - "prepublish": "./build" - }, - "dependencies": { - "formatio": "1.1.1", - "util": ">=0.10.3 <1", - "lolex": "1.1.0", - "samsam": "1.1.2" - }, - "devDependencies": { - "buster": "0.7.18", - "jscs": "1.11.3", - "buster-istanbul": "0.1.13" - }, - "files": [ - "lib", - "pkg", - "AUTHORS", - "CONTRIBUTING.md", - "Changelog.txt", - "LICENSE", - "README.md" - ], - "main": "./lib/sinon.js", - "engines": { - "node": ">=0.1.103" - }, - "contributors": [ - { - "name": "Sinon.JS was written by" - }, - { - "name": "Christian Johansen, christian@cjohansen.no" - }, - { - "name": "Contributors" - }, - { - "name": "Adam Hull, adam@hmlad.com" - }, - { - "name": "Adrian Phinney, adrian.phinney@bellaliant.net" - }, - { - "name": "AJ Ortega, ajo@renitservices.com" - }, - { - "name": "Alex Kessaris, alex@artsy.ca" - }, - { - "name": "Alex Urbano, asgaroth.belem@gmail.com" - }, - { - "name": "Alexander Schmidt, alexanderschmidt1@gmail.com" - }, - { - "name": "Alfonso Boza, alfonso@cloud.com" - }, - { - "name": "Ali Shakiba, ali@shakiba.me" - }, - { - "name": "August Lilleaas, august.lilleaas@gmail.com" - }, - { - "name": "Ben Hockey, neonstalwart@gmail.com" - }, - { - "name": "Ben Fleis, ben.fleis@gmail.com" - }, - { - "name": "Benjamin Coe, ben@yesware.com" - }, - { - "name": "Blaine Bublitz, blaine@iceddev.com" - }, - { - "name": "Blake Embrey, hello@blakeembrey.com" - }, - { - "name": "Blake Israel, blake@blakeisrael.com" - }, - { - "name": "Brandon Heyer, brandonheyer@gmail.com" - }, - { - "name": "Brian M Hunt, brianmhunt@gmail.com" - }, - { - "name": "Bryan Donovan, bdondo@gmail.com" - }, - { - "name": "Burak Yiğit Kaya, ben@byk.im" - }, - { - "name": "Charlie Rudolph, charles.w.rudolph@gmail.com" - }, - { - "name": "Christian Johansen, christian@cjohansen.no" - }, - { - "name": "Cormac Flynn, cormac.flynn@viadeoteam.com" - }, - { - "name": "Cory, seeflanigan@gmail.com" - }, - { - "name": "Devin Weaver, suki@tritarget.org" - }, - { - "name": "Domenic Denicola, domenic@domenicdenicola.com" - }, - { - "name": "Farid Neshat, FaridN_SOAD@yahoo.com" - }, - { - "name": "Felix Geisendörfer, felix@debuggable.com" - }, - { - "name": "G.Serebryanskyi, x5x3x5x@gmail.com" - }, - { - "name": "Garrick Cheung, garrick@garrickcheung.com" - }, - { - "name": "Gavin Huang, gravof@gmail.com" - }, - { - "name": "Geries Handal, geries.handal@videoplaza.com" - }, - { - "name": "Giorgos Giannoutsos, contact@nuc.gr" - }, - { - "name": "Gilad Peleg, giladp007@gmail.com" - }, - { - "name": "Glen Mailer, glen.mailer@bskyb.com" - }, - { - "name": "Goligo, ich@malte.de" - }, - { - "name": "Gord Tanner, gord@tinyhippos.com" - }, - { - "name": "Gordon L. Hempton, ghempton@gmail.com" - }, - { - "name": "Harry Wolff, hswolff@gmail.com" - }, - { - "name": "Ian Lewis, IanMLewis@gmail.com" - }, - { - "name": "Irina Dumitrascu, me@dira.ro" - }, - { - "name": "James Barwell, jb@jamesbarwell.co.uk" - }, - { - "name": "James Talmage, james.talmage@jrtechnical.com" - }, - { - "name": "Jan Kopriva, jan.kopriva@gooddata.com" - }, - { - "name": "Jan Suchý, jan.sandokan@gmail.com" - }, - { - "name": "John Bernardo, jbernardo@linkedin.com" - }, - { - "name": "Jonathan Freeman, freethejazz@gmail.com" - }, - { - "name": "Jonathan Sokolowski, jonathan.sokolowski@gmail.com" - }, - { - "name": "Jonny Reeves, github@jonnyreeves.co.uk" - }, - { - "name": "Josh Graham, josh@canva.com" - }, - { - "name": "Jmeas, jellyes2@gmail.com" - }, - { - "name": "kbackowski, kbackowski@gmail.com" - }, - { - "name": "Keith Cirkel, github@keithcirkel.co.uk" - }, - { - "name": "Kevin Decker, kpdecker@gmail.com" - }, - { - "name": "Kevin Turner, kevin@decipherinc.com" - }, - { - "name": "Kim Joar Bekkelund, kjbekkelund@gmail.com" - }, - { - "name": "Kris Kowal, kris.kowal@cixar.com" - }, - { - "name": "Konrad Holowinski, konrad.holowinski@gmail.com" - }, - { - "name": "Lars Thorup, lars@zealake.com" - }, - { - "name": "Luchs, Luchs@euirc.eu" - }, - { - "name": "Luis Cardoso, luis.cardoso@feedzai.com" - }, - { - "name": "Marcus Hüsgen, marcus.huesgen@lusini.com" - }, - { - "name": "Marco Ramirez, marco-ramirez@bankofamerica.com" - }, - { - "name": "Marten Lienen, marten.lienen@gmail.com" - }, - { - "name": "Martin Brochhaus, mbrochh@gmail.com" - }, - { - "name": "Martin Hansen, martin@martinhansen.no" - }, - { - "name": "Martin Sander, forke@uni-bonn.de" - }, - { - "name": "Matt Kern, matt@bloomcrush.com" - }, - { - "name": "Max Antoni, mail@maxantoni.de" - }, - { - "name": "Max Klymyshyn, klymyshyn@gmail.com" - }, - { - "name": "Maximilian Antoni, mail@maxantoni.de" - }, - { - "name": "Michael Heim, heim@zeilenwechsel.de" - }, - { - "name": "Michael Jackson, mjijackson@gmail.com" - }, - { - "name": "Ming Liu, vmliu1@gmail.com" - }, - { - "name": "Márton Salomváry, salomvary@gmail.com" - }, - { - "name": "Mohayanao, mohayonao@gmail.com" - }, - { - "name": "Nikita Litvin, deltaidea@derpy.ru" - }, - { - "name": "Niklas Andreasson, eaglus_@hotmail.com" - }, - { - "name": "Olmo Maldonado, olmo.maldonado@gmail.com" - }, - { - "name": "Phred, fearphage@gmail.com" - }, - { - "name": "Rajeesh C V, cvrajeesh@gmail.com" - }, - { - "name": "Raynos, raynos2@gmail.com" - }, - { - "name": "Robin Pedersen, robinp@snap.tv" - }, - { - "name": "Rodion Vynnychenko, roddiku@gmail.com" - }, - { - "name": "Roman Potashow, justgook@gmail.com" - }, - { - "name": "Scott Andrews, scothis@gmail.com" - }, - { - "name": "Sergio Cinos, scinos@atlassian.com" - }, - { - "name": "Shawn Krisman, skrisman@nodelings" - }, - { - "name": "Shinnosuke Watanabe, snnskwtnb@gmail.com" - }, - { - "name": "Simon Zack, simonzack@gmail.com" - }, - { - "name": "Simone Fonda, fonda@netseven.it" - }, - { - "name": "Sven Fuchs, svenfuchs@artweb-design.de" - }, - { - "name": "Søren Enemærke, soren.enemaerke@gmail.com" - }, - { - "name": "TEHEK Firefox, tehek@tehek.net" - }, - { - "name": "Tek Nynja, github@teknynja.com" - }, - { - "name": "Thomas Meyer, meyertee@gmail.com" - }, - { - "name": "Till, till@php.net" - }, - { - "name": "Tim Branyen, tim@tabdeveloper.com" - }, - { - "name": "Tim Fischbach, mail@timfischbach.de" - }, - { - "name": "Tim Perry, pimterry@gmail.com" - }, - { - "name": "Tim Ruffles, timr@picklive.com" - }, - { - "name": "Timo Tijhof, krinklemail@gmail.com" - }, - { - "name": "Tobias Ebnöther, ebi@gorn.ch" - }, - { - "name": "Tamas Szebeni, tamas_szebeni@epam.com" - }, - { - "name": "Tristan Koch, tristan.koch@1und1.de" - }, - { - "name": "Victor Costan, costan@gmail.com" - }, - { - "name": "Volkan Ozcelik, volkan.ozcelik@jivesoftware.com" - }, - { - "name": "Will Butler, will@butlerhq.com" - }, - { - "name": "William Meleyal, w.meleyal@wollzelle.com" - }, - { - "name": "William Sears, MrBigDog2U@gmail.com" - }, - { - "name": "Wesley Walser, waw325@gmail.com" - }, - { - "name": "Zcicala, zcicala@fitbit.com" - }, - { - "name": "Xiao Ma, x@medium.com" - }, - { - "name": "なつき, i@ntk.me" - } - ], - "gitHead": "9469e69895ec934e4e145d9b8a1c5a0165692036", - "_id": "sinon@1.15.4", - "_shasum": "0315f174ce5b31792aea2e3a2afc5bb7804c7a6a", - "_from": "sinon@*", - "_npmVersion": "2.4.1", - "_nodeVersion": "1.1.0", - "_npmUser": { - "name": "cjohansen", - "email": "christian@cjohansen.no" - }, - "dist": { - "shasum": "0315f174ce5b31792aea2e3a2afc5bb7804c7a6a", - "tarball": "http://registry.npmjs.org/sinon/-/sinon-1.15.4.tgz" - }, - "maintainers": [ - { - "name": "cjohansen", - "email": "christian@cjohansen.no" - }, - { - "name": "mrgnrdrck", - "email": "morgan@roderick.dk" - }, - { - "name": "mantoni", - "email": "mail@maxantoni.de" - } - ], - "directories": {}, - "_resolved": "https://registry.npmjs.org/sinon/-/sinon-1.15.4.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/node_modules/sinon/pkg/sinon-1.14.1.js b/node_modules/sinon/pkg/sinon-1.14.1.js deleted file mode 100644 index 797b7df..0000000 --- a/node_modules/sinon/pkg/sinon-1.14.1.js +++ /dev/null @@ -1,5933 +0,0 @@ -/** - * Sinon.JS 1.14.1, 2015/05/01 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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) { - 'use strict'; - 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 () { - 'use strict'; - var samsam, formatio, lolex; - (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 + - ""; - - 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 module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 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@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@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) { - // In some cases `delete` may throw an error - try { - delete object[property]; - } catch (e) {} - // For native code functions `delete` fails without throwing an error - // on Chrome < 43, PhantomJS, etc. - } else if (hasES5Support) { - Object.defineProperty(object, property, wrappedMethodDesc); - } - - // Use strict equality comparison to check failures then force a reset - // via direct assignment. - if (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@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@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@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@cjohansen.no) - * @author Maximilian Antoni (mail@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@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@cjohansen.no) - * @author Tim Fischbach (mail@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@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 sinon.getPropertyDescriptor(object, prop).value === "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@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@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@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@artweb-design.de) - * @author Christian Johansen (christian@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@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); - } -})(typeof global !== "undefined" ? global : self); - -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XMLHttpRequest object - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ - -(function (global) { - - var supportsProgress = typeof ProgressEvent !== "undefined"; - var supportsCustomEvent = typeof CustomEvent !== "undefined"; - var supportsFormData = typeof FormData !== "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); - } - } - - switch (this.readyState) { - case FakeXMLHttpRequest.DONE: - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - } - this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("loadend", false, false, this)); - break; - } - - this.dispatchEvent(new sinon.Event("readystatechange")); - }, - - 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 (supportsFormData && !(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 : self); - -/** - * @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@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@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@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@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@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) { - if (!tests || typeof tests != "object") { - throw new TypeError("sinon.testCase needs an object with test functions"); - } - - 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) && !/^(setUp|tearDown)$/.test(testName)) { - property = tests[testName]; - - 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@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/node_modules/sinon/pkg/sinon-1.15.0.js b/node_modules/sinon/pkg/sinon-1.15.0.js deleted file mode 100644 index 04150fc..0000000 --- a/node_modules/sinon/pkg/sinon-1.15.0.js +++ /dev/null @@ -1,5939 +0,0 @@ -/** - * Sinon.JS 1.15.0, 2015/06/10 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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) { - 'use strict'; - 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 () { - 'use strict'; - var samsam, formatio, lolex; - (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 + - ""; - - 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 module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 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@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@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) { - // In some cases `delete` may throw an error - try { - delete object[property]; - } catch (e) {} - // For native code functions `delete` fails without throwing an error - // on Chrome < 43, PhantomJS, etc. - } else if (hasES5Support) { - Object.defineProperty(object, property, wrappedMethodDesc); - } - - // Use strict equality comparison to check failures then force a reset - // via direct assignment. - if (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@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@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@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@cjohansen.no) - * @author Maximilian Antoni (mail@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@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)); - }; - } - p.isSinonProxy = true; - 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@cjohansen.no) - * @author Tim Fischbach (mail@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@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 sinon.getPropertyDescriptor(object, prop).value === "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@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 (typeof console !== undefined && console.warn) { - console.warn("mock will be removed from Sinon.JS v2.0"); - } - - 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@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@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@artweb-design.de) - * @author Christian Johansen (christian@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@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); - } -})(typeof global !== "undefined" ? global : self); - -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XMLHttpRequest object - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ - -(function (global) { - - var supportsProgress = typeof ProgressEvent !== "undefined"; - var supportsCustomEvent = typeof CustomEvent !== "undefined"; - var supportsFormData = typeof FormData !== "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); - } - } - - switch (this.readyState) { - case FakeXMLHttpRequest.DONE: - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - } - this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("loadend", false, false, this)); - break; - } - - this.dispatchEvent(new sinon.Event("readystatechange")); - }, - - 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 (supportsFormData && !(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 = {}; - this.responseHeaders = {}; - - 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 : self); - -/** - * @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@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@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@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@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@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) { - if (!tests || typeof tests != "object") { - throw new TypeError("sinon.testCase needs an object with test functions"); - } - - 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) && !/^(setUp|tearDown)$/.test(testName)) { - property = tests[testName]; - - 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@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 && method.proxy.isSinonProxy) { - 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/node_modules/sinon/pkg/sinon-1.15.1.js b/node_modules/sinon/pkg/sinon-1.15.1.js deleted file mode 100644 index fd919e1..0000000 --- a/node_modules/sinon/pkg/sinon-1.15.1.js +++ /dev/null @@ -1,5939 +0,0 @@ -/** - * Sinon.JS 1.15.1, 2015/06/10 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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) { - 'use strict'; - 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 () { - 'use strict'; - var samsam, formatio, lolex; - (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 + - ""; - - 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 module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 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@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@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) { - // In some cases `delete` may throw an error - try { - delete object[property]; - } catch (e) {} - // For native code functions `delete` fails without throwing an error - // on Chrome < 43, PhantomJS, etc. - } else if (hasES5Support) { - Object.defineProperty(object, property, wrappedMethodDesc); - } - - // Use strict equality comparison to check failures then force a reset - // via direct assignment. - if (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@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@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@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@cjohansen.no) - * @author Maximilian Antoni (mail@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@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)); - }; - } - p.isSinonProxy = true; - 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@cjohansen.no) - * @author Tim Fischbach (mail@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@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 sinon.getPropertyDescriptor(object, prop).value === "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@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 (typeof console !== undefined && console.warn) { - console.warn("mock will be removed from Sinon.JS v2.0"); - } - - 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@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@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@artweb-design.de) - * @author Christian Johansen (christian@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@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); - } -})(typeof global !== "undefined" ? global : self); - -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XMLHttpRequest object - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ - -(function (global) { - - var supportsProgress = typeof ProgressEvent !== "undefined"; - var supportsCustomEvent = typeof CustomEvent !== "undefined"; - var supportsFormData = typeof FormData !== "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); - } - } - - switch (this.readyState) { - case FakeXMLHttpRequest.DONE: - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - } - this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("loadend", false, false, this)); - break; - } - - this.dispatchEvent(new sinon.Event("readystatechange")); - }, - - 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 (supportsFormData && !(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 = {}; - this.responseHeaders = {}; - - 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 : self); - -/** - * @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@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@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@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@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@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) { - if (!tests || typeof tests != "object") { - throw new TypeError("sinon.testCase needs an object with test functions"); - } - - 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) && !/^(setUp|tearDown)$/.test(testName)) { - property = tests[testName]; - - 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@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 && method.proxy.isSinonProxy) { - 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/node_modules/sinon/pkg/sinon-1.15.4.js b/node_modules/sinon/pkg/sinon-1.15.4.js deleted file mode 100644 index 20bc9e2..0000000 --- a/node_modules/sinon/pkg/sinon-1.15.4.js +++ /dev/null @@ -1,5949 +0,0 @@ -/** - * Sinon.JS 1.15.4, 2015/06/27 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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) { - 'use strict'; - 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 () { - 'use strict'; - var samsam, formatio, lolex; - (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 + - ""; - - 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 module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 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@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@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) { - // In some cases `delete` may throw an error - try { - delete object[property]; - } catch (e) {} - // For native code functions `delete` fails without throwing an error - // on Chrome < 43, PhantomJS, etc. - } else if (hasES5Support) { - Object.defineProperty(object, property, wrappedMethodDesc); - } - - // Use strict equality comparison to check failures then force a reset - // via direct assignment. - if (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@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@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@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@cjohansen.no) - * @author Maximilian Antoni (mail@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@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)); - }; - } - p.isSinonProxy = true; - 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@cjohansen.no) - * @author Tim Fischbach (mail@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@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 sinon.getPropertyDescriptor(object, prop).value === "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@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 (typeof console !== undefined && console.warn) { - // console.warn("mock will be removed from Sinon.JS v2.0"); - // } - - 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@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@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@artweb-design.de) - * @author Christian Johansen (christian@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@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); - } -})(typeof global !== "undefined" ? global : self); - -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XMLHttpRequest object - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ - -(function (global) { - - var supportsProgress = typeof ProgressEvent !== "undefined"; - var supportsCustomEvent = typeof CustomEvent !== "undefined"; - var supportsFormData = typeof FormData !== "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*/ - - // Note that for FakeXMLHttpRequest to work pre ES5 - // we lose some of the alignment with the spec. - // To ensure as close a match as possible, - // set responseType before calling open, send or respond; - function FakeXMLHttpRequest() { - this.readyState = FakeXMLHttpRequest.UNSENT; - this.requestHeaders = {}; - this.requestBody = null; - this.status = 0; - this.statusText = ""; - this.upload = new UploadProgress(); - this.responseType = ""; - this.response = ""; - 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.response = this.responseType === "json" ? 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); - } - } - - switch (this.readyState) { - case FakeXMLHttpRequest.DONE: - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - } - this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("loadend", false, false, this)); - break; - } - - this.dispatchEvent(new sinon.Event("readystatechange")); - }, - - 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 (supportsFormData && !(data instanceof FormData)) { - this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; - } - - this.requestBody = data; - } - - this.errorFlag = false; - this.sendFlag = this.async; - this.response = this.responseType === "json" ? null : ""; - 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.response = this.responseType === "json" ? null : ""; - this.errorFlag = true; - this.requestHeaders = {}; - this.responseHeaders = {}; - - 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.response = this.responseType === "json" ? JSON.parse(this.responseText) : this.responseText; - 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 : self); - -/** - * @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@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@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@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@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@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) { - if (!tests || typeof tests != "object") { - throw new TypeError("sinon.testCase needs an object with test functions"); - } - - 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) && !/^(setUp|tearDown)$/.test(testName)) { - property = tests[testName]; - - 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@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 && method.proxy.isSinonProxy) { - 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/node_modules/sinon/pkg/sinon-ie-1.14.1.js b/node_modules/sinon/pkg/sinon-ie-1.14.1.js deleted file mode 100644 index 4dae31c..0000000 --- a/node_modules/sinon/pkg/sinon-ie-1.14.1.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Sinon.JS 1.14.1, 2015/05/01 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Helps IE run the fake timers. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake timers to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function setTimeout() {} - function clearTimeout() {} - function setImmediate() {} - function clearImmediate() {} - function setInterval() {} - function clearInterval() {} - function Date() {} - - // Reassign the original functions. Now their writable attribute - // should be true. Hackish, I know, but it works. - setTimeout = sinon.timers.setTimeout; - clearTimeout = sinon.timers.clearTimeout; - setImmediate = sinon.timers.setImmediate; - clearImmediate = sinon.timers.clearImmediate; - setInterval = sinon.timers.setInterval; - clearInterval = sinon.timers.clearInterval; - Date = sinon.timers.Date; -} - -/** - * Helps IE run the fake XMLHttpRequest. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake XHR to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function XMLHttpRequest() {} - - // Reassign the original function. Now its writable attribute - // should be true. Hackish, I know, but it works. - XMLHttpRequest = sinon.xhr.XMLHttpRequest || undefined; -} -/** - * Helps IE run the fake XDomainRequest. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake XDR to work in IE, don't include this file. - */ -if (typeof window !== "undefined") { - function XDomainRequest() {} - - // Reassign the original function. Now its writable attribute - // should be true. Hackish, I know, but it works. - XDomainRequest = sinon.xdr.XDomainRequest || undefined; -} diff --git a/node_modules/sinon/pkg/sinon-ie-1.15.0.js b/node_modules/sinon/pkg/sinon-ie-1.15.0.js deleted file mode 100644 index cd11482..0000000 --- a/node_modules/sinon/pkg/sinon-ie-1.15.0.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Sinon.JS 1.15.0, 2015/06/10 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Helps IE run the fake timers. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake timers to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function setTimeout() {} - function clearTimeout() {} - function setImmediate() {} - function clearImmediate() {} - function setInterval() {} - function clearInterval() {} - function Date() {} - - // Reassign the original functions. Now their writable attribute - // should be true. Hackish, I know, but it works. - setTimeout = sinon.timers.setTimeout; - clearTimeout = sinon.timers.clearTimeout; - setImmediate = sinon.timers.setImmediate; - clearImmediate = sinon.timers.clearImmediate; - setInterval = sinon.timers.setInterval; - clearInterval = sinon.timers.clearInterval; - Date = sinon.timers.Date; -} - -/** - * Helps IE run the fake XMLHttpRequest. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake XHR to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function XMLHttpRequest() {} - - // Reassign the original function. Now its writable attribute - // should be true. Hackish, I know, but it works. - XMLHttpRequest = sinon.xhr.XMLHttpRequest || undefined; -} -/** - * Helps IE run the fake XDomainRequest. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake XDR to work in IE, don't include this file. - */ -if (typeof window !== "undefined") { - function XDomainRequest() {} - - // Reassign the original function. Now its writable attribute - // should be true. Hackish, I know, but it works. - XDomainRequest = sinon.xdr.XDomainRequest || undefined; -} diff --git a/node_modules/sinon/pkg/sinon-ie-1.15.1.js b/node_modules/sinon/pkg/sinon-ie-1.15.1.js deleted file mode 100644 index 1599731..0000000 --- a/node_modules/sinon/pkg/sinon-ie-1.15.1.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Sinon.JS 1.15.1, 2015/06/10 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Helps IE run the fake timers. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake timers to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function setTimeout() {} - function clearTimeout() {} - function setImmediate() {} - function clearImmediate() {} - function setInterval() {} - function clearInterval() {} - function Date() {} - - // Reassign the original functions. Now their writable attribute - // should be true. Hackish, I know, but it works. - setTimeout = sinon.timers.setTimeout; - clearTimeout = sinon.timers.clearTimeout; - setImmediate = sinon.timers.setImmediate; - clearImmediate = sinon.timers.clearImmediate; - setInterval = sinon.timers.setInterval; - clearInterval = sinon.timers.clearInterval; - Date = sinon.timers.Date; -} - -/** - * Helps IE run the fake XMLHttpRequest. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake XHR to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function XMLHttpRequest() {} - - // Reassign the original function. Now its writable attribute - // should be true. Hackish, I know, but it works. - XMLHttpRequest = sinon.xhr.XMLHttpRequest || undefined; -} -/** - * Helps IE run the fake XDomainRequest. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake XDR to work in IE, don't include this file. - */ -if (typeof window !== "undefined") { - function XDomainRequest() {} - - // Reassign the original function. Now its writable attribute - // should be true. Hackish, I know, but it works. - XDomainRequest = sinon.xdr.XDomainRequest || undefined; -} diff --git a/node_modules/sinon/pkg/sinon-ie-1.15.4.js b/node_modules/sinon/pkg/sinon-ie-1.15.4.js deleted file mode 100644 index 9eac958..0000000 --- a/node_modules/sinon/pkg/sinon-ie-1.15.4.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Sinon.JS 1.15.4, 2015/06/27 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Helps IE run the fake timers. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake timers to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function setTimeout() {} - function clearTimeout() {} - function setImmediate() {} - function clearImmediate() {} - function setInterval() {} - function clearInterval() {} - function Date() {} - - // Reassign the original functions. Now their writable attribute - // should be true. Hackish, I know, but it works. - setTimeout = sinon.timers.setTimeout; - clearTimeout = sinon.timers.clearTimeout; - setImmediate = sinon.timers.setImmediate; - clearImmediate = sinon.timers.clearImmediate; - setInterval = sinon.timers.setInterval; - clearInterval = sinon.timers.clearInterval; - Date = sinon.timers.Date; -} - -/** - * Helps IE run the fake XMLHttpRequest. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake XHR to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function XMLHttpRequest() {} - - // Reassign the original function. Now its writable attribute - // should be true. Hackish, I know, but it works. - XMLHttpRequest = sinon.xhr.XMLHttpRequest || undefined; -} -/** - * Helps IE run the fake XDomainRequest. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake XDR to work in IE, don't include this file. - */ -if (typeof window !== "undefined") { - function XDomainRequest() {} - - // Reassign the original function. Now its writable attribute - // should be true. Hackish, I know, but it works. - XDomainRequest = sinon.xdr.XDomainRequest || undefined; -} diff --git a/node_modules/sinon/pkg/sinon-ie.js b/node_modules/sinon/pkg/sinon-ie.js deleted file mode 100644 index 9eac958..0000000 --- a/node_modules/sinon/pkg/sinon-ie.js +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Sinon.JS 1.15.4, 2015/06/27 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Helps IE run the fake timers. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake timers to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function setTimeout() {} - function clearTimeout() {} - function setImmediate() {} - function clearImmediate() {} - function setInterval() {} - function clearInterval() {} - function Date() {} - - // Reassign the original functions. Now their writable attribute - // should be true. Hackish, I know, but it works. - setTimeout = sinon.timers.setTimeout; - clearTimeout = sinon.timers.clearTimeout; - setImmediate = sinon.timers.setImmediate; - clearImmediate = sinon.timers.clearImmediate; - setInterval = sinon.timers.setInterval; - clearInterval = sinon.timers.clearInterval; - Date = sinon.timers.Date; -} - -/** - * Helps IE run the fake XMLHttpRequest. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake XHR to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function XMLHttpRequest() {} - - // Reassign the original function. Now its writable attribute - // should be true. Hackish, I know, but it works. - XMLHttpRequest = sinon.xhr.XMLHttpRequest || undefined; -} -/** - * Helps IE run the fake XDomainRequest. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake XDR to work in IE, don't include this file. - */ -if (typeof window !== "undefined") { - function XDomainRequest() {} - - // Reassign the original function. Now its writable attribute - // should be true. Hackish, I know, but it works. - XDomainRequest = sinon.xdr.XDomainRequest || undefined; -} diff --git a/node_modules/sinon/pkg/sinon-server-1.14.1.js b/node_modules/sinon/pkg/sinon-server-1.14.1.js deleted file mode 100644 index 5e4955a..0000000 --- a/node_modules/sinon/pkg/sinon-server-1.14.1.js +++ /dev/null @@ -1,2107 +0,0 @@ -/** - * Sinon.JS 1.14.1, 2015/05/01 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Sinon core utilities. For internal use only. - * - * @author Christian Johansen (christian@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@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) { - // In some cases `delete` may throw an error - try { - delete object[property]; - } catch (e) {} - // For native code functions `delete` fails without throwing an error - // on Chrome < 43, PhantomJS, etc. - } else if (hasES5Support) { - Object.defineProperty(object, property, wrappedMethodDesc); - } - - // Use strict equality comparison to check failures then force a reset - // via direct assignment. - if (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)); - -/** - * Minimal Event interface implementation - * - * Original implementation by Sven Fuchs: https://gist.github.com/995028 - * Modifications and tests by Christian Johansen. - * - * @author Sven Fuchs (svenfuchs@artweb-design.de) - * @author Christian Johansen (christian@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@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); - } -})(typeof global !== "undefined" ? global : self); - -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XMLHttpRequest object - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ - -(function (global) { - - var supportsProgress = typeof ProgressEvent !== "undefined"; - var supportsCustomEvent = typeof CustomEvent !== "undefined"; - var supportsFormData = typeof FormData !== "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); - } - } - - switch (this.readyState) { - case FakeXMLHttpRequest.DONE: - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - } - this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("loadend", false, false, this)); - break; - } - - this.dispatchEvent(new sinon.Event("readystatechange")); - }, - - 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 (supportsFormData && !(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 : self); - -/** - * @depend util/core.js - */ -/** - * Format functions - * - * @author Christian Johansen (christian@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 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@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); - } -}()); - -/*global lolex */ - -/** - * Fake timer API - * setTimeout - * setInterval - * clearTimeout - * clearInterval - * tick - * reset - * Date - * - * Inspired by jsUnitMockTimeOut from JsUnit - * - * @author Christian Johansen (christian@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)); - -/** - * @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@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); - } -}()); - diff --git a/node_modules/sinon/pkg/sinon-server-1.15.0.js b/node_modules/sinon/pkg/sinon-server-1.15.0.js deleted file mode 100644 index e205d2a..0000000 --- a/node_modules/sinon/pkg/sinon-server-1.15.0.js +++ /dev/null @@ -1,2108 +0,0 @@ -/** - * Sinon.JS 1.15.0, 2015/06/10 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Sinon core utilities. For internal use only. - * - * @author Christian Johansen (christian@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@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) { - // In some cases `delete` may throw an error - try { - delete object[property]; - } catch (e) {} - // For native code functions `delete` fails without throwing an error - // on Chrome < 43, PhantomJS, etc. - } else if (hasES5Support) { - Object.defineProperty(object, property, wrappedMethodDesc); - } - - // Use strict equality comparison to check failures then force a reset - // via direct assignment. - if (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)); - -/** - * Minimal Event interface implementation - * - * Original implementation by Sven Fuchs: https://gist.github.com/995028 - * Modifications and tests by Christian Johansen. - * - * @author Sven Fuchs (svenfuchs@artweb-design.de) - * @author Christian Johansen (christian@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@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); - } -})(typeof global !== "undefined" ? global : self); - -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XMLHttpRequest object - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ - -(function (global) { - - var supportsProgress = typeof ProgressEvent !== "undefined"; - var supportsCustomEvent = typeof CustomEvent !== "undefined"; - var supportsFormData = typeof FormData !== "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); - } - } - - switch (this.readyState) { - case FakeXMLHttpRequest.DONE: - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - } - this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("loadend", false, false, this)); - break; - } - - this.dispatchEvent(new sinon.Event("readystatechange")); - }, - - 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 (supportsFormData && !(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 = {}; - this.responseHeaders = {}; - - 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 : self); - -/** - * @depend util/core.js - */ -/** - * Format functions - * - * @author Christian Johansen (christian@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 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@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); - } -}()); - -/*global lolex */ - -/** - * Fake timer API - * setTimeout - * setInterval - * clearTimeout - * clearInterval - * tick - * reset - * Date - * - * Inspired by jsUnitMockTimeOut from JsUnit - * - * @author Christian Johansen (christian@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)); - -/** - * @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@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); - } -}()); - diff --git a/node_modules/sinon/pkg/sinon-server-1.15.1.js b/node_modules/sinon/pkg/sinon-server-1.15.1.js deleted file mode 100644 index 4b11142..0000000 --- a/node_modules/sinon/pkg/sinon-server-1.15.1.js +++ /dev/null @@ -1,2108 +0,0 @@ -/** - * Sinon.JS 1.15.1, 2015/06/10 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Sinon core utilities. For internal use only. - * - * @author Christian Johansen (christian@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@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) { - // In some cases `delete` may throw an error - try { - delete object[property]; - } catch (e) {} - // For native code functions `delete` fails without throwing an error - // on Chrome < 43, PhantomJS, etc. - } else if (hasES5Support) { - Object.defineProperty(object, property, wrappedMethodDesc); - } - - // Use strict equality comparison to check failures then force a reset - // via direct assignment. - if (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)); - -/** - * Minimal Event interface implementation - * - * Original implementation by Sven Fuchs: https://gist.github.com/995028 - * Modifications and tests by Christian Johansen. - * - * @author Sven Fuchs (svenfuchs@artweb-design.de) - * @author Christian Johansen (christian@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@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); - } -})(typeof global !== "undefined" ? global : self); - -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XMLHttpRequest object - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ - -(function (global) { - - var supportsProgress = typeof ProgressEvent !== "undefined"; - var supportsCustomEvent = typeof CustomEvent !== "undefined"; - var supportsFormData = typeof FormData !== "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); - } - } - - switch (this.readyState) { - case FakeXMLHttpRequest.DONE: - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - } - this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("loadend", false, false, this)); - break; - } - - this.dispatchEvent(new sinon.Event("readystatechange")); - }, - - 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 (supportsFormData && !(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 = {}; - this.responseHeaders = {}; - - 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 : self); - -/** - * @depend util/core.js - */ -/** - * Format functions - * - * @author Christian Johansen (christian@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 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@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); - } -}()); - -/*global lolex */ - -/** - * Fake timer API - * setTimeout - * setInterval - * clearTimeout - * clearInterval - * tick - * reset - * Date - * - * Inspired by jsUnitMockTimeOut from JsUnit - * - * @author Christian Johansen (christian@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)); - -/** - * @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@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); - } -}()); - diff --git a/node_modules/sinon/pkg/sinon-server-1.15.4.js b/node_modules/sinon/pkg/sinon-server-1.15.4.js deleted file mode 100644 index c26da01..0000000 --- a/node_modules/sinon/pkg/sinon-server-1.15.4.js +++ /dev/null @@ -1,2118 +0,0 @@ -/** - * Sinon.JS 1.15.4, 2015/06/27 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Sinon core utilities. For internal use only. - * - * @author Christian Johansen (christian@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@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) { - // In some cases `delete` may throw an error - try { - delete object[property]; - } catch (e) {} - // For native code functions `delete` fails without throwing an error - // on Chrome < 43, PhantomJS, etc. - } else if (hasES5Support) { - Object.defineProperty(object, property, wrappedMethodDesc); - } - - // Use strict equality comparison to check failures then force a reset - // via direct assignment. - if (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)); - -/** - * Minimal Event interface implementation - * - * Original implementation by Sven Fuchs: https://gist.github.com/995028 - * Modifications and tests by Christian Johansen. - * - * @author Sven Fuchs (svenfuchs@artweb-design.de) - * @author Christian Johansen (christian@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@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); - } -})(typeof global !== "undefined" ? global : self); - -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XMLHttpRequest object - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ - -(function (global) { - - var supportsProgress = typeof ProgressEvent !== "undefined"; - var supportsCustomEvent = typeof CustomEvent !== "undefined"; - var supportsFormData = typeof FormData !== "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*/ - - // Note that for FakeXMLHttpRequest to work pre ES5 - // we lose some of the alignment with the spec. - // To ensure as close a match as possible, - // set responseType before calling open, send or respond; - function FakeXMLHttpRequest() { - this.readyState = FakeXMLHttpRequest.UNSENT; - this.requestHeaders = {}; - this.requestBody = null; - this.status = 0; - this.statusText = ""; - this.upload = new UploadProgress(); - this.responseType = ""; - this.response = ""; - 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.response = this.responseType === "json" ? 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); - } - } - - switch (this.readyState) { - case FakeXMLHttpRequest.DONE: - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - } - this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("loadend", false, false, this)); - break; - } - - this.dispatchEvent(new sinon.Event("readystatechange")); - }, - - 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 (supportsFormData && !(data instanceof FormData)) { - this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; - } - - this.requestBody = data; - } - - this.errorFlag = false; - this.sendFlag = this.async; - this.response = this.responseType === "json" ? null : ""; - 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.response = this.responseType === "json" ? null : ""; - this.errorFlag = true; - this.requestHeaders = {}; - this.responseHeaders = {}; - - 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.response = this.responseType === "json" ? JSON.parse(this.responseText) : this.responseText; - 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 : self); - -/** - * @depend util/core.js - */ -/** - * Format functions - * - * @author Christian Johansen (christian@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 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@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); - } -}()); - -/*global lolex */ - -/** - * Fake timer API - * setTimeout - * setInterval - * clearTimeout - * clearInterval - * tick - * reset - * Date - * - * Inspired by jsUnitMockTimeOut from JsUnit - * - * @author Christian Johansen (christian@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)); - -/** - * @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@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); - } -}()); - diff --git a/node_modules/sinon/pkg/sinon-timers-1.14.1.js b/node_modules/sinon/pkg/sinon-timers-1.14.1.js deleted file mode 100644 index a8f2461..0000000 --- a/node_modules/sinon/pkg/sinon-timers-1.14.1.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Sinon.JS 1.14.1, 2015/05/01 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/*global lolex */ - -/** - * Fake timer API - * setTimeout - * setInterval - * clearTimeout - * clearInterval - * tick - * reset - * Date - * - * Inspired by jsUnitMockTimeOut from JsUnit - * - * @author Christian Johansen (christian@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)); diff --git a/node_modules/sinon/pkg/sinon-timers-1.15.0.js b/node_modules/sinon/pkg/sinon-timers-1.15.0.js deleted file mode 100644 index 088c601..0000000 --- a/node_modules/sinon/pkg/sinon-timers-1.15.0.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Sinon.JS 1.15.0, 2015/06/10 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/*global lolex */ - -/** - * Fake timer API - * setTimeout - * setInterval - * clearTimeout - * clearInterval - * tick - * reset - * Date - * - * Inspired by jsUnitMockTimeOut from JsUnit - * - * @author Christian Johansen (christian@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)); diff --git a/node_modules/sinon/pkg/sinon-timers-1.15.1.js b/node_modules/sinon/pkg/sinon-timers-1.15.1.js deleted file mode 100644 index cadcebf..0000000 --- a/node_modules/sinon/pkg/sinon-timers-1.15.1.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Sinon.JS 1.15.1, 2015/06/10 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/*global lolex */ - -/** - * Fake timer API - * setTimeout - * setInterval - * clearTimeout - * clearInterval - * tick - * reset - * Date - * - * Inspired by jsUnitMockTimeOut from JsUnit - * - * @author Christian Johansen (christian@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)); diff --git a/node_modules/sinon/pkg/sinon-timers-1.15.4.js b/node_modules/sinon/pkg/sinon-timers-1.15.4.js deleted file mode 100644 index d70e9aa..0000000 --- a/node_modules/sinon/pkg/sinon-timers-1.15.4.js +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Sinon.JS 1.15.4, 2015/06/27 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/*global lolex */ - -/** - * Fake timer API - * setTimeout - * setInterval - * clearTimeout - * clearInterval - * tick - * reset - * Date - * - * Inspired by jsUnitMockTimeOut from JsUnit - * - * @author Christian Johansen (christian@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)); diff --git a/node_modules/sinon/pkg/sinon-timers-ie-1.14.1.js b/node_modules/sinon/pkg/sinon-timers-ie-1.14.1.js deleted file mode 100644 index a469d98..0000000 --- a/node_modules/sinon/pkg/sinon-timers-ie-1.14.1.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Sinon.JS 1.14.1, 2015/05/01 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Helps IE run the fake timers. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake timers to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function setTimeout() {} - function clearTimeout() {} - function setImmediate() {} - function clearImmediate() {} - function setInterval() {} - function clearInterval() {} - function Date() {} - - // Reassign the original functions. Now their writable attribute - // should be true. Hackish, I know, but it works. - setTimeout = sinon.timers.setTimeout; - clearTimeout = sinon.timers.clearTimeout; - setImmediate = sinon.timers.setImmediate; - clearImmediate = sinon.timers.clearImmediate; - setInterval = sinon.timers.setInterval; - clearInterval = sinon.timers.clearInterval; - Date = sinon.timers.Date; -} diff --git a/node_modules/sinon/pkg/sinon-timers-ie-1.15.0.js b/node_modules/sinon/pkg/sinon-timers-ie-1.15.0.js deleted file mode 100644 index 0e54677..0000000 --- a/node_modules/sinon/pkg/sinon-timers-ie-1.15.0.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Sinon.JS 1.15.0, 2015/06/10 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Helps IE run the fake timers. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake timers to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function setTimeout() {} - function clearTimeout() {} - function setImmediate() {} - function clearImmediate() {} - function setInterval() {} - function clearInterval() {} - function Date() {} - - // Reassign the original functions. Now their writable attribute - // should be true. Hackish, I know, but it works. - setTimeout = sinon.timers.setTimeout; - clearTimeout = sinon.timers.clearTimeout; - setImmediate = sinon.timers.setImmediate; - clearImmediate = sinon.timers.clearImmediate; - setInterval = sinon.timers.setInterval; - clearInterval = sinon.timers.clearInterval; - Date = sinon.timers.Date; -} diff --git a/node_modules/sinon/pkg/sinon-timers-ie-1.15.1.js b/node_modules/sinon/pkg/sinon-timers-ie-1.15.1.js deleted file mode 100644 index b690f47..0000000 --- a/node_modules/sinon/pkg/sinon-timers-ie-1.15.1.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Sinon.JS 1.15.1, 2015/06/10 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Helps IE run the fake timers. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake timers to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function setTimeout() {} - function clearTimeout() {} - function setImmediate() {} - function clearImmediate() {} - function setInterval() {} - function clearInterval() {} - function Date() {} - - // Reassign the original functions. Now their writable attribute - // should be true. Hackish, I know, but it works. - setTimeout = sinon.timers.setTimeout; - clearTimeout = sinon.timers.clearTimeout; - setImmediate = sinon.timers.setImmediate; - clearImmediate = sinon.timers.clearImmediate; - setInterval = sinon.timers.setInterval; - clearInterval = sinon.timers.clearInterval; - Date = sinon.timers.Date; -} diff --git a/node_modules/sinon/pkg/sinon-timers-ie-1.15.4.js b/node_modules/sinon/pkg/sinon-timers-ie-1.15.4.js deleted file mode 100644 index 08c0972..0000000 --- a/node_modules/sinon/pkg/sinon-timers-ie-1.15.4.js +++ /dev/null @@ -1,67 +0,0 @@ -/** - * Sinon.JS 1.15.4, 2015/06/27 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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. - */ - -/** - * Helps IE run the fake timers. By defining global functions, IE allows - * them to be overwritten at a later point. If these are not defined like - * this, overwriting them will result in anything from an exception to browser - * crash. - * - * If you don't require fake timers to work in IE, don't include this file. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -if (typeof window !== "undefined") { - function setTimeout() {} - function clearTimeout() {} - function setImmediate() {} - function clearImmediate() {} - function setInterval() {} - function clearInterval() {} - function Date() {} - - // Reassign the original functions. Now their writable attribute - // should be true. Hackish, I know, but it works. - setTimeout = sinon.timers.setTimeout; - clearTimeout = sinon.timers.clearTimeout; - setImmediate = sinon.timers.setImmediate; - clearImmediate = sinon.timers.clearImmediate; - setInterval = sinon.timers.setInterval; - clearInterval = sinon.timers.clearInterval; - Date = sinon.timers.Date; -} diff --git a/node_modules/sinon/pkg/sinon.js b/node_modules/sinon/pkg/sinon.js deleted file mode 100644 index 20bc9e2..0000000 --- a/node_modules/sinon/pkg/sinon.js +++ /dev/null @@ -1,5949 +0,0 @@ -/** - * Sinon.JS 1.15.4, 2015/06/27 - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS - * - * (The BSD License) - * - * Copyright (c) 2010-2014, Christian Johansen, christian@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) { - 'use strict'; - 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 () { - 'use strict'; - var samsam, formatio, lolex; - (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 + - ""; - - 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 module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 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@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@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) { - // In some cases `delete` may throw an error - try { - delete object[property]; - } catch (e) {} - // For native code functions `delete` fails without throwing an error - // on Chrome < 43, PhantomJS, etc. - } else if (hasES5Support) { - Object.defineProperty(object, property, wrappedMethodDesc); - } - - // Use strict equality comparison to check failures then force a reset - // via direct assignment. - if (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@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@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@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@cjohansen.no) - * @author Maximilian Antoni (mail@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@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)); - }; - } - p.isSinonProxy = true; - 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@cjohansen.no) - * @author Tim Fischbach (mail@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@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 sinon.getPropertyDescriptor(object, prop).value === "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@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 (typeof console !== undefined && console.warn) { - // console.warn("mock will be removed from Sinon.JS v2.0"); - // } - - 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@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@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@artweb-design.de) - * @author Christian Johansen (christian@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@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); - } -})(typeof global !== "undefined" ? global : self); - -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XMLHttpRequest object - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ - -(function (global) { - - var supportsProgress = typeof ProgressEvent !== "undefined"; - var supportsCustomEvent = typeof CustomEvent !== "undefined"; - var supportsFormData = typeof FormData !== "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*/ - - // Note that for FakeXMLHttpRequest to work pre ES5 - // we lose some of the alignment with the spec. - // To ensure as close a match as possible, - // set responseType before calling open, send or respond; - function FakeXMLHttpRequest() { - this.readyState = FakeXMLHttpRequest.UNSENT; - this.requestHeaders = {}; - this.requestBody = null; - this.status = 0; - this.statusText = ""; - this.upload = new UploadProgress(); - this.responseType = ""; - this.response = ""; - 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.response = this.responseType === "json" ? 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); - } - } - - switch (this.readyState) { - case FakeXMLHttpRequest.DONE: - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - } - this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("loadend", false, false, this)); - break; - } - - this.dispatchEvent(new sinon.Event("readystatechange")); - }, - - 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 (supportsFormData && !(data instanceof FormData)) { - this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; - } - - this.requestBody = data; - } - - this.errorFlag = false; - this.sendFlag = this.async; - this.response = this.responseType === "json" ? null : ""; - 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.response = this.responseType === "json" ? null : ""; - this.errorFlag = true; - this.requestHeaders = {}; - this.responseHeaders = {}; - - 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.response = this.responseType === "json" ? JSON.parse(this.responseText) : this.responseText; - 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 : self); - -/** - * @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@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@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@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@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@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) { - if (!tests || typeof tests != "object") { - throw new TypeError("sinon.testCase needs an object with test functions"); - } - - 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) && !/^(setUp|tearDown)$/.test(testName)) { - property = tests[testName]; - - 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@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 && method.proxy.isSinonProxy) { - 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/test/lib/receiver.test.coffee b/test/lib/receiver.test.coffee index 0e4a8be..428be10 100644 --- a/test/lib/receiver.test.coffee +++ b/test/lib/receiver.test.coffee @@ -1,4 +1,14 @@ -# Copyright (c) 2014, Kinvey, Inc. All rights reserved. +# Copyright (c) 2015 Kinvey Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +# in compliance with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software distributed under the License +# is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +# or implied. See the License for the specific language governing permissions and limitations under +# the License. should = require 'should' assert = require 'assert' diff --git a/test/scripts/sampleTask.js b/test/scripts/sampleTask.js index 202ebbb..5b5901a 100644 --- a/test/scripts/sampleTask.js +++ b/test/scripts/sampleTask.js @@ -1,3 +1,15 @@ +// Copyright (c) 2015 Kinvey Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except +// in compliance with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software distributed under the License +// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express +// or implied. See the License for the specific language governing permissions and limitations under +// the License. + /** * Sample task for runner test */