diff --git a/node/Gruntfile.js b/node/Gruntfile.js new file mode 100644 index 000000000..49b302beb --- /dev/null +++ b/node/Gruntfile.js @@ -0,0 +1,19 @@ +module.exports = function(grunt) { + grunt.loadNpmTasks('grunt-css'); + grunt.loadNpmTasks('grunt-bower-task'); + grunt.loadNpmTasks('grunt-contrib-watch'); + var gruntConfig = require('./grunt-config.json'); + grunt.initConfig({ + watch: { + scripts: { + files: ["../src/**/*"], + tasks: ["bower"] + } + }, + bower: { + install: { + } + } + }); + grunt.registerTask('default', Object.keys(gruntConfig).join(' ')); +}; diff --git a/node/grunt-config.json b/node/grunt-config.json index 6f0f47531..c2c2ea1c4 100755 --- a/node/grunt-config.json +++ b/node/grunt-config.json @@ -1,43 +1,8 @@ { - "min": { - "js": { - "src": [ - "out/javascript/library/jquery.js", - "out/javascript/library/ace/ace.js", - "out/javascript/library/sidr.js", - "out/javascript/library/waypoints.js", - "out/modules/behavior/state.js", - "out/modules/ui/shape.js", - "out/javascript/semantic.js" - ], - "dest": "out/scripts/all.min.js" - } - }, - "concat": { - "css": { - "src": [ - "out/stylesheets/reset.css", - "out/stylesheets/semantic.css", - "out/ui/flat/elements/icons.css", - "out/ui/flat/elements/button.css", - "out/ui/flat/elements/checkbox.css", - "out/ui/flat/elements/label.css", - "out/ui/flat/elements/divider.css", - "out/ui/flat/elements/block.css", - "out/ui/flat/elements/segment.css", - "out/ui/flat/collections/grid.css", - "out/ui/flat/collections/form.css", - "out/ui/flat/collections/menu.css", - "out/ui/flat/modules/shape.css", - "out/stylesheets/library/sidr.css" - ], - "dest": "out/styles/all.css" - } - }, - "cssmin": { - "all": { - "src": ["out/styles/all.css"], - "dest": "out/styles/all.min.css" + "watch": { + "scripts": { + "files": ["../src/**/*"], + "tasks": ["bower"] } } -} \ No newline at end of file +} diff --git a/node/grunt.js b/node/grunt.js deleted file mode 100644 index 1fa8ce27e..000000000 --- a/node/grunt.js +++ /dev/null @@ -1,6 +0,0 @@ -module.exports = function(grunt) { - grunt.loadNpmTasks('grunt-css'); - var gruntConfig = require('./grunt-config.json'); - grunt.initConfig(gruntConfig); - grunt.registerTask('default', Object.keys(gruntConfig).join(' ')); -}; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/.jshintrc b/node/node_modules/grunt-bower-task/.jshintrc new file mode 100644 index 000000000..6b4c1a9b1 --- /dev/null +++ b/node/node_modules/grunt-bower-task/.jshintrc @@ -0,0 +1,14 @@ +{ + "curly": true, + "eqeqeq": true, + "immed": true, + "latedef": true, + "newcap": true, + "noarg": true, + "sub": true, + "undef": true, + "boss": true, + "eqnull": true, + "node": true, + "es5": true +} diff --git a/node/node_modules/grunt-bower-task/.npmignore b/node/node_modules/grunt-bower-task/.npmignore new file mode 100644 index 000000000..b785247e5 --- /dev/null +++ b/node/node_modules/grunt-bower-task/.npmignore @@ -0,0 +1,3 @@ +node_modules +npm-debug.log +tmp diff --git a/node/node_modules/grunt-bower-task/.travis.yml b/node/node_modules/grunt-bower-task/.travis.yml new file mode 100644 index 000000000..eff496a85 --- /dev/null +++ b/node/node_modules/grunt-bower-task/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - 0.8 +before_install: + - npm install -g grunt-cli diff --git a/node/node_modules/grunt-bower-task/Gruntfile.js b/node/node_modules/grunt-bower-task/Gruntfile.js new file mode 100644 index 000000000..0d063af3b --- /dev/null +++ b/node/node_modules/grunt-bower-task/Gruntfile.js @@ -0,0 +1,55 @@ +/* + * grunt-bower-task + * https://github.com/yatskevich/grunt-bower-task + * + * Copyright (c) 2012 Ivan Yatskevich + * Licensed under the MIT license. + */ + +'use strict'; + +module.exports = function(grunt) { + + grunt.initConfig({ + jshint: { + all: [ 'Gruntfile.js', 'tasks/**/*.js', 'test/**/*_test.js' ], + options: { + jshintrc: '.jshintrc' + } + }, + + bower: { + install: { + options: { + cleanTargetDir: true, + cleanBowerDir: true, + install: true, + copy: true + } + }, + cleanup: { + options: { + cleanTargetDir: true, + cleanBowerDir: true, + install: false, + copy: false + } + } + }, + + nodeunit: { + tests: ['test/*_test.js'] + } + + }); + + grunt.loadTasks('tasks'); + + grunt.loadNpmTasks('grunt-contrib-jshint'); + grunt.loadNpmTasks('grunt-contrib-nodeunit'); + + grunt.registerTask('test', ['jshint', 'nodeunit']); + + grunt.registerTask('default', ['test']); + +}; diff --git a/node/node_modules/grunt-bower-task/LICENSE-MIT b/node/node_modules/grunt-bower-task/LICENSE-MIT new file mode 100644 index 000000000..4b233f601 --- /dev/null +++ b/node/node_modules/grunt-bower-task/LICENSE-MIT @@ -0,0 +1,22 @@ +Copyright (c) 2012 Ivan Yatskevich + +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/node_modules/grunt-bower-task/README.md b/node/node_modules/grunt-bower-task/README.md new file mode 100644 index 000000000..3c0efc898 --- /dev/null +++ b/node/node_modules/grunt-bower-task/README.md @@ -0,0 +1,229 @@ +# grunt-bower-task [![Build Status](https://travis-ci.org/yatskevich/grunt-bower-task.png)](https://travis-ci.org/yatskevich/grunt-bower-task) + +> Install Bower packages. Smartly. + +## Getting Started +_If you haven't used [grunt][] before, be sure to check out the [Getting Started][] guide._ + +Please note, this plugin works **only with grunt 0.4+**. If you are using grunt 0.3.x then consider an [upgrade to 0.4][]. + +From the same directory as your project's [Gruntfile][Getting Started] and [package.json][], install this plugin with the following command: + +```bash +npm install grunt-bower-task --save-dev +``` + +Once that's done, add this line to your project's Gruntfile: + +```js +grunt.loadNpmTasks('grunt-bower-task'); +``` + +If the plugin has been installed correctly, running `grunt --help` at the command line should list the newly-installed plugin's task or tasks. In addition, the plugin should be listed in package.json as a `devDependency`, which ensures that it will be installed whenever the `npm install` command is run. + +[grunt]: http://gruntjs.com/ +[Getting Started]: https://github.com/gruntjs/grunt/wiki/Getting-started +[package.json]: https://npmjs.org/doc/json.html +[upgrade to 0.4]: https://github.com/gruntjs/grunt/wiki/Upgrading-from-0.3-to-0.4 + +## Grunt task for Bower + +### Overview +In your project's Gruntfile, add a section named `bower` to the data object passed into `grunt.initConfig()`. + +```js +grunt.initConfig({ + bower: { + install: { + //just run 'grunt bower:install' and you'll see files from your Bower packages in lib directory + } + }, +}) +``` + +### Options + +#### options.targetDir +Type: `String` +Default value: `./lib` + +A directory where you want to keep your Bower packages. + +### options.install +Type: `Boolean` +Default value: `true` + +Whether you want to run bower install task itself (e.g. you might not want to do this each time on CI server). + +### options.cleanTargetDir +Type: `Boolean` +Default value: `false` + +Will clean target dir before running install. + +### options.cleanBowerDir +Type: `Boolean` +Default value: `false` + +Will remove bower's dir after copying all needed files into target dir. + +#### options.cleanup +Type: `boolean` +Default value: `undefined` + +**NOTE:** If set to true or false then both `cleanBowerDir` & `cleanTargetDir` are set to the value of `cleanup`. + +#### options.layout +Type: `string` or `function` +Default value: `byType` + +There are two built-in named layouts: `byType` and `byComponent`. + +`byType` layout will produce the following structure: + +``` +lib +|-- js +| |- bootstrap +| \- require +|-- css + \- bootstrap +``` +where `js`, `css` come from `exportsOverride` section described below. + +`byComponent` will group assets by type under component name: + +``` +lib +|-- bootstrap +| |- js +| \- css +|-- require + \- js +``` + +If you need to support custom layout then you can specify `layout` as a function of `type` and `component`: + +```js +var path = require('path'); + +grunt.initConfig({ + bower: { + install: { + options: { + layout: function(type, component) { + var renamedType = type; + if (type == 'js') renamedType = 'javascripts'; + else if (type == 'css') renamedType = 'stylesheets'; + + return path.join(component, renamedType); + } + } + } + } +}); +``` + +#### options.verbose +Type: `boolean` +Default value: `false` + +The task will provide more (debug) output when this option is set to `true`. You can also use `--verbose` when running task for same effect. + +### Usage Examples + +#### Default Options +Default options are good enough if you want to install Bower packages and keep only `"main"` files (as specified by package's `component.json`) in separate directory. + +```js +grunt.initConfig({ + bower: { + install: { + options: { + targetDir: './lib', + layout: 'byType', + install: true, + verbose: false, + cleanTargetDir: false, + cleanBowerDir: false + } + } + }, +}) +``` + +#### Custom Options +In this initial version there are no more options in plugin itself. **BUT!** + +### Advanced usage +At this point of time "Bower package" = "its git repository". It means that package includes tests, licenses, etc. +Bower's community actively discusses this issue (GitHub issues [#46][],[#88][], [on Google Groups][GG]) +That's why you can find such tools like [blittle/bower-installer][] which inspired this project. + +[GG]: https://groups.google.com/forum/?fromgroups=#!topic/twitter-bower/SQEDDA_gmh0 +[#88]: https://github.com/twitter/bower/issues/88 +[#46]: https://github.com/twitter/bower/issues/46 +[blittle/bower-installer]: https://github.com/blittle/bower-installer + +Okay, if you want more than `"main"` files in `./lib` directory then put `"exportsOverride"` section into your `component.json`: + +```json +{ + "name": "simple-bower", + "version": "0.0.0", + "dependencies": { + "jquery": "~1.8.3", + "bootstrap-sass": "*", + "requirejs": "*" + }, + "exportsOverride": { + "bootstrap-sass": { + "js": "js/*.js", + "scss": "lib/*.scss", + "img": "img/*.png" + }, + "requirejs": { + "js": "require.js" + } + } +} +``` +`grunt-bower-task` will do the rest: + +* If Bower package has defined `"main"` files then they will be copied to `./lib//`. +* If `"main"` files are empty then the whole package directory will be copied to `./lib`. +* When you define `"exportsOverride"` only asset types and files specified by you will be copied to `./lib`. + +For the example above you'll get the following files in `.lib` directory: + +``` +jquery/jquery.js +js/bootstrap-sass/bootstrap-affix.js +... +js/bootstrap-sass/bootstrap-typeahead.js +js/requirejs/require.js +scss/bootstrap-sass/_accordion.scss +... +scss/bootstrap-sass/_wells.scss +scss/bootstrap-sass/bootstrap.scss +scss/bootstrap-sass/responsive.scss +img/bootstrap-sass/glyphicons-halflings-white.png +img/bootstrap-sass/glyphicons-halflings.png +``` + +## Contributing +In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt][]. + +## Release History +* 2013/04/23 - v0.2.2 - Fix backward-compatibility issue (related to `cleanup` option). +* 2013/04/22 - v0.2.1 - Split 'install' to 'install' and 'copy' steps to support flexible workflow, add support for grunt's `--base` option. +* 2013/03/30 - v0.2.0 - Added support for flexible assets layout, honor native Bower's configuration, reduce log output. +* 2013/03/18 - v0.1.1 - Updated dependencies, minor fixes. +* 2012/11/25 - v0.1.0 - Initial release. + +## License +Copyright (c) 2012-2013 Ivan Yatskevich + +Licensed under the MIT license. + + diff --git a/node/node_modules/grunt-bower-task/node_modules/.bin/bower b/node/node_modules/grunt-bower-task/node_modules/.bin/bower new file mode 120000 index 000000000..fb1412991 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/.bin/bower @@ -0,0 +1 @@ +../bower/bin/bower \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/.bin/lodash b/node/node_modules/grunt-bower-task/node_modules/.bin/lodash new file mode 120000 index 000000000..24deae288 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/.bin/lodash @@ -0,0 +1 @@ +../lodash/build.js \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/async/.gitmodules b/node/node_modules/grunt-bower-task/node_modules/async/.gitmodules new file mode 100644 index 000000000..a9aae984f --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/async/.gitmodules @@ -0,0 +1,9 @@ +[submodule "deps/nodeunit"] + path = deps/nodeunit + url = git://github.com/caolan/nodeunit.git +[submodule "deps/UglifyJS"] + path = deps/UglifyJS + url = https://github.com/mishoo/UglifyJS.git +[submodule "deps/nodelint"] + path = deps/nodelint + url = https://github.com/tav/nodelint.git diff --git a/node/node_modules/grunt-bower-task/node_modules/async/.npmignore b/node/node_modules/grunt-bower-task/node_modules/async/.npmignore new file mode 100644 index 000000000..9bdfc97ca --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/async/.npmignore @@ -0,0 +1,4 @@ +deps +dist +test +nodelint.cfg \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/LICENSE b/node/node_modules/grunt-bower-task/node_modules/async/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/async/LICENSE diff --git a/node/node_modules/grunt-bower-task/node_modules/async/Makefile b/node/node_modules/grunt-bower-task/node_modules/async/Makefile new file mode 100644 index 000000000..bad647c63 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/async/Makefile @@ -0,0 +1,25 @@ +PACKAGE = asyncjs +NODEJS = $(if $(shell test -f /usr/bin/nodejs && echo "true"),nodejs,node) +CWD := $(shell pwd) +NODEUNIT = $(CWD)/node_modules/nodeunit/bin/nodeunit +UGLIFY = $(CWD)/node_modules/uglify-js/bin/uglifyjs +NODELINT = $(CWD)/node_modules/nodelint/nodelint + +BUILDDIR = dist + +all: clean test build + +build: $(wildcard lib/*.js) + mkdir -p $(BUILDDIR) + $(UGLIFY) lib/async.js > $(BUILDDIR)/async.min.js + +test: + $(NODEUNIT) test + +clean: + rm -rf $(BUILDDIR) + +lint: + $(NODELINT) --config nodelint.cfg lib/async.js + +.PHONY: test build all diff --git a/node/node_modules/grunt-bower-task/node_modules/async/README.md b/node/node_modules/grunt-bower-task/node_modules/async/README.md new file mode 100644 index 000000000..1bbbc477e --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/async/README.md @@ -0,0 +1,1021 @@ +# Async.js + +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. + +Async provides around 20 functions that include the usual 'functional' +suspects (map, reduce, filter, forEach…) 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 + + 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'], path.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. + + +## Download + +Releases are available for download from +[GitHub](http://github.com/caolan/async/downloads). +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) - 17.5kb Uncompressed + +__Production:__ [async.min.js](https://github.com/caolan/async/raw/master/dist/async.min.js) - 1.7kb Packed and Gzipped + + +## In the Browser + +So far its been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. Usage: + + + + + +## Documentation + +### Collections + +* [forEach](#forEach) +* [map](#map) +* [filter](#filter) +* [reject](#reject) +* [reduce](#reduce) +* [detect](#detect) +* [sortBy](#sortBy) +* [some](#some) +* [every](#every) +* [concat](#concat) + +### Control Flow + +* [series](#series) +* [parallel](#parallel) +* [whilst](#whilst) +* [until](#until) +* [waterfall](#waterfall) +* [queue](#queue) +* [auto](#auto) +* [iterator](#iterator) +* [apply](#apply) +* [nextTick](#nextTick) + +### Utils + +* [memoize](#memoize) +* [unmemoize](#unmemoize) +* [log](#log) +* [dir](#dir) +* [noConflict](#noConflict) + + +## Collections + + +### forEach(arr, iterator, callback) + +Applies an iterator function to each item in an array, 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 this callback, the main +callback for the forEach 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. + +__Arguments__ + +* arr - An array to iterate over. +* iterator(item, callback) - A function to apply to each item in the array. + The iterator is passed a callback which must be called once it has completed. +* callback(err) - A callback which is called after all the iterator functions + have finished, or an error has occurred. + +__Example__ + + // assuming openFiles is an array of file names and saveFile is a function + // to save the modified contents of that file: + + async.forEach(openFiles, saveFile, function(err){ + // if any of the saves produced an error, err would equal that error + }); + +--------------------------------------- + + +### forEachSeries(arr, iterator, callback) + +The same as forEach only the iterator is applied to each item in the array in +series. The next iterator is only called once the current one has completed +processing. This means the iterator functions will complete in order. + + +--------------------------------------- + + +### forEachLimit(arr, limit, iterator, callback) + +The same as forEach only the iterator is applied to batches of items in the +array, in series. The next batch of iterators is only called once the current +one has completed processing. + +__Arguments__ + +* arr - An array to iterate over. +* limit - How many items should be in each batch. +* iterator(item, callback) - A function to apply to each item in the array. + The iterator is passed a callback which must be called once it has completed. +* callback(err) - A callback which is called after all the iterator functions + have finished, or an error has occurred. + +__Example__ + + // Assume documents is an array of JSON objects and requestApi is a + // function that interacts with a rate-limited REST api. + + async.forEachLimit(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 the given array through +the iterator function. The iterator is called with an item from the array and a +callback for when it has finished processing. The callback takes 2 arguments, +an error and the transformed item from the array. If the 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 array. + +__Arguments__ + +* arr - An array to iterate over. +* iterator(item, callback) - A function to apply to each item in the array. + The iterator is passed a callback 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 after all the iterator + functions have finished, or an error has occurred. Results is an array of the + transformed items from the original array. + +__Example__ + + 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 only the iterator is applied to each item in the array in +series. The next iterator is only called once the current one has completed +processing. The results array will be in the same order as the original. + + +--------------------------------------- + + +### filter(arr, iterator, callback) + +__Alias:__ select + +Returns a new array of all the values 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 path.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 the array. + The iterator is passed a callback which must be called once it has completed. +* callback(results) - A callback which is called after all the iterator + functions have finished. + +__Example__ + + async.filter(['file1','file2','file3'], path.exists, function(results){ + // results now equals an array of the existing files + }); + +--------------------------------------- + + +### filterSeries(arr, iterator, callback) + +__alias:__ selectSeries + +The same as filter only the iterator is applied to each item in the array in +series. The next iterator is only called once the current one has completed +processing. The results array will be in the same order as the original. + +--------------------------------------- + + +### reject(arr, iterator, callback) + +The opposite of filter. Removes values that pass an async truth test. + +--------------------------------------- + + +### rejectSeries(arr, iterator, callback) + +The same as filter, only the iterator is applied to each item in the array +in series. + + +--------------------------------------- + + +### reduce(arr, memo, iterator, callback) + +__aliases:__ inject, foldl + +Reduces a list of values 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, 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 its 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 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__ + + 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, only operates on the items in the array in reverse order. + + +--------------------------------------- + + +### detect(arr, iterator, callback) + +Returns the first value in a list 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 array (in terms of order) that passes the test. + +If order within the original array is important then look at detectSeries. + +__Arguments__ + +* arr - An array to iterate over. +* iterator(item, callback) - A truth test to apply to each item in the array. + The iterator is passed a callback which must be called 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__ + + async.detect(['file1','file2','file3'], path.exists, function(result){ + // result now equals the first file in the list that exists + }); + +--------------------------------------- + + +### detectSeries(arr, iterator, callback) + +The same as detect, only the iterator is applied to each item in the array +in series. This means the result is always the first in the original array (in +terms of array order) that passes the truth test. + + +--------------------------------------- + + +### sortBy(arr, iterator, callback) + +Sorts a list by the results of running each value through an async iterator. + +__Arguments__ + +* arr - An array to iterate over. +* iterator(item, callback) - A function to apply to each item in the array. + The iterator is passed a callback 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 has occurred. Results is the items from + the original array sorted by the values returned by the iterator calls. + +__Example__ + + 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 + }); + + +--------------------------------------- + + +### some(arr, iterator, callback) + +__Alias:__ any + +Returns true if at least one element in the array 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 path.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. + The iterator is passed a callback which must be called 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__ + + async.some(['file1','file2','file3'], path.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 the array 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 path.exists. + +__Arguments__ + +* arr - An array to iterate over. +* iterator(item, callback) - A truth test to apply to each item in the array. + The iterator is passed a callback which must be called 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__ + + async.every(['file1','file2','file3'], path.exists, function(result){ + // if result is true then every file exists + }); + +--------------------------------------- + + +### concat(arr, iterator, callback) + +Applies an iterator to each item in a list, concatenating the results. Returns the +concatenated list. The iterators 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 the arguments passed to the iterator function. + +__Arguments__ + +* arr - An array to iterate over +* iterator(item, callback) - A function to apply to each item in the array. + The iterator is passed a callback 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 has occurred. Results is an array containing + the concatenated results of the iterator function. + +__Example__ + + 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 async.concat, but executes in series instead of parallel. + + +## Control Flow + + +### series(tasks, [callback]) + +Run an array of functions 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 the callback for the series 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 +async.series. + + +__Arguments__ + +* tasks - An array or object containing functions to run, each function is passed + a callback it must call on completion. +* callback(err, results) - An optional callback to run once all the functions + have completed. This function gets an array of all the arguments passed to + the callbacks used in the array. + +__Example__ + + 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 an 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 +async.parallel. + + +__Arguments__ + +* tasks - An array or object containing functions to run, each function is passed a + callback it must call on completion. +* callback(err, results) - An optional callback to run once all the functions + have completed. This function gets an array of all the arguments passed to + the callbacks used in the array. + +__Example__ + + 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} + }); + + +--------------------------------------- + + +### whilst(test, fn, callback) + +Repeatedly call fn, while test returns true. Calls the callback when stopped, +or an error occurs. + +__Arguments__ + +* test() - synchronous truth test to perform before each execution of fn. +* fn(callback) - A function to call each time the test passes. The function is + passed a callback which must be called once it has completed with an optional + error as the first argument. +* callback(err) - A callback which is called after the test fails and repeated + execution of fn has stopped. + +__Example__ + + var count = 0; + + async.whilst( + function () { return count < 5; }, + function (callback) { + count++; + setTimeout(callback, 1000); + }, + function (err) { + // 5 seconds have passed + } + ); + + +--------------------------------------- + + +### until(test, fn, callback) + +Repeatedly call fn, until test returns true. Calls the callback when stopped, +or an error occurs. + +The inverse of async.whilst. + + +--------------------------------------- + + +### waterfall(tasks, [callback]) + +Runs an array of functions in series, each passing their results to the next in +the array. However, if any of the functions pass an error to the 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 it + must call on completion. +* 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__ + + async.waterfall([ + function(callback){ + callback(null, 'one', 'two'); + }, + function(arg1, arg2, callback){ + callback(null, 'three'); + }, + function(arg1, callback){ + // arg1 now equals 'three' + callback(null, 'done'); + } + ], function (err, result) { + // result now equals 'done' + }); + + +--------------------------------------- + + +### queue(worker, concurrency) + +Creates a queue object with the specified concurrency. Tasks added to the +queue will be processed in parallel (up to the concurrency limit). If all +workers are in progress, the task is queued until one is available. Once +a worker has completed a task, the task's callback is called. + +__Arguments__ + +* worker(task, callback) - An asynchronous function for processing a queued + task. +* 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. +* 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, 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__ + + // 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'); + }); + + +--------------------------------------- + + +### auto(tasks, [callback]) + +Determines the best order for running functions 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, that function will not complete +(so any other functions depending on it will not run) and the main callback +will be called immediately with the error. Functions also receive an object +containing the results of functions which have completed so far. + +__Arguments__ + +* tasks - An object literal containing named functions or an array of + requirements, with the function itself the last item in the array. The key + used for each function or array is used when specifying requirements. The + syntax is easier to understand by looking at the example. +* callback(err, results) - An optional callback which is called when all the + tasks have been completed. The callback will receive an error as an argument + if any tasks pass an error to their callback. If all tasks complete + successfully, it will receive an object containing their results. + +__Example__ + + async.auto({ + get_data: function(callback){ + // async code to get some data + }, + make_folder: function(callback){ + // async code to create a directory to store a file in + // this is run at the same time as getting the data + }, + write_file: ['get_data', 'make_folder', function(callback){ + // 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){ + // once the file is written let's email a link to it... + // results.write_file contains the filename returned by write_file. + }] + }); + +This is a fairly trivial example, but to do this using the basic parallel and +series functions would look like this: + + async.parallel([ + function(callback){ + // async code to get some data + }, + function(callback){ + // async code to create a directory to store a file in + // this is run at the same time as getting the data + } + ], + function(results){ + async.series([ + function(callback){ + // once there is some data and the directory exists, + // write the data to a file in the directory + }, + email_link: function(callback){ + // once the file is written let's email a link to it... + } + ]); + }); + +For a complicated series of async tasks using the auto function makes adding +new tasks much easier and makes the code more readable. + + +--------------------------------------- + + +### iterator(tasks) + +Creates an iterator function which calls the next function in the array, +returning a continuation to call the next one after that. Its also possible to +'peek' the next iterator by doing 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, each function is passed a callback it + must call on completion. + +__Example__ + + 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, a useful +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__ + + // 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: + + node> var fn = async.apply(sys.puts, 'one'); + node> fn('two', 'three'); + one + two + three + +--------------------------------------- + + +### nextTick(callback) + +Calls the callback on a later loop around the event loop. In node.js this just +calls process.nextTick, in the browser it falls back to setTimeout(callback, 0), +which means other higher priority events may precede the execution of the callback. + +This is used internally for browser-compatibility purposes. + +__Arguments__ + +* callback - The function to call on a later loop around the event loop. + +__Example__ + + var call_order = []; + async.nextTick(function(){ + call_order.push('two'); + // call_order now equals ['one','two] + }); + call_order.push('one') + + +## 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. + +__Arguments__ + +* fn - the function you to proxy and cache results from. +* hasher - an 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__ + + 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 memoized function, reverting it to the original, unmemoized +form. Comes handy in tests. + +__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__ + + var hello = function(name, callback){ + setTimeout(function(){ + callback(null, 'hello ' + name); + }, 1000); + }; + + 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__ + + var hello = function(name, callback){ + setTimeout(function(){ + callback(null, {hello: name}); + }, 1000); + }; + + 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/node_modules/grunt-bower-task/node_modules/async/index.js b/node/node_modules/grunt-bower-task/node_modules/async/index.js new file mode 100644 index 000000000..8e238453e --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/async/index.js @@ -0,0 +1,3 @@ +// This file is just added for convenience so this repository can be +// directly checked out into a project's deps folder +module.exports = require('./lib/async'); diff --git a/node/node_modules/grunt-bower-task/node_modules/async/lib/async.js b/node/node_modules/grunt-bower-task/node_modules/async/lib/async.js new file mode 100644 index 000000000..7cc4f5eac --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/async/lib/async.js @@ -0,0 +1,692 @@ +/*global setTimeout: false, console: false */ +(function () { + + var async = {}; + + // global on the server, window in the browser + var root = this, + previous_async = root.async; + + if (typeof module !== 'undefined' && module.exports) { + module.exports = async; + } + else { + root.async = async; + } + + async.noConflict = function () { + root.async = previous_async; + return async; + }; + + //// cross-browser compatiblity functions //// + + var _forEach = 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 = []; + _forEach(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); + } + _forEach(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)) { + async.nextTick = function (fn) { + setTimeout(fn, 0); + }; + } + else { + async.nextTick = process.nextTick; + } + + async.forEach = function (arr, iterator, callback) { + callback = callback || function () {}; + if (!arr.length) { + return callback(); + } + var completed = 0; + _forEach(arr, function (x) { + iterator(x, function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + if (completed === arr.length) { + callback(null); + } + } + }); + }); + }; + + async.forEachSeries = 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(null); + } + else { + iterate(); + } + } + }); + }; + iterate(); + }; + + async.forEachLimit = function (arr, limit, 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.forEach].concat(args)); + }; + }; + var doSeries = function (fn) { + return function () { + var args = Array.prototype.slice.call(arguments); + return fn.apply(null, [async.forEachSeries].concat(args)); + }; + }; + + + var _asyncMap = 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 (err, v) { + results[x.index] = v; + callback(err); + }); + }, function (err) { + callback(err, results); + }); + }; + async.map = doParallel(_asyncMap); + async.mapSeries = doSeries(_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.forEachSeries(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.forEach(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.forEach(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); + if (!keys.length) { + return callback(null); + } + + 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 () { + _forEach(listeners.slice(0), function (fn) { + fn(); + }); + }; + + addListener(function () { + if (_keys(results).length === keys.length) { + callback(null, results); + callback = function () {}; + } + }); + + _forEach(keys, function (k) { + var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; + var taskCallback = function (err) { + if (err) { + callback(err); + // stop subsequent errors hitting callback multiple times + callback = function () {}; + } + else { + var args = Array.prototype.slice.call(arguments, 1); + if (args.length <= 1) { + args = args[0]; + } + results[k] = args; + 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.waterfall = function (tasks, callback) { + callback = callback || function () {}; + if (!tasks.length) { + return callback(); + } + var wrapIterator = function (iterator) { + return function (err) { + if (err) { + callback(err); + 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.nextTick(function () { + iterator.apply(null, args); + }); + } + }; + }; + wrapIterator(async.iterator(tasks))(); + }; + + async.parallel = function (tasks, callback) { + callback = callback || function () {}; + if (tasks.constructor === Array) { + async.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 = {}; + async.forEach(_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.series = function (tasks, callback) { + callback = callback || function () {}; + if (tasks.constructor === Array) { + 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.forEachSeries(_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.until = function (test, iterator, callback) { + if (!test()) { + iterator(function (err) { + if (err) { + return callback(err); + } + async.until(test, iterator, callback); + }); + } + else { + callback(); + } + }; + + async.queue = function (worker, concurrency) { + var workers = 0; + var q = { + tasks: [], + concurrency: concurrency, + saturated: null, + empty: null, + drain: null, + push: function (data, callback) { + if(data.constructor !== Array) { + data = [data]; + } + _forEach(data, function(task) { + q.tasks.push({ + data: task, + callback: typeof callback === 'function' ? callback : null + }); + if (q.saturated && q.tasks.length == concurrency) { + q.saturated(); + } + async.nextTick(q.process); + }); + }, + process: function () { + if (workers < q.concurrency && q.tasks.length) { + var task = q.tasks.shift(); + if(q.empty && q.tasks.length == 0) q.empty(); + workers += 1; + worker(task.data, function () { + workers -= 1; + if (task.callback) { + task.callback.apply(task, arguments); + } + if(q.drain && q.tasks.length + workers == 0) q.drain(); + q.process(); + }); + } + }, + length: function () { + return q.tasks.length; + }, + running: function () { + return workers; + } + }; + return q; + }; + + 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]) { + _forEach(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) { + 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.unmemoized = fn; + return memoized; + }; + + async.unmemoize = function (fn) { + return function () { + return (fn.unmemoized || fn).apply(null, arguments); + }; + }; + +}()); diff --git a/node/node_modules/grunt-bower-task/node_modules/async/package.json b/node/node_modules/grunt-bower-task/node_modules/async/package.json new file mode 100644 index 000000000..4f74950bb --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/async/package.json @@ -0,0 +1,31 @@ +{ + "name": "async", + "description": "Higher-order functions and common patterns for asynchronous code", + "main": "./index", + "author": { + "name": "Caolan McMahon" + }, + "version": "0.1.22", + "repository": { + "type": "git", + "url": "http://github.com/caolan/async.git" + }, + "bugs": { + "url": "http://github.com/caolan/async/issues" + }, + "licenses": [ + { + "type": "MIT", + "url": "http://github.com/caolan/async/raw/master/LICENSE" + } + ], + "devDependencies": { + "nodeunit": ">0.0.0", + "uglify-js": "1.2.x", + "nodelint": ">0.0.0" + }, + "readme": "# Async.js\n\nAsync is a utility module which provides straight-forward, powerful functions\nfor working with asynchronous JavaScript. Although originally designed for\nuse with [node.js](http://nodejs.org), it can also be used directly in the\nbrowser.\n\nAsync provides around 20 functions that include the usual 'functional'\nsuspects (map, reduce, filter, forEach…) as well as some common patterns\nfor asynchronous control flow (parallel, series, waterfall…). All these\nfunctions assume you follow the node.js convention of providing a single\ncallback as the last argument of your async function.\n\n\n## Quick Examples\n\n async.map(['file1','file2','file3'], fs.stat, function(err, results){\n // results is now an array of stats for each file\n });\n\n async.filter(['file1','file2','file3'], path.exists, function(results){\n // results now equals an array of the existing files\n });\n\n async.parallel([\n function(){ ... },\n function(){ ... }\n ], callback);\n\n async.series([\n function(){ ... },\n function(){ ... }\n ]);\n\nThere are many more functions available so take a look at the docs below for a\nfull list. This module aims to be comprehensive, so if you feel anything is\nmissing please create a GitHub issue for it.\n\n\n## Download\n\nReleases are available for download from\n[GitHub](http://github.com/caolan/async/downloads).\nAlternatively, you can install using Node Package Manager (npm):\n\n npm install async\n\n\n__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 17.5kb Uncompressed\n\n__Production:__ [async.min.js](https://github.com/caolan/async/raw/master/dist/async.min.js) - 1.7kb Packed and Gzipped\n\n\n## In the Browser\n\nSo far its been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. Usage:\n\n \n \n\n\n## Documentation\n\n### Collections\n\n* [forEach](#forEach)\n* [map](#map)\n* [filter](#filter)\n* [reject](#reject)\n* [reduce](#reduce)\n* [detect](#detect)\n* [sortBy](#sortBy)\n* [some](#some)\n* [every](#every)\n* [concat](#concat)\n\n### Control Flow\n\n* [series](#series)\n* [parallel](#parallel)\n* [whilst](#whilst)\n* [until](#until)\n* [waterfall](#waterfall)\n* [queue](#queue)\n* [auto](#auto)\n* [iterator](#iterator)\n* [apply](#apply)\n* [nextTick](#nextTick)\n\n### Utils\n\n* [memoize](#memoize)\n* [unmemoize](#unmemoize)\n* [log](#log)\n* [dir](#dir)\n* [noConflict](#noConflict)\n\n\n## Collections\n\n\n### forEach(arr, iterator, callback)\n\nApplies an iterator function to each item in an array, in parallel.\nThe iterator is called with an item from the list and a callback for when it\nhas finished. If the iterator passes an error to this callback, the main\ncallback for the forEach function is immediately called with the error.\n\nNote, that since this function applies the iterator to each item in parallel\nthere is no guarantee that the iterator functions will complete in order.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback which must be called once it has completed.\n* callback(err) - A callback which is called after all the iterator functions\n have finished, or an error has occurred.\n\n__Example__\n\n // assuming openFiles is an array of file names and saveFile is a function\n // to save the modified contents of that file:\n\n async.forEach(openFiles, saveFile, function(err){\n // if any of the saves produced an error, err would equal that error\n });\n\n---------------------------------------\n\n\n### forEachSeries(arr, iterator, callback)\n\nThe same as forEach only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. This means the iterator functions will complete in order.\n\n\n---------------------------------------\n\n\n### forEachLimit(arr, limit, iterator, callback)\n\nThe same as forEach only the iterator is applied to batches of items in the\narray, in series. The next batch of iterators is only called once the current\none has completed processing.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* limit - How many items should be in each batch.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback which must be called once it has completed.\n* callback(err) - A callback which is called after all the iterator functions\n have finished, or an error has occurred.\n\n__Example__\n\n // Assume documents is an array of JSON objects and requestApi is a\n // function that interacts with a rate-limited REST api.\n\n async.forEachLimit(documents, 20, requestApi, function(err){\n // if any of the saves produced an error, err would equal that error\n });\n---------------------------------------\n\n\n### map(arr, iterator, callback)\n\nProduces a new array of values by mapping each value in the given array through\nthe iterator function. The iterator is called with an item from the array and a\ncallback for when it has finished processing. The callback takes 2 arguments, \nan error and the transformed item from the array. If the iterator passes an\nerror to this callback, the main callback for the map function is immediately\ncalled with the error.\n\nNote, that since this function applies the iterator to each item in parallel\nthere is no guarantee that the iterator functions will complete in order, however\nthe results array will be in the same order as the original array.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback which must be called once it has completed\n with an error (which can be null) and a transformed item.\n* callback(err, results) - A callback which is called after all the iterator\n functions have finished, or an error has occurred. Results is an array of the\n transformed items from the original array.\n\n__Example__\n\n async.map(['file1','file2','file3'], fs.stat, function(err, results){\n // results is now an array of stats for each file\n });\n\n---------------------------------------\n\n\n### mapSeries(arr, iterator, callback)\n\nThe same as map only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n\n---------------------------------------\n\n\n### filter(arr, iterator, callback)\n\n__Alias:__ select\n\nReturns a new array of all the values which pass an async truth test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like path.exists. This operation is\nperformed in parallel, but the results array will be in the same order as the\noriginal.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n The iterator is passed a callback which must be called once it has completed.\n* callback(results) - A callback which is called after all the iterator\n functions have finished.\n\n__Example__\n\n async.filter(['file1','file2','file3'], path.exists, function(results){\n // results now equals an array of the existing files\n });\n\n---------------------------------------\n\n\n### filterSeries(arr, iterator, callback)\n\n__alias:__ selectSeries\n\nThe same as filter only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n---------------------------------------\n\n\n### reject(arr, iterator, callback)\n\nThe opposite of filter. Removes values that pass an async truth test.\n\n---------------------------------------\n\n\n### rejectSeries(arr, iterator, callback)\n\nThe same as filter, only the iterator is applied to each item in the array\nin series.\n\n\n---------------------------------------\n\n\n### reduce(arr, memo, iterator, callback)\n\n__aliases:__ inject, foldl\n\nReduces a list of values into a single value using an async iterator to return\neach successive step. Memo is the initial state of the reduction. This\nfunction only operates in series. For performance reasons, it may make sense to\nsplit a call to this function into a parallel map, then use the normal\nArray.prototype.reduce on the results. This function is for situations where\neach step in the reduction needs to be async, if you can get the data before\nreducing it then its probably a good idea to do so.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* memo - The initial state of the reduction.\n* iterator(memo, item, callback) - A function applied to each item in the\n array to produce the next step in the reduction. The iterator is passed a\n callback which accepts an optional error as its first argument, and the state\n of the reduction as the second. If an error is passed to the callback, the\n reduction is stopped and the main callback is immediately called with the\n error.\n* callback(err, result) - A callback which is called after all the iterator\n functions have finished. Result is the reduced value.\n\n__Example__\n\n async.reduce([1,2,3], 0, function(memo, item, callback){\n // pointless async:\n process.nextTick(function(){\n callback(null, memo + item)\n });\n }, function(err, result){\n // result is now equal to the last value of memo, which is 6\n });\n\n---------------------------------------\n\n\n### reduceRight(arr, memo, iterator, callback)\n\n__Alias:__ foldr\n\nSame as reduce, only operates on the items in the array in reverse order.\n\n\n---------------------------------------\n\n\n### detect(arr, iterator, callback)\n\nReturns the first value in a list that passes an async truth test. The\niterator is applied in parallel, meaning the first iterator to return true will\nfire the detect callback with that result. That means the result might not be\nthe first item in the original array (in terms of order) that passes the test.\n\nIf order within the original array is important then look at detectSeries.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n The iterator is passed a callback which must be called once it has completed.\n* callback(result) - A callback which is called as soon as any iterator returns\n true, or after all the iterator functions have finished. Result will be\n the first item in the array that passes the truth test (iterator) or the\n value undefined if none passed.\n\n__Example__\n\n async.detect(['file1','file2','file3'], path.exists, function(result){\n // result now equals the first file in the list that exists\n });\n\n---------------------------------------\n\n\n### detectSeries(arr, iterator, callback)\n\nThe same as detect, only the iterator is applied to each item in the array\nin series. This means the result is always the first in the original array (in\nterms of array order) that passes the truth test.\n\n\n---------------------------------------\n\n\n### sortBy(arr, iterator, callback)\n\nSorts a list by the results of running each value through an async iterator.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback which must be called once it has completed\n with an error (which can be null) and a value to use as the sort criteria.\n* callback(err, results) - A callback which is called after all the iterator\n functions have finished, or an error has occurred. Results is the items from\n the original array sorted by the values returned by the iterator calls.\n\n__Example__\n\n async.sortBy(['file1','file2','file3'], function(file, callback){\n fs.stat(file, function(err, stats){\n callback(err, stats.mtime);\n });\n }, function(err, results){\n // results is now the original array of files sorted by\n // modified date\n });\n\n\n---------------------------------------\n\n\n### some(arr, iterator, callback)\n\n__Alias:__ any\n\nReturns true if at least one element in the array satisfies an async test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like path.exists. Once any iterator\ncall returns true, the main callback is immediately called.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n The iterator is passed a callback which must be called once it has completed.\n* callback(result) - A callback which is called as soon as any iterator returns\n true, or after all the iterator functions have finished. Result will be\n either true or false depending on the values of the async tests.\n\n__Example__\n\n async.some(['file1','file2','file3'], path.exists, function(result){\n // if result is true then at least one of the files exists\n });\n\n---------------------------------------\n\n\n### every(arr, iterator, callback)\n\n__Alias:__ all\n\nReturns true if every element in the array satisfies an async test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like path.exists.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n The iterator is passed a callback which must be called once it has completed.\n* callback(result) - A callback which is called after all the iterator\n functions have finished. Result will be either true or false depending on\n the values of the async tests.\n\n__Example__\n\n async.every(['file1','file2','file3'], path.exists, function(result){\n // if result is true then every file exists\n });\n\n---------------------------------------\n\n\n### concat(arr, iterator, callback)\n\nApplies an iterator to each item in a list, concatenating the results. Returns the\nconcatenated list. The iterators are called in parallel, and the results are\nconcatenated as they return. There is no guarantee that the results array will\nbe returned in the original order of the arguments passed to the iterator function.\n\n__Arguments__\n\n* arr - An array to iterate over\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback which must be called once it has completed\n with an error (which can be null) and an array of results.\n* callback(err, results) - A callback which is called after all the iterator\n functions have finished, or an error has occurred. Results is an array containing\n the concatenated results of the iterator function.\n\n__Example__\n\n async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){\n // files is now a list of filenames that exist in the 3 directories\n });\n\n---------------------------------------\n\n\n### concatSeries(arr, iterator, callback)\n\nSame as async.concat, but executes in series instead of parallel.\n\n\n## Control Flow\n\n\n### series(tasks, [callback])\n\nRun an array of functions in series, each one running once the previous\nfunction has completed. If any functions in the series pass an error to its\ncallback, no more functions are run and the callback for the series is\nimmediately called with the value of the error. Once the tasks have completed,\nthe results are passed to the final callback as an array.\n\nIt is also possible to use an object instead of an array. Each property will be\nrun as a function and the results will be passed to the final callback as an object\ninstead of an array. This can be a more readable way of handling results from\nasync.series.\n\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed\n a callback it must call on completion.\n* callback(err, results) - An optional callback to run once all the functions\n have completed. This function gets an array of all the arguments passed to\n the callbacks used in the array.\n\n__Example__\n\n async.series([\n function(callback){\n // do some stuff ...\n callback(null, 'one');\n },\n function(callback){\n // do some more stuff ...\n callback(null, 'two');\n },\n ],\n // optional callback\n function(err, results){\n // results is now equal to ['one', 'two']\n });\n\n\n // an example using an object instead of an array\n async.series({\n one: function(callback){\n setTimeout(function(){\n callback(null, 1);\n }, 200);\n },\n two: function(callback){\n setTimeout(function(){\n callback(null, 2);\n }, 100);\n },\n },\n function(err, results) {\n // results is now equal to: {one: 1, two: 2}\n });\n\n\n---------------------------------------\n\n\n### parallel(tasks, [callback])\n\nRun an array of functions in parallel, without waiting until the previous\nfunction has completed. If any of the functions pass an error to its\ncallback, the main callback is immediately called with the value of the error.\nOnce the tasks have completed, the results are passed to the final callback as an\narray.\n\nIt is also possible to use an object instead of an array. Each property will be\nrun as a function and the results will be passed to the final callback as an object\ninstead of an array. This can be a more readable way of handling results from\nasync.parallel.\n\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed a\n callback it must call on completion.\n* callback(err, results) - An optional callback to run once all the functions\n have completed. This function gets an array of all the arguments passed to\n the callbacks used in the array.\n\n__Example__\n\n async.parallel([\n function(callback){\n setTimeout(function(){\n callback(null, 'one');\n }, 200);\n },\n function(callback){\n setTimeout(function(){\n callback(null, 'two');\n }, 100);\n },\n ],\n // optional callback\n function(err, results){\n // the results array will equal ['one','two'] even though\n // the second function had a shorter timeout.\n });\n\n\n // an example using an object instead of an array\n async.parallel({\n one: function(callback){\n setTimeout(function(){\n callback(null, 1);\n }, 200);\n },\n two: function(callback){\n setTimeout(function(){\n callback(null, 2);\n }, 100);\n },\n },\n function(err, results) {\n // results is now equals to: {one: 1, two: 2}\n });\n\n\n---------------------------------------\n\n\n### whilst(test, fn, callback)\n\nRepeatedly call fn, while test returns true. Calls the callback when stopped,\nor an error occurs.\n\n__Arguments__\n\n* test() - synchronous truth test to perform before each execution of fn.\n* fn(callback) - A function to call each time the test passes. The function is\n passed a callback which must be called once it has completed with an optional\n error as the first argument.\n* callback(err) - A callback which is called after the test fails and repeated\n execution of fn has stopped.\n\n__Example__\n\n var count = 0;\n\n async.whilst(\n function () { return count < 5; },\n function (callback) {\n count++;\n setTimeout(callback, 1000);\n },\n function (err) {\n // 5 seconds have passed\n }\n );\n\n\n---------------------------------------\n\n\n### until(test, fn, callback)\n\nRepeatedly call fn, until test returns true. Calls the callback when stopped,\nor an error occurs.\n\nThe inverse of async.whilst.\n\n\n---------------------------------------\n\n\n### waterfall(tasks, [callback])\n\nRuns an array of functions in series, each passing their results to the next in\nthe array. However, if any of the functions pass an error to the callback, the\nnext function is not executed and the main callback is immediately called with\nthe error.\n\n__Arguments__\n\n* tasks - An array of functions to run, each function is passed a callback it\n must call on completion.\n* callback(err, [results]) - An optional callback to run once all the functions\n have completed. This will be passed the results of the last task's callback.\n\n\n\n__Example__\n\n async.waterfall([\n function(callback){\n callback(null, 'one', 'two');\n },\n function(arg1, arg2, callback){\n callback(null, 'three');\n },\n function(arg1, callback){\n // arg1 now equals 'three'\n callback(null, 'done');\n }\n ], function (err, result) {\n // result now equals 'done' \n });\n\n\n---------------------------------------\n\n\n### queue(worker, concurrency)\n\nCreates a queue object with the specified concurrency. Tasks added to the\nqueue will be processed in parallel (up to the concurrency limit). If all\nworkers are in progress, the task is queued until one is available. Once\na worker has completed a task, the task's callback is called.\n\n__Arguments__\n\n* worker(task, callback) - An asynchronous function for processing a queued\n task.\n* concurrency - An integer for determining how many worker functions should be\n run in parallel.\n\n__Queue objects__\n\nThe queue object returned by this function has the following properties and\nmethods:\n\n* length() - a function returning the number of items waiting to be processed.\n* concurrency - an integer for determining how many worker functions should be\n run in parallel. This property can be changed after a queue is created to\n alter the concurrency on-the-fly.\n* push(task, [callback]) - add a new task to the queue, the callback is called\n once the worker has finished processing the task.\n instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list.\n* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued\n* empty - a callback that is called when the last item from the queue is given to a worker\n* drain - a callback that is called when the last item from the queue has returned from the worker\n\n__Example__\n\n // create a queue object with concurrency 2\n\n var q = async.queue(function (task, callback) {\n console.log('hello ' + task.name);\n callback();\n }, 2);\n\n\n // assign a callback\n q.drain = function() {\n console.log('all items have been processed');\n }\n\n // add some items to the queue\n\n q.push({name: 'foo'}, function (err) {\n console.log('finished processing foo');\n });\n q.push({name: 'bar'}, function (err) {\n console.log('finished processing bar');\n });\n\n // add some items to the queue (batch-wise)\n\n q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {\n console.log('finished processing bar');\n });\n\n\n---------------------------------------\n\n\n### auto(tasks, [callback])\n\nDetermines the best order for running functions based on their requirements.\nEach function can optionally depend on other functions being completed first,\nand each function is run as soon as its requirements are satisfied. If any of\nthe functions pass an error to their callback, that function will not complete\n(so any other functions depending on it will not run) and the main callback\nwill be called immediately with the error. Functions also receive an object\ncontaining the results of functions which have completed so far.\n\n__Arguments__\n\n* tasks - An object literal containing named functions or an array of\n requirements, with the function itself the last item in the array. The key\n used for each function or array is used when specifying requirements. The\n syntax is easier to understand by looking at the example.\n* callback(err, results) - An optional callback which is called when all the\n tasks have been completed. The callback will receive an error as an argument\n if any tasks pass an error to their callback. If all tasks complete\n successfully, it will receive an object containing their results.\n\n__Example__\n\n async.auto({\n get_data: function(callback){\n // async code to get some data\n },\n make_folder: function(callback){\n // async code to create a directory to store a file in\n // this is run at the same time as getting the data\n },\n write_file: ['get_data', 'make_folder', function(callback){\n // once there is some data and the directory exists,\n // write the data to a file in the directory\n callback(null, filename);\n }],\n email_link: ['write_file', function(callback, results){\n // once the file is written let's email a link to it...\n // results.write_file contains the filename returned by write_file.\n }]\n });\n\nThis is a fairly trivial example, but to do this using the basic parallel and\nseries functions would look like this:\n\n async.parallel([\n function(callback){\n // async code to get some data\n },\n function(callback){\n // async code to create a directory to store a file in\n // this is run at the same time as getting the data\n }\n ],\n function(results){\n async.series([\n function(callback){\n // once there is some data and the directory exists,\n // write the data to a file in the directory\n },\n email_link: function(callback){\n // once the file is written let's email a link to it...\n }\n ]);\n });\n\nFor a complicated series of async tasks using the auto function makes adding\nnew tasks much easier and makes the code more readable.\n\n\n---------------------------------------\n\n\n### iterator(tasks)\n\nCreates an iterator function which calls the next function in the array,\nreturning a continuation to call the next one after that. Its also possible to\n'peek' the next iterator by doing iterator.next().\n\nThis function is used internally by the async module but can be useful when\nyou want to manually control the flow of functions in series.\n\n__Arguments__\n\n* tasks - An array of functions to run, each function is passed a callback it\n must call on completion.\n\n__Example__\n\n var iterator = async.iterator([\n function(){ sys.p('one'); },\n function(){ sys.p('two'); },\n function(){ sys.p('three'); }\n ]);\n\n node> var iterator2 = iterator();\n 'one'\n node> var iterator3 = iterator2();\n 'two'\n node> iterator3();\n 'three'\n node> var nextfn = iterator2.next();\n node> nextfn();\n 'three'\n\n\n---------------------------------------\n\n\n### apply(function, arguments..)\n\nCreates a continuation function with some arguments already applied, a useful\nshorthand when combined with other control flow functions. Any arguments\npassed to the returned function are added to the arguments originally passed\nto apply.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to automatically apply when the\n continuation is called.\n\n__Example__\n\n // using apply\n\n async.parallel([\n async.apply(fs.writeFile, 'testfile1', 'test1'),\n async.apply(fs.writeFile, 'testfile2', 'test2'),\n ]);\n\n\n // the same process without using apply\n\n async.parallel([\n function(callback){\n fs.writeFile('testfile1', 'test1', callback);\n },\n function(callback){\n fs.writeFile('testfile2', 'test2', callback);\n },\n ]);\n\nIt's possible to pass any number of additional arguments when calling the\ncontinuation:\n\n node> var fn = async.apply(sys.puts, 'one');\n node> fn('two', 'three');\n one\n two\n three\n\n---------------------------------------\n\n\n### nextTick(callback)\n\nCalls the callback on a later loop around the event loop. In node.js this just\ncalls process.nextTick, in the browser it falls back to setTimeout(callback, 0),\nwhich means other higher priority events may precede the execution of the callback.\n\nThis is used internally for browser-compatibility purposes.\n\n__Arguments__\n\n* callback - The function to call on a later loop around the event loop.\n\n__Example__\n\n var call_order = [];\n async.nextTick(function(){\n call_order.push('two');\n // call_order now equals ['one','two]\n });\n call_order.push('one')\n\n\n## Utils\n\n\n### memoize(fn, [hasher])\n\nCaches the results of an async function. When creating a hash to store function\nresults against, the callback is omitted from the hash and an optional hash\nfunction can be used.\n\n__Arguments__\n\n* fn - the function you to proxy and cache results from.\n* hasher - an optional function for generating a custom hash for storing\n results, it has all the arguments applied to it apart from the callback, and\n must be synchronous.\n\n__Example__\n\n var slow_fn = function (name, callback) {\n // do something\n callback(null, result);\n };\n var fn = async.memoize(slow_fn);\n\n // fn can now be used as if it were slow_fn\n fn('some name', function () {\n // callback\n });\n\n\n### unmemoize(fn)\n\nUndoes a memoized function, reverting it to the original, unmemoized\nform. Comes handy in tests.\n\n__Arguments__\n\n* fn - the memoized function\n\n\n### log(function, arguments)\n\nLogs the result of an async function to the console. Only works in node.js or\nin browsers that support console.log and console.error (such as FF and Chrome).\nIf multiple arguments are returned from the async function, console.log is\ncalled on each argument in order.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to apply to the function.\n\n__Example__\n\n var hello = function(name, callback){\n setTimeout(function(){\n callback(null, 'hello ' + name);\n }, 1000);\n };\n\n node> async.log(hello, 'world');\n 'hello world'\n\n\n---------------------------------------\n\n\n### dir(function, arguments)\n\nLogs the result of an async function to the console using console.dir to\ndisplay the properties of the resulting object. Only works in node.js or\nin browsers that support console.dir and console.error (such as FF and Chrome).\nIf multiple arguments are returned from the async function, console.dir is\ncalled on each argument in order.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to apply to the function.\n\n__Example__\n\n var hello = function(name, callback){\n setTimeout(function(){\n callback(null, {hello: name});\n }, 1000);\n };\n\n node> async.dir(hello, 'world');\n {hello: 'world'}\n\n\n---------------------------------------\n\n\n### noConflict()\n\nChanges the value of async back to its original value, returning a reference to the\nasync object.\n", + "readmeFilename": "README.md", + "_id": "async@0.1.22", + "_from": "async@~0.1.22" +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/.jshintrc b/node/node_modules/grunt-bower-task/node_modules/bower/.jshintrc new file mode 100644 index 000000000..2d1464ec3 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/.jshintrc @@ -0,0 +1,62 @@ +{ + "predef": [ + "console", + "describe", + "it", + "after", + "afterEach", + "before", + "beforeEach" + ], + + "indent": 2, + "node": true, + "devel": true, + + "bitwise": false, + "curly": false, + "eqeqeq": true, + "forin": false, + "immed": true, + "latedef": false, + "newcap": true, + "noarg": true, + "noempty": false, + "nonew": true, + "plusplus": true, + "regexp": false, + "undef": true, + "unused": true, + "quotmark": "single", + "strict": false, + "trailing": true, + + "asi": false, + "boss": false, + "debug": false, + "eqnull": true, + "es5": false, + "esnext": false, + "evil": false, + "expr": false, + "funcscope": false, + "globalstrict": false, + "iterator": false, + "lastsemic": false, + "laxbreak": true, + "laxcomma": false, + "loopfunc": true, + "multistr": false, + "onecase": true, + "regexdash": false, + "scripturl": false, + "smarttabs": false, + "shadow": false, + "sub": false, + "supernew": true, + "validthis": false, + + "nomen": false, + "onevar": false, + "white": true +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/.npmignore b/node/node_modules/grunt-bower-task/node_modules/bower/.npmignore new file mode 100644 index 000000000..e24e1d403 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/.npmignore @@ -0,0 +1,3 @@ +node_modules +components +.DS_Store \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/.travis.yml b/node/node_modules/grunt-bower-task/node_modules/bower/.travis.yml similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/.travis.yml rename to node/node_modules/grunt-bower-task/node_modules/bower/.travis.yml diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/CHANGELOG.md b/node/node_modules/grunt-bower-task/node_modules/bower/CHANGELOG.md new file mode 100644 index 000000000..bb403fcb8 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/CHANGELOG.md @@ -0,0 +1,117 @@ +# Changelog + +## 0.8.6 - 2013-04-03 +- Lock `unzip` to `0.1.4` to fix extraction of zip files in node `0.8.x` + An upcoming release to fix node `0.10.x` will be available soon. +- Fix error summary being displayed too soon. + +## 0.8.5 - 2013-03-04 +- Fix `cache-clean` command clearing the completion cache when the command was called with specific packages +- Add error message when an error is caught parsing an invalid `component.json` + +## 0.8.4 - 2013-03-01 +- Fix some more duplicate async callbacks being called twice +- Preserve new lines when saving `component.json` ([#285](https://github.com/twitter/bower/issues/285)) + +## 0.8.3 - 2013-02-27 +- Fix error when using the `update` command ([#282](https://github.com/twitter/bower/issues/282)) + +## 0.8.2 - 2013-02-26 +- Fix some errors in windows while removing directories, had to downgrade `rimraf` ([#274](https://github.com/twitter/bower/issues/274)) +- Prevent duplicate package names in error summaries ([#277](https://github.com/twitter/bower/issues/277)) + +## 0.8.1 - 2013-02-25 +- Fix some async callbacks being fired twice ([#274](https://github.com/twitter/bower/issues/274)) + +## 0.8.0 - 2013-02-24 +- __Add init command similar to `npm init`__ ([#219](https://github.com/twitter/bower/issues/219)) +- __Add devDependencies__ support ([#251](https://github.com/twitter/bower/issues/251)) +- __Add `--save-dev` flag to install/uninstall commands__ ([#258](https://github.com/twitter/bower/issues/258)) +- `cache-clean` command now clears links pointing to nonexistent folders ([#182](https://github.com/twitter/bower/issues/182)) +- Fix issue when downloading assets behind a proxy using `https` ([#230](https://github.com/twitter/bower/issues/230)) +- Fix --save saving unresolved components ([#240](https://github.com/twitter/bower/issues/240)) +- Fix issue when extracting some zip files ([#225](https://github.com/twitter/bower/issues/225)) +- Fix automatic conflict resolver not selecting the correct version +- Add `--sources` option to the `list` command ([#235](https://github.com/twitter/bower/issues/235)) +- Automatically clear cache when git commands fail with code 128 ([#216](https://github.com/twitter/bower/issues/216)) +- Fix `bower` not working correctly behind a proxy in some commands ([#208](https://github.com/twitter/bower/issues/208)) + +## 0.7.1 - 2013-02-20 +- Remove postinstall script from `bower` installation + +## 0.7.0 - 2013-02-01 +- __Ability to resolve conflicts__ ([#214](https://github.com/twitter/bower/issues/214)) +- __Ability to search and publish to different endpoints by specifiying them in the `.bowerrc` file__ +- __Experimental autocompletion__ +- __Ability to exclude (ignore) files__ +- Fix minor issues in the cache clean command +- Better error message for invalid semver tags ([#185](https://github.com/twitter/bower/issues/185)) +- Only show discover message in the list command only if there are packages +- Fix mismatch issue due to reading cached component.json files ([#214](https://github.com/twitter/bower/issues/214)) +- Better error messages when reading invalid .bowerrc files ([#220](https://github.com/twitter/bower/issues/220)) +- Fix update command when used in packages pointing to assets ([#197](https://github.com/twitter/bower/issues/197)) +- Bower now obeys packages's `.bowerrc` if they define a different `json` ([#205](https://github.com/twitter/bower/issues/205)) + +## 0.6.8 - 2012-12-14 +- Improve list command + - Does not fetch versions if not necessary (for --map and --paths options) + - Add --offline option to prevent versions from being fetched +- Fix uninstall command not firing the `end` event +- Fix error when executing an unknown command ([#179](https://github.com/twitter/bower/issues/179)) +- Fix help for the ls command (alias of list) + +## 0.6.7 - 2012-12-10 +- Fix uninstall removing all unsaved dependencies ([#178](https://github.com/twitter/bower/issues/178)) +- Fix uninstall --force flag in some cases +- Add --silent option to the register option, to avoid questioning +- Fix possible issues with options in some commands +- Fix error reporting when reading invalid project component.json + +## 0.6.6 - 2012-12-03 +- Improve error handling while reading component.json +- Fix package name not being correctly collected in the error summary + +## 0.6.5 - 2012-12-01 +- Fix error summary not being displayed in some edge cases +- Fix bower not fetching latest commits correctly in some cases + +## 0.6.4 - 2012-11-29 +- Fix permission on downloaded files ([#160](https://github.com/twitter/bower/issues/160)) + +## 0.6.3 - 2012-11-24 +- Fix version not being correctly set for local packages ([#155](https://github.com/twitter/bower/issues/155)) + +## 0.6.2 - 2012-11-23 +- Fix uninstall --save when there is no component.json + +## 0.6.1 - 2012-11-22 +- Fix uninstall when the project component.json has no deps saved ([#153](https://github.com/twitter/bower/issues/153)) +- Fix uncaught errors when using file writter (they are now caught and reported) +- Fix temporary directories not being deleted when an exception occurs ([#153](https://github.com/twitter/bower/issues/140)) + +## 0.6.0 - 2012-11-21 +- __Add link command__ (similar to npm) +- Fix error reporting for nested deps +- Abort if a repository is detected when installing. + This is useful to prevent people from loosing their work +- Minor fixes and improvements + +## 0.5.1 - 2012-11-20 +- Add errors summary to the end of install/update commands +- Add windows instructions to the README + +## 0.5.0 - 2012-11-19 +- __Remove package.json support__ +- __Support for local path repositories__ ([#132](https://github.com/twitter/bower/issues/132)) +- `install --save` now saves the correct tag (e.g: ~0.0.1) instead of 'latest' +- `install --save` now saves packages pointing directly to assets correctly +- Bower automatically creates a component.json when install with `--save` is used +- Fix issues with list command ([#142](https://github.com/twitter/bower/issues/142)) +- Fix local paths not being saved when installing with --save ([#114](https://github.com/twitter/bower/issues/114)) +- `uninstall` now uninstalls nested dependencies if they are not shared ([#83](https://github.com/twitter/bower/issues/83)) +- `uninstall` now warns when a dependency conflict occurs and aborts. + It will only proceed if the `--force` flag is passed +- Bower now detects mismatches between the version specified in the component.json and the tag, informing the user +- `bower ls` now informs when a package has a new commit (for non-tagged repos) +- Add jshintrc and fix a lot of issues related with JSHint warnings +- `bower register` now prompts if the user really wants to proceed diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/LICENSE new file mode 100644 index 000000000..fc4e20bc0 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/LICENSE @@ -0,0 +1,7 @@ +Copyright (c) 2012 Twitter 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. \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/Makefile b/node/node_modules/grunt-bower-task/node_modules/bower/Makefile new file mode 100644 index 000000000..e390fc673 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/Makefile @@ -0,0 +1,4 @@ +test: + ./node_modules/.bin/mocha -R spec -t 10000 + +.PHONY: test \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/README.md new file mode 100644 index 000000000..7104cf997 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/README.md @@ -0,0 +1,363 @@ +BOWER [![Build Status](https://secure.travis-ci.org/twitter/bower.png)](http://travis-ci.org/twitter/bower) +===== + +### Introduction + +Bower is a package manager for the web. Bower lets you easily install assets such as images, CSS and JavaScript, and manages dependencies for you. + +For example, to install a package, run: + + bower install jquery + +This will download jQuery to `./components/jquery`. That's it. The idea is that Bower does package management and package management only. + +### Installing Bower + +Bower is installed using [Node](http://nodejs.org/) and [npm](http://npmjs.org/) (oh my, how meta). + + npm install bower -g + +### Usage + +Your best friend at this stage is probably `bower --help`. + +To install a package: + + bower install jquery + bower install git://github.com/components/jquery.git + bower install components/jquery (same as above) + bower install http://foo.com/jquery.awesome-plugin.js + bower install ./repos/jquery + +As you can see, packages can be installed by name, Git endpoint, GitHub shorthand, URL or local path. +If you install from a URL that points to a zip or tar file, bower will automatically extract its contents. +When tags are available in the endpoint, you can specify a [semver](http://semver.org/) tag to fetch concrete versions: + + bower install jquery#1.8.1 + bower install git://github.com/components/jquery.git#~1.8.1 + bower install components/jquery#1.8.x + +Bower also works with private Git repositories. Simply reference them by their SSH endpoint: + + bower install git@github.com:user/private-package.git + +[View all packages available through Bower's registry](http://sindresorhus.com/bower-components/). + +During install you can have Bower add an entry to your component.json as well: + + bower install --save jquery + +To update a package, reference it by name: + + bower update jquery-ui + +To list installed packages: + + bower list + +To search for packages: + + bower search [name] + +To list all the available packages, just call `bower search` without specifying a name. + +To clean the cache: + + bower cache-clean [name] + +Several packages can be cleaned at the same time. +To clean the entire cache, just call `bower cache-clean` without any names. +Also, both the install and update commands have a `--force` flag that tells bower to bypass the cache and always fetch remote sources. + +You can disable colors by using the `--no-color` flag. + +### Bower Configuration + +Bower can be configured by creating a .bowerrc file in your home folder (usually ~/.bowerrc) with one or all of the following configuration parameters. You can also configure Bower on a per-project basis by creating a .bowerrc file in the project directory, Bower will merge this configuration with the configuration found in your home directory. This allows you to version your project specific Bower configuration with the rest of your code base. + +```json +{ + "directory" : "components", + "json" : "component.json", + "endpoint" : "https://bower.herokuapp.com" +} +``` + +To run your own Bower Endpoint for custom components/packages that are behind a firewall you can use a simple implementation of bower server at https://github.com/twitter/bower-server. + +The __searchpath__ array provides additional URLs of read-only Bower registries that should be consulted to look up components. This is most typically used if your business wishes to +house some components internally while still taking advantage of public Bower registries. For example, you might configure the following: + +```json +{ + "directory" : "components", + "json" : "component.json", + "endpoint" : "http://bower.mycompany.com", + "searchpath" : ["https://bower.herokuapp.com"] +} +``` + +Bower will first look to **http://bower.mycompany.com** while trying to find your components. If not found, the main registry at **https://bower.herokuapp.com** will be consulted to see if a copy of the resource can be retrieved. + + +### Defining a package + +You can create a `component.json` file in your project's root, specifying all of its dependencies. This is similar to Node's `package.json`, or Ruby's `Gemfile`, and is useful for locking down a project's dependencies. + +```json +{ + "name": "myProject", + "version": "1.0.0", + "main": "./path/to/main.css", + "dependencies": { + "jquery": "~1.7.2" + } +} +``` + +Put this under your project's root, listing all of your dependencies. When you run `bower install`, Bower will read this `component.json` file, resolve all the relevant dependencies and install them. + +For now, `name`, `version`, `main`, `dependencies`, `devDependencies`, and `ignore` are the only properties that are used by Bower. If you have several files you're distributing as part of your package, pass an array to `main` like this: + +```json +{ + "name": "myProject", + "version": "1.0.0", + "main": ["./path/to/app.css", "./path/to/app.js", "./path/to/sprite.img"], + "dependencies": { + "jquery": "~1.7.2" + } +} +``` + +Bower only recognizes versions that follow the [semver](http://semver.org/) specification. +There should only be at most one file per file type in the `main` list. So only one `.js` or `.css`. + +You can also point to packages by adding their URL or file path in the dependency's property. + +```json +{ + "dependencies": { + "eventEmitter": "Wolfy87/EventEmitter", // GitHub short URL + "eventEmitter": "Wolfy87/EventEmitter#>=3", // with version + "eventEmitter": "git://github.com/Wolfy87/EventEmitter", + "eventEmitter": "git@github.com:Wolfy87/EventEmitter.git" + } +} +``` + +Chances are you have a bunch of extra stuff in the repo that are not needed in production. List these non-necessary file paths in `ignore`. + +```json +{ + "ignore": [ + "tests/", + "**/*.txt" + ] +} +``` + +You may add non-essential packages in `devDependencies`. This is useful for packages aren't required to support the package, but that are used in your project, i.e. to build documentation, run a demo, or run tests. + +```json +{ + "devDependencies": [ + "qunit": "~1" + ] +} +``` + +### Installing dependencies + +Dependencies are installed locally via the `bower install` command. First they’re resolved to find conflicts. Then they’re downloaded and unpacked in a local subdirectory called `./components`, for example: + + +``` +/component.json +/components/jquery/index.js +/components/jquery/component.json +``` + +You can also install packages one at a time `bower install git://my/git/thing` + +There are no system wide dependencies, no dependencies are shared between different apps, and the dependency tree is flat. + +### Deploying + +The easiest approach is to use Bower statically, just reference the packages manually from a script tag: + + + +For more complex projects, you'll probably want to concatenate your scripts. Bower is just a package manager, but there are lots of awesome libraries out there to help you do this, such as [Sprockets](https://github.com/sstephenson/sprockets) and [RequireJS](http://requirejs.org/). + +For example, to use Sprockets: + +```ruby +environment = Sprockets::Environment.new +environment.append_path 'components' +environment.append_path 'public' +run environment +``` + +### Package Consumption + +Bower also makes available a source mapping – this can be used by build tools to easily consume Bower components. + +If you pass the option `--map` to bower's `list` command, it will generate a JSON with dependency objects. Alternatively, you can pass the `--paths` flag to the `list` command to get a simple path to name mapping: + +```json +{ + "backbone": "components/backbone/index.js", + "jquery": "components/jquery/index.js", + "underscore": "components/underscore/index.js" +} +``` + +### Authoring packages + +To register a new package, it's as simple as specifying a `component.json`, pushing the package to a Git endpoint, say GitHub, and running: + + bower register myawesomepackagename git://github.com/maccmans/face + +There's no authentication or user management. It's on a first come, first served basis. Think of it like a URL shortener. Now anyone can run `bower install myawesomepackagename`, and get your library installed. + +There is no direct way to unregister a package yet. Meanwhile you can request it [here](https://github.com/twitter/bower/issues/120). + +### Philosophy + +Currently, people are managing dependencies, such as JavaScript libraries, manually. This sucks, and we want to change it. + +In a nutshell, Bower is a generic tool which will resolve dependencies and lock packages down to a version. It runs over Git, and is package-agnostic. A package may contain JavaScript, CSS, images, etc., and doesn't rely on any particular transport (AMD, CommonJS, etc.). + +Bower then makes available a simple programmatic API which exposes the package dependency model, so that existing build tools (like Sprockets, LoadBuilder, curls.js, Ender, etc.) can consume it and build files accordingly. + + +### Programmatic API + +Bower provides a pretty powerful programmatic api. All commands can be accessed through the `bower.commands` object. + +```js +var bower = require('bower'); + +bower.commands + .install(paths, options) + .on('end', function (data) { + data && console.log(data); + }); + +bower.commands + .search('jquery', {}) + .on('packages', function(packages) { + /* `packages` is a list of packages returned by searching for 'jquery' */ + }); + +``` + +Commands emit four types of events: `data`, `end`, `result`, and `error`. `error` will only be emitted if something goes wrong. Not all commands emit all events; for a detailed look, check out the code in `lib/commands`. `data` is typically a colorized string, ready to show to an end user. `search` and `lookup` emit `packages` and `package`, respectively. Those events contain a json representation of the result of the command. + +For a better of idea how this works, you may want to check out [our bin file](https://github.com/twitter/bower/blob/master/bin/bower). + +For the install command, there is an additional `package` event that is emitted for each installed/uninstalled package. + + +### Completion + +**experimental** + +Based on the completion feature and fantastic work done in +[npm](https://npmjs.org/doc/completion.html), Bower now has an experimental +`completion` command that works similarly. + +This command will output a Bash / ZSH script to put into your `~/.bashrc`, `~/.bash_profile` or `~/.zshrc` file. + +``` +bower completion >> ~/.bash_profile +``` + +*This doesn't work for Windows user, even with Cygwin.* + + +### Windows users + +A lot of people are experiencing problems using bower on windows because [msysgit](http://code.google.com/p/msysgit/) must be installed correctly. +Be sure to check the option shown above, otherwise it will simply not work: + +![msysgit](http://f.cl.ly/items/2V2O3i1p3R2F1r2v0a12/mysgit.png) + + +### FAQ + +**What distinguishes Bower from Jam, Volo or Ender? What does it do better?** + +Bower is a lower level component than Jam, Volo, or Ender. These managers could consume Bower as a dependency. + +Bower's aim is simply to install Git paths, resolve dependencies from a `component.json`, check versions, and then provide an API which reports on these things. Nothing more. This is a major diversion from past attempts at browser package management. + +Bower is working under the assumption that there is a single, common problem in frontend application development: dependency resolution. Past attempts (Jam, Volo, Ender) try to tackle this problem in such a way that they actually end up alienating and further segregating the JavaScript community around transports (Sprockets, CommonJS, RequireJS, regular script tags). + +Bower offers a generic, unopinionated solution to the problem of package management, while exposing an API that can be consumed by a more opinionated build stack. + +**Volo is an arguably more established project and works with the GitHub search API. Will it take long for Bower to contain a decent number of packages?** + +Bower (being a Git powered package manager) should, in theory, be capable of consuming every package that Volo does, with the additional benefit of supporting internal networks and other Git repositories not hosted on GitHub. + +**We recently saw what happened when the main NPM registry went down. Is a single point of failure possible for Bower and if so, do you have redundancy planned?** + +There's no redundancy planned at the moment, as Bower just installs Git URLs. It's up to the URL provider to establish redundancy. + +**Isn't having a `package.json` file going to conflict with my npm's `package.json`? Will this be a problem?** + +Don't use a `package.json` – use a `component.json`. + +**Bower is an open-source Twitter project. How well can we expect it to be maintained in the future?** + +Twitter is in the process of migrating its frontend architecture onto Bower, so it's fairly safe to say it will be maintained and invested in going forward. + + +### Contact + +Have a question? + +- [StackOverflow](http://stackoverflow.com/questions/tagged/bower) +- [Mailinglist](http://groups.google.com/group/twitter-bower) - twitter-bower@googlegroups.com +- [\#bower](http://webchat.freenode.net/?channels=bower) on Freenode + + +### Authors + ++ [@fat](http://github.com/fat) ++ [@maccman](http://github.com/maccman) ++ [@satazor](http://github.com/satazor) + +Thanks for assistance and contributions: + ++ [@addyosmani](http://github.com/addyosmani) ++ [@angus-c](http://github.com/angus-c) ++ [@borismus](http://github.com/borismus) ++ [@chriseppstein](http://github.com/chriseppstein) ++ [@danwrong](http://github.com/danwrong) ++ [@desandro](http://github.com/desandro) ++ [@isaacs](http://github.com/isaacs) ++ [@josh](http://github.com/josh) ++ [@jrburke](http://github.com/jrburke) ++ [@mklabs](http://github.com/mklabs) ++ [@paulirish](http://github.com/paulirish) ++ [@rvagg](http://github.com/rvagg) ++ [@sindresorhus](http://github.com/sindresorhus) ++ [@SlexAxton](http://github.com/SlexAxton) ++ [@sstephenson](http://github.com/sstephenson) ++ [@tomdale](http://github.com/tomdale) ++ [@uzquiano](http://github.com/uzquiano) ++ [@visionmedia](http://github.com/visionmedia) ++ [@wagenet](http://github.com/wagenet) ++ [@wycats](http://github.com/wycats) ++ [@sindresorhus](http://github.com/sindresorhus) ++ [@hemanth](http://github.com/hemanth) ++ [@wibblymat](http://github.com/wibblymat) ++ [@marcelombc](http://github.com/marcelombc) + +## License + +Copyright 2012 Twitter, Inc. + +Licensed under the MIT License diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/bin/bower b/node/node_modules/grunt-bower-task/node_modules/bower/bin/bower new file mode 100755 index 000000000..9840bf0a3 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/bin/bower @@ -0,0 +1,44 @@ +#!/usr/bin/env node + +var semver = require('semver'); +var nopt = require('nopt'); +var path = require('path'); +var pkg = require(path.join(__dirname, '..', 'package.json')); + +var template = require('../lib/util/template'); +var bower = require('../lib'); + +var command; +var options; +var shorthand; +var input = process.argv; +var cmdList = Object.keys(bower.commands); +var nodeVer = process.version; +var reqVer = pkg.engines.node; + +process.title = 'bower'; + +if (reqVer && !semver.satisfies(nodeVer, reqVer)) { + throw new Error('Required: node ' + reqVer); +} + +shorthand = { 'v': ['--version'] }; +options = { version: Boolean }; +options = nopt(options, shorthand, process.argv); + +bower.version = pkg.version; + +if (options.version) return console.log(bower.version); +if (~cmdList.indexOf(command = options.argv.remain && options.argv.remain.shift())) bower.command = command; + +bower.commands[bower.command || 'help'].line(input) + .on('data', function (data) { + if (data) console.log(data); + }) + .on('end', function (data) { + if (data) console.log(data); + }) + .on('error', function (err) { + if (options.verbose) throw err; + else console.log(template('error', { message: err.message }, true)); + }); \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/cache-clean.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/cache-clean.js new file mode 100644 index 000000000..093767605 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/cache-clean.js @@ -0,0 +1,164 @@ +// ========================================== +// BOWER: CacheClean API +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var Emitter = require('events').EventEmitter; +var async = require('async'); +var nopt = require('nopt'); +var rimraf = require('rimraf'); +var path = require('path'); +var glob = require('glob'); +var fs = require('fs'); +var _ = require('lodash'); + +var help = require('./help'); +var config = require('../core/config'); +var template = require('../util/template'); +var fileExists = require('../util/file-exists'); + +var optionTypes = { help: Boolean }; +var shorthand = { 'h': ['--help'] }; + +var processCachedPackage = function (emitter, pkg, next) { + removeCachedPackage(pkg, function (err, exists) { + if (err) { + emitter.emit('error', err); + return next(); + } + + if (exists) { + template('action', { name: 'cache cleared', shizzle: pkg }) + .on('data', emitter.emit.bind(emitter, 'data')); + } + + next(); + }); +}; + +var removeCachedPackage = function (pkg, next) { + var folder = path.join(config.cache, pkg); + + fileExists(folder, function (exists) { + if (!exists) return next(null, false); + rimraf(folder, function (err) { + if (err) return next(err); + next(null, true); + }); + }); +}; + +var processLinkedPackage = function (emitter, pkg, next) { + checkAndRemoveLinkToPackage(pkg, function (err, removed) { + if (err) { + emitter.emit('error', err); + return next(); + } + + if (removed) { + template('action', { name: 'link cleared', shizzle: pkg }) + .on('data', emitter.emit.bind(emitter, 'data')); + } + + next(); + }); +}; + +var checkAndRemoveLinkToPackage = function (pkg, next) { + var folder = path.join(config.links, pkg); + + fs.readlink(folder, function (err, linkString) { + if (err && err.code === 'ENOENT') return next(); + + fileExists(linkString, function (exists) { + if (!exists) { + return rimraf(folder, function (err) { + if (err) return next(err); + next(null, true); + }); + } + + next(null, false); + }); + }); +}; + +module.exports = function (pkgs) { + var emitter = new Emitter; + + async.parallel({ + cache: function (next) { + if (!pkgs || !pkgs.length) { + glob('./*', { cwd: config.cache }, function (err, dirs) { + if (err) { + emitter.emit('error', err); + return next(); + } + + var pkgs = dirs.map(function (dir) { return dir.replace(/^\.\//, ''); }); + async.forEach(pkgs, processCachedPackage.bind(this, emitter), next); + }); + } else { + pkgs = _.uniq(pkgs); + async.forEach(pkgs, processCachedPackage.bind(this, emitter), next); + } + }, + links: function (next) { + if (!pkgs || !pkgs.length) { + glob('./*', { cwd: config.links }, function (err, dirs) { + if (err) { + emitter.emit('error', err); + return next(); + } + + var pkgs = dirs.map(function (dir) { return dir.replace(/^\.\//, ''); }); + async.forEach(pkgs, processLinkedPackage.bind(this, emitter), next); + }); + } else { + pkgs = _.uniq(pkgs); + async.forEach(pkgs, processLinkedPackage.bind(this, emitter), next); + } + }, + completion: function (next) { + // Do not run completion cache if packages where passed + if (pkgs && pkgs.length) return next(); + + rimraf(config.completion, function (err) { + if (err) { + emitter.emit('error', err); + return next(); + } + + template('action', { name: 'completion cleared', shizzle: 'completion cache' }) + .on('data', emitter.emit.bind(emitter, 'data')); + + next(); + }); + } + }, emitter.emit.bind(emitter, 'end')); + + return emitter; +}; + +module.exports.line = function (argv) { + var options = nopt(optionTypes, shorthand, argv); + var pkgs = options.argv.remain.slice(1); + + if (options.help) return help('cache-clean'); + return module.exports(pkgs); +}; + +module.exports.completion = function (opts, cb) { + glob('./*', { cwd: config.cache }, function (err, dirs) { + if (err) return cb(err); + dirs = dirs.map(function (dir) { + return dir.replace(/^\.\//, ''); + }); + cb(null, dirs); + }); +}; + +module.exports.completion.options = shorthand; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/completion.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/completion.js new file mode 100644 index 000000000..7634e67ec --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/completion.js @@ -0,0 +1,112 @@ +// ========================================== +// BOWER: Completion API +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var Emitter = require('events').EventEmitter; +var path = require('path'); +var nopt = require('nopt'); +var mkdirp = require('mkdirp'); + +var template = require('../util/template'); +var complete = require('../util/completion'); +var config = require('../core/config'); +var help = require('./help'); + +var optionTypes = { help: Boolean }; +var shorthand = { 'h': ['--help'] }; + +module.exports = function (argv, env) { + env = env || process.env; + + var emitter = new Emitter; + var commands = require('../commands'); + + // top level flags + var flags = ['--no-color', '--help', '--version']; + + var done = function done() { + process.nextTick(function () { + emitter.emit('end'); + }); + + return emitter; + }; + + // if the COMP_* isn't in the env, then just dump the script. + if (!env.COMP_CWORD) { + template('completion').on('data', emitter.emit.bind(emitter, 'end')); + return emitter; + } + + // parse environment and arguments, returns a hash of completion config. + var opts = complete(argv, env); + + // if only one word, complete the list of command or top level flags + if (opts.w === 1) { + if (opts.word.charAt(0) === '-') complete.log(flags, opts); + else complete.log(Object.keys(commands), opts); + return done(); + } + + // try to find the bower command. first thing after all the configs. + var parsed = opts.conf = nopt({}, {}, opts.partialWords, 0); + var cmd = parsed.argv.remain[0]; + + // unable to find a command, complete the lisf of commands + if (!cmd) { + complete.log(Object.keys(commands), opts); + return done(); + } + + // if words[0] is a bower command, then complete on it. + cmd = commands[cmd]; + + if (cmd && cmd.completion) { + // prior to that, ensure the completion cache directory is created first + mkdirp(path.join(config.completion), function (err) { + if (err) return emitter.emit('error', err); + + var options = cmd.completion.options; + if (options && opts.word.charAt(0) === '-') { + complete.log(Object.keys(options).map(function (option) { + return opts.word.charAt(1) === '-' ? options[option][0] : '-' + option; + }), opts); + return done(); + } + + cmd.completion(opts, function (err, data) { + if (err) return emitter.emit('error', err); + + // completing options, then append top level flags + if (opts.word.charAt(0) === '-') data = data.concat(flags); + + complete.log(data, opts); + + done(); + }); + }); + + return emitter; + } + + // otherwise, do nothing + return emitter; +}; + +module.exports.line = function (argv) { + var emitter = new Emitter; + var options = nopt(optionTypes, shorthand, argv); + + if (options.help) return help('completion'); + + module.exports(options.argv.remain.slice(2), process.env) + .on('data', emitter.emit.bind(emitter, 'data')) + .on('error', emitter.emit.bind(emitter, 'error')) + .on('end', emitter.emit.bind(emitter, 'end')); + + return emitter; +}; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/help.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/help.js new file mode 100644 index 000000000..478a6da77 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/help.js @@ -0,0 +1,49 @@ +// ========================================== +// BOWER: Help API +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var events = require('events'); +var nopt = require('nopt'); +var _ = require('lodash'); + +var template = require('../util/template'); +var config = require('../core/config'); + +module.exports = function (name) { + var context = {}; + var emitter = new events.EventEmitter; + var commands = require('../commands'); + + // Aliases + // At the moment we just have the ls, but we might have more + switch (name) { + case 'ls': + name = 'list'; + break; + } + + var validCommand = !!(name && commands[name]); + var templateName = validCommand ? 'help-' + name : 'help'; + + if (!validCommand) context = { commands: Object.keys(commands).join(', ') }; + _.extend(context, config); + + template(templateName, context) + .on('data', emitter.emit.bind(emitter, 'end')); + + return emitter; +}; + +module.exports.line = function (argv) { + var options = nopt({}, {}, argv); + var paths = options.argv.remain.slice(1); + return module.exports(paths[0]); +}; + +module.exports.completion = function (opts, cb) { + return cb(null, Object.keys(require('../commands'))); +}; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/index.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/index.js new file mode 100644 index 000000000..1e3aad92b --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/index.js @@ -0,0 +1,24 @@ +// ========================================== +// BOWER: Public Commands List +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +module.exports = { + 'help': require('./help'), + 'install': require('./install'), + 'list': require('./list'), + 'ls': require('./list'), + 'uninstall': require('./uninstall'), + 'update': require('./update'), + 'link': require('./link'), + 'lookup': require('./lookup'), + 'info': require('./info'), + 'init': require('./init'), + 'register': require('./register'), + 'search': require('./search'), + 'cache-clean': require('./cache-clean'), + 'completion': require('./completion') +}; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/info.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/info.js new file mode 100644 index 000000000..4d746ae87 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/info.js @@ -0,0 +1,50 @@ +// ========================================== +// BOWER: Lookup API +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var Emitter = require('events').EventEmitter; +var nopt = require('nopt'); + +var template = require('../util/template'); +var source = require('../core/source'); +var install = require('./install'); +var help = require('./help'); + +var optionTypes = { help: Boolean }; +var shorthand = { 'h': ['--help'] }; + +module.exports = function (name) { + var emitter = new Emitter; + + if (name) { + source.info(name, function (err, result) { + if (err) return emitter.emit('error', err); + emitter.emit('end', result); + }); + } + + return emitter; +}; + +module.exports.line = function (argv) { + var emitter = new Emitter; + var options = nopt(optionTypes, shorthand, argv); + var names = options.argv.remain.slice(1); + + if (options.help || !names.length) return help('info'); + + module.exports(names[0]) + .on('error', emitter.emit.bind(emitter, 'error')) + .on('end', function (data) { + template('info', data).on('data', emitter.emit.bind(emitter, 'end')); + }); + + return emitter; +}; + +module.exports.completion = install.completion; +module.exports.completion.options = shorthand; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/init.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/init.js new file mode 100644 index 000000000..208c76d42 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/init.js @@ -0,0 +1,150 @@ +// ========================================== +// BOWER: Init API +// ========================================== +// Copyright 2013 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + + +var path = require('path'); +var fs = require('fs'); +var util = require('util'); + +var nopt = require('nopt'); +var promptly = require('promptly'); +var _ = require('lodash'); + +var help = require('./help'); +var Manager = require('../core/manager'); +var config = require('../core/config'); + +var optionTypes = { help: Boolean }; +var shorthand = { 'h': ['--help'] }; + +var commonIgnore = ['**/.*', 'node_modules', 'components']; + +var Init = function () { + Manager.call(this); +}; + +util.inherits(Init, Manager); + +Init.prototype.getDependenciesJSON = function () { + var dependencies = Object.keys(this.dependencies); + var remaining = dependencies.length; + var json = {}; + + dependencies.forEach(function (name) { + var pkg = this.dependencies[name][0]; + + pkg.on('loadJSON', function () { + // TODO: use fetch endpoint here + json[pkg.name] = '~' + pkg.version; + remaining -= 1; + if (remaining === 0) { + this.manager.emit('loadDependencies', json); + } + }).loadJSON(); + }, this); + + if (remaining === 0) { + this.emit('loadDependencies', json); + } + + return this; +}; + +Init.prototype.getMain = function (name) { + name = path.basename(name, '.js'); + if (fs.existsSync(path.join(process.cwd(), 'index.js'))) { + return 'index.js'; + } else if (fs.existsSync(path.join(process.cwd(), name + '.js'))) { + return name + '.js'; + } else { + return null; + } +}; + +Init.prototype.showPrompt = function (question, cb) { + var prompt = question.prompt + ': [' + (question.yesno ? 'y' : question.value) + ']'; + if (question.yesno) { + promptly.confirm(prompt, {'default': 'y'}, cb); + } else { + promptly.prompt(prompt, {'default': question.value}, cb); + } + this.emit('prompt', prompt); +}; + +Init.prototype.prompts = function (dependencies) { + var main = this.json.main || this.getMain(this.json.name) || ''; + + var questions = _.compact([ + {key: 'name', prompt: 'name', value: this.json.name, yesno: false}, + {key: 'version', prompt: 'version', value: this.json.version, yesno: false}, + {key: 'main', prompt: 'main file', value: main, yesno: false}, + _.size(dependencies) ? {key: 'dependencies', prompt: 'add current components as dependencies? (y/n)', value: dependencies, yesno: true} : null, + {key: 'ignore', prompt: 'add commonly ignored files to ignore list? (y/n)', value: commonIgnore, yesno: true} + ]); + var index = 0; + var question = questions[index]; + + var cb = function (err, value) { + if (question.yesno) { + if (value) { + this.json[question.key] = question.value; + } + } else if (value) { + this.json[question.key] = value; + } + index += 1; + if (index < questions.length) { + question = questions[index]; + this.showPrompt(question, cb); + } else { + this.emit('prompts'); + } + }.bind(this); + + this.showPrompt(question, cb); +}; + +Init.prototype.save = function (data) { + fs.writeFileSync(path.join(this.cwd, config.json), JSON.stringify(data, null, 2)); +}; + +module.exports = function () { + var init = new Init(); + + init + .on('resolveLocal', init.loadJSON.bind(init)) + .on('loadJSON', init.getDependenciesJSON.bind(init)) + .on('loadDependencies', init.prompts.bind(init)) + .on('prompts', function () { + init.save(init.json); + init.emit('end'); + }) + .resolveLocal(); + + return init; +}; + +module.exports.Init = Init; // Purely for testing + +module.exports.line = function (argv) { + var options = nopt(optionTypes, shorthand, argv); + if (options.help) return help('init'); + return module.exports(); +}; + +module.exports.completion = function (opts, cb) { + var word = opts.word; + + // completing options? + if (word.charAt(0) === '-') { + return cb(null, Object.keys(optionTypes).map(function (option) { + return '--' + option; + })); + } +}; + diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/install.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/install.js new file mode 100644 index 000000000..e84e45960 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/install.js @@ -0,0 +1,81 @@ +// ========================================== +// BOWER: Install API +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var Emitter = require('events').EventEmitter; +var nopt = require('nopt'); +var fs = require('fs'); +var path = require('path'); + +var Manager = require('../core/manager'); +var config = require('../core/config'); +var source = require('../core/source'); +var save = require('../util/save'); +var help = require('./help'); + +var optionTypes = { help: Boolean, save: Boolean, 'save-dev': Boolean, force: Boolean, 'force-latest': Boolean, production: Boolean }; +var shorthand = { 'h': ['--help'], 'S': ['--save'], 'D': ['--save-dev'], 'f': ['--force'], 'F': ['--force-latest'], 'p': ['--production'] }; + +module.exports = function (paths, options) { + options = options || {}; + + var emitter = new Emitter; + var manager = new Manager(paths, { + force: options.force, + forceLatest: options['force-latest'], + production: options.production + }); + + manager + .on('data', emitter.emit.bind(emitter, 'data')) + .on('error', emitter.emit.bind(emitter, 'error')) + .on('resolve', function (resolved) { + // Handle save/save-dev + if (resolved && (options.save || options['save-dev'])) { + save(manager, paths, !options.save, emitter.emit.bind(emitter, 'end')); + } else { + emitter.emit('end'); + } + }) + .resolve(); + + return emitter; +}; + +module.exports.line = function (argv) { + var options = nopt(optionTypes, shorthand, argv); + var paths = options.argv.remain.slice(1); + + if (options.help) return help('install'); + return module.exports(paths, options); +}; + +module.exports.completion = function (opts, cb) { + var cache = path.join(config.completion, 'install.json'); + var done = function done(err, results) { + if (err) return cb(err); + var names = results.map(function (pkg) { + return pkg.name; + }); + + return cb(null, names); + }; + + fs.readFile(cache, function (err, body) { + if (!err) return done(null, JSON.parse(body)); + + // expected error, do the first request and cache the results + source.all(function (err, results) { + if (err) return cb(err); + fs.writeFile(cache, JSON.stringify(results, null, 2), function (err) { + done(err, results); + }); + }); + }); +}; + +module.exports.completion.options = shorthand; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/link.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/link.js new file mode 100644 index 000000000..ac705063a --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/link.js @@ -0,0 +1,121 @@ +// ========================================== +// BOWER: Link API +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var Emitter = require('events').EventEmitter; +var nopt = require('nopt'); +var fs = require('fs'); +var path = require('path'); +var mkdirp = require('mkdirp'); +var rimraf = require('rimraf'); + +var Manager = require('../core/manager'); +var help = require('./help'); +var template = require('../util/template'); +var config = require('../core/config'); +var isRepo = require('../util/is-repo'); + +var optionTypes = { help: Boolean }; +var shorthand = { 'h': ['--help'] }; + +function linkSelf(emitter) { + var manager = new Manager; + + manager + .on('error', emitter.emit.bind('error')) + .once('loadJSON', function () { + var destPath = path.join(config.links, manager.name); + var srcPath = process.cwd(); + + deleteLink(destPath, function (err) { + if (err) return emitter.emit('error', err); + + createLink(srcPath, destPath, function (err) { + if (err) return emitter.emit('error', err); + + template('link', { src: srcPath, dest: destPath }) + .on('data', emitter.emit.bind(emitter, 'end')); + }); + }); + }).loadJSON(); +} + +function linkTo(name, emitter) { + var destPath = path.join(process.cwd(), config.directory, name); + var srcPath = path.join(config.links, name); + + deleteLink(destPath, function (err) { + if (err) return emitter.emit('error', err); + + createLink(srcPath, destPath, function (err) { + if (err) return emitter.emit('error', err); + + template('link', { src: srcPath, dest: destPath }) + .on('data', emitter.emit.bind(emitter, 'end')); + }); + }); +} + +function deleteLink(dest, callback) { + // Delete symlink if already present + // Beware that if the target is a git repo, we can't proceed + isRepo(dest, function (is) { + if (is) return callback(new Error(dest + ' is a local repository, please remove it manually')); + + fs.lstat(dest, function (err) { + if (!err || err.code !== 'ENOENT') rimraf(dest, callback); + else callback(); + }); + }); +} + +function createLink(src, dest, callback) { + var destDir = path.dirname(dest); + + // Create directory + mkdirp(destDir, function (err) { + if (err) return callback(err); + + fs.lstat(src, function (err) { + if (err && err.code === 'ENOENT') { + return callback(new Error('Attempting to link an unknown package: ' + path.basename(src))); + } + + // Create symlink + fs.symlink(src, dest, 'dir', function (err) { + callback(err); + }); + }); + }); +} + +module.exports = function (name) { + var emitter = new Emitter; + + if (!name) linkSelf(emitter); + else linkTo(name, emitter); + + return emitter; +}; + +module.exports.line = function (argv) { + var options = nopt(optionTypes, shorthand, argv); + var name = options.argv.remain[1]; + + if (options.help) return help('link'); + return module.exports(name); +}; + +module.exports.completion = function (opts, cb) { + fs.readdir(config.links, function (err, dirs) { + // ignore ENOENT, ~/.bower/links not created yet + if (err && err.code === 'ENOENT') return cb(null, []); + cb(err, dirs); + }); +}; + +module.exports.completion.options = shorthand; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/list.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/list.js new file mode 100644 index 000000000..dd61afc16 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/list.js @@ -0,0 +1,236 @@ +// ========================================== +// BOWER: List API +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var Emitter = require('events').EventEmitter; +var archy = require('archy'); +var nopt = require('nopt'); +var path = require('path'); +var _ = require('lodash'); + +var template = require('../util/template'); +var Manager = require('../core/manager'); +var Package = require('../core/package'); +var config = require('../core/config'); +var help = require('./help'); + +var shorthand = { 'h': ['--help'], 'o': ['--offline'] }; +var optionTypes = { help: Boolean, paths: Boolean, map: Boolean, offline: Boolean, sources: Boolean }; + +var getTree = function (packages, subPackages, result) { + result = result || {}; + + _.each(subPackages || packages, function (pkg) { + + result[pkg.name] = {}; + + Object.keys(pkg.json.dependencies || {}).forEach(function (name) { + result[pkg.name][name] = {}; + }); + + var subPackages = {}; + + Object.keys(pkg.json.dependencies || {}).forEach(function (name) { + subPackages[name] = packages[name] || new Package(name, null); + }); + + getTree(packages, subPackages, result[pkg.name]); + }); + + return result; +}; + +var generatePath = function (name, main) { + if (typeof main === 'string') { + return path.join(config.directory, name, main); + } else if (_.isArray(main)) { + main = main.map(function (main) { return generatePath(name, main); }); + return main.length === 1 ? main[0] : main; + } +}; + +var mainTypes = ['main', 'scripts', 'styles', 'templates', 'images']; + +var buildSource = function (pkg, shallow) { + var result = {}; + + if (pkg) { + mainTypes.forEach(function (type) { + if (pkg.json[type]) result[type] = generatePath(pkg.name, pkg.json[type]); + }); + } + + if (shallow) { + result.main = getMain(result) || generatePath(pkg.name, ''); + } + + return result; +}; + +var getMain = function (source) { + for (var i = 0, len = mainTypes.length; i < len; i += 1) { + var type = mainTypes[i]; + if (source[type]) { + return source[type]; + } + } +}; + +var shallowTree = function (packages, tree) { + var result = {}; + + Object.keys(tree).forEach(function (packageName) { + result[packageName] = buildSource(packages[packageName], true).main; + }); + + return result; +}; + +var deepTree = function (packages, tree) { + + var result = {}; + + Object.keys(tree).forEach(function (packageName) { + + result[packageName] = {}; + result[packageName].source = buildSource(packages[packageName]); + + if (Object.keys(tree[packageName]).length) { + result[packageName].dependencies = deepTree(packages, tree[packageName]); + } + + }); + + return result; +}; + +var getNodes = function (packages, tree) { + return Object.keys(tree).map(function (key) { + var version = packages[key] ? packages[key].version || '' : null; + var upgrade; + + if (version && packages[key].tags.indexOf(version)) { + upgrade = packages[key].tags[0]; + } + + if (Object.keys(tree[key]).length) { + return { + label: template('tree-branch', { 'package': key, version: version, upgrade: upgrade }, true), + nodes: getNodes(packages, tree[key]) + }; + } else { + return template('tree-branch', { 'package': key, version: version, upgrade: upgrade }, true); + } + }); +}; + +var getDependencySrcs = function (list) { + var srcs = []; + var dependency, main; + for (var name in list) { + dependency = list[name]; + main = dependency.source && getMain(dependency.source); + + if (dependency.dependencies) { + var depSrcs = getDependencySrcs(dependency.dependencies); + srcs.push.apply(srcs, depSrcs); + } + + // add main sources to srcs + if (main) { + if (Array.isArray(main)) { + srcs.push.apply(srcs, main); + } else { + srcs.push(main); + } + } + + } + return srcs; +}; + +var organizeSources = function (tree) { + // flat source filepaths + var srcs = getDependencySrcs(tree); + // remove duplicates, organize by file extension + var sources = {}; + + srcs.forEach(function (src) { + var ext = path.extname(src); + sources[ext] = sources[ext] || []; + if (sources[ext].indexOf(src) === -1) { + sources[ext].push(src); + } + }); + + return sources; +}; + +module.exports = function (options) { + var manager = new Manager; + var emitter = new Emitter; + + options = options || {}; + + if (options.sources) { + options.map = true; + } + + var emitOut = function (obj) { + // make JSON pretty if started from command line + var output = options.argv ? JSON.stringify(obj, null, 2) : obj; + emitter.emit('data', output); + }; + manager + .on('data', emitter.emit.bind(emitter, 'data')) + .on('error', emitter.emit.bind(emitter, 'error')) + .on('list', function (packages) { + // console.log(packages); + // listTree(packages, options); + var tree = getTree(packages); + if (!options.paths && !options.map) { + emitter.emit('data', archy({ + label: process.cwd(), + nodes: getNodes(packages, tree) + })); + return; + } + + tree = options.paths ? shallowTree(packages, tree) : deepTree(packages, tree); + + if (options.sources) { + // with map, organize it and emit + var sources = organizeSources(tree); + emitOut(sources); + } else { + emitOut(tree); + } + + }) + .list(options); + + return emitter; + +}; + +module.exports.line = function (argv) { + var options = nopt(optionTypes, shorthand, argv); + if (options.help) return help('list'); + return module.exports(options); +}; + +module.exports.completion = function (opts, cb) { + if (!/^-/.test(opts.word)) return cb(null, []); + + var results = Object.keys(optionTypes).map(function (option) { + return '--' + option; + }); + + cb(null, results); +}; + +module.exports.completion.options = shorthand; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/lookup.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/lookup.js new file mode 100644 index 000000000..2162a60a0 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/lookup.js @@ -0,0 +1,64 @@ +// ========================================== +// BOWER: Lookup API +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var Emitter = require('events').EventEmitter; +var nopt = require('nopt'); + +var template = require('../util/template'); +var source = require('../core/source'); +var install = require('./install'); +var help = require('./help'); + +var optionTypes = { help: Boolean }; +var shorthand = { 'h': ['--help'] }; + +module.exports = function (name) { + var emitter = new Emitter; + + source.lookup(name, function (err, url) { + if (err) { + source.search(name, function (err, packages) { + if (packages.length) { + template('suggestions', { packages: packages, name: name }) + .on('data', function (data) { + emitter.emit('data', data); + emitter.emit('end'); + }); + } else { + template('warning-missing', {name: name}) + .on('data', function (data) { + emitter.emit('data', data); + emitter.emit('end'); + }); + } + }); + } else { + var result = { name: name, url: url }; + emitter.emit('package', result); + + template('lookup', result) + .on('data', function (data) { + emitter.emit('data', data); + emitter.emit('end'); + }); + } + }); + + return emitter; +}; + +module.exports.line = function (argv) { + var options = nopt(optionTypes, shorthand, argv); + var names = options.argv.remain.slice(1); + + if (options.help || !names.length) return help('lookup'); + return module.exports(names[0]); +}; + +module.exports.completion = install.completion; +module.exports.completion.options = shorthand; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/register.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/register.js new file mode 100644 index 000000000..bc895ca92 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/register.js @@ -0,0 +1,66 @@ +// ========================================== +// BOWER: Lookup API +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var Emitter = require('events').EventEmitter; +var nopt = require('nopt'); +var readline = require('readline'); + +var template = require('../util/template'); +var source = require('../core/source'); +var help = require('./help'); + +var optionTypes = { help: Boolean }; +var shorthand = { 'h': ['--help'], '-s': ['--silent'] }; + +var register = function (name, url, emitter) { + source.register(name, url, function (err) { + if (err) return emitter.emit('error', err); + + template('register', {name: name, url: url}) + .on('data', emitter.emit.bind(emitter, 'data')); + }); +}; + +module.exports = function (name, url, options) { + var emitter = new Emitter; + + if (options.silent) register(name, url, emitter); + else { + var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); + + console.log('Registering a package will make it visible and installable via the registry.'); + rl.question('Proceed (y/n)? ', function (res) { + rl.close(); + + res = res.toLowerCase(); + + if (res === 'y' || res === 'yes') register(name, url, emitter); + }); + } + + return emitter; +}; + +module.exports.line = function (argv) { + var options = nopt(optionTypes, shorthand, argv); + var args = options.argv.remain.slice(1); + + if (options.help || args.length !== 2) return help('register'); + return module.exports(args[0], args[1], options); +}; + +module.exports.completion = function (opts, cb) { + var word = opts.word; + + // completing options? + if (word.charAt(0) === '-') { + return cb(null, Object.keys(optionTypes).map(function (option) { + return '--' + option; + })); + } +}; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/search.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/search.js new file mode 100644 index 000000000..bdbc57547 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/search.js @@ -0,0 +1,61 @@ +// ========================================== +// BOWER: Lookup API +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var Emitter = require('events').EventEmitter; +var nopt = require('nopt'); + +var template = require('../util/template'); +var source = require('../core/source'); +var install = require('./install'); +var help = require('./help'); + +var optionTypes = { help: Boolean }; +var shorthand = { 'h': ['--help'] }; + +module.exports = function (name) { + var emitter = new Emitter; + + var callback = function (err, results) { + if (err) return emitter.emit('error', err); + + emitter.emit('packages', results); + + if (results.length) { + template('search', {results: results}) + .on('data', function (data) { + emitter.emit('data', data); + emitter.emit('end'); + }); + } else { + template('search-empty', {results: results}) + .on('data', function (data) { + emitter.emit('data', data); + emitter.emit('end'); + }); + } + }; + + if (name) { + source.search(name, callback); + } else { + source.all(callback); + } + + return emitter; +}; + +module.exports.line = function (argv) { + var options = nopt(optionTypes, shorthand, argv); + var names = options.argv.remain.slice(1); + + if (options.help) return help('search'); + return module.exports(names[0]); +}; + +module.exports.completion = install.completion; +module.exports.completion.options = shorthand; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/uninstall.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/uninstall.js new file mode 100644 index 000000000..912f54239 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/uninstall.js @@ -0,0 +1,206 @@ +// ========================================== +// BOWER: Uninstall API +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var Emitter = require('events').EventEmitter; +var async = require('async'); +var nopt = require('nopt'); +var fs = require('fs'); +var path = require('path'); +var _ = require('lodash'); + +var template = require('../util/template'); +var Manager = require('../core/manager'); +var config = require('../core/config'); +var help = require('./help'); + +var optionTypes = { help: Boolean, force: Boolean, save: Boolean }; +var shorthand = { 'h': ['--help'], 'S': ['--save'], 'D': ['--save-dev'], 'f': ['--force'] }; + +module.exports = function (names, options) { + var packages, uninstallables, packagesCount = {}; + var emitter = new Emitter; + var manager = new Manager; + var jsonDeps; + var newLine; + + options = options || {}; + + manager.on('data', emitter.emit.bind(emitter, 'data')); + manager.on('error', emitter.emit.bind(emitter, 'error')); + + var resolveLocal = function () { + jsonDeps = manager.json.dependencies || {}; + packages = _.flatten(_.values(manager.dependencies)); + uninstallables = packages.filter(function (pkg) { + return _.include(names, pkg.name); + }); + async.forEach(packages, function (pkg, next) { + pkg.once('loadJSON', next).loadJSON(); + }, function () { + if (showWarnings(options.force) && !options.force) return; + expandUninstallabes(options.force); + uninstall(); + }); + }; + + var showWarnings = function (force) { + var foundConflicts = false; + + packages.forEach(function (pkg) { + if (!pkg.json.dependencies) return; + if (containsPkg(uninstallables, pkg)) return; + + var conflicts = _.intersection( + Object.keys(pkg.json.dependencies), + _.pluck(uninstallables, 'name') + ); + + if (conflicts.length) { + foundConflicts = true; + if (!force) { + conflicts.forEach(function (conflictName) { + emitter.emit('data', template('warning-uninstall', { packageName: pkg.name, conflictName: conflictName }, true)); + }); + } + } + }); + + if (foundConflicts && !force) { + emitter.emit('data', template('warn', { message: 'To proceed, run uninstall with the --force flag'}, true)); + } + + return foundConflicts; + }; + + var expandUninstallabes = function (force) { + var x, + pkg, + forcedUninstallables = {}; + + // Direct JSON deps have a count of 1 + for (var key in jsonDeps) { + packagesCount[key] = 1; + } + + // Count all packages + count(packages, packagesCount); + + if (force) { + uninstallables.forEach(function (pkg) { + forcedUninstallables[pkg.name] = true; + }); + } + + // Expand the uninstallables deps and nested deps + // Also update the count accordingly + for (x = uninstallables.length - 1; x >= 0; x -= 1) { + parseUninstallableDeps(uninstallables[x]); + } + + // Foreach uninstallable, check if it is really to be removed by reading the final count + // If the final count is greater than 0, then it is a shared dep + // In that case, we remove it from the uninstallables unless it's forced to be uninstalled + for (x = uninstallables.length - 1; x >= 0; x -= 1) { + pkg = uninstallables[x]; + if (packagesCount[pkg.name] > 0 && !forcedUninstallables[pkg.name]) uninstallables.splice(x, 1); + } + }; + + var count = function (packages, counts, nested) { + packages.forEach(function (pkg) { + counts[pkg.name] = (counts[pkg.name] || 0); + if (nested) counts[pkg.name] += 1; + + if (pkg.json.dependencies) { + for (var key in pkg.json.dependencies) { + count(manager.dependencies[key], counts, true); + } + } + }); + }; + + var parseUninstallableDeps = function (pkg) { + if (!containsPkg(uninstallables, pkg)) uninstallables.push(pkg); + packagesCount[pkg.name] -= 1; + + if (pkg.json.dependencies) { + for (var key in pkg.json.dependencies) { + parseUninstallableDeps(manager.dependencies[key][0]); + } + } + }; + + var containsPkg = function (packages, pkg) { + for (var x = packages.length - 1; x >= 0; x -= 1) { + if (packages[x].name === pkg.name) return true; + } + + return false; + }; + + var uninstall = function () { + async.forEach(uninstallables, function (pkg, next) { + pkg.on('uninstall', function () { + emitter.emit('package', pkg); + next(); + }).uninstall(); + }, function () { + // Finally save + if (options.save || options['save-dev']) save(!options.save); + emitter.emit('end'); + }); + }; + + var save = function (dev) { + var key = dev ? 'devDependencies' : 'dependencies'; + var contents; + + if (manager.json[key]) { + names.forEach(function (name) { + delete manager.json[key][name]; + }); + + contents = JSON.stringify(manager.json, null, 2) + (newLine ? '\n' : ''); + fs.writeFileSync(path.join(manager.cwd, config.json), contents); + } + }; + + manager.on('loadJSON', function (hasNewLine) { + newLine = hasNewLine; + manager.on('resolveLocal', resolveLocal).resolveLocal(); + }).loadJSON(); + + return emitter; +}; + +module.exports.line = function (argv) { + var options = nopt(optionTypes, shorthand, argv); + var names = options.argv.remain.slice(1); + + if (options.help || !names.length) return help('uninstall'); + return module.exports(names, options); +}; + +module.exports.completion = function (opts, cb) { + var word = opts.word; + + // completing options? + if (opts.words[0] === 'uninstall' && word.charAt(0) === '-') { + return cb(null, Object.keys(optionTypes).map(function (option) { + return '--' + option; + })); + } + + fs.readdir(config.directory, function (err, dirs) { + // ignore ENOENT, ./components not created yet + if (err && err.code === 'ENOENT') return cb(null, []); + cb(err, dirs); + }); +}; + +module.exports.completion.options = shorthand; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/update.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/update.js new file mode 100644 index 000000000..c6757c29b --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/commands/update.js @@ -0,0 +1,95 @@ +// ========================================== +// BOWER: Update API +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var Emitter = require('events').EventEmitter; +var async = require('async'); +var nopt = require('nopt'); +var _ = require('lodash'); + +var Manager = require('../core/manager'); +var help = require('./help'); +var uninstall = require('./uninstall'); +var save = require('../util/save'); + +var optionTypes = { help: Boolean, save: Boolean, force: Boolean, 'force-latest': Boolean }; +var shorthand = { 'h': ['--help'], 'S': ['--save'], 'f': ['--force'], 'F': ['--force-latest'] }; + +module.exports = function (names, options) { + options = options || {}; + + var emitter = new Emitter; + var manager = new Manager([], { + force: options.force, + forceLatest: options['force-latest'] + }); + + manager.on('data', emitter.emit.bind(emitter, 'data')); + manager.on('error', emitter.emit.bind(emitter, 'error')); + + var installURLS = function (err, arr) { + var mappings = {}, + endpoints = []; + + arr = _.compact(arr); + _.each(arr, function (info) { + endpoints.push(info.endpoint); + mappings[info.endpoint] = info.name; + }); + + options.endpointNames = mappings; + + // By default the manager will guess the name of the package from the url + // But this leads to problems when the package name does not match the one in the url + // So the manager now has an option (endpointNames) to deal with this + manager = new Manager(endpoints, options); + + manager + .on('data', emitter.emit.bind(emitter, 'data')) + .on('error', emitter.emit.bind(emitter, 'error')) + .on('resolve', function (resolved) { + // Handle save + if (resolved && options.save) save(manager, null, false, emitter.emit.bind(emitter, 'end')); + else emitter.emit('end'); + }) + .resolve(); + }; + + manager.once('resolveLocal', function () { + names = names.length ? _.uniq(names) : null; + + async.map(_.values(manager.dependencies), function (pkgs, next) { + var pkg = pkgs[0]; + pkg.once('loadJSON', function () { + var endpointInfo = pkg.readEndpoint(); + if (!endpointInfo) return next(); + + // Add tag only if the endpoint is a repository + var endpoint = endpointInfo.endpoint; + var json = pkg.json; + if (!json.commit && (endpointInfo.type === 'git' || endpointInfo.type === 'local-repo')) { + endpoint += '#' + ((!names || names.indexOf(pkg.name) > -1) ? '~' : '') + pkg.version; + } + + next(null, { name: pkg.name, endpoint: endpoint }); + }).loadJSON(); + }, installURLS); + }).resolveLocal(); + + return emitter; +}; + +module.exports.line = function (argv) { + var options = nopt(optionTypes, shorthand, argv); + if (options.help) return help('update'); + + var paths = options.argv.remain.slice(1); + return module.exports(paths, options); +}; + +module.exports.completion = uninstall.completion; +module.exports.completion.options = shorthand; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/config.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/config.js new file mode 100644 index 000000000..a369335e2 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/config.js @@ -0,0 +1,60 @@ +var path = require('path'); +var fs = require('fs'); +var _ = require('lodash'); +var tmp = require('tmp'); + +var fileExists = require('../util/file-exists').sync; + +var temp = process.env.TMPDIR + || process.env.TMP + || process.env.TEMP + || process.platform === 'win32' ? 'c:\\windows\\temp' : '/tmp'; + +var home = (process.platform === 'win32' + ? process.env.USERPROFILE + : process.env.HOME) || temp; + +var roaming = process.platform === 'win32' + ? path.resolve(process.env.APPDATA || home || temp) + : path.resolve(home || temp); + +var folder = process.platform === 'win32' + ? 'bower' + : '.bower'; + +var proxy = process.env.HTTPS_PROXY + || process.env.https_proxy + || process.env.HTTP_PROXY + || process.env.http_proxy; + +// Bower Config +var config; +try { + config = require('rc') ('bower', { + cache : path.join(roaming, folder, 'cache'), + links : path.join(roaming, folder, 'links'), + completion : path.join(roaming, folder, 'completion'), + json : 'component.json', + endpoint : 'https://bower.herokuapp.com', + directory : 'components', + proxy : proxy + }); +} catch (e) { + throw new Error('Unable to parse global .bowerrc file: ' + e.message); +} + +// If there is a local .bowerrc file, merge it +var localFile = path.join(process.cwd(), '.bowerrc'); +if (fileExists(localFile)) { + try { + _.extend(config, JSON.parse(fs.readFileSync(localFile))); + } catch (e) { + throw new Error('Unable to parse local .bowerrc file: ' + e.message); + } +} + +// Configure tmp package to use graceful degradationn +// If an uncaught exception occurs, the temporary directories will be deleted nevertheless +tmp.setGracefulCleanup(); + +module.exports = config; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/manager.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/manager.js new file mode 100644 index 000000000..1f4fbeb1d --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/manager.js @@ -0,0 +1,361 @@ +// ========================================== +// BOWER: Manager Object Definition +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== +// Events: +// - install: fired when everything is installed +// - package: fired for each installed packaged +// - resolve: fired when deps resolved (with a true/false indicating success or error) +// - error: fired on all errors +// - data: fired when trying to output data +// - end: fired when finished installing +// ========================================== + +var events = require('events'); +var semver = require('semver'); +var async = require('async'); +var path = require('path'); +var glob = require('glob'); +var fs = require('fs'); +var _ = require('lodash'); + +var Package = require('./package'); +var UnitWork = require('./unit_work'); +var config = require('./config'); +var fileExists = require('../util/file-exists'); +var template = require('../util/template'); +var prune = require('../util/prune'); + +// read local dependencies (with versions) +// read json dependencies (resolving along the way into temp dir) +// merge local dependencies with json dependencies +// prune and move dependencies into local directory + +var Manager = function (endpoints, opts) { + this.dependencies = {}; + this.cwd = process.cwd(); + this.endpoints = endpoints || []; + this.unitWork = new UnitWork; + this.opts = opts || {}; + this.errors = []; +}; + +Manager.prototype = Object.create(events.EventEmitter.prototype); +Manager.prototype.constructor = Manager; + +Manager.prototype.loadJSON = function () { + var json = path.join(this.cwd, config.json); + fileExists(json, function (exists) { + if (!exists) { + // If the json does not exist, assume one + this.json = { + name: path.basename(this.cwd), + version: '0.0.0' + }, + this.name = this.json.name; + this.version = this.json.version; + return this.emit('loadJSON'); + } + + fs.readFile(json, 'utf8', function (err, json) { + if (err) return this.emit('error', err); + try { + this.json = JSON.parse(json); + } catch (e) { + return this.emit('error', new Error('There was an error while reading the ' + config.json + ': ' + e.message)); + } + this.name = this.json.name; + this.version = this.json.version; + this.emit('loadJSON', json.slice(-1) === '\n'); + }.bind(this)); + }.bind(this)); + + return this; +}; + +Manager.prototype.resolve = function () { + var resolved = function () { + // If there is errors, report them + if (this.errors.length) return this.reportErrors(); + // If there is an error while pruning (conflict) then abort installation + if (!this.prune()) return this.emit('resolve', false); + // Otherwise all is fine, so we install + this.once('install', this.emit.bind(this, 'resolve', true)).install(); + }.bind(this); + + // Resolve locally first + this.once('resolveLocal', function () { + if (this.endpoints.length) { + // TODO: When resolving specific endpoints we need to restore all the local + // packages and their hierarchy (all from the local folder) + // If something goes wrong, simply do resolveFromJSON before + // calling resolved() (slower) + // This will solve issue #200 + this.once('resolveEndpoints', resolved).resolveEndpoints(); + } else { + this.once('resolveFromJson', resolved).resolveFromJson(); + } + }).resolveLocal(); + + return this; +}; + +Manager.prototype.resolveLocal = function () { + glob('./' + config.directory + '/*', function (err, dirs) { + if (err) return this.emit('error', err); + dirs.forEach(function (dir) { + var name = path.basename(dir); + var pkg = new Package(name, dir, this); + + this.dependencies[name] = []; + this.dependencies[name].push(pkg); + + this.gatherPackageErrors(pkg); + }.bind(this)); + this.emit('resolveLocal'); + }.bind(this)); + + return this; +}; + +Manager.prototype.resolveEndpoints = function () { + var endpointNames = this.opts.endpointNames || {}; + + async.forEach(this.endpoints, function (endpoint, next) { + var name = endpointNames[endpoint]; + var pkg = new Package(name, endpoint, this); + var errorNext; + + pkg.root = true; + this.dependencies[name] = this.dependencies[name] || []; + this.dependencies[name].push(pkg); + + this.gatherPackageErrors(pkg); + pkg.once('error', errorNext = next.bind(next, null)); + pkg.once('resolve', function () { + pkg.removeListener('error', errorNext); + next(); + }).resolve(); + }.bind(this), this.emit.bind(this, 'resolveEndpoints')); + + return this; +}; + +Manager.prototype.resolveFromJson = function () { + this.once('loadJSON', function () { + var dependencies = this.json.dependencies || {}; + + // add devDependencies + if (!this.opts.production && this.json.devDependencies) { + dependencies = _.extend({}, dependencies, this.json.devDependencies); + } + + async.forEach(Object.keys(dependencies), function (name, next) { + var endpoint = dependencies[name]; + var pkg = new Package(name, endpoint, this); + var errorNext; + + pkg.root = true; + this.dependencies[name] = this.dependencies[name] || []; + this.dependencies[name].push(pkg); + + this.gatherPackageErrors(pkg); + pkg.once('error', errorNext = next.bind(next, null)); + pkg.once('resolve', function () { + pkg.removeListener('error', errorNext); + next(); + }).resolve(); + }.bind(this), this.emit.bind(this, 'resolveFromJson')); + }.bind(this)).loadJSON(); + + return this; +}; + +// Private +Manager.prototype.getDeepDependencies = function () { + var result = {}; + + for (var name in this.dependencies) { + this.dependencies[name].forEach(function (pkg) { + result[pkg.name] = result[pkg.name] || []; + result[pkg.name].push(pkg); + pkg.getDeepDependencies().forEach(function (pkg) { + result[pkg.name] = result[pkg.name] || []; + result[pkg.name].push(pkg); + }); + }); + } + + return result; +}; + +Manager.prototype.prune = function () { + var result = prune(this.getDeepDependencies(), this.opts.forceLatest); + var name; + + // If there is conflicted deps, print them and fail + if (result.conflicted) { + for (name in result.conflicted) { + this.reportConflicts(name, result.conflicted[name]); + } + + return false; + } + + this.dependencies = {}; + + // If there is conflicted deps but they where forcebly resolved + // Print a warning about them + if (result.forceblyResolved) { + for (name in result.forceblyResolved) { + this.reportForceblyResolved(name, result.forceblyResolved[name]); + this.dependencies[name] = result.forceblyResolved[name]; + this.dependencies[name][0].root = true; + } + } + + _.extend(this.dependencies, result.resolved); + + return true; +}; + +Manager.prototype.gatherPackageErrors = function (pkg) { + pkg.on('error', function (err, origin) { + pkg = origin || pkg; + + // If the error message starts with the package name, strip it + if (!err.message.indexOf(pkg.name + ' ')) { + err.message = err.message.substr(pkg.name.length + 1); + } + + this.errors.push({ pkg: pkg, error: err }); + }.bind(this)); +}; + +Manager.prototype.install = function () { + async.forEach(Object.keys(this.dependencies), function (name, next) { + var pkg = this.dependencies[name][0]; + pkg.once('install', function () { + this.emit('package', pkg); + next(); + }.bind(this)).install(); + pkg.once('error', next); + }.bind(this), function () { + if (this.errors.length) this.reportErrors(); + return this.emit('install'); + }.bind(this)); +}; + +Manager.prototype.muteDependencies = function () { + for (var name in this.dependencies) { + this.dependencies[name].forEach(function (pkg) { + pkg.removeAllListeners(); + pkg.on('error', function () {}); + }); + } +}; + +Manager.prototype.reportErrors = function () { + this.muteDependencies(); + template('error-summary', { errors: this.errors }).on('data', function (data) { + this.emit('data', data); + this.emit('resolve', false); + }.bind(this)); +}; + +Manager.prototype.reportConflicts = function (name, packages) { + var versions = []; + var requirements = []; + + packages = packages.filter(function (pkg) { return !!pkg.version; }); + packages.forEach(function (pkg) { + requirements.push({ pkg: pkg, tag: pkg.originalTag || '~' + pkg.version }); + versions.push((pkg.originalTag || '~' + pkg.version).white); + }); + + this.emit('error', new Error('No resolvable version for ' + name)); + this.emit('data', template('conflict', { + name: name, + requirements: requirements, + json: config.json, + versions: versions.slice(0, -1).join(', ') + ' or ' + versions[versions.length - 1] + }, true)); +}; + +Manager.prototype.reportForceblyResolved = function (name, packages) { + var requirements = []; + + packages = packages.filter(function (pkg) { return !!pkg.version; }); + packages.forEach(function (pkg) { + requirements.push({ pkg: pkg, tag: pkg.originalTag || '~' + pkg.version }); + }); + + this.emit('data', template('resolved-conflict', { + name: name, + requirements: requirements, + json: config.json, + resolvedTo: packages[0].version, + forceLatest: this.opts.forceLatest + }, true)); +}; + + +// ----- list ----- // + +// Used in list command +// TODO: not sure if this belongs here.. maybe move it to the list command? +Manager.prototype.list = function (options) { + options = options || {}; + // If the user passed the paths or map options, we don't need to fetch versions + this._isCheckingVersions = !options.offline && !options.paths && !options.map && options.argv; + this.once('resolveLocal', this.getDependencyList.bind(this)) + .resolveLocal(); +}; + +Manager.prototype.getDependencyList = function () { + + var packages = {}; + var values; + var checkVersions = this._isCheckingVersions; + + if (checkVersions) { + template('action', { name: 'discover', shizzle: 'Please wait while newer package versions are being discovered' }) + .on('data', this.emit.bind(this, 'data')); + } + + Object.keys(this.dependencies).forEach(function (key) { + packages[key] = this.dependencies[key][0]; + }.bind(this)); + + values = _.values(packages); + // Do not proceed if no values + if (!values.length) { + return packages; + } + // Load JSON and get version for each package + async.forEach(values, function (pkg, next) { + pkg.once('loadJSON', function () { + // Only check versions if not offline and it's a repo + var fetchVersions = checkVersions && + pkg.json.repository && + (pkg.json.repository.type === 'git' || pkg.json.repository.type === 'local-repo'); + + if (fetchVersions) { + pkg.once('versions', function (versions) { + pkg.tags = versions.map(function (ver) { + return semver.valid(ver) ? semver.clean(ver) : ver; + }); + next(); + }).versions(); + } else { + pkg.tags = []; + next(); + } + }).loadJSON(); + }.bind(this), this.emit.bind(this, 'list', packages)); +}; + +module.exports = Manager; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/package.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/package.js new file mode 100644 index 000000000..50a96d1d1 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/package.js @@ -0,0 +1,819 @@ +// ========================================== +// BOWER: Package Object Definition +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== +// Events: +// - install: fired when package installed +// - resolve: fired when deps resolved +// - error: fired on all errors +// - data: fired when trying to output data +// ========================================== + +var fstream = require('fstream'); +var mkdirp = require('mkdirp'); +var events = require('events'); +var rimraf = require('rimraf'); +var semver = require('semver'); +var async = require('async'); +var https = require('https'); +var http = require('http'); +var path = require('path'); +var glob = require('glob'); +var url = require('url'); +var tmp = require('tmp'); +var fs = require('fs'); +var crypto = require('crypto'); +var unzip = require('unzip'); +var tar = require('tar'); +var _ = require('lodash'); + +var config = require('./config'); +var source = require('./source'); +var template = require('../util/template'); +var readJSON = require('../util/read-json'); +var fileExists = require('../util/file-exists'); +var isRepo = require('../util/is-repo'); +var git = require('../util/git-cmd'); +var UnitWork = require('./unit_work'); + +var Package = function (name, endpoint, manager) { + this.dependencies = {}; + this.json = {}; + this.name = name; + this.manager = manager; + this.unitWork = manager ? manager.unitWork : new UnitWork; + this.opts = manager ? manager.opts : {}; + + if (endpoint) { + var split; + + if (/^(.*\.git)$/.exec(endpoint)) { + this.gitUrl = RegExp.$1.replace(/^git\+/, ''); + this.tag = false; + + } else if (/^(.*\.git)#(.*)$/.exec(endpoint)) { + this.tag = RegExp.$2; + this.gitUrl = RegExp.$1.replace(/^git\+/, ''); + + } else if (/^(?:(git):|git\+(https?):)\/\/([^#]+)#?(.*)$/.exec(endpoint)) { + this.gitUrl = (RegExp.$1 || RegExp.$2) + '://' + RegExp.$3; + this.tag = RegExp.$4; + + } else if (semver.validRange(endpoint)) { + this.tag = endpoint; + + } else if (/^[\.\/~]\.?[^.]*\.(js|css)/.test(endpoint) && fs.statSync(endpoint).isFile()) { + this.path = path.resolve(endpoint); + this.assetType = path.extname(endpoint); + + } else if (/^https?:\/\//.exec(endpoint)) { + this.assetUrl = endpoint; + this.assetType = path.extname(endpoint); + + } else if (fileExists.sync((split = endpoint.split('#', 2))[0]) && fs.statSync(split[0]).isDirectory()) { + this.path = path.resolve(split[0]); + this.tag = split[1]; + + } else if (/^[\.\/~]/.test(endpoint)) { + this.path = path.resolve(endpoint); + + } else if (endpoint.split('/').length === 2) { + split = endpoint.split('#', 2); + this.gitUrl = 'git://github.com/' + split[0] + '.git'; + this.tag = split[1]; + } else { + split = endpoint.split('#', 2); + this.tag = split[1]; + } + + // Guess names + if (!this.name) { + if (this.gitUrl) this.name = path.basename(endpoint).replace(/(\.git)?(#.*)?$/, ''); + else if (this.path) this.name = path.basename(this.path, this.assetType); + else if (this.assetUrl) this.name = this.name = path.basename(this.assetUrl, this.assetType); + else if (split) this.name = split[0]; + } + + // Store a reference to the original tag & original path + // This is because the tag & paths can get rewriten later + if (this.tag) this.originalTag = this.tag; + if (this.path) this.originalPath = endpoint; + + // The id is an unique id that describes this package + this.id = crypto.createHash('md5').update(this.name + '%' + this.tag + '%' + this.gitUrl + '%' + this.path + '%' + this.assetUrl).digest('hex'); + + // Generate a resource id + if (this.gitUrl) this.generateResourceId(); + } + + if (this.manager) { + this.on('data', this.manager.emit.bind(this.manager, 'data')); + this.on('error', function (err, origin) { + // Unlock the unit of work automatically on error (only if the error is from this package) + if (!origin && this.unitWork.isLocked(this.name)) this.unitWork.unlock(this.name, this); + // Propagate the error event to the parent package/manager + this.manager.emit('error', err, origin || this); + }.bind(this)); + } + + // Cache a self bound function + this.waitUnlock = this.waitUnlock.bind(this); + + this.setMaxListeners(30); // Increase the number of listeners because a package can have more than the default 10 dependencies +}; + +Package.prototype = Object.create(events.EventEmitter.prototype); + +Package.prototype.constructor = Package; + +Package.prototype.resolve = function () { + // Ensure that nobody is resolving the same dep at the same time + // If there is, we wait for the unlock event + if (this.unitWork.isLocked(this.name)) return this.unitWork.on('unlock', this.waitUnlock); + + var data = this.unitWork.retrieve(this.name); + if (data) { + // Check if this exact package is the last resolved one + // If so, we copy the resolved result and we don't need to do anything else + if (data.id === this.id) { + this.unserialize(data); + this.emit('resolve'); + return this; + } + } + + // If not, we lock and resolve it + this.unitWork.lock(this.name, this); + + if (this.assetUrl) { + this.download(); + } else if (this.gitUrl) { + this.clone(); + } else if (this.path) { + this.copy(); + } else { + this.once('lookup', this.clone).lookup(); + } + + return this; +}; + +Package.prototype.lookup = function () { + source.lookup(this.name, function (err, url) { + if (err) return this.emit('error', err); + this.lookedUp = true; + this.gitUrl = url; + this.generateResourceId(); + this.emit('lookup'); + }.bind(this)); +}; + +Package.prototype.install = function () { + // Only print the installing action if this package has been resolved + if (this.unitWork.retrieve(this.name)) { + template('action', { name: 'installing', shizzle: this.name + (this.version ? '#' + this.version : '') }) + .on('data', this.emit.bind(this, 'data')); + } + + var localPath = this.localPath; + + if (path.resolve(this.path) === localPath) { + this.emit('install'); + return this; + } + + // Remove stuff from the local path (if any) + // Rename path to the local path + // Beware that if the local path exists and is a git repository, the process is aborted + isRepo(localPath, function (is) { + if (is) { + var err = new Error('Local path is a local repository'); + err.details = 'To avoid losing work, please remove ' + localPath + ' manually.'; + return this.emit('error', err, this); + } + + mkdirp(path.dirname(localPath), function (err) { + if (err) return this.emit('error', err); + rimraf(localPath, function (err) { + if (err) return this.emit('error', err); + return fs.rename(this.path, localPath, function (err) { + if (!err) return this.cleanUpLocal(); + + var writter = fstream.Writer({ + type: 'Directory', + path: localPath + }); + writter + .on('error', this.emit.bind(this, 'error')) + .on('end', rimraf.bind(this, this.path, this.cleanUpLocal.bind(this))); + + fstream.Reader(this.path) + .on('error', this.emit.bind(this, 'error')) + .pipe(writter); + }.bind(this)); + }.bind(this)); + }.bind(this)); + }.bind(this)); + + return this; +}; + +Package.prototype.cleanUpLocal = function () { + this.once('readLocalConfig', function () { + this.json.name = this.name; + this.json.version = this.commit ? '0.0.0' : this.version || '0.0.0'; + + // Detect commit and save it in the json for later use + if (this.commit) this.json.commit = this.commit; + else delete this.json.commit; + + if (this.gitUrl) this.json.repository = { type: 'git', url: this.gitUrl }; + else if (this.gitPath) this.json.repository = { type: 'local-repo', path: this.originalPath }; + else if (this.originalPath) this.json.repository = { type: 'local', path: this.originalPath }; + else if (this.assetUrl) this.json = this.generateAssetJSON(); + + var jsonStr = JSON.stringify(this.json, null, 2); + + fs.writeFile(path.join(this.localPath, this.localConfig.json), jsonStr); + if (this.gitUrl || this.gitPath) fs.writeFile(path.join(this.gitPath, this.localConfig.json), jsonStr); + + this.removeLocalPaths(); + }.bind(this)).readLocalConfig(); +}; + +// finish clean up local by removing .git/ and any ignored files +Package.prototype.removeLocalPaths = function () { + var removePatterns = ['.git']; + if (this.json.ignore) { + removePatterns.push.apply(removePatterns, this.json.ignore); + } + + var removePaths = []; + + // 3: done + var pathsRemoved = function (err) { + if (err) return this.emit('error', err); + this.emit('install'); + }.bind(this); + + // 2: trigger after paths have been globbed + var rimrafPaths = function (err) { + if (err) return this.emit('error', err); + async.forEach(removePaths, function (removePath, next) { + // rimraf all the paths + rimraf(path.join(this.localPath, removePath), next); + }.bind(this), pathsRemoved); + }.bind(this); + + // 1: get paths + var globOpts = { dot: true, cwd: this.localPath }; + async.forEach(removePatterns, function (removePattern, next) { + // glob path for file path pattern matching + glob(removePattern, globOpts, function (err, globPaths) { + if (err) return next(err); + removePaths.push.apply(removePaths, globPaths); + next(); + }.bind(this)); + }.bind(this), rimrafPaths); +}; + +Package.prototype.generateAssetJSON = function () { + return { + name: this.name, + main: this.assetType !== '.zip' && this.assetType !== '.tar' ? 'index' + this.assetType : '', + version: '0.0.0', + repository: { type: 'asset', url: this.assetUrl } + }; +}; + +Package.prototype.uninstall = function () { + template('action', { name: 'uninstalling', shizzle: this.path }) + .on('data', this.emit.bind(this, 'data')); + rimraf(this.path, function (err) { + if (err) return this.emit('error', err); + this.emit('uninstall'); + }.bind(this)); +}; + +// Private +Package.prototype.readLocalConfig = function () { + if (this.localConfig) return this.emit('readLocalConfig'); + + var checkExistence = function () { + fileExists(path.join(this.path, this.localConfig.json), function (exists) { + if (!exists) { + this.localConfig.json = 'component.json'; + } + + this.emit('readLocalConfig'); + }.bind(this)); + }.bind(this); + + fs.readFile(path.join(this.path, '.bowerrc'), function (err, file) { + // If the local .bowerrc file do not exists then we check if the + // json specific in the config exists (if not, we fallback to component.json) + if (err) { + this.localConfig = { json: config.json }; + checkExistence(); + } else { + // If the local .bowerrc file exists, we read it and check if a custom json file + // is defined. If not, we check if the global config json file exists (if not, we fallback to component.json) + try { + this.localConfig = JSON.parse(file); + } catch (e) { + return this.emit('error', new Error('Unable to parse local .bowerrc file: ' + e.message)); + } + + if (!this.localConfig.json) { + this.localConfig.json = config.json; + return checkExistence(); + } + + this.emit('readLocalConfig'); + } + }.bind(this)); +}; + +Package.prototype.loadJSON = function () { + if (!this.path || this.assetUrl) return this.emit('loadJSON'); + + this.once('readLocalConfig', function () { + var jsonFile = path.join(this.path, this.localConfig.json); + fileExists(jsonFile, function (exists) { + // If the json does not exists, we attempt to get the version + if (!exists) { + return this.once('describeTag', function (tag) { + tag = semver.clean(tag); + if (!tag) this.version = this.tag; + else { + this.version = tag; + if (!this.tag) this.tag = this.version; + } + + this.emit('loadJSON'); + }.bind(this)).describeTag(); + } + + readJSON(jsonFile, function (err, json) { + if (err) { + err.details = 'An error was caught when reading the ' + this.localConfig.json + ':' + err.message; + return this.emit('error', err); + } + + this.json = json; + this.version = this.commit || json.commit || json.version; + this.commit = this.commit || json.commit; + // Only overwrite the name if not already set + // This is because some packages have different names declared in the registry and the json + if (!this.name) this.name = json.name; + + // Read the endpoint from the json to ensure it is set correctly + this.readEndpoint(); + + // Detect if the tag mismatches the json.version + // This is very often to happen because developers tag their new releases but forget to update the json accordingly + var cleanedTag; + if (this.tag && (cleanedTag = semver.clean(this.tag)) && cleanedTag !== this.version) { + // Only print the warning once + if (!this.unitWork.retrieve('mismatch#' + this.name + '_' + cleanedTag)) { + template('warning-mismatch', { name: this.name, json: this.localConfig.json, tag: cleanedTag, version: this.version || 'N/A' }) + .on('data', this.emit.bind(this, 'data')); + this.unitWork.store('mismatch#' + this.name + '_' + cleanedTag, true); + } + // Assume the tag + this.version = cleanedTag; + } + + this.emit('loadJSON'); + }.bind(this), this); + }.bind(this)); + }.bind(this)).readLocalConfig(); +}; + +Package.prototype.download = function () { + template('action', { name: 'downloading', shizzle: this.assetUrl }) + .on('data', this.emit.bind(this, 'data')); + + var src; + + if (config.proxy) { + src = url.parse(config.proxy); + src.path = this.assetUrl; + } else { + src = url.parse(this.assetUrl); + } + + tmp.dir({ prefix: 'bower-' + this.name + '-', mode: parseInt('0777', 8) & (~process.umask()) }, function (err, tmpPath) { + if (err) return this.emit('error', err); + + var req = src.protocol === 'https:' ? https : http; + req.get(src, function (res) { + // If assetUrl results in a redirect we update the assetUrl to the redirect to url + if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + template('action', { name: 'redirect detected', shizzle: this.assetUrl }) + .on('data', this.emit.bind(this, 'data')); + this.assetUrl = res.headers.location; + return this.download(); + } + + // Detect not OK status codes + if (res.statusCode < 200 || res.statusCode >= 300) { + return this.emit('error', new Error(res.statusCode + ' status code for ' + this.assetUrl)); + } + + var file = fs.createWriteStream(path.join((this.path = tmpPath), 'index' + this.assetType)); + + res.on('data', function (data) { + file.write(data); + }); + + res.on('end', function () { + file.end(); + + var next = function () { + this.once('loadJSON', this.saveUnit).loadJSON(); + }.bind(this); + + if (this.assetType === '.zip' || this.assetType === '.tar') this.once('extract', next).extract(); + else next(); + }.bind(this)); + }.bind(this)).on('error', this.emit.bind(this, 'error')); + }.bind(this)); +}; + +Package.prototype.extract = function () { + var file = path.join(this.path, 'index' + this.assetType); + template('action', { name: 'extracting', shizzle: file }).on('data', this.emit.bind(this, 'data')); + + fs.createReadStream(file).pipe(this.assetType === '.zip' ? unzip.Extract({ path: this.path }) : tar.Extract({ path: this.path })) + .on('error', this.emit.bind(this, 'error')) + .on('close', function () { + // Delete zip + fs.unlink(file, function (err) { + if (err) return this.emit('error', err); + + // If we extracted only a folder, move all the files within it to the original path + fs.readdir(this.path, function (err, files) { + if (err) return this.emit('error', err); + + if (files.length !== 1) return this.emit('extract'); + + var dir = path.join(this.path, files[0]); + fs.stat(dir, function (err, stat) { + if (err) return this.emit('error', err); + if (!stat.isDirectory()) return this.emit('extract'); + + fs.readdir(dir, function (err, files) { + if (err) return this.emit('error', err); + + async.forEachSeries(files, function (file, next) { + fs.rename(path.join(dir, file), path.join(this.path, file), next); + }.bind(this), function (err) { + if (err) return this.emit('error'); + + fs.rmdir(dir, function (err) { + if (err) return this.emit('error'); + this.emit('extract'); + }.bind(this)); + }.bind(this)); + }.bind(this)); + }.bind(this)); + }.bind(this)); + }.bind(this)); + }.bind(this)); +}; + +Package.prototype.copy = function () { + template('action', { name: 'copying', shizzle: this.path }).on('data', this.emit.bind(this, 'data')); + + tmp.dir({ prefix: 'bower-' + this.name + '-' }, function (err, tmpPath) { + if (err) return this.emit('error', err); + + fs.stat(this.path, function (err, stats) { + if (err) return this.emit('error', err); + + // Copy file permission for directory + fs.chmod(tmpPath, stats.mode, function (err) { + if (err) return this.emit('error', err); + + if (this.assetType) { + return fs.readFile(this.path, function (err, data) { + fs.writeFile(path.join((this.path = tmpPath), 'index' + this.assetType), data, function () { + this.once('loadJSON', this.saveUnit).loadJSON(); + }.bind(this)); + }.bind(this)); + } + + this.once('loadJSON', function () { + if (this.gitUrl) return this.saveUnit(); + + // Check if the copied directory is a git repository and is a local endpoint + // If so, treat it like a repository. + fileExists(path.join(this.path, '.git'), function (exists) { + if (!exists) return this.saveUnit(); + + this.gitPath = this.path; + this.once('loadJSON', this.saveUnit.bind(this)).checkout(); + }.bind(this)); + }.bind(this)); + + var writter = fstream.Writer({ + type: 'Directory', + path: tmpPath + }) + .on('error', this.emit.bind(this, 'error')) + .on('end', this.loadJSON.bind(this)); + + fstream.Reader(this.path) + .on('error', this.emit.bind(this, 'error')) + .pipe(writter); + + this.path = tmpPath; + }.bind(this)); + }.bind(this)); + }.bind(this)); +}; + +Package.prototype.getDeepDependencies = function (result) { + result = result || []; + for (var name in this.dependencies) { + result.push(this.dependencies[name]); + this.dependencies[name].getDeepDependencies(result); + } + return result; +}; + +Package.prototype.saveUnit = function () { + this.unitWork.store(this.name, this.serialize(), this); + this.unitWork.unlock(this.name, this); + this.addDependencies(); +}; + +Package.prototype.addDependencies = function () { + var dependencies = this.json.dependencies || {}; + var callbacks = Object.keys(dependencies).map(function (name) { + return function (callback) { + var endpoint = dependencies[name]; + this.dependencies[name] = new Package(name, endpoint, this); + this.dependencies[name].once('resolve', callback).resolve(); + }.bind(this); + }.bind(this)); + async.parallel(callbacks, function (err) { + if (err) return this.emit('error', err); + this.emit('resolve'); + }.bind(this)); +}; + +Package.prototype.exists = function (callback) { + fileExists(this.localPath, callback); +}; + +Package.prototype.clone = function () { + template('action', { name: 'cloning', shizzle: this.gitUrl }).on('data', this.emit.bind(this, 'data')); + this.path = this.gitPath; + this.once('cache', function () { + this.once('loadJSON', this.copy.bind(this)).checkout(); + }.bind(this)).cache(); +}; + +Package.prototype.cache = function () { + // If the force options is true, we need to erase from the cache + // Be aware that a similar package might already flushed it + // To prevent that we check the unit of work storage + if (this.opts.force && !this.unitWork.retrieve('flushed#' + this.name + '_' + this.resourceId)) { + rimraf(this.path, function (err) { + if (err) return this.emit('error', err); + this.unitWork.store('flushed#' + this.name + '_' + this.resourceId, true); + this.cache(); + }.bind(this)); + return this; + } + + mkdirp(config.cache, function (err) { + if (err) return this.emit('error', err); + fileExists(this.path, function (exists) { + if (exists) { + template('action', { name: 'cached', shizzle: this.gitUrl }).on('data', this.emit.bind(this, 'data')); + return this.emit('cache'); + } + template('action', { name: 'caching', shizzle: this.gitUrl }).on('data', this.emit.bind(this, 'data')); + var url = this.gitUrl; + if (config.proxy) { + url = url.replace(/^git:/, 'https:'); + } + + mkdirp(this.path, function (err) { + if (err) return this.emit('error', err); + + var cp = git(['clone', url, this.path], null, this); + cp.on('close', function (code) { + if (code) return; + this.emit('cache'); + }.bind(this)); + }.bind(this)); + }.bind(this)); + }.bind(this)); +}; + +Package.prototype.checkout = function () { + template('action', { name: 'fetching', shizzle: this.name }) + .on('data', this.emit.bind(this, 'data')); + + this.once('versions', function (versions) { + if (!versions.length) { + this.emit('checkout'); + this.loadJSON(); + } + + // If tag is specified, try to satisfy it + if (this.tag) { + if (!semver.validRange(this.tag)) { + return this.emit('error', new Error('Tag ' + this.tag + ' is not a valid semver range/version')); + } + + versions = versions.filter(function (version) { + return semver.satisfies(version, this.tag); + }.bind(this)); + + if (!versions.length) { + var error = new Error('Could not find tag satisfying: ' + this.name + '#' + this.tag); + error.details = 'The tag ' + this.tag + ' could not be found within the repository'; + return this.emit('error', error); + } + } + + // Use latest version + this.tag = versions[0]; + if (!semver.valid(this.tag)) this.commit = this.tag; // If the version is not valid, then its a commit + + if (this.tag) { + template('action', { + name: 'checking out', + shizzle: this.name + '#' + this.tag + }).on('data', this.emit.bind(this, 'data')); + + // Checkout the tag + git([ 'checkout', this.tag, '-f'], { cwd: this.path }, this).on('close', function (code) { + if (code) return; + // Ensure that checkout the tag as it is, removing all untracked files + git(['clean', '-f', '-d'], { cwd: this.path }, this).on('close', function (code) { + if (code) return; + this.emit('checkout'); + this.loadJSON(); + }.bind(this)); + }.bind(this)); + } + }).versions(); +}; + +Package.prototype.describeTag = function () { + var cp = git(['describe', '--always', '--tag'], { cwd: this.gitPath || this.path, ignoreCodes: [128] }, this); + var tag = ''; + + cp.stdout.setEncoding('utf8'); + cp.stdout.on('data', function (data) { + tag += data; + }); + + cp.on('close', function (code) { + if (code === 128) tag = 'unspecified'.grey; // Not a git repo + this.emit('describeTag', tag.replace(/\n$/, '')); + }.bind(this)); +}; + +Package.prototype.versions = function () { + this.once('fetch', function () { + var cp = git(['tag'], { cwd: this.gitPath }, this); + + var versions = ''; + + cp.stdout.setEncoding('utf8'); + cp.stdout.on('data', function (data) { + versions += data; + }); + + cp.on('close', function (code) { + if (code) return; + versions = versions.split('\n'); + versions = versions.filter(function (ver) { + return semver.valid(ver); + }); + versions = versions.sort(function (a, b) { + return semver.gt(a, b) ? -1 : 1; + }); + + if (versions.length) return this.emit('versions', versions); + + // If there is no versions tagged in the repo + // then we grab the hash of the last commit + versions = ''; + cp = git(['log', '-n', 1, '--format=%H'], { cwd: this.gitPath }, this); + + cp.stdout.setEncoding('utf8'); + cp.stdout.on('data', function (data) { + versions += data; + }); + cp.on('close', function (code) { + if (code) return; + versions = _.compact(versions.split('\n')); + this.emit('versions', versions); + }.bind(this)); + }.bind(this)); + }.bind(this)).fetch(); +}; + +Package.prototype.fetch = function () { + fileExists(this.gitPath, function (exists) { + if (!exists) return this.emit('error', new Error('Unable to fetch package ' + this.name + ' (if the cache was deleted, run install again)')); + + var cp = git(['fetch', '--prune'], { cwd: this.gitPath }, this); + cp.on('close', function (code) { + if (code) return; + cp = git(['reset', '--hard', this.gitUrl ? 'origin/HEAD' : 'HEAD'], { cwd: this.gitPath }, this); + cp.on('close', function (code) { + if (code) return; + this.emit('fetch'); + }.bind(this)); + }.bind(this)); + }.bind(this)); +}; + +Package.prototype.readEndpoint = function (replace) { + if (!this.json.repository) return; + + if (this.json.repository.type === 'git') { + if (replace || !this.gitUrl) { + this.gitUrl = this.json.repository.url; + this.generateResourceId(); + } + return { type: 'git', endpoint: this.gitUrl }; + } + if (this.json.repository.type === 'local-repo') { + if (replace || !this.gitPath) { + this.gitPath = path.resolve(this.json.repository.path); + } + return { type: 'local', endpoint: this.path }; + } + if (this.json.repository.type === 'local') { + if (replace || !this.path) { + this.path = path.resolve(this.json.repository.path); + } + return { type: 'local', endpoint: this.path }; + } + if (this.json.repository.type === 'asset') { + if (replace || !this.assetUrl) { + this.assetUrl = this.json.repository.url; + this.assetType = path.extname(this.assetUrl); + } + return { type: 'asset', endpoint: this.assetUrl }; + } +}; + +Package.prototype.waitUnlock = function (name) { + if (this.name === name) { + this.unitWork.removeListener('unlock', this.waitUnlock); + this.resolve(); + } +}; + +Package.prototype.serialize = function () { + return { + id: this.id, + resourceId: this.resourceId, + path: this.path, + originalPath: this.originalPath, + tag: this.tag, + originalTag: this.originalTag, + commit: this.commit, + assetUrl: this.assetUrl, + assetType: this.assetType, + lookedUp: this.lookedUp, + json: this.json, + gitUrl: this.gitUrl, + gitPath: this.gitPath, + dependencies: this.dependencies, + localConfig: this.localConfig + }; +}; + +Package.prototype.unserialize = function (obj) { + for (var key in obj) { + this[key] = obj[key]; + } + + this.version = this.tag; +}; + +Package.prototype.generateResourceId = function () { + this.resourceId = crypto.createHash('md5').update(this.name + '%' + this.gitUrl).digest('hex'); + this.gitPath = path.join(config.cache, this.name, this.resourceId); +}; + +Package.prototype.__defineGetter__('localPath', function () { + return path.join(process.cwd(), config.directory, this.name); +}); + +module.exports = Package; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/source.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/source.js new file mode 100644 index 000000000..3ab1f74d4 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/source.js @@ -0,0 +1,146 @@ +// ========================================== +// BOWER: Source Api +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var request = require('request'); +var config = require('./config'); + +var endpoint = config.endpoint + '/packages'; + +if (config.proxy) { + request = request.defaults({ proxy: config.proxy, timeout: 5000 }); +} + + +// allow for searchpath endpoints to be used for search and lookup +var endpoints = []; +endpoints.push(endpoint); +if (config.searchpath) { + for (var i = 0; i < config.searchpath.length; i += 1) { + endpoints.push(config.searchpath[i] + '/packages'); + } +} + +exports.lookup = function (name, callback) { + // walk all endpoints to find the first matching component + var f = function (i) { + var endpoint = endpoints[i]; + request.get(endpoint + '/' + encodeURIComponent(name), function (err, response, body) { + if (err || (response.statusCode !== 200 && response.statusCode !== 404)) { + return callback(err || new Error(name + ' failed to look up for endpoint: ' + endpoint)); + } + + if (response && response.statusCode !== 404) { + callback(err, body && JSON.parse(body).url); + } else { + if (i + 1 < endpoints.length) f(i + 1); + else return callback(new Error(name + ' not found')); + } + }); + }; + f(0); +}; + +exports.register = function (name, url, callback) { + var body = {name: name, url: url}; + + request.post({url: endpoint, form: body}, function (err, response) { + if (err) return callback(err); + + if (response.statusCode === 406) { + return callback(new Error('Duplicate package')); + } + + if (response.statusCode === 400) { + return callback(new Error('Incorrect format')); + } + + if (response.statusCode !== 201) { + return callback(new Error('Unknown error: ' + response.statusCode)); + } + + callback(); + }); +}; + +exports.search = function (name, callback) { + // walk all endpoints to produced federated search results + var f = function (i, map, results) { + var endpoint = endpoints[i]; + + request.get(endpoint + '/search/' + encodeURIComponent(name), function (err, response, body) { + if (err || (response.statusCode !== 200 && response.statusCode !== 404)) { + return callback(err || new Error(name + ' failed to look up for endpoint: ' + endpoint)); + } + + if (response && response.statusCode !== 404) { + var array = body && JSON.parse(body); + for (var x = 0; x < array.length; x += 1) { + var pkgName = array[x].name; + if (!map[pkgName]) { + map[pkgName] = pkgName; + results.push({ name: pkgName, url: array[x].url, endpoint: array[x].endpoint }); + } + } + } + + if (i + 1 < endpoints.length) f(i + 1, map, results); + else return callback(null, results); + }); + }; + + f(0, {}, []); +}; + +exports.info = function (name, callback) { + exports.lookup(name, function (err, url) { + if (err) return callback(err); + + var Package = require('./package'); + var pkg = new Package(name, url); + + pkg.once('error', function (err) { + pkg.removeAllListeners(); + callback(err); + }); + pkg.once('resolve', function () { + pkg.once('versions', function (versions) { + pkg.removeAllListeners(); + callback(null, { pkg: pkg, versions: versions }); + }).versions(); + }).resolve(); + }); +}; + +exports.all = function (callback) { + // walk all endpoints to produced federated search results + var f = function (i, map, results) { + var endpoint = endpoints[i]; + + request.get(endpoint, function (err, response, body) { + if (err || (response.statusCode !== 200 && response.statusCode !== 404)) { + return callback(err || new Error('Failed to look up endpoint: ' + endpoint)); + } + + if (response && response.statusCode !== 404) { + var array = body && JSON.parse(body); + for (var x = 0; x < array.length; x += 1) { + var pkgName = array[x].name; + if (!map[pkgName]) { + map[pkgName] = pkgName; + results.push({ name: pkgName, url: array[x].url, endpoint: array[x].endpoint }); + } + } + } + + if (i + 1 < endpoints.length) f(i + 1, map, results); + else return callback(null, results); + }); + }; + + f(0, {}, []); +}; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/unit_work.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/unit_work.js new file mode 100644 index 000000000..91a05e55d --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/core/unit_work.js @@ -0,0 +1,64 @@ +// ========================================== +// BOWER: Package Object Definition +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== +// Events: +// - lock: fired when a lock write over a key is acquired +// - unlock: fired when an unlock write over a key is acquired +// ========================================== + +var events = require('events'); + +var UnitWork = function () { + this.locks = []; + this.data = []; + + this.setMaxListeners(100); // Increase the number of listeners because this is a central storage +}; + +UnitWork.prototype = Object.create(events.EventEmitter.prototype); + +UnitWork.prototype.constructor = UnitWork; + +UnitWork.prototype.lock = function (key, owner) { + if (this.locks[key]) throw new Error('A write lock for "' + key + '" was already acquired.'); + if (!owner) throw new Error('A lock requires an owner.'); + this.locks[key] = owner; + + return this.emit('lock', key); +}; + +UnitWork.prototype.unlock = function (key, owner) { + if (!owner) throw new Error('A write lock requires an owner.'); + if (this.locks[key]) { + if (this.locks[key] !== owner) throw new Error('Lock owner for "' + key + '" mismatch.'); + delete this.locks[key]; + this.emit('unlock', key); + } + + return this; +}; + +UnitWork.prototype.isLocked = function (key) { + return !!this.locks[key]; +}; + +UnitWork.prototype.store = function (key, data, owner) { + if (this.locks[key] && owner !== this.locks[key]) throw new Error('A write lock for "' + key + '" is acquired therefore only its owner can write to it.'); + this.data[key] = data; + + return this; +}; + +UnitWork.prototype.retrieve = function (key) { + return this.data[key]; +}; + +UnitWork.prototype.keys = function () { + return Object.keys(this.data); +}; + +module.exports = UnitWork; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/index.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/index.js new file mode 100644 index 000000000..53cec1d46 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/index.js @@ -0,0 +1,12 @@ +// ========================================== +// BOWER: Public API Defintion +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +module.exports = { + commands: require('./commands'), + config: require('./core/config') +}; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/completion.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/completion.js new file mode 100644 index 000000000..957255468 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/completion.js @@ -0,0 +1,65 @@ +// ========================================== +// BOWER: completion +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +// This module exposes a simple helper to parse the environment variables in +// case of a tab completion command. It parses the provided `argv` (nopt's +// remain arguments after `--`) and `env` (should be process.env) +// +// It is inspired and based off Isaac's work on npm. + +module.exports = function (argv, env) { + var opts = {}; + + // w is the words number, based on the cursor position + opts.w = +env.COMP_CWORD; + + // words is the escaped sequence of words following `bower` + opts.words = argv.map(function (word) { + return word.charAt(0) === '"' ? + word.replace(/^"|"$/g, '') : + word.replace(/\\ /g, ' '); + }); + + // word is a shortcut to the last word in the line + opts.word = opts.words[opts.w - 1]; + + // line is the sequence of tab completed words. + opts.line = env.COMP_LINE; + + // point is the cursor position in the line + opts.point = +env.COMP_POINT; + + // length is the whole line's length. + opts.length = opts.line.length; + + // partialLine is the line ignoring the sequence of characters after + // cursor position, ie. tabbing at: bower install j|qu + // gives back a partialLine: bower install j + opts.partialLine = opts.line.slice(0, opts.point); + + // partialWords is only returning the words based on cursor position, + // ie tabbing at: bower install ze|pto backbone + // gives back a partialWords array: ['install', 'zepto'] + opts.partialWords = opts.words.slice(0, opts.w); + + return opts; +}; + +module.exports.log = function (arr, opts) { + arr = Array.isArray(arr) ? arr : [arr]; + arr.filter(module.exports.abbrev(opts)).forEach(function (word) { + console.log(word); + }); +}; + +module.exports.abbrev = function abbrev(opts) { + var word = opts.word.replace(/\./g, '\\.'); + return function (it) { + return new RegExp('^' + word).test(it); + }; +}; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/file-exists.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/file-exists.js new file mode 100644 index 000000000..5984f4da1 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/file-exists.js @@ -0,0 +1,26 @@ +// ========================================== +// BOWER: file-exists +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var fs = require('fs'); + +// This module exposes a version of fs.exists and fs.existsSync with a correct behaviour +// See: https://github.com/joyent/node/pull/2603 + +module.exports = function (path, callback) { + fs.stat(path, function (error) { + callback(!error || error.code !== 'ENOENT'); + }); +}; + +module.exports.sync = function (path) { + try { + return !!fs.statSync(path); + } catch (e) { + return e.code !== 'ENOENT'; + } +}; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/git-cmd.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/git-cmd.js new file mode 100644 index 000000000..a530bf545 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/git-cmd.js @@ -0,0 +1,28 @@ +// ========================================== +// BOWER: git-cmd +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +// Extension of the spawn command, that only executes git commands +// If a git command fails with code 128 in the cache, that directory +// will be deleted to prevent more issues + +var path = require('path'); +var spawn = require('./spawn'); +var rimraf = require('rimraf'); +var config = require('../core/config'); + +module.exports = function (args, options, emitter) { + var cp = spawn('git', args, options, emitter); + var cwd = options ? options.cwd || process.cwd() : process.cwd(); + var isTmp = path.normalize(cwd).indexOf(config.cache) === 0; + + cp.on('exit', function (code) { + if (code === 128 && isTmp) rimraf.sync(cwd); + }); + + return cp; +}; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/hogan-colors.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/hogan-colors.js new file mode 100644 index 000000000..2587d35d2 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/hogan-colors.js @@ -0,0 +1,28 @@ +// ========================================== +// BOWER: Hogan.js renderWithColors extension +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var colors = require('colors'); +var hogan = require('hogan.js'); +var _ = require('lodash'); +var nopt = require('nopt'); + +module.exports = hogan.Template.prototype.renderWithColors = function (context, partials, indent) { + if (nopt(process.argv).color === false) { + colors.mode = 'none'; + } + + context = _.extend({ + yellow : function (s) { return s.yellow; }, + green : function (s) { return s.green; }, + cyan : function (s) { return s.cyan; }, + grey : function (s) { return s.grey; }, + red : function (s) { return s.red; }, + white : function (s) { return s.white; } + }, context); + return this.ri([context], partials || {}, indent); +}; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/is-repo.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/is-repo.js new file mode 100644 index 000000000..aa7d84356 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/is-repo.js @@ -0,0 +1,23 @@ +// ========================================== +// BOWER: is-repo +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var fs = require('fs'); +var path = require('path'); +var fileExists = require('./file-exists'); + +// This module checks if a path is a local repository +// If the repository is a link, it will be falsy +module.exports = function (dir, callback) { + fileExists(path.join(dir, '.git'), function (exists) { + if (!exists) return callback(false); + fs.lstat(dir, function (err, stat) { + if (err) return callback(false); + callback(!stat.isSymbolicLink()); + }); + }); +}; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/prune.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/prune.js new file mode 100644 index 000000000..489cc134e --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/prune.js @@ -0,0 +1,103 @@ +// ========================================== +// BOWER: prune +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var semver = require('semver'); +var sort = require('stable'); + +var versionRequirements = function (dependencyMap) { + var result = {}; + + for (var name in dependencyMap) { + dependencyMap[name].forEach(function (pkg) { + result[name] = result[name] || []; + if (pkg.originalTag && result[name].indexOf(pkg.originalTag) === -1) { + result[name].push(pkg.originalTag); + } + }); + } + + return result; +}; + +var validVersions = function (versions, dependency) { + if (!versions || !versions.length) return true; + + // If a non resolved dependency is passed, we simply ignore it + if (!dependency.version) return false; + + if (!semver.valid(dependency.version)) { + throw new Error('Invalid semver version ' + dependency.version + ' specified in ' + dependency.name); + } + + return versions.every(function (version) { + return semver.satisfies(dependency.version, version); + }); +}; + +module.exports = function (dependencyMap, forceLatest) { + // generate version requirements + // compare dependency map with version requirements + // check for conflicts + // select best version + // return an object with the resolved deps, conflict deps and forcebly resolved ones + + var resolved = {}; + var conflicted = null; + var forceblyResolved = null; + var versionMap = versionRequirements(dependencyMap); + + var sortFunc = function (a, b) { + if (semver.gt(a.version, b.version)) return -1; + if (semver.lt(a.version, b.version)) return 1; + + // If the comparison determines that both packages are equal, do not give priority to local ones + if (a.path === a.localPath && b.path !== b.localPath) return 1; + return 0; + }; + + // Note that bellow we use a stable sort algorithm + // This is because if two packages are equal, the initial order should be respected + + for (var name in dependencyMap) { + var matches = dependencyMap[name].filter(validVersions.bind(this, versionMap[name])); + if (!matches.length) { + // No resolvable dependency + // We resolve to the latest package if the forceLatest is true + // Otherwise, check if any of those are root packages + // If so, we assume that as the resolver (with a warning) + // Otherwise there's a conflict + if (forceLatest) { + forceblyResolved = forceblyResolved || {}; + forceblyResolved[name] = sort(dependencyMap[name], sortFunc); + continue; + } + + matches = dependencyMap[name].filter(function (pkg) { return !!pkg.root; }); + if (matches.length) { + forceblyResolved = forceblyResolved || {}; + forceblyResolved[name] = dependencyMap[name].sort(function (a, b) { + if (a.root && b.root) return sortFunc(a, b); + if (a.root) return -1; + if (b.root) return 1; + return sortFunc(a, b); + }); + } else { + conflicted = conflicted || {}; + conflicted[name] = dependencyMap[name]; + } + } else { + resolved[name] = [ sort(matches, sortFunc)[0] ]; + } + } + + return { + resolved: resolved, + conflicted: conflicted, + forceblyResolved: forceblyResolved + }; +}; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/read-json.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/read-json.js new file mode 100644 index 000000000..f38b1b6d6 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/read-json.js @@ -0,0 +1,25 @@ +// ========================================== +// BOWER: read-json.js - with logging fun +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var readJSON = require('read-package-json'); +var template = require('./template'); + +var read = module.exports = function (path, cb, obj) { + readJSON.log = { + info: function () {}, + verbose: function () {}, + warn: function (what, name, shizzle) { + if (read.showWarnings) { + template('warn', { name: name.replace(/@/, '#'), shizzle: shizzle }) + .on('data', obj.emit.bind(obj, 'data')); + } + } + }; + readJSON.cache.reset(); + readJSON(path, cb); +}; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/save.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/save.js new file mode 100644 index 000000000..e60f133db --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/save.js @@ -0,0 +1,97 @@ +// ========================================== +// BOWER: save +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var path = require('path'); +var fs = require('fs'); +var semver = require('semver'); + +var _ = require('lodash'); + +var config = require('../core/config'); + +function save(manager, paths, dev, cb) { + // If there is specific paths to save, redirect to the appropriate function + if (paths && paths.length) return savePkgs.apply(savePkgs, arguments); + + manager.on('loadJSON', function (newLine) { + manager.json.dependencies = manager.json.dependencies || {}; + manager.json.devDependencies = manager.json.devDependencies || {}; + + // Only include the root packages + for (var name in manager.dependencies) { + var curr = manager.dependencies[name][0]; + if (curr.root) { + addDependency(manager.json, curr, !!manager.json.devDependencies[name]); + } + } + + // Cleanup dependencies from the json if empty + if (!Object.keys(manager.json.dependencies).length) { + delete manager.json.dependencies; + } + + // Cleanup dependencies if empty + if (!Object.keys(manager.json.devDependencies).length) { + delete manager.json.devDependencies; + } + + // Finally save the modified json + var contents = JSON.stringify(manager.json, null, 2) + (newLine ? '\n' : ''); + fs.writeFile(path.join(manager.cwd, config.json), contents, cb); + }).loadJSON(); +} + +function savePkgs(manager, paths, dev, cb) { + manager.on('loadJSON', function (newLine) { + // Find the package names that match the paths + var names = _.compact(paths.map(function (endpoint) { + endpoint = endpoint.split('#')[0]; + + return _.find(Object.keys(manager.dependencies), function (key) { + var dep = manager.dependencies[key][0]; + if (dep.name === endpoint) return true; + + var fetchedEndpoint = dep.readEndpoint(); + return fetchedEndpoint && fetchedEndpoint.endpoint === endpoint; + }); + })); + + var key = dev ? 'devDependencies' : 'dependencies'; + manager.json[key] = manager.json[key] || {}; + + // Save each of them + // Only include the root packages + names.forEach(function (name) { + addDependency(manager.json, manager.dependencies[name][0], dev); + }); + + // Finally save the modified json + var contents = JSON.stringify(manager.json, null, 2) + (newLine ? '\n' : ''); + fs.writeFile(path.join(manager.cwd, config.json), contents, cb); + }).loadJSON(); +} + +function addDependency(json, pkg, dev) { + var path; + var tag; + var key = dev ? 'devDependencies' : 'dependencies'; + + if (pkg.lookedUp) { + tag = pkg.originalTag || '~' + pkg.version; + } else { + path = (pkg.gitUrl || pkg.assetUrl || pkg.originalPath || ''); + tag = pkg.originalTag || '~' + pkg.version; + } + + // If the tag is not valid (e.g.: a commit), null it + if (!semver.valid(tag) && !semver.validRange(tag)) tag = null; + + json[key][pkg.name] = path ? path + (tag ? '#' + tag : '') : tag || 'latest'; +} + +module.exports = save; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/spawn.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/spawn.js new file mode 100644 index 000000000..28571e2bb --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/spawn.js @@ -0,0 +1,36 @@ +// ========================================== +// BOWER: spawn +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var spawn = require('child_process').spawn; + +// This module is similar to child-process spawn +// but automatically handles errors +// When an error occurs, it emits the error event containing the details of the error +// It also removes all the listeners of the command + +module.exports = function (command, args, options, emitter) { + var cp = spawn(command, args, options); + var stderr = ''; + + cp.stderr.on('data', function (data) { + stderr += data; + }); + + cp.on('exit', function (code) { + if (code && (!options || !options.ignoreCodes || options.ignoreCodes.indexOf(code) === -1)) { + cp.removeAllListeners(); + var err = new Error('status code of ' + command + ': ' + code); + err.details = stderr; + err.command = command; + err.code = code; + emitter.emit('error', err); + } + }); + + return cp; +}; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/template.js b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/template.js new file mode 100644 index 000000000..fdd5548cf --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/lib/util/template.js @@ -0,0 +1,41 @@ +// ========================================== +// BOWER: Hogan Renderer w/ template cache +// ========================================== +// Copyright 2012 Twitter, Inc +// Licensed under The MIT License +// http://opensource.org/licenses/MIT +// ========================================== + +var events = require('events'); +var hogan = require('hogan.js'); +var path = require('path'); +var fs = require('fs'); + +require('../util/hogan-colors'); + +var templates = {}; + +module.exports = function (name, context, sync) { + var emitter = new events.EventEmitter; + + var templateName = name + '.mustache'; + var templatePath = path.join(__dirname, '../../templates/', templateName); + + if (sync) { + if (!templates[templatePath]) templates[templatePath] = fs.readFileSync(templatePath, 'utf-8'); + return hogan.compile(templates[templatePath]).renderWithColors(context); + } else if (templates[templatePath]) { + process.nextTick(function () { + emitter.emit('data', hogan.compile(templates[templatePath]).renderWithColors(context)); + }); + } else { + fs.readFile(templatePath, 'utf-8', function (err, file) { + if (err) return emitter.emit('error', err); + + templates[templatePath] = file; + emitter.emit('data', hogan.compile(file).renderWithColors(context)); + }); + } + + return emitter; +}; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/.bin/hulk b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/.bin/hulk new file mode 120000 index 000000000..b1a981653 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/.bin/hulk @@ -0,0 +1 @@ +../hogan.js/bin/hulk \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/.bin/lodash b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/.bin/lodash new file mode 120000 index 000000000..24deae288 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/.bin/lodash @@ -0,0 +1 @@ +../lodash/build.js \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/.bin/nopt b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/.bin/nopt similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/.bin/nopt rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/.bin/nopt diff --git a/node/node_modules/grunt/node_modules/.bin/semver b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/.bin/semver similarity index 100% rename from node/node_modules/grunt/node_modules/.bin/semver rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/.bin/semver diff --git a/node/node_modules/grunt/node_modules/connect/node_modules/formidable/.travis.yml b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/.travis.yml similarity index 100% rename from node/node_modules/grunt/node_modules/connect/node_modules/formidable/.travis.yml rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/.travis.yml diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/README.markdown b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/README.markdown new file mode 100644 index 000000000..deaba0fd1 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/README.markdown @@ -0,0 +1,92 @@ +archy +===== + +Render nested hierarchies `npm ls` style with unicode pipes. + +[![build status](https://secure.travis-ci.org/substack/node-archy.png)](http://travis-ci.org/substack/node-archy) + +example +======= + +``` js +var archy = require('archy'); +var s = archy({ + label : 'beep', + nodes : [ + 'ity', + { + label : 'boop', + nodes : [ + { + label : 'o_O', + nodes : [ + { + label : 'oh', + nodes : [ 'hello', 'puny' ] + }, + 'human' + ] + }, + 'party\ntime!' + ] + } + ] +}); +console.log(s); +``` + +output + +``` +beep +├── ity +└─┬ boop + ├─┬ o_O + │ ├─┬ oh + │ │ ├── hello + │ │ └── puny + │ └── human + └── party + time! +``` + +methods +======= + +var archy = require('archy') + +archy(obj, prefix='', opts={}) +------------------------------ + +Return a string representation of `obj` with unicode pipe characters like how +`npm ls` looks. + +`obj` should be a tree of nested objects with `'label'` and `'nodes'` fields. +`'label'` is a string of text to display at a node level and `'nodes'` is an +array of the descendents of the current node. + +If a node is a string, that string will be used as the `'label'` and an empty +array of `'nodes'` will be used. + +`prefix` gets prepended to all the lines and is used by the algorithm to +recursively update. + +If `'label'` has newlines they will be indented at the present indentation level +with the current prefix. + +To disable unicode results in favor of all-ansi output set `opts.unicode` to +`false`. + +install +======= + +With [npm](http://npmjs.org) do: + +``` +npm install archy +``` + +license +======= + +MIT/X11 diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/examples/beep.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/examples/beep.js new file mode 100644 index 000000000..9c0704797 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/examples/beep.js @@ -0,0 +1,24 @@ +var archy = require('../'); +var s = archy({ + label : 'beep', + nodes : [ + 'ity', + { + label : 'boop', + nodes : [ + { + label : 'o_O', + nodes : [ + { + label : 'oh', + nodes : [ 'hello', 'puny' ] + }, + 'human' + ] + }, + 'party\ntime!' + ] + } + ] +}); +console.log(s); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/examples/multi_line.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/examples/multi_line.js new file mode 100644 index 000000000..8afdfada9 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/examples/multi_line.js @@ -0,0 +1,25 @@ +var archy = require('../'); + +var s = archy({ + label : 'beep\none\ntwo', + nodes : [ + 'ity', + { + label : 'boop', + nodes : [ + { + label : 'o_O\nwheee', + nodes : [ + { + label : 'oh', + nodes : [ 'hello', 'puny\nmeat' ] + }, + 'creature' + ] + }, + 'party\ntime!' + ] + } + ] +}); +console.log(s); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/index.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/index.js new file mode 100644 index 000000000..869d64e65 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/index.js @@ -0,0 +1,35 @@ +module.exports = function archy (obj, prefix, opts) { + if (prefix === undefined) prefix = ''; + if (!opts) opts = {}; + var chr = function (s) { + var chars = { + '│' : '|', + '└' : '`', + '├' : '+', + '─' : '-', + '┬' : '-' + }; + return opts.unicode === false ? chars[s] : s; + }; + + if (typeof obj === 'string') obj = { label : obj }; + + var nodes = obj.nodes || []; + var lines = (obj.label || '').split('\n'); + var splitter = '\n' + prefix + (nodes.length ? chr('│') : ' ') + ' '; + + return prefix + + lines.join(splitter) + '\n' + + nodes.map(function (node, ix) { + var last = ix === nodes.length - 1; + var more = node.nodes && node.nodes.length; + var prefix_ = prefix + (last ? ' ' : chr('│')) + ' '; + + return prefix + + (last ? chr('└') : chr('├')) + chr('─') + + (more ? chr('┬') : chr('─')) + ' ' + + archy(node, prefix_, opts).slice(prefix.length + 2) + ; + }).join('') + ; +}; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/package.json new file mode 100644 index 000000000..011a44c4f --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/package.json @@ -0,0 +1,41 @@ +{ + "name": "archy", + "version": "0.0.2", + "description": "render nested hierarchies `npm ls` style with unicode pipes", + "main": "index.js", + "directories": { + "lib": ".", + "example": "example", + "test": "test" + }, + "devDependencies": { + "tap": "~0.2.3" + }, + "scripts": { + "test": "tap test" + }, + "repository": { + "type": "git", + "url": "http://github.com/substack/node-archy.git" + }, + "keywords": [ + "hierarchy", + "npm ls", + "unicode", + "pretty", + "print" + ], + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "license": "MIT/X11", + "engine": { + "node": ">=0.4" + }, + "readme": "archy\n=====\n\nRender nested hierarchies `npm ls` style with unicode pipes.\n\n[![build status](https://secure.travis-ci.org/substack/node-archy.png)](http://travis-ci.org/substack/node-archy)\n\nexample\n=======\n\n``` js\nvar archy = require('archy');\nvar s = archy({\n label : 'beep',\n nodes : [\n 'ity',\n {\n label : 'boop',\n nodes : [\n {\n label : 'o_O',\n nodes : [\n {\n label : 'oh',\n nodes : [ 'hello', 'puny' ]\n },\n 'human'\n ]\n },\n 'party\\ntime!'\n ]\n }\n ]\n});\nconsole.log(s);\n```\n\noutput\n\n```\nbeep\n├── ity\n└─┬ boop\n ├─┬ o_O\n │ ├─┬ oh\n │ │ ├── hello\n │ │ └── puny\n │ └── human\n └── party\n time!\n```\n\nmethods\n=======\n\nvar archy = require('archy')\n\narchy(obj, prefix='', opts={})\n------------------------------\n\nReturn a string representation of `obj` with unicode pipe characters like how\n`npm ls` looks.\n\n`obj` should be a tree of nested objects with `'label'` and `'nodes'` fields.\n`'label'` is a string of text to display at a node level and `'nodes'` is an\narray of the descendents of the current node.\n\nIf a node is a string, that string will be used as the `'label'` and an empty\narray of `'nodes'` will be used.\n\n`prefix` gets prepended to all the lines and is used by the algorithm to\nrecursively update.\n\nIf `'label'` has newlines they will be indented at the present indentation level\nwith the current prefix.\n\nTo disable unicode results in favor of all-ansi output set `opts.unicode` to\n`false`.\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install archy\n```\n\nlicense\n=======\n\nMIT/X11\n", + "readmeFilename": "README.markdown", + "_id": "archy@0.0.2", + "_from": "archy@~0.0.2" +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/test/beep.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/test/beep.js new file mode 100644 index 000000000..b978c7587 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/test/beep.js @@ -0,0 +1,40 @@ +var test = require('tap').test; +var archy = require('../'); + +test('beep', function (t) { + var s = archy({ + label : 'beep', + nodes : [ + 'ity', + { + label : 'boop', + nodes : [ + { + label : 'o_O', + nodes : [ + { + label : 'oh', + nodes : [ 'hello', 'puny' ] + }, + 'human' + ] + }, + 'party!' + ] + } + ] + }); + t.equal(s, [ + 'beep', + '├── ity', + '└─┬ boop', + ' ├─┬ o_O', + ' │ ├─┬ oh', + ' │ │ ├── hello', + ' │ │ └── puny', + ' │ └── human', + ' └── party!', + '' + ].join('\n')); + t.end(); +}); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/test/multi_line.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/test/multi_line.js new file mode 100644 index 000000000..737cb654c --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/test/multi_line.js @@ -0,0 +1,45 @@ +var test = require('tap').test; +var archy = require('../'); + +test('multi-line', function (t) { + var s = archy({ + label : 'beep\none\ntwo', + nodes : [ + 'ity', + { + label : 'boop', + nodes : [ + { + label : 'o_O\nwheee', + nodes : [ + { + label : 'oh', + nodes : [ 'hello', 'puny\nmeat' ] + }, + 'creature' + ] + }, + 'party\ntime!' + ] + } + ] + }); + t.equal(s, [ + 'beep', + '│ one', + '│ two', + '├── ity', + '└─┬ boop', + ' ├─┬ o_O', + ' │ │ wheee', + ' │ ├─┬ oh', + ' │ │ ├── hello', + ' │ │ └── puny', + ' │ │ meat', + ' │ └── creature', + ' └── party', + ' time!', + '' + ].join('\n')); + t.end(); +}); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/test/non_unicode.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/test/non_unicode.js new file mode 100644 index 000000000..2f7cdafd1 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/archy/test/non_unicode.js @@ -0,0 +1,40 @@ +var test = require('tap').test; +var archy = require('../'); + +test('beep', function (t) { + var s = archy({ + label : 'beep', + nodes : [ + 'ity', + { + label : 'boop', + nodes : [ + { + label : 'o_O', + nodes : [ + { + label : 'oh', + nodes : [ 'hello', 'puny' ] + }, + 'human' + ] + }, + 'party!' + ] + } + ] + }, '', { unicode : false }); + t.equal(s, [ + 'beep', + '+-- ity', + '`-- boop', + ' +-- o_O', + ' | +-- oh', + ' | | +-- hello', + ' | | `-- puny', + ' | `-- human', + ' `-- party!', + '' + ].join('\n')); + t.end(); +}); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/async/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/async/LICENSE new file mode 100644 index 000000000..b7f9d5001 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/async/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2010 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/node_modules/grunt-bower-task/node_modules/bower/node_modules/async/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/async/README.md new file mode 100644 index 000000000..c5e8b5189 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/async/README.md @@ -0,0 +1,1414 @@ +# Async.js + +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. + +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'], path.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) +* [map](#map) +* [filter](#filter) +* [reject](#reject) +* [reduce](#reduce) +* [detect](#detect) +* [sortBy](#sortBy) +* [some](#some) +* [every](#every) +* [concat](#concat) + +### Control Flow + +* [series](#series) +* [parallel](#parallel) +* [whilst](#whilst) +* [doWhilst](#doWhilst) +* [until](#until) +* [doUntil](#doUntil) +* [forever](#forever) +* [waterfall](#waterfall) +* [compose](#compose) +* [applyEach](#applyEach) +* [queue](#queue) +* [cargo](#cargo) +* [auto](#auto) +* [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 an iterator function to each item in an array, 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 this callback, the main +callback for the each 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. + +__Arguments__ + +* arr - An array to iterate over. +* iterator(item, callback) - A function to apply to each item in the array. + 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 after all the iterator functions + have finished, or an error has occurred. + +__Example__ + +```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 +}); +``` + +--------------------------------------- + + + +### eachSeries(arr, iterator, callback) + +The same as each only the iterator is applied to each item in the array in +series. The next iterator is only called once the current one has completed +processing. This means the iterator functions will complete in order. + + +--------------------------------------- + + + +### eachLimit(arr, limit, iterator, callback) + +The same as each only no more than "limit" iterators 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 iterators to run at any time. +* iterator(item, callback) - A function to apply to each item in the array. + 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 after all the iterator functions + have finished, or an error has occurred. + +__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 the given array through +the iterator function. The iterator is called with an item from the array and a +callback for when it has finished processing. The callback takes 2 arguments, +an error and the transformed item from the array. If the 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 array. + +__Arguments__ + +* arr - An array to iterate over. +* iterator(item, callback) - A function to apply to each item in the array. + 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 after all the iterator + functions have finished, or an error has occurred. Results is an array of the + transformed items from the original array. + +__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 only the iterator is applied to each item in the array in +series. The next iterator is only called once the current one has completed +processing. The results array will be in the same order as the original. + + +--------------------------------------- + + +### mapLimit(arr, limit, iterator, callback) + +The same as map only no more than "limit" iterators 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 iterators to run at any time. +* iterator(item, callback) - A function to apply to each item in the array. + 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 after all the iterator + functions have finished, or an error has occurred. Results is an array of the + transformed items from the original array. + +__Example__ + +```js +async.map(['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 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 path.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 the array. + 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'], path.exists, function(results){ + // results now equals an array of the existing files +}); +``` + +--------------------------------------- + + +### filterSeries(arr, iterator, callback) + +__alias:__ selectSeries + +The same as filter only the iterator is applied to each item in the array in +series. The next iterator is only called once the current one has completed +processing. The results array will be in the same order as the original. + +--------------------------------------- + + +### reject(arr, iterator, callback) + +The opposite of filter. Removes values that pass an async truth test. + +--------------------------------------- + + +### rejectSeries(arr, iterator, callback) + +The same as reject, only the iterator is applied to each item in the array +in series. + + +--------------------------------------- + + +### reduce(arr, memo, iterator, callback) + +__aliases:__ inject, foldl + +Reduces a list of values 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, 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, only operates on the items in the array in reverse order. + + +--------------------------------------- + + +### detect(arr, iterator, callback) + +Returns the first value in a list 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 array (in terms of order) that passes the test. + +If order within the original array is important then look at detectSeries. + +__Arguments__ + +* arr - An array to iterate over. +* iterator(item, callback) - A truth test to apply to each item in the array. + 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'], path.exists, function(result){ + // result now equals the first file in the list that exists +}); +``` + +--------------------------------------- + + +### detectSeries(arr, iterator, callback) + +The same as detect, only the iterator is applied to each item in the array +in series. This means the result is always the first in the original array (in +terms of array order) that passes the truth test. + + +--------------------------------------- + + +### sortBy(arr, iterator, callback) + +Sorts a list by the results of running each value through an async iterator. + +__Arguments__ + +* arr - An array to iterate over. +* iterator(item, callback) - A function to apply to each item in the array. + 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 has occurred. Results is the items from + the original array 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 +}); +``` + +--------------------------------------- + + +### some(arr, iterator, callback) + +__Alias:__ any + +Returns true if at least one element in the array 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 path.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. + 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'], path.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 the array 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 path.exists. + +__Arguments__ + +* arr - An array to iterate over. +* iterator(item, callback) - A truth test to apply to each item in the array. + 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'], path.exists, function(result){ + // if result is true then every file exists +}); +``` + +--------------------------------------- + + +### concat(arr, iterator, callback) + +Applies an iterator to each item in a list, concatenating the results. Returns the +concatenated list. The iterators 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 the arguments passed to the iterator function. + +__Arguments__ + +* arr - An array to iterate over +* iterator(item, callback) - A function to apply to each item in the array. + 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 has occurred. 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 async.concat, but executes in series instead of parallel. + + +## Control Flow + + +### series(tasks, [callback]) + +Run an array of functions 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 the callback for the series 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 +async.series. + + +__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 (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 an 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 +async.parallel. + + +__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 (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 only the 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 (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 the callback when stopped, +or an error occurs. + +__Arguments__ + +* test() - synchronous truth test to perform before each execution of fn. +* fn(callback) - A function to call each time the test passes. The function is + passed a callback(err) which must be called once it has completed with an + optional error 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. To reflect the difference in the order of operations `test` and `fn` arguments 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 the callback when stopped, +or an error occurs. + +The inverse of async.whilst. + +--------------------------------------- + + +### doUntil(fn, test, callback) + +Like doWhilst except the test is inverted. Note the argument ordering differs from `until`. + +--------------------------------------- + + +### forever(fn, callback) + +Calls the asynchronous function 'fn' repeatedly, in series, indefinitely. +If an error is passed to fn's callback then 'callback' is called with the +error, otherwise it will never be called. + +--------------------------------------- + + +### waterfall(tasks, [callback]) + +Runs an array of functions in series, each passing their results to the next in +the array. However, if any of the functions pass an error to the 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){ + 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 +}); +``` + +--------------------------------------- + +### applyEach(fns, args..., callback) + +Applies the provided arguments to each function in the array, calling the +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 only the functions are applied in series. + +--------------------------------------- + + +### queue(worker, concurrency) + +Creates a queue object with the specified concurrency. Tasks added to the +queue will be processed in parallel (up to the concurrency limit). If all +workers are in progress, the task is queued until one is available. Once +a worker has completed a task, the 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. +* 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, 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. +* 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 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 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'); +}); +``` + +--------------------------------------- + + +### 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 is available. Once +the worker has completed some tasks, each callback of those tasks is called. + +__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 error as an 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]) - add a new 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 functions 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, that function will not complete +(so any other functions depending on it will not run) and the main callback +will be called immediately 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 literal containing named functions or an array of + requirements, with the function itself the last item in the array. The key + used for each function or array is used when specifying requirements. 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. The callback will receive an error as an argument + if any tasks pass an error to their callback. Results will always be passed + but if an error occurred, no other tasks will be performed, and the results + object will only contain partial results. + + +__Example__ + +```js +async.auto({ + get_data: function(callback){ + // async code to get some data + }, + make_folder: function(callback){ + // async code to create a directory to store a file in + // this is run at the same time as getting the data + }, + write_file: ['get_data', 'make_folder', function(callback){ + // 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){ + // once the file is written let's email a link to it... + // results.write_file contains the filename returned by write_file. + }] +}); +``` + +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){ + // async code to get some data + }, + function(callback){ + // async code to create a directory to store a file in + // this is run at the same time as getting the data + } +], +function(err, results){ + async.series([ + function(callback){ + // once there is some data and the directory exists, + // write the data to a file in the directory + }, + function(callback){ + // once the file is written let's email a link to it... + } + ]); +}); +``` + +For a complicated series of async tasks using the auto function makes adding +new tasks much easier and makes the code more readable. + + +--------------------------------------- + + +### iterator(tasks) + +Creates an iterator function which calls the next function in the array, +returning a continuation to call the next one after that. It's also possible to +'peek' the next iterator by doing 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, a useful +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 the 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 the 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 n times and accumulates results in the same manner +you would use with async.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 only the iterator is applied to each item in the array in +series. The next iterator is only called once the current one has completed +processing. 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 you to proxy and cache results from. +* hasher - an 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 memoized function, reverting it to the original, unmemoized +form. Comes handy in tests. + +__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/node_modules/grunt-bower-task/node_modules/bower/node_modules/async/lib/async.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/async/lib/async.js new file mode 100755 index 000000000..46f4f509e --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/async/lib/async.js @@ -0,0 +1,952 @@ +/*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 _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.setImmediate = setImmediate; + async.nextTick = setImmediate; + } + else { + async.nextTick = function (fn) { + setTimeout(fn, 0); + }; + async.setImmediate = async.nextTick; + } + } + else { + async.nextTick = process.nextTick; + if (typeof setImmediate !== 'undefined') { + async.setImmediate = setImmediate; + } + 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(function (err) { + if (err) { + callback(err); + callback = function () {}; + } + else { + completed += 1; + if (completed >= arr.length) { + callback(null); + } + } + })); + }); + }; + 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(null); + } + 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) { + var results = []; + arr = _map(arr, function (x, i) { + return {index: i, value: x}; + }); + 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); + if (!keys.length) { + return callback(null); + } + + 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 () { + _each(listeners.slice(0), function (fn) { + fn(); + }); + }; + + addListener(function () { + if (_keys(results).length === keys.length) { + callback(null, results); + callback = function () {}; + } + }); + + _each(keys, function (k) { + var task = (tasks[k] instanceof Function) ? [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.waterfall = function (tasks, callback) { + callback = callback || function () {}; + if (tasks.constructor !== Array) { + 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 (tasks.constructor === Array) { + 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 (tasks.constructor === Array) { + 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); + } + if (test()) { + 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); + } + if (!test()) { + async.doUntil(iterator, test, callback); + } + else { + callback(); + } + }); + }; + + async.queue = function (worker, concurrency) { + if (concurrency === undefined) { + concurrency = 1; + } + function _insert(q, data, pos, callback) { + if(data.constructor !== Array) { + data = [data]; + } + _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 === concurrency) { + q.saturated(); + } + async.setImmediate(q.process); + }); + } + + var workers = 0; + var q = { + tasks: [], + concurrency: concurrency, + saturated: null, + empty: null, + drain: null, + push: function (data, callback) { + _insert(q, data, false, callback); + }, + unshift: function (data, callback) { + _insert(q, data, true, callback); + }, + process: function () { + if (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; + } + }; + return q; + }; + + async.cargo = function (worker, payload) { + var working = false, + tasks = []; + + var cargo = { + tasks: tasks, + payload: payload, + saturated: null, + empty: null, + drain: null, + push: function (data, callback) { + if(data.constructor !== Array) { + data = [data]; + } + _each(data, function(task) { + tasks.push({ + data: task, + callback: typeof callback === 'function' ? callback : null + }); + 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.drain(); + return; + } + + var ts = typeof payload === 'number' + ? tasks.splice(0, payload) + : tasks.splice(0); + + 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) { + 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.compose = function (/* functions... */) { + var fns = Array.prototype.reverse.call(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)); + }); + }; + }; + + 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(); + }; + + // AMD / RequireJS + if (typeof define !== 'undefined' && define.amd) { + define([], function () { + return async; + }); + } + // Node.js + else if (typeof module !== 'undefined' && module.exports) { + module.exports = async; + } + // included directly via \n\n```\n\n## Documentation\n\n### Collections\n\n* [each](#each)\n* [map](#map)\n* [filter](#filter)\n* [reject](#reject)\n* [reduce](#reduce)\n* [detect](#detect)\n* [sortBy](#sortBy)\n* [some](#some)\n* [every](#every)\n* [concat](#concat)\n\n### Control Flow\n\n* [series](#series)\n* [parallel](#parallel)\n* [whilst](#whilst)\n* [doWhilst](#doWhilst)\n* [until](#until)\n* [doUntil](#doUntil)\n* [forever](#forever)\n* [waterfall](#waterfall)\n* [compose](#compose)\n* [applyEach](#applyEach)\n* [queue](#queue)\n* [cargo](#cargo)\n* [auto](#auto)\n* [iterator](#iterator)\n* [apply](#apply)\n* [nextTick](#nextTick)\n* [times](#times)\n* [timesSeries](#timesSeries)\n\n### Utils\n\n* [memoize](#memoize)\n* [unmemoize](#unmemoize)\n* [log](#log)\n* [dir](#dir)\n* [noConflict](#noConflict)\n\n\n## Collections\n\n\n\n### each(arr, iterator, callback)\n\nApplies an iterator function to each item in an array, in parallel.\nThe iterator is called with an item from the list and a callback for when it\nhas finished. If the iterator passes an error to this callback, the main\ncallback for the each function is immediately called with the error.\n\nNote, that since this function applies the iterator to each item in parallel\nthere is no guarantee that the iterator functions will complete in order.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback(err) which must be called once it has \n completed. If no error has occured, the callback should be run without \n arguments or with an explicit null argument.\n* callback(err) - A callback which is called after all the iterator functions\n have finished, or an error has occurred.\n\n__Example__\n\n```js\n// assuming openFiles is an array of file names and saveFile is a function\n// to save the modified contents of that file:\n\nasync.each(openFiles, saveFile, function(err){\n // if any of the saves produced an error, err would equal that error\n});\n```\n\n---------------------------------------\n\n\n\n### eachSeries(arr, iterator, callback)\n\nThe same as each only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. This means the iterator functions will complete in order.\n\n\n---------------------------------------\n\n\n\n### eachLimit(arr, limit, iterator, callback)\n\nThe same as each only no more than \"limit\" iterators will be simultaneously \nrunning at any time.\n\nNote that the items are not processed in batches, so there is no guarantee that\n the first \"limit\" iterator functions will complete before any others are \nstarted.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* limit - The maximum number of iterators to run at any time.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback(err) which must be called once it has \n completed. If no error has occured, the callback should be run without \n arguments or with an explicit null argument.\n* callback(err) - A callback which is called after all the iterator functions\n have finished, or an error has occurred.\n\n__Example__\n\n```js\n// Assume documents is an array of JSON objects and requestApi is a\n// function that interacts with a rate-limited REST api.\n\nasync.eachLimit(documents, 20, requestApi, function(err){\n // if any of the saves produced an error, err would equal that error\n});\n```\n\n---------------------------------------\n\n\n### map(arr, iterator, callback)\n\nProduces a new array of values by mapping each value in the given array through\nthe iterator function. The iterator is called with an item from the array and a\ncallback for when it has finished processing. The callback takes 2 arguments, \nan error and the transformed item from the array. If the iterator passes an\nerror to this callback, the main callback for the map function is immediately\ncalled with the error.\n\nNote, that since this function applies the iterator to each item in parallel\nthere is no guarantee that the iterator functions will complete in order, however\nthe results array will be in the same order as the original array.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback(err, transformed) which must be called once \n it has completed with an error (which can be null) and a transformed item.\n* callback(err, results) - A callback which is called after all the iterator\n functions have finished, or an error has occurred. Results is an array of the\n transformed items from the original array.\n\n__Example__\n\n```js\nasync.map(['file1','file2','file3'], fs.stat, function(err, results){\n // results is now an array of stats for each file\n});\n```\n\n---------------------------------------\n\n\n### mapSeries(arr, iterator, callback)\n\nThe same as map only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n\n---------------------------------------\n\n\n### mapLimit(arr, limit, iterator, callback)\n\nThe same as map only no more than \"limit\" iterators will be simultaneously \nrunning at any time.\n\nNote that the items are not processed in batches, so there is no guarantee that\n the first \"limit\" iterator functions will complete before any others are \nstarted.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* limit - The maximum number of iterators to run at any time.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback(err, transformed) which must be called once \n it has completed with an error (which can be null) and a transformed item.\n* callback(err, results) - A callback which is called after all the iterator\n functions have finished, or an error has occurred. Results is an array of the\n transformed items from the original array.\n\n__Example__\n\n```js\nasync.map(['file1','file2','file3'], 1, fs.stat, function(err, results){\n // results is now an array of stats for each file\n});\n```\n\n---------------------------------------\n\n\n### filter(arr, iterator, callback)\n\n__Alias:__ select\n\nReturns a new array of all the values which pass an async truth test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like path.exists. This operation is\nperformed in parallel, but the results array will be in the same order as the\noriginal.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n The iterator is passed a callback(truthValue) which must be called with a \n boolean argument once it has completed.\n* callback(results) - A callback which is called after all the iterator\n functions have finished.\n\n__Example__\n\n```js\nasync.filter(['file1','file2','file3'], path.exists, function(results){\n // results now equals an array of the existing files\n});\n```\n\n---------------------------------------\n\n\n### filterSeries(arr, iterator, callback)\n\n__alias:__ selectSeries\n\nThe same as filter only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n---------------------------------------\n\n\n### reject(arr, iterator, callback)\n\nThe opposite of filter. Removes values that pass an async truth test.\n\n---------------------------------------\n\n\n### rejectSeries(arr, iterator, callback)\n\nThe same as reject, only the iterator is applied to each item in the array\nin series.\n\n\n---------------------------------------\n\n\n### reduce(arr, memo, iterator, callback)\n\n__aliases:__ inject, foldl\n\nReduces a list of values into a single value using an async iterator to return\neach successive step. Memo is the initial state of the reduction. This\nfunction only operates in series. For performance reasons, it may make sense to\nsplit a call to this function into a parallel map, then use the normal\nArray.prototype.reduce on the results. This function is for situations where\neach step in the reduction needs to be async, if you can get the data before\nreducing it then it's probably a good idea to do so.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* memo - The initial state of the reduction.\n* iterator(memo, item, callback) - A function applied to each item in the\n array to produce the next step in the reduction. The iterator is passed a\n callback(err, reduction) which accepts an optional error as its first \n argument, and the state of the reduction as the second. If an error is \n passed to the callback, the reduction is stopped and the main callback is \n immediately called with the error.\n* callback(err, result) - A callback which is called after all the iterator\n functions have finished. Result is the reduced value.\n\n__Example__\n\n```js\nasync.reduce([1,2,3], 0, function(memo, item, callback){\n // pointless async:\n process.nextTick(function(){\n callback(null, memo + item)\n });\n}, function(err, result){\n // result is now equal to the last value of memo, which is 6\n});\n```\n\n---------------------------------------\n\n\n### reduceRight(arr, memo, iterator, callback)\n\n__Alias:__ foldr\n\nSame as reduce, only operates on the items in the array in reverse order.\n\n\n---------------------------------------\n\n\n### detect(arr, iterator, callback)\n\nReturns the first value in a list that passes an async truth test. The\niterator is applied in parallel, meaning the first iterator to return true will\nfire the detect callback with that result. That means the result might not be\nthe first item in the original array (in terms of order) that passes the test.\n\nIf order within the original array is important then look at detectSeries.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n The iterator is passed a callback(truthValue) which must be called with a \n boolean argument once it has completed.\n* callback(result) - A callback which is called as soon as any iterator returns\n true, or after all the iterator functions have finished. Result will be\n the first item in the array that passes the truth test (iterator) or the\n value undefined if none passed.\n\n__Example__\n\n```js\nasync.detect(['file1','file2','file3'], path.exists, function(result){\n // result now equals the first file in the list that exists\n});\n```\n\n---------------------------------------\n\n\n### detectSeries(arr, iterator, callback)\n\nThe same as detect, only the iterator is applied to each item in the array\nin series. This means the result is always the first in the original array (in\nterms of array order) that passes the truth test.\n\n\n---------------------------------------\n\n\n### sortBy(arr, iterator, callback)\n\nSorts a list by the results of running each value through an async iterator.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback(err, sortValue) which must be called once it\n has completed with an error (which can be null) and a value to use as the sort\n criteria.\n* callback(err, results) - A callback which is called after all the iterator\n functions have finished, or an error has occurred. Results is the items from\n the original array sorted by the values returned by the iterator calls.\n\n__Example__\n\n```js\nasync.sortBy(['file1','file2','file3'], function(file, callback){\n fs.stat(file, function(err, stats){\n callback(err, stats.mtime);\n });\n}, function(err, results){\n // results is now the original array of files sorted by\n // modified date\n});\n```\n\n---------------------------------------\n\n\n### some(arr, iterator, callback)\n\n__Alias:__ any\n\nReturns true if at least one element in the array satisfies an async test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like path.exists. Once any iterator\ncall returns true, the main callback is immediately called.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n The iterator is passed a callback(truthValue) which must be called with a \n boolean argument once it has completed.\n* callback(result) - A callback which is called as soon as any iterator returns\n true, or after all the iterator functions have finished. Result will be\n either true or false depending on the values of the async tests.\n\n__Example__\n\n```js\nasync.some(['file1','file2','file3'], path.exists, function(result){\n // if result is true then at least one of the files exists\n});\n```\n\n---------------------------------------\n\n\n### every(arr, iterator, callback)\n\n__Alias:__ all\n\nReturns true if every element in the array satisfies an async test.\n_The callback for each iterator call only accepts a single argument of true or\nfalse, it does not accept an error argument first!_ This is in-line with the\nway node libraries work with truth tests like path.exists.\n\n__Arguments__\n\n* arr - An array to iterate over.\n* iterator(item, callback) - A truth test to apply to each item in the array.\n The iterator is passed a callback(truthValue) which must be called with a \n boolean argument once it has completed.\n* callback(result) - A callback which is called after all the iterator\n functions have finished. Result will be either true or false depending on\n the values of the async tests.\n\n__Example__\n\n```js\nasync.every(['file1','file2','file3'], path.exists, function(result){\n // if result is true then every file exists\n});\n```\n\n---------------------------------------\n\n\n### concat(arr, iterator, callback)\n\nApplies an iterator to each item in a list, concatenating the results. Returns the\nconcatenated list. The iterators are called in parallel, and the results are\nconcatenated as they return. There is no guarantee that the results array will\nbe returned in the original order of the arguments passed to the iterator function.\n\n__Arguments__\n\n* arr - An array to iterate over\n* iterator(item, callback) - A function to apply to each item in the array.\n The iterator is passed a callback(err, results) which must be called once it \n has completed with an error (which can be null) and an array of results.\n* callback(err, results) - A callback which is called after all the iterator\n functions have finished, or an error has occurred. Results is an array containing\n the concatenated results of the iterator function.\n\n__Example__\n\n```js\nasync.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){\n // files is now a list of filenames that exist in the 3 directories\n});\n```\n\n---------------------------------------\n\n\n### concatSeries(arr, iterator, callback)\n\nSame as async.concat, but executes in series instead of parallel.\n\n\n## Control Flow\n\n\n### series(tasks, [callback])\n\nRun an array of functions in series, each one running once the previous\nfunction has completed. If any functions in the series pass an error to its\ncallback, no more functions are run and the callback for the series is\nimmediately called with the value of the error. Once the tasks have completed,\nthe results are passed to the final callback as an array.\n\nIt is also possible to use an object instead of an array. Each property will be\nrun as a function and the results will be passed to the final callback as an object\ninstead of an array. This can be a more readable way of handling results from\nasync.series.\n\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed\n a callback(err, result) it must call on completion with an error (which can\n be null) and an optional result value.\n* callback(err, results) - An optional callback to run once all the functions\n have completed. This function gets a results array (or object) containing all \n the result arguments passed to the task callbacks.\n\n__Example__\n\n```js\nasync.series([\n function(callback){\n // do some stuff ...\n callback(null, 'one');\n },\n function(callback){\n // do some more stuff ...\n callback(null, 'two');\n }\n],\n// optional callback\nfunction(err, results){\n // results is now equal to ['one', 'two']\n});\n\n\n// an example using an object instead of an array\nasync.series({\n one: function(callback){\n setTimeout(function(){\n callback(null, 1);\n }, 200);\n },\n two: function(callback){\n setTimeout(function(){\n callback(null, 2);\n }, 100);\n }\n},\nfunction(err, results) {\n // results is now equal to: {one: 1, two: 2}\n});\n```\n\n---------------------------------------\n\n\n### parallel(tasks, [callback])\n\nRun an array of functions in parallel, without waiting until the previous\nfunction has completed. If any of the functions pass an error to its\ncallback, the main callback is immediately called with the value of the error.\nOnce the tasks have completed, the results are passed to the final callback as an\narray.\n\nIt is also possible to use an object instead of an array. Each property will be\nrun as a function and the results will be passed to the final callback as an object\ninstead of an array. This can be a more readable way of handling results from\nasync.parallel.\n\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed \n a callback(err, result) it must call on completion with an error (which can\n be null) and an optional result value.\n* callback(err, results) - An optional callback to run once all the functions\n have completed. This function gets a results array (or object) containing all \n the result arguments passed to the task callbacks.\n\n__Example__\n\n```js\nasync.parallel([\n function(callback){\n setTimeout(function(){\n callback(null, 'one');\n }, 200);\n },\n function(callback){\n setTimeout(function(){\n callback(null, 'two');\n }, 100);\n }\n],\n// optional callback\nfunction(err, results){\n // the results array will equal ['one','two'] even though\n // the second function had a shorter timeout.\n});\n\n\n// an example using an object instead of an array\nasync.parallel({\n one: function(callback){\n setTimeout(function(){\n callback(null, 1);\n }, 200);\n },\n two: function(callback){\n setTimeout(function(){\n callback(null, 2);\n }, 100);\n }\n},\nfunction(err, results) {\n // results is now equals to: {one: 1, two: 2}\n});\n```\n\n---------------------------------------\n\n\n### parallelLimit(tasks, limit, [callback])\n\nThe same as parallel only the tasks are executed in parallel with a maximum of \"limit\" \ntasks executing at any time.\n\nNote that the tasks are not executed in batches, so there is no guarantee that \nthe first \"limit\" tasks will complete before any others are started.\n\n__Arguments__\n\n* tasks - An array or object containing functions to run, each function is passed \n a callback(err, result) it must call on completion with an error (which can\n be null) and an optional result value.\n* limit - The maximum number of tasks to run at any time.\n* callback(err, results) - An optional callback to run once all the functions\n have completed. This function gets a results array (or object) containing all \n the result arguments passed to the task callbacks.\n\n---------------------------------------\n\n\n### whilst(test, fn, callback)\n\nRepeatedly call fn, while test returns true. Calls the callback when stopped,\nor an error occurs.\n\n__Arguments__\n\n* test() - synchronous truth test to perform before each execution of fn.\n* fn(callback) - A function to call each time the test passes. The function is\n passed a callback(err) which must be called once it has completed with an \n optional error argument.\n* callback(err) - A callback which is called after the test fails and repeated\n execution of fn has stopped.\n\n__Example__\n\n```js\nvar count = 0;\n\nasync.whilst(\n function () { return count < 5; },\n function (callback) {\n count++;\n setTimeout(callback, 1000);\n },\n function (err) {\n // 5 seconds have passed\n }\n);\n```\n\n---------------------------------------\n\n\n### doWhilst(fn, test, callback)\n\nThe post check version of whilst. To reflect the difference in the order of operations `test` and `fn` arguments are switched. `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript.\n\n---------------------------------------\n\n\n### until(test, fn, callback)\n\nRepeatedly call fn, until test returns true. Calls the callback when stopped,\nor an error occurs.\n\nThe inverse of async.whilst.\n\n---------------------------------------\n\n\n### doUntil(fn, test, callback)\n\nLike doWhilst except the test is inverted. Note the argument ordering differs from `until`.\n\n---------------------------------------\n\n\n### forever(fn, callback)\n\nCalls the asynchronous function 'fn' repeatedly, in series, indefinitely.\nIf an error is passed to fn's callback then 'callback' is called with the\nerror, otherwise it will never be called.\n\n---------------------------------------\n\n\n### waterfall(tasks, [callback])\n\nRuns an array of functions in series, each passing their results to the next in\nthe array. However, if any of the functions pass an error to the callback, the\nnext function is not executed and the main callback is immediately called with\nthe error.\n\n__Arguments__\n\n* tasks - An array of functions to run, each function is passed a \n callback(err, result1, result2, ...) it must call on completion. The first\n argument is an error (which can be null) and any further arguments will be \n passed as arguments in order to the next task.\n* callback(err, [results]) - An optional callback to run once all the functions\n have completed. This will be passed the results of the last task's callback.\n\n\n\n__Example__\n\n```js\nasync.waterfall([\n function(callback){\n callback(null, 'one', 'two');\n },\n function(arg1, arg2, callback){\n callback(null, 'three');\n },\n function(arg1, callback){\n // arg1 now equals 'three'\n callback(null, 'done');\n }\n], function (err, result) {\n // result now equals 'done' \n});\n```\n\n---------------------------------------\n\n### compose(fn1, fn2...)\n\nCreates a function which is a composition of the passed asynchronous\nfunctions. Each function consumes the return value of the function that\nfollows. Composing functions f(), g() and h() would produce the result of\nf(g(h())), only this version uses callbacks to obtain the return values.\n\nEach function is executed with the `this` binding of the composed function.\n\n__Arguments__\n\n* functions... - the asynchronous functions to compose\n\n\n__Example__\n\n```js\nfunction add1(n, callback) {\n setTimeout(function () {\n callback(null, n + 1);\n }, 10);\n}\n\nfunction mul3(n, callback) {\n setTimeout(function () {\n callback(null, n * 3);\n }, 10);\n}\n\nvar add1mul3 = async.compose(mul3, add1);\n\nadd1mul3(4, function (err, result) {\n // result now equals 15\n});\n```\n\n---------------------------------------\n\n### applyEach(fns, args..., callback)\n\nApplies the provided arguments to each function in the array, calling the\ncallback after all functions have completed. If you only provide the first\nargument then it will return a function which lets you pass in the\narguments as if it were a single function call.\n\n__Arguments__\n\n* fns - the asynchronous functions to all call with the same arguments\n* args... - any number of separate arguments to pass to the function\n* callback - the final argument should be the callback, called when all\n functions have completed processing\n\n\n__Example__\n\n```js\nasync.applyEach([enableSearch, updateSchema], 'bucket', callback);\n\n// partial application example:\nasync.each(\n buckets,\n async.applyEach([enableSearch, updateSchema]),\n callback\n);\n```\n\n---------------------------------------\n\n\n### applyEachSeries(arr, iterator, callback)\n\nThe same as applyEach only the functions are applied in series.\n\n---------------------------------------\n\n\n### queue(worker, concurrency)\n\nCreates a queue object with the specified concurrency. Tasks added to the\nqueue will be processed in parallel (up to the concurrency limit). If all\nworkers are in progress, the task is queued until one is available. Once\na worker has completed a task, the task's callback is called.\n\n__Arguments__\n\n* worker(task, callback) - An asynchronous function for processing a queued\n task, which must call its callback(err) argument when finished, with an \n optional error as an argument.\n* concurrency - An integer for determining how many worker functions should be\n run in parallel.\n\n__Queue objects__\n\nThe queue object returned by this function has the following properties and\nmethods:\n\n* length() - a function returning the number of items waiting to be processed.\n* concurrency - an integer for determining how many worker functions should be\n run in parallel. This property can be changed after a queue is created to\n alter the concurrency on-the-fly.\n* push(task, [callback]) - add a new task to the queue, the callback is called\n once the worker has finished processing the task.\n instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list.\n* unshift(task, [callback]) - add a new task to the front of the queue.\n* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued\n* empty - a callback that is called when the last item from the queue is given to a worker\n* drain - a callback that is called when the last item from the queue has returned from the worker\n\n__Example__\n\n```js\n// create a queue object with concurrency 2\n\nvar q = async.queue(function (task, callback) {\n console.log('hello ' + task.name);\n callback();\n}, 2);\n\n\n// assign a callback\nq.drain = function() {\n console.log('all items have been processed');\n}\n\n// add some items to the queue\n\nq.push({name: 'foo'}, function (err) {\n console.log('finished processing foo');\n});\nq.push({name: 'bar'}, function (err) {\n console.log('finished processing bar');\n});\n\n// add some items to the queue (batch-wise)\n\nq.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) {\n console.log('finished processing bar');\n});\n\n// add some items to the front of the queue\n\nq.unshift({name: 'bar'}, function (err) {\n console.log('finished processing bar');\n});\n```\n\n---------------------------------------\n\n\n### cargo(worker, [payload])\n\nCreates a cargo object with the specified payload. Tasks added to the\ncargo will be processed altogether (up to the payload limit). If the\nworker is in progress, the task is queued until it is available. Once\nthe worker has completed some tasks, each callback of those tasks is called.\n\n__Arguments__\n\n* worker(tasks, callback) - An asynchronous function for processing an array of\n queued tasks, which must call its callback(err) argument when finished, with \n an optional error as an argument.\n* payload - An optional integer for determining how many tasks should be\n processed per round; if omitted, the default is unlimited.\n\n__Cargo objects__\n\nThe cargo object returned by this function has the following properties and\nmethods:\n\n* length() - a function returning the number of items waiting to be processed.\n* payload - an integer for determining how many tasks should be\n process per round. This property can be changed after a cargo is created to\n alter the payload on-the-fly.\n* push(task, [callback]) - add a new task to the queue, the callback is called\n once the worker has finished processing the task.\n instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list.\n* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued\n* empty - a callback that is called when the last item from the queue is given to a worker\n* drain - a callback that is called when the last item from the queue has returned from the worker\n\n__Example__\n\n```js\n// create a cargo object with payload 2\n\nvar cargo = async.cargo(function (tasks, callback) {\n for(var i=0; i\n### auto(tasks, [callback])\n\nDetermines the best order for running functions based on their requirements.\nEach function can optionally depend on other functions being completed first,\nand each function is run as soon as its requirements are satisfied. If any of\nthe functions pass an error to their callback, that function will not complete\n(so any other functions depending on it will not run) and the main callback\nwill be called immediately with the error. Functions also receive an object\ncontaining the results of functions which have completed so far.\n\nNote, all functions are called with a results object as a second argument, \nso it is unsafe to pass functions in the tasks object which cannot handle the\nextra argument. For example, this snippet of code:\n\n```js\nasync.auto({\n readData: async.apply(fs.readFile, 'data.txt', 'utf-8');\n}, callback);\n```\n\nwill have the effect of calling readFile with the results object as the last\nargument, which will fail:\n\n```js\nfs.readFile('data.txt', 'utf-8', cb, {});\n```\n\nInstead, wrap the call to readFile in a function which does not forward the \nresults object:\n\n```js\nasync.auto({\n readData: function(cb, results){\n fs.readFile('data.txt', 'utf-8', cb);\n }\n}, callback);\n```\n\n__Arguments__\n\n* tasks - An object literal containing named functions or an array of\n requirements, with the function itself the last item in the array. The key\n used for each function or array is used when specifying requirements. The \n function receives two arguments: (1) a callback(err, result) which must be \n called when finished, passing an error (which can be null) and the result of \n the function's execution, and (2) a results object, containing the results of\n the previously executed functions.\n* callback(err, results) - An optional callback which is called when all the\n tasks have been completed. The callback will receive an error as an argument\n if any tasks pass an error to their callback. Results will always be passed\n\tbut if an error occurred, no other tasks will be performed, and the results\n\tobject will only contain partial results.\n \n\n__Example__\n\n```js\nasync.auto({\n get_data: function(callback){\n // async code to get some data\n },\n make_folder: function(callback){\n // async code to create a directory to store a file in\n // this is run at the same time as getting the data\n },\n write_file: ['get_data', 'make_folder', function(callback){\n // once there is some data and the directory exists,\n // write the data to a file in the directory\n callback(null, filename);\n }],\n email_link: ['write_file', function(callback, results){\n // once the file is written let's email a link to it...\n // results.write_file contains the filename returned by write_file.\n }]\n});\n```\n\nThis is a fairly trivial example, but to do this using the basic parallel and\nseries functions would look like this:\n\n```js\nasync.parallel([\n function(callback){\n // async code to get some data\n },\n function(callback){\n // async code to create a directory to store a file in\n // this is run at the same time as getting the data\n }\n],\nfunction(err, results){\n async.series([\n function(callback){\n // once there is some data and the directory exists,\n // write the data to a file in the directory\n },\n function(callback){\n // once the file is written let's email a link to it...\n }\n ]);\n});\n```\n\nFor a complicated series of async tasks using the auto function makes adding\nnew tasks much easier and makes the code more readable.\n\n\n---------------------------------------\n\n\n### iterator(tasks)\n\nCreates an iterator function which calls the next function in the array,\nreturning a continuation to call the next one after that. It's also possible to\n'peek' the next iterator by doing iterator.next().\n\nThis function is used internally by the async module but can be useful when\nyou want to manually control the flow of functions in series.\n\n__Arguments__\n\n* tasks - An array of functions to run.\n\n__Example__\n\n```js\nvar iterator = async.iterator([\n function(){ sys.p('one'); },\n function(){ sys.p('two'); },\n function(){ sys.p('three'); }\n]);\n\nnode> var iterator2 = iterator();\n'one'\nnode> var iterator3 = iterator2();\n'two'\nnode> iterator3();\n'three'\nnode> var nextfn = iterator2.next();\nnode> nextfn();\n'three'\n```\n\n---------------------------------------\n\n\n### apply(function, arguments..)\n\nCreates a continuation function with some arguments already applied, a useful\nshorthand when combined with other control flow functions. Any arguments\npassed to the returned function are added to the arguments originally passed\nto apply.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to automatically apply when the\n continuation is called.\n\n__Example__\n\n```js\n// using apply\n\nasync.parallel([\n async.apply(fs.writeFile, 'testfile1', 'test1'),\n async.apply(fs.writeFile, 'testfile2', 'test2'),\n]);\n\n\n// the same process without using apply\n\nasync.parallel([\n function(callback){\n fs.writeFile('testfile1', 'test1', callback);\n },\n function(callback){\n fs.writeFile('testfile2', 'test2', callback);\n }\n]);\n```\n\nIt's possible to pass any number of additional arguments when calling the\ncontinuation:\n\n```js\nnode> var fn = async.apply(sys.puts, 'one');\nnode> fn('two', 'three');\none\ntwo\nthree\n```\n\n---------------------------------------\n\n\n### nextTick(callback)\n\nCalls the callback on a later loop around the event loop. In node.js this just\ncalls process.nextTick, in the browser it falls back to setImmediate(callback)\nif available, otherwise setTimeout(callback, 0), which means other higher priority\nevents may precede the execution of the callback.\n\nThis is used internally for browser-compatibility purposes.\n\n__Arguments__\n\n* callback - The function to call on a later loop around the event loop.\n\n__Example__\n\n```js\nvar call_order = [];\nasync.nextTick(function(){\n call_order.push('two');\n // call_order now equals ['one','two']\n});\ncall_order.push('one')\n```\n\n\n### times(n, callback)\n\nCalls the callback n times and accumulates results in the same manner\nyou would use with async.map.\n\n__Arguments__\n\n* n - The number of times to run the function.\n* callback - The function to call n times.\n\n__Example__\n\n```js\n// Pretend this is some complicated async factory\nvar createUser = function(id, callback) {\n callback(null, {\n id: 'user' + id\n })\n}\n// generate 5 users\nasync.times(5, function(n, next){\n createUser(n, function(err, user) {\n next(err, user)\n })\n}, function(err, users) {\n // we should now have 5 users\n});\n```\n\n\n### timesSeries(n, callback)\n\nThe same as times only the iterator is applied to each item in the array in\nseries. The next iterator is only called once the current one has completed\nprocessing. The results array will be in the same order as the original.\n\n\n## Utils\n\n\n### memoize(fn, [hasher])\n\nCaches the results of an async function. When creating a hash to store function\nresults against, the callback is omitted from the hash and an optional hash\nfunction can be used.\n\nThe cache of results is exposed as the `memo` property of the function returned\nby `memoize`.\n\n__Arguments__\n\n* fn - the function you to proxy and cache results from.\n* hasher - an optional function for generating a custom hash for storing\n results, it has all the arguments applied to it apart from the callback, and\n must be synchronous.\n\n__Example__\n\n```js\nvar slow_fn = function (name, callback) {\n // do something\n callback(null, result);\n};\nvar fn = async.memoize(slow_fn);\n\n// fn can now be used as if it were slow_fn\nfn('some name', function () {\n // callback\n});\n```\n\n\n### unmemoize(fn)\n\nUndoes a memoized function, reverting it to the original, unmemoized\nform. Comes handy in tests.\n\n__Arguments__\n\n* fn - the memoized function\n\n\n### log(function, arguments)\n\nLogs the result of an async function to the console. Only works in node.js or\nin browsers that support console.log and console.error (such as FF and Chrome).\nIf multiple arguments are returned from the async function, console.log is\ncalled on each argument in order.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to apply to the function.\n\n__Example__\n\n```js\nvar hello = function(name, callback){\n setTimeout(function(){\n callback(null, 'hello ' + name);\n }, 1000);\n};\n```\n```js\nnode> async.log(hello, 'world');\n'hello world'\n```\n\n---------------------------------------\n\n\n### dir(function, arguments)\n\nLogs the result of an async function to the console using console.dir to\ndisplay the properties of the resulting object. Only works in node.js or\nin browsers that support console.dir and console.error (such as FF and Chrome).\nIf multiple arguments are returned from the async function, console.dir is\ncalled on each argument in order.\n\n__Arguments__\n\n* function - The function you want to eventually apply all arguments to.\n* arguments... - Any number of arguments to apply to the function.\n\n__Example__\n\n```js\nvar hello = function(name, callback){\n setTimeout(function(){\n callback(null, {hello: name});\n }, 1000);\n};\n```\n```js\nnode> async.dir(hello, 'world');\n{hello: 'world'}\n```\n\n---------------------------------------\n\n\n### noConflict()\n\nChanges the value of async back to its original value, returning a reference to the\nasync object.\n", + "readmeFilename": "README.md", + "_id": "async@0.2.8", + "_from": "async@~0.2.5" +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/.npmignore b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/.npmignore new file mode 100644 index 000000000..494272a81 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/.npmignore @@ -0,0 +1,5 @@ +.*.swp +node_modules/ +examples/deep-copy/ +examples/path/ +examples/filter-copy/ diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/.travis.yml b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/.travis.yml similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/.travis.yml rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/.travis.yml diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/sigmund/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/sigmund/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/LICENSE diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/README.md new file mode 100644 index 000000000..9d8cb77e5 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/README.md @@ -0,0 +1,76 @@ +Like FS streams, but with stat on them, and supporting directories and +symbolic links, as well as normal files. Also, you can use this to set +the stats on a file, even if you don't change its contents, or to create +a symlink, etc. + +So, for example, you can "write" a directory, and it'll call `mkdir`. You +can specify a uid and gid, and it'll call `chown`. You can specify a +`mtime` and `atime`, and it'll call `utimes`. You can call it a symlink +and provide a `linkpath` and it'll call `symlink`. + +Note that it won't automatically resolve symbolic links. So, if you +call `fstream.Reader('/some/symlink')` then you'll get an object +that stats and then ends immediately (since it has no data). To follow +symbolic links, do this: `fstream.Reader({path:'/some/symlink', follow: +true })`. + +There are various checks to make sure that the bytes emitted are the +same as the intended size, if the size is set. + +## Examples + +```javascript +fstream + .Writer({ path: "path/to/file" + , mode: 0755 + , size: 6 + }) + .write("hello\n") + .end() +``` + +This will create the directories if they're missing, and then write +`hello\n` into the file, chmod it to 0755, and assert that 6 bytes have +been written when it's done. + +```javascript +fstream + .Writer({ path: "path/to/file" + , mode: 0755 + , size: 6 + , flags: "a" + }) + .write("hello\n") + .end() +``` + +You can pass flags in, if you want to append to a file. + +```javascript +fstream + .Writer({ path: "path/to/symlink" + , linkpath: "./file" + , SymbolicLink: true + , mode: "0755" // octal strings supported + }) + .end() +``` + +If isSymbolicLink is a function, it'll be called, and if it returns +true, then it'll treat it as a symlink. If it's not a function, then +any truish value will make a symlink, or you can set `type: +'SymbolicLink'`, which does the same thing. + +Note that the linkpath is relative to the symbolic link location, not +the parent dir or cwd. + +```javascript +fstream + .Reader("path/to/dir") + .pipe(fstream.Writer("path/to/other/dir")) +``` + +This will do like `cp -Rp path/to/dir path/to/other/dir`. If the other +dir exists and isn't a directory, then it'll emit an error. It'll also +set the uid, gid, mode, etc. to be identical. In this way, it's more +like `rsync -a` than simply a copy. diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/examples/filter-pipe.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/examples/filter-pipe.js new file mode 100644 index 000000000..c6b55b3e0 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/examples/filter-pipe.js @@ -0,0 +1,131 @@ +var fstream = require("../fstream.js") +var path = require("path") + +var r = fstream.Reader({ path: path.dirname(__dirname) + , filter: function () { + return !this.basename.match(/^\./) && + !this.basename.match(/^node_modules$/) + !this.basename.match(/^deep-copy$/) + !this.basename.match(/^filter-copy$/) + } + }) + +// this writer will only write directories +var w = fstream.Writer({ path: path.resolve(__dirname, "filter-copy") + , type: "Directory" + , filter: function () { + return this.type === "Directory" + } + }) + +var indent = "" +var escape = {} + +r.on("entry", appears) +r.on("ready", function () { + console.error("ready to begin!", r.path) +}) + +function appears (entry) { + console.error(indent + "a %s appears!", entry.type, entry.basename, typeof entry.basename) + if (foggy) { + console.error("FOGGY!") + var p = entry + do { + console.error(p.depth, p.path, p._paused) + } while (p = p.parent) + + throw new Error("\033[mshould not have entries while foggy") + } + indent += "\t" + entry.on("data", missile(entry)) + entry.on("end", runaway(entry)) + entry.on("entry", appears) +} + +var foggy +function missile (entry) { + if (entry.type === "Directory") { + var ended = false + entry.once("end", function () { ended = true }) + return function (c) { + // throw in some pathological pause()/resume() behavior + // just for extra fun. + process.nextTick(function () { + if (!foggy && !ended) { // && Math.random() < 0.3) { + console.error(indent +"%s casts a spell", entry.basename) + console.error("\na slowing fog comes over the battlefield...\n\033[32m") + entry.pause() + entry.once("resume", liftFog) + foggy = setTimeout(liftFog, 1000) + + function liftFog (who) { + if (!foggy) return + if (who) { + console.error("%s breaks the spell!", who && who.path) + } else { + console.error("the spell expires!") + } + console.error("\033[mthe fog lifts!\n") + clearTimeout(foggy) + foggy = null + if (entry._paused) entry.resume() + } + + } + }) + } + } + + return function (c) { + var e = Math.random() < 0.5 + console.error(indent + "%s %s for %d damage!", + entry.basename, + e ? "is struck" : "fires a chunk", + c.length) + } +} + +function runaway (entry) { return function () { + var e = Math.random() < 0.5 + console.error(indent + "%s %s", + entry.basename, + e ? "turns to flee" : "is vanquished!") + indent = indent.slice(0, -1) +}} + + +w.on("entry", attacks) +//w.on("ready", function () { attacks(w) }) +function attacks (entry) { + console.error(indent + "%s %s!", entry.basename, + entry.type === "Directory" ? "calls for backup" : "attacks") + entry.on("entry", attacks) +} + +ended = false +var i = 1 +r.on("end", function () { + if (foggy) clearTimeout(foggy) + console.error("\033[mIT'S OVER!!") + console.error("A WINNAR IS YOU!") + + console.log("ok " + (i ++) + " A WINNAR IS YOU") + ended = true + // now go through and verify that everything in there is a dir. + var p = path.resolve(__dirname, "filter-copy") + var checker = fstream.Reader({ path: p }) + checker.checker = true + checker.on("child", function (e) { + var ok = e.type === "Directory" + console.log((ok ? "" : "not ") + "ok " + (i ++) + + " should be a dir: " + + e.path.substr(checker.path.length + 1)) + }) +}) + +process.on("exit", function () { + console.log((ended ? "" : "not ") + "ok " + (i ++) + " ended") +}) + +r.pipe(w) diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/examples/pipe.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/examples/pipe.js new file mode 100644 index 000000000..648ec8493 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/examples/pipe.js @@ -0,0 +1,115 @@ +var fstream = require("../fstream.js") +var path = require("path") + +var r = fstream.Reader({ path: path.dirname(__dirname) + , filter: function () { + return !this.basename.match(/^\./) && + !this.basename.match(/^node_modules$/) + !this.basename.match(/^deep-copy$/) + } + }) + +var w = fstream.Writer({ path: path.resolve(__dirname, "deep-copy") + , type: "Directory" + }) + +var indent = "" +var escape = {} + +r.on("entry", appears) +r.on("ready", function () { + console.error("ready to begin!", r.path) +}) + +function appears (entry) { + console.error(indent + "a %s appears!", entry.type, entry.basename, typeof entry.basename, entry) + if (foggy) { + console.error("FOGGY!") + var p = entry + do { + console.error(p.depth, p.path, p._paused) + } while (p = p.parent) + + throw new Error("\033[mshould not have entries while foggy") + } + indent += "\t" + entry.on("data", missile(entry)) + entry.on("end", runaway(entry)) + entry.on("entry", appears) +} + +var foggy +function missile (entry) { + if (entry.type === "Directory") { + var ended = false + entry.once("end", function () { ended = true }) + return function (c) { + // throw in some pathological pause()/resume() behavior + // just for extra fun. + process.nextTick(function () { + if (!foggy && !ended) { // && Math.random() < 0.3) { + console.error(indent +"%s casts a spell", entry.basename) + console.error("\na slowing fog comes over the battlefield...\n\033[32m") + entry.pause() + entry.once("resume", liftFog) + foggy = setTimeout(liftFog, 10) + + function liftFog (who) { + if (!foggy) return + if (who) { + console.error("%s breaks the spell!", who && who.path) + } else { + console.error("the spell expires!") + } + console.error("\033[mthe fog lifts!\n") + clearTimeout(foggy) + foggy = null + if (entry._paused) entry.resume() + } + + } + }) + } + } + + return function (c) { + var e = Math.random() < 0.5 + console.error(indent + "%s %s for %d damage!", + entry.basename, + e ? "is struck" : "fires a chunk", + c.length) + } +} + +function runaway (entry) { return function () { + var e = Math.random() < 0.5 + console.error(indent + "%s %s", + entry.basename, + e ? "turns to flee" : "is vanquished!") + indent = indent.slice(0, -1) +}} + + +w.on("entry", attacks) +//w.on("ready", function () { attacks(w) }) +function attacks (entry) { + console.error(indent + "%s %s!", entry.basename, + entry.type === "Directory" ? "calls for backup" : "attacks") + entry.on("entry", attacks) +} + +ended = false +r.on("end", function () { + if (foggy) clearTimeout(foggy) + console.error("\033[mIT'S OVER!!") + console.error("A WINNAR IS YOU!") + + console.log("ok 1 A WINNAR IS YOU") + ended = true +}) + +process.on("exit", function () { + console.log((ended ? "" : "not ") + "ok 2 ended") +}) + +r.pipe(w) diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/examples/reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/examples/reader.js new file mode 100644 index 000000000..9aa1a9538 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/examples/reader.js @@ -0,0 +1,54 @@ +var fstream = require("../fstream.js") +var tap = require("tap") +var fs = require("fs") +var path = require("path") +var children = -1 +var dir = path.dirname(__dirname) + +var gotReady = false +var ended = false + +tap.test("reader test", function (t) { + + var r = fstream.Reader({ path: dir + , filter: function () { + // return this.parent === r + return this.parent === r || this === r + } + }) + + r.on("ready", function () { + gotReady = true + children = fs.readdirSync(dir).length + console.error("Setting expected children to "+children) + t.equal(r.type, "Directory", "should be a directory") + }) + + r.on("entry", function (entry) { + children -- + if (!gotReady) { + t.fail("children before ready!") + } + t.equal(entry.dirname, r.path, "basename is parent dir") + }) + + r.on("error", function (er) { + t.fail(er) + t.end() + process.exit(1) + }) + + r.on("end", function () { + t.equal(children, 0, "should have seen all children") + ended = true + }) + + var closed = false + r.on("close", function () { + t.ok(ended, "saw end before close") + t.notOk(closed, "close should only happen once") + closed = true + t.end() + }) + +}) diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/examples/symlink-write.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/examples/symlink-write.js new file mode 100644 index 000000000..d7816d24d --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/examples/symlink-write.js @@ -0,0 +1,24 @@ +var fstream = require("../fstream.js") + , closed = false + +fstream + .Writer({ path: "path/to/symlink" + , linkpath: "./file" + , isSymbolicLink: true + , mode: "0755" // octal strings supported + }) + .on("close", function () { + closed = true + var fs = require("fs") + var s = fs.lstatSync("path/to/symlink") + var isSym = s.isSymbolicLink() + console.log((isSym?"":"not ") +"ok 1 should be symlink") + var t = fs.readlinkSync("path/to/symlink") + var isTarget = t === "./file" + console.log((isTarget?"":"not ") +"ok 2 should link to ./file") + }) + .end() + +process.on("exit", function () { + console.log((closed?"":"not ")+"ok 3 should be closed") +}) diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/fstream.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/fstream.js new file mode 100644 index 000000000..c66d26f51 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/fstream.js @@ -0,0 +1,31 @@ +exports.Abstract = require("./lib/abstract.js") +exports.Reader = require("./lib/reader.js") +exports.Writer = require("./lib/writer.js") + +exports.File = + { Reader: require("./lib/file-reader.js") + , Writer: require("./lib/file-writer.js") } + +exports.Dir = + { Reader : require("./lib/dir-reader.js") + , Writer : require("./lib/dir-writer.js") } + +exports.Link = + { Reader : require("./lib/link-reader.js") + , Writer : require("./lib/link-writer.js") } + +exports.Proxy = + { Reader : require("./lib/proxy-reader.js") + , Writer : require("./lib/proxy-writer.js") } + +exports.Reader.Dir = exports.DirReader = exports.Dir.Reader +exports.Reader.File = exports.FileReader = exports.File.Reader +exports.Reader.Link = exports.LinkReader = exports.Link.Reader +exports.Reader.Proxy = exports.ProxyReader = exports.Proxy.Reader + +exports.Writer.Dir = exports.DirWriter = exports.Dir.Writer +exports.Writer.File = exports.FileWriter = exports.File.Writer +exports.Writer.Link = exports.LinkWriter = exports.Link.Writer +exports.Writer.Proxy = exports.ProxyWriter = exports.Proxy.Writer + +exports.collect = require("./lib/collect.js") diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/abstract.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/abstract.js new file mode 100644 index 000000000..11ef0e28f --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/abstract.js @@ -0,0 +1,85 @@ +// the parent class for all fstreams. + +module.exports = Abstract + +var Stream = require("stream").Stream + , inherits = require("inherits") + +function Abstract () { + Stream.call(this) +} + +inherits(Abstract, Stream) + +Abstract.prototype.on = function (ev, fn) { + if (ev === "ready" && this.ready) { + process.nextTick(fn.bind(this)) + } else { + Stream.prototype.on.call(this, ev, fn) + } + return this +} + +Abstract.prototype.abort = function () { + this._aborted = true + this.emit("abort") +} + +Abstract.prototype.destroy = function () {} + +Abstract.prototype.warn = function (msg, code) { + var me = this + , er = decorate(msg, code, me) + if (!me.listeners("warn")) { + console.error("%s %s\n" + + "path = %s\n" + + "syscall = %s\n" + + "fstream_type = %s\n" + + "fstream_path = %s\n" + + "fstream_unc_path = %s\n" + + "fstream_class = %s\n" + + "fstream_stack =\n%s\n", + code || "UNKNOWN", + er.stack, + er.path, + er.syscall, + er.fstream_type, + er.fstream_path, + er.fstream_unc_path, + er.fstream_class, + er.fstream_stack.join("\n")) + } else { + me.emit("warn", er) + } +} + +Abstract.prototype.info = function (msg, code) { + this.emit("info", msg, code) +} + +Abstract.prototype.error = function (msg, code, th) { + var er = decorate(msg, code, this) + if (th) throw er + else this.emit("error", er) +} + +function decorate (er, code, me) { + if (!(er instanceof Error)) er = new Error(er) + er.code = er.code || code + er.path = er.path || me.path + er.fstream_type = er.fstream_type || me.type + er.fstream_path = er.fstream_path || me.path + if (me._path !== me.path) { + er.fstream_unc_path = er.fstream_unc_path || me._path + } + if (me.linkpath) { + er.fstream_linkpath = er.fstream_linkpath || me.linkpath + } + er.fstream_class = er.fstream_class || me.constructor.name + er.fstream_stack = er.fstream_stack || + new Error().stack.split(/\n/).slice(3).map(function (s) { + return s.replace(/^ at /, "") + }) + + return er +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/collect.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/collect.js new file mode 100644 index 000000000..a36f780eb --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/collect.js @@ -0,0 +1,67 @@ +module.exports = collect + +function collect (stream) { + if (stream._collected) return + + stream._collected = true + stream.pause() + + stream.on("data", save) + stream.on("end", save) + var buf = [] + function save (b) { + if (typeof b === "string") b = new Buffer(b) + if (Buffer.isBuffer(b) && !b.length) return + buf.push(b) + } + + stream.on("entry", saveEntry) + var entryBuffer = [] + function saveEntry (e) { + collect(e) + entryBuffer.push(e) + } + + stream.on("proxy", proxyPause) + function proxyPause (p) { + p.pause() + } + + + // replace the pipe method with a new version that will + // unlock the buffered stuff. if you just call .pipe() + // without a destination, then it'll re-play the events. + stream.pipe = (function (orig) { return function (dest) { + // console.error(" === open the pipes", dest && dest.path) + + // let the entries flow through one at a time. + // Once they're all done, then we can resume completely. + var e = 0 + ;(function unblockEntry () { + var entry = entryBuffer[e++] + // console.error(" ==== unblock entry", entry && entry.path) + if (!entry) return resume() + entry.on("end", unblockEntry) + if (dest) dest.add(entry) + else stream.emit("entry", entry) + })() + + function resume () { + stream.removeListener("entry", saveEntry) + stream.removeListener("data", save) + stream.removeListener("end", save) + + stream.pipe = orig + if (dest) stream.pipe(dest) + + buf.forEach(function (b) { + if (b) stream.emit("data", b) + else stream.emit("end") + }) + + stream.resume() + } + + return dest + }})(stream.pipe) +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/dir-reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/dir-reader.js new file mode 100644 index 000000000..dd9883b22 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/dir-reader.js @@ -0,0 +1,250 @@ +// A thing that emits "entry" events with Reader objects +// Pausing it causes it to stop emitting entry events, and also +// pauses the current entry if there is one. + +module.exports = DirReader + +var fs = require("graceful-fs") + , fstream = require("../fstream.js") + , Reader = fstream.Reader + , inherits = require("inherits") + , mkdir = require("mkdirp") + , path = require("path") + , Reader = require("./reader.js") + , assert = require("assert").ok + +inherits(DirReader, Reader) + +function DirReader (props) { + var me = this + if (!(me instanceof DirReader)) throw new Error( + "DirReader must be called as constructor.") + + // should already be established as a Directory type + if (props.type !== "Directory" || !props.Directory) { + throw new Error("Non-directory type "+ props.type) + } + + me.entries = null + me._index = -1 + me._paused = false + me._length = -1 + + if (props.sort) { + this.sort = props.sort + } + + Reader.call(this, props) +} + +DirReader.prototype._getEntries = function () { + var me = this + + // race condition. might pause() before calling _getEntries, + // and then resume, and try to get them a second time. + if (me._gotEntries) return + me._gotEntries = true + + fs.readdir(me._path, function (er, entries) { + if (er) return me.error(er) + + me.entries = entries + + me.emit("entries", entries) + if (me._paused) me.once("resume", processEntries) + else processEntries() + + function processEntries () { + me._length = me.entries.length + if (typeof me.sort === "function") { + me.entries = me.entries.sort(me.sort.bind(me)) + } + me._read() + } + }) +} + +// start walking the dir, and emit an "entry" event for each one. +DirReader.prototype._read = function () { + var me = this + + if (!me.entries) return me._getEntries() + + if (me._paused || me._currentEntry || me._aborted) { + // console.error("DR paused=%j, current=%j, aborted=%j", me._paused, !!me._currentEntry, me._aborted) + return + } + + me._index ++ + if (me._index >= me.entries.length) { + if (!me._ended) { + me._ended = true + me.emit("end") + me.emit("close") + } + return + } + + // ok, handle this one, then. + + // save creating a proxy, by stat'ing the thing now. + var p = path.resolve(me._path, me.entries[me._index]) + assert(p !== me._path) + assert(me.entries[me._index]) + + // set this to prevent trying to _read() again in the stat time. + me._currentEntry = p + fs[ me.props.follow ? "stat" : "lstat" ](p, function (er, stat) { + if (er) return me.error(er) + + var who = me._proxy || me + + stat.path = p + stat.basename = path.basename(p) + stat.dirname = path.dirname(p) + var childProps = me.getChildProps.call(who, stat) + childProps.path = p + childProps.basename = path.basename(p) + childProps.dirname = path.dirname(p) + + var entry = Reader(childProps, stat) + + // console.error("DR Entry", p, stat.size) + + me._currentEntry = entry + + // "entry" events are for direct entries in a specific dir. + // "child" events are for any and all children at all levels. + // This nomenclature is not completely final. + + entry.on("pause", function (who) { + if (!me._paused && !entry._disowned) { + me.pause(who) + } + }) + + entry.on("resume", function (who) { + if (me._paused && !entry._disowned) { + me.resume(who) + } + }) + + entry.on("stat", function (props) { + me.emit("_entryStat", entry, props) + if (entry._aborted) return + if (entry._paused) entry.once("resume", function () { + me.emit("entryStat", entry, props) + }) + else me.emit("entryStat", entry, props) + }) + + entry.on("ready", function EMITCHILD () { + // console.error("DR emit child", entry._path) + if (me._paused) { + // console.error(" DR emit child - try again later") + // pause the child, and emit the "entry" event once we drain. + // console.error("DR pausing child entry") + entry.pause(me) + return me.once("resume", EMITCHILD) + } + + // skip over sockets. they can't be piped around properly, + // so there's really no sense even acknowledging them. + // if someone really wants to see them, they can listen to + // the "socket" events. + if (entry.type === "Socket") { + me.emit("socket", entry) + } else { + me.emitEntry(entry) + } + }) + + var ended = false + entry.on("close", onend) + entry.on("disown", onend) + function onend () { + if (ended) return + ended = true + me.emit("childEnd", entry) + me.emit("entryEnd", entry) + me._currentEntry = null + if (!me._paused) { + me._read() + } + } + + // XXX Remove this. Works in node as of 0.6.2 or so. + // Long filenames should not break stuff. + entry.on("error", function (er) { + if (entry._swallowErrors) { + me.warn(er) + entry.emit("end") + entry.emit("close") + } else { + me.emit("error", er) + } + }) + + // proxy up some events. + ; [ "child" + , "childEnd" + , "warn" + ].forEach(function (ev) { + entry.on(ev, me.emit.bind(me, ev)) + }) + }) +} + +DirReader.prototype.disown = function (entry) { + entry.emit("beforeDisown") + entry._disowned = true + entry.parent = entry.root = null + if (entry === this._currentEntry) { + this._currentEntry = null + } + entry.emit("disown") +} + +DirReader.prototype.getChildProps = function (stat) { + return { depth: this.depth + 1 + , root: this.root || this + , parent: this + , follow: this.follow + , filter: this.filter + , sort: this.props.sort + } +} + +DirReader.prototype.pause = function (who) { + var me = this + if (me._paused) return + who = who || me + me._paused = true + if (me._currentEntry && me._currentEntry.pause) { + me._currentEntry.pause(who) + } + me.emit("pause", who) +} + +DirReader.prototype.resume = function (who) { + var me = this + if (!me._paused) return + who = who || me + + me._paused = false + // console.error("DR Emit Resume", me._path) + me.emit("resume", who) + if (me._paused) { + // console.error("DR Re-paused", me._path) + return + } + + if (me._currentEntry) { + if (me._currentEntry.resume) me._currentEntry.resume(who) + } else me._read() +} + +DirReader.prototype.emitEntry = function (entry) { + this.emit("entry", entry) + this.emit("child", entry) +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/dir-writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/dir-writer.js new file mode 100644 index 000000000..7073b883e --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/dir-writer.js @@ -0,0 +1,171 @@ +// It is expected that, when .add() returns false, the consumer +// of the DirWriter will pause until a "drain" event occurs. Note +// that this is *almost always going to be the case*, unless the +// thing being written is some sort of unsupported type, and thus +// skipped over. + +module.exports = DirWriter + +var fs = require("graceful-fs") + , fstream = require("../fstream.js") + , Writer = require("./writer.js") + , inherits = require("inherits") + , mkdir = require("mkdirp") + , path = require("path") + , collect = require("./collect.js") + +inherits(DirWriter, Writer) + +function DirWriter (props) { + var me = this + if (!(me instanceof DirWriter)) me.error( + "DirWriter must be called as constructor.", null, true) + + // should already be established as a Directory type + if (props.type !== "Directory" || !props.Directory) { + me.error("Non-directory type "+ props.type + " " + + JSON.stringify(props), null, true) + } + + Writer.call(this, props) +} + +DirWriter.prototype._create = function () { + var me = this + mkdir(me._path, Writer.dirmode, function (er) { + if (er) return me.error(er) + // ready to start getting entries! + me.ready = true + me.emit("ready") + me._process() + }) +} + +// a DirWriter has an add(entry) method, but its .write() doesn't +// do anything. Why a no-op rather than a throw? Because this +// leaves open the door for writing directory metadata for +// gnu/solaris style dumpdirs. +DirWriter.prototype.write = function () { + return true +} + +DirWriter.prototype.end = function () { + this._ended = true + this._process() +} + +DirWriter.prototype.add = function (entry) { + var me = this + + // console.error("\tadd", entry._path, "->", me._path) + collect(entry) + if (!me.ready || me._currentEntry) { + me._buffer.push(entry) + return false + } + + // create a new writer, and pipe the incoming entry into it. + if (me._ended) { + return me.error("add after end") + } + + me._buffer.push(entry) + me._process() + + return 0 === this._buffer.length +} + +DirWriter.prototype._process = function () { + var me = this + + // console.error("DW Process p=%j", me._processing, me.basename) + + if (me._processing) return + + var entry = me._buffer.shift() + if (!entry) { + // console.error("DW Drain") + me.emit("drain") + if (me._ended) me._finish() + return + } + + me._processing = true + // console.error("DW Entry", entry._path) + + me.emit("entry", entry) + + // ok, add this entry + // + // don't allow recursive copying + var p = entry + do { + var pp = p._path || p.path + if (pp === me.root._path || pp === me._path || + (pp && pp.indexOf(me._path) === 0)) { + // console.error("DW Exit (recursive)", entry.basename, me._path) + me._processing = false + if (entry._collected) entry.pipe() + return me._process() + } + } while (p = p.parent) + + // console.error("DW not recursive") + + // chop off the entry's root dir, replace with ours + var props = { parent: me + , root: me.root || me + , type: entry.type + , depth: me.depth + 1 } + + var p = entry._path || entry.path || entry.props.path + if (entry.parent) { + p = p.substr(entry.parent._path.length + 1) + } + // get rid of any ../../ shenanigans + props.path = path.join(me.path, path.join("/", p)) + + // if i have a filter, the child should inherit it. + props.filter = me.filter + + // all the rest of the stuff, copy over from the source. + Object.keys(entry.props).forEach(function (k) { + if (!props.hasOwnProperty(k)) { + props[k] = entry.props[k] + } + }) + + // not sure at this point what kind of writer this is. + var child = me._currentChild = new Writer(props) + child.on("ready", function () { + // console.error("DW Child Ready", child.type, child._path) + // console.error(" resuming", entry._path) + entry.pipe(child) + entry.resume() + }) + + // XXX Make this work in node. + // Long filenames should not break stuff. + child.on("error", function (er) { + if (child._swallowErrors) { + me.warn(er) + child.emit("end") + child.emit("close") + } else { + me.emit("error", er) + } + }) + + // we fire _end internally *after* end, so that we don't move on + // until any "end" listeners have had their chance to do stuff. + child.on("close", onend) + var ended = false + function onend () { + if (ended) return + ended = true + // console.error("* DW Child end", child.basename) + me._currentChild = null + me._processing = false + me._process() + } +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/file-reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/file-reader.js new file mode 100644 index 000000000..b1f986183 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/file-reader.js @@ -0,0 +1,147 @@ +// Basically just a wrapper around an fs.ReadStream + +module.exports = FileReader + +var fs = require("graceful-fs") + , fstream = require("../fstream.js") + , Reader = fstream.Reader + , inherits = require("inherits") + , mkdir = require("mkdirp") + , Reader = require("./reader.js") + , EOF = {EOF: true} + , CLOSE = {CLOSE: true} + +inherits(FileReader, Reader) + +function FileReader (props) { + // console.error(" FR create", props.path, props.size, new Error().stack) + var me = this + if (!(me instanceof FileReader)) throw new Error( + "FileReader must be called as constructor.") + + // should already be established as a File type + // XXX Todo: preserve hardlinks by tracking dev+inode+nlink, + // with a HardLinkReader class. + if (!((props.type === "Link" && props.Link) || + (props.type === "File" && props.File))) { + throw new Error("Non-file type "+ props.type) + } + + me._buffer = [] + me._bytesEmitted = 0 + Reader.call(me, props) +} + +FileReader.prototype._getStream = function () { + var me = this + , stream = me._stream = fs.createReadStream(me._path, me.props) + + if (me.props.blksize) { + stream.bufferSize = me.props.blksize + } + + stream.on("open", me.emit.bind(me, "open")) + + stream.on("data", function (c) { + // console.error("\t\t%d %s", c.length, me.basename) + me._bytesEmitted += c.length + // no point saving empty chunks + if (!c.length) return + else if (me._paused || me._buffer.length) { + me._buffer.push(c) + me._read() + } else me.emit("data", c) + }) + + stream.on("end", function () { + if (me._paused || me._buffer.length) { + // console.error("FR Buffering End", me._path) + me._buffer.push(EOF) + me._read() + } else { + me.emit("end") + } + + if (me._bytesEmitted !== me.props.size) { + me.error("Didn't get expected byte count\n"+ + "expect: "+me.props.size + "\n" + + "actual: "+me._bytesEmitted) + } + }) + + stream.on("close", function () { + if (me._paused || me._buffer.length) { + // console.error("FR Buffering Close", me._path) + me._buffer.push(CLOSE) + me._read() + } else { + // console.error("FR close 1", me._path) + me.emit("close") + } + }) + + me._read() +} + +FileReader.prototype._read = function () { + var me = this + // console.error("FR _read", me._path) + if (me._paused) { + // console.error("FR _read paused", me._path) + return + } + + if (!me._stream) { + // console.error("FR _getStream calling", me._path) + return me._getStream() + } + + // clear out the buffer, if there is one. + if (me._buffer.length) { + // console.error("FR _read has buffer", me._buffer.length, me._path) + var buf = me._buffer + for (var i = 0, l = buf.length; i < l; i ++) { + var c = buf[i] + if (c === EOF) { + // console.error("FR Read emitting buffered end", me._path) + me.emit("end") + } else if (c === CLOSE) { + // console.error("FR Read emitting buffered close", me._path) + me.emit("close") + } else { + // console.error("FR Read emitting buffered data", me._path) + me.emit("data", c) + } + + if (me._paused) { + // console.error("FR Read Re-pausing at "+i, me._path) + me._buffer = buf.slice(i) + return + } + } + me._buffer.length = 0 + } + // console.error("FR _read done") + // that's about all there is to it. +} + +FileReader.prototype.pause = function (who) { + var me = this + // console.error("FR Pause", me._path) + if (me._paused) return + who = who || me + me._paused = true + if (me._stream) me._stream.pause() + me.emit("pause", who) +} + +FileReader.prototype.resume = function (who) { + var me = this + // console.error("FR Resume", me._path) + if (!me._paused) return + who = who || me + me.emit("resume", who) + me._paused = false + if (me._stream) me._stream.resume() + me._read() +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/file-writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/file-writer.js new file mode 100644 index 000000000..681146258 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/file-writer.js @@ -0,0 +1,100 @@ +module.exports = FileWriter + +var fs = require("graceful-fs") + , mkdir = require("mkdirp") + , Writer = require("./writer.js") + , inherits = require("inherits") + , EOF = {} + +inherits(FileWriter, Writer) + +function FileWriter (props) { + var me = this + if (!(me instanceof FileWriter)) throw new Error( + "FileWriter must be called as constructor.") + + // should already be established as a File type + if (props.type !== "File" || !props.File) { + throw new Error("Non-file type "+ props.type) + } + + me._buffer = [] + me._bytesWritten = 0 + + Writer.call(this, props) +} + +FileWriter.prototype._create = function () { + var me = this + if (me._stream) return + + var so = {} + if (me.props.flags) so.flags = me.props.flags + so.mode = Writer.filemode + if (me._old && me._old.blksize) so.bufferSize = me._old.blksize + + me._stream = fs.createWriteStream(me._path, so) + + me._stream.on("open", function (fd) { + // console.error("FW open", me._buffer, me._path) + me.ready = true + me._buffer.forEach(function (c) { + if (c === EOF) me._stream.end() + else me._stream.write(c) + }) + me.emit("ready") + // give this a kick just in case it needs it. + me.emit("drain") + }) + + me._stream.on("drain", function () { me.emit("drain") }) + + me._stream.on("close", function () { + // console.error("\n\nFW Stream Close", me._path, me.size) + me._finish() + }) +} + +FileWriter.prototype.write = function (c) { + var me = this + + me._bytesWritten += c.length + + if (!me.ready) { + if (!Buffer.isBuffer(c) && typeof c !== 'string') + throw new Error('invalid write data') + me._buffer.push(c) + return false + } + + var ret = me._stream.write(c) + // console.error("\t-- fw wrote, _stream says", ret, me._stream._queue.length) + + // allow 2 buffered writes, because otherwise there's just too + // much stop and go bs. + return ret || (me._stream._queue && me._stream._queue.length <= 2) +} + +FileWriter.prototype.end = function (c) { + var me = this + + if (c) me.write(c) + + if (!me.ready) { + me._buffer.push(EOF) + return false + } + + return me._stream.end() +} + +FileWriter.prototype._finish = function () { + var me = this + if (typeof me.size === "number" && me._bytesWritten != me.size) { + me.error( + "Did not get expected byte count.\n" + + "expect: " + me.size + "\n" + + "actual: " + me._bytesWritten) + } + Writer.prototype._finish.call(me) +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/get-type.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/get-type.js new file mode 100644 index 000000000..cd65c41d8 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/get-type.js @@ -0,0 +1,32 @@ +module.exports = getType + +function getType (st) { + var types = + [ "Directory" + , "File" + , "SymbolicLink" + , "Link" // special for hardlinks from tarballs + , "BlockDevice" + , "CharacterDevice" + , "FIFO" + , "Socket" ] + , type + + if (st.type && -1 !== types.indexOf(st.type)) { + st[st.type] = true + return st.type + } + + for (var i = 0, l = types.length; i < l; i ++) { + type = types[i] + var is = st[type] || st["is" + type] + if (typeof is === "function") is = is.call(st) + if (is) { + st[type] = true + st.type = type + return type + } + } + + return null +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/link-reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/link-reader.js new file mode 100644 index 000000000..7e7ab6ce5 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/link-reader.js @@ -0,0 +1,54 @@ +// Basically just a wrapper around an fs.readlink +// +// XXX: Enhance this to support the Link type, by keeping +// a lookup table of {:}, so that hardlinks +// can be preserved in tarballs. + +module.exports = LinkReader + +var fs = require("graceful-fs") + , fstream = require("../fstream.js") + , inherits = require("inherits") + , mkdir = require("mkdirp") + , Reader = require("./reader.js") + +inherits(LinkReader, Reader) + +function LinkReader (props) { + var me = this + if (!(me instanceof LinkReader)) throw new Error( + "LinkReader must be called as constructor.") + + if (!((props.type === "Link" && props.Link) || + (props.type === "SymbolicLink" && props.SymbolicLink))) { + throw new Error("Non-link type "+ props.type) + } + + Reader.call(me, props) +} + +// When piping a LinkReader into a LinkWriter, we have to +// already have the linkpath property set, so that has to +// happen *before* the "ready" event, which means we need to +// override the _stat method. +LinkReader.prototype._stat = function (currentStat) { + var me = this + fs.readlink(me._path, function (er, linkpath) { + if (er) return me.error(er) + me.linkpath = me.props.linkpath = linkpath + me.emit("linkpath", linkpath) + Reader.prototype._stat.call(me, currentStat) + }) +} + +LinkReader.prototype._read = function () { + var me = this + if (me._paused) return + // basically just a no-op, since we got all the info we need + // from the _stat method + if (!me._ended) { + me.emit("end") + me.emit("close") + me._ended = true + } +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/link-writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/link-writer.js new file mode 100644 index 000000000..5c8f1e701 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/link-writer.js @@ -0,0 +1,95 @@ + +module.exports = LinkWriter + +var fs = require("graceful-fs") + , Writer = require("./writer.js") + , inherits = require("inherits") + , path = require("path") + , rimraf = require("rimraf") + +inherits(LinkWriter, Writer) + +function LinkWriter (props) { + var me = this + if (!(me instanceof LinkWriter)) throw new Error( + "LinkWriter must be called as constructor.") + + // should already be established as a Link type + if (!((props.type === "Link" && props.Link) || + (props.type === "SymbolicLink" && props.SymbolicLink))) { + throw new Error("Non-link type "+ props.type) + } + + if (props.linkpath === "") props.linkpath = "." + if (!props.linkpath) { + me.error("Need linkpath property to create " + props.type) + } + + Writer.call(this, props) +} + +LinkWriter.prototype._create = function () { + // console.error(" LW _create") + var me = this + , hard = me.type === "Link" || process.platform === "win32" + , link = hard ? "link" : "symlink" + , lp = hard ? path.resolve(me.dirname, me.linkpath) : me.linkpath + + // can only change the link path by clobbering + // For hard links, let's just assume that's always the case, since + // there's no good way to read them if we don't already know. + if (hard) return clobber(me, lp, link) + + fs.readlink(me._path, function (er, p) { + // only skip creation if it's exactly the same link + if (p && p === lp) return finish(me) + clobber(me, lp, link) + }) +} + +function clobber (me, lp, link) { + rimraf(me._path, function (er) { + if (er) return me.error(er) + create(me, lp, link) + }) +} + +function create (me, lp, link) { + fs[link](lp, me._path, function (er) { + // if this is a hard link, and we're in the process of writing out a + // directory, it's very possible that the thing we're linking to + // doesn't exist yet (especially if it was intended as a symlink), + // so swallow ENOENT errors here and just soldier in. + // Additionally, an EPERM or EACCES can happen on win32 if it's trying + // to make a link to a directory. Again, just skip it. + // A better solution would be to have fs.symlink be supported on + // windows in some nice fashion. + if (er) { + if ((er.code === "ENOENT" || + er.code === "EACCES" || + er.code === "EPERM" ) && process.platform === "win32") { + me.ready = true + me.emit("ready") + me.emit("end") + me.emit("close") + me.end = me._finish = function () {} + } else return me.error(er) + } + finish(me) + }) +} + +function finish (me) { + me.ready = true + me.emit("ready") + if (me._ended && !me._finished) me._finish() +} + +LinkWriter.prototype.end = function () { + // console.error("LW finish in end") + this._ended = true + if (this.ready) { + this._finished = true + this._finish() + } +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/proxy-reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/proxy-reader.js new file mode 100644 index 000000000..a0ece34a2 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/proxy-reader.js @@ -0,0 +1,93 @@ +// A reader for when we don't yet know what kind of thing +// the thing is. + +module.exports = ProxyReader + +var Reader = require("./reader.js") + , getType = require("./get-type.js") + , inherits = require("inherits") + , fs = require("graceful-fs") + +inherits(ProxyReader, Reader) + +function ProxyReader (props) { + var me = this + if (!(me instanceof ProxyReader)) throw new Error( + "ProxyReader must be called as constructor.") + + me.props = props + me._buffer = [] + me.ready = false + + Reader.call(me, props) +} + +ProxyReader.prototype._stat = function () { + var me = this + , props = me.props + // stat the thing to see what the proxy should be. + , stat = props.follow ? "stat" : "lstat" + + fs[stat](props.path, function (er, current) { + var type + if (er || !current) { + type = "File" + } else { + type = getType(current) + } + + props[type] = true + props.type = me.type = type + + me._old = current + me._addProxy(Reader(props, current)) + }) +} + +ProxyReader.prototype._addProxy = function (proxy) { + var me = this + if (me._proxyTarget) { + return me.error("proxy already set") + } + + me._proxyTarget = proxy + proxy._proxy = me + + ; [ "error" + , "data" + , "end" + , "close" + , "linkpath" + , "entry" + , "entryEnd" + , "child" + , "childEnd" + , "warn" + , "stat" + ].forEach(function (ev) { + // console.error("~~ proxy event", ev, me.path) + proxy.on(ev, me.emit.bind(me, ev)) + }) + + me.emit("proxy", proxy) + + proxy.on("ready", function () { + // console.error("~~ proxy is ready!", me.path) + me.ready = true + me.emit("ready") + }) + + var calls = me._buffer + me._buffer.length = 0 + calls.forEach(function (c) { + proxy[c[0]].apply(proxy, c[1]) + }) +} + +ProxyReader.prototype.pause = function () { + return this._proxyTarget ? this._proxyTarget.pause() : false +} + +ProxyReader.prototype.resume = function () { + return this._proxyTarget ? this._proxyTarget.resume() : false +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/proxy-writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/proxy-writer.js new file mode 100644 index 000000000..b0476633a --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/proxy-writer.js @@ -0,0 +1,109 @@ +// A writer for when we don't know what kind of thing +// the thing is. That is, it's not explicitly set, +// so we're going to make it whatever the thing already +// is, or "File" +// +// Until then, collect all events. + +module.exports = ProxyWriter + +var Writer = require("./writer.js") + , getType = require("./get-type.js") + , inherits = require("inherits") + , collect = require("./collect.js") + , fs = require("fs") + +inherits(ProxyWriter, Writer) + +function ProxyWriter (props) { + var me = this + if (!(me instanceof ProxyWriter)) throw new Error( + "ProxyWriter must be called as constructor.") + + me.props = props + me._needDrain = false + + Writer.call(me, props) +} + +ProxyWriter.prototype._stat = function () { + var me = this + , props = me.props + // stat the thing to see what the proxy should be. + , stat = props.follow ? "stat" : "lstat" + + fs[stat](props.path, function (er, current) { + var type + if (er || !current) { + type = "File" + } else { + type = getType(current) + } + + props[type] = true + props.type = me.type = type + + me._old = current + me._addProxy(Writer(props, current)) + }) +} + +ProxyWriter.prototype._addProxy = function (proxy) { + // console.error("~~ set proxy", this.path) + var me = this + if (me._proxy) { + return me.error("proxy already set") + } + + me._proxy = proxy + ; [ "ready" + , "error" + , "close" + , "pipe" + , "drain" + , "warn" + ].forEach(function (ev) { + proxy.on(ev, me.emit.bind(me, ev)) + }) + + me.emit("proxy", proxy) + + var calls = me._buffer + calls.forEach(function (c) { + // console.error("~~ ~~ proxy buffered call", c[0], c[1]) + proxy[c[0]].apply(proxy, c[1]) + }) + me._buffer.length = 0 + if (me._needsDrain) me.emit("drain") +} + +ProxyWriter.prototype.add = function (entry) { + // console.error("~~ proxy add") + collect(entry) + + if (!this._proxy) { + this._buffer.push(["add", [entry]]) + this._needDrain = true + return false + } + return this._proxy.add(entry) +} + +ProxyWriter.prototype.write = function (c) { + // console.error("~~ proxy write") + if (!this._proxy) { + this._buffer.push(["write", [c]]) + this._needDrain = true + return false + } + return this._proxy.write(c) +} + +ProxyWriter.prototype.end = function (c) { + // console.error("~~ proxy end") + if (!this._proxy) { + this._buffer.push(["end", [c]]) + return false + } + return this._proxy.end(c) +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/reader.js new file mode 100644 index 000000000..e4e1b482c --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/reader.js @@ -0,0 +1,259 @@ + +module.exports = Reader + +var fs = require("graceful-fs") + , Stream = require("stream").Stream + , inherits = require("inherits") + , path = require("path") + , getType = require("./get-type.js") + , hardLinks = Reader.hardLinks = {} + , Abstract = require("./abstract.js") + +// Must do this *before* loading the child classes +inherits(Reader, Abstract) + +var DirReader = require("./dir-reader.js") + , FileReader = require("./file-reader.js") + , LinkReader = require("./link-reader.js") + , SocketReader = require("./socket-reader.js") + , ProxyReader = require("./proxy-reader.js") + +function Reader (props, currentStat) { + var me = this + if (!(me instanceof Reader)) return new Reader(props, currentStat) + + if (typeof props === "string") { + props = { path: props } + } + + if (!props.path) { + me.error("Must provide a path", null, true) + } + + // polymorphism. + // call fstream.Reader(dir) to get a DirReader object, etc. + // Note that, unlike in the Writer case, ProxyReader is going + // to be the *normal* state of affairs, since we rarely know + // the type of a file prior to reading it. + + + var type + , ClassType + + if (props.type && typeof props.type === "function") { + type = props.type + ClassType = type + } else { + type = getType(props) + ClassType = Reader + } + + if (currentStat && !type) { + type = getType(currentStat) + props[type] = true + props.type = type + } + + switch (type) { + case "Directory": + ClassType = DirReader + break + + case "Link": + // XXX hard links are just files. + // However, it would be good to keep track of files' dev+inode + // and nlink values, and create a HardLinkReader that emits + // a linkpath value of the original copy, so that the tar + // writer can preserve them. + // ClassType = HardLinkReader + // break + + case "File": + ClassType = FileReader + break + + case "SymbolicLink": + ClassType = LinkReader + break + + case "Socket": + ClassType = SocketReader + break + + case null: + ClassType = ProxyReader + break + } + + if (!(me instanceof ClassType)) { + return new ClassType(props) + } + + Abstract.call(me) + + me.readable = true + me.writable = false + + me.type = type + me.props = props + me.depth = props.depth = props.depth || 0 + me.parent = props.parent || null + me.root = props.root || (props.parent && props.parent.root) || me + + me._path = me.path = path.resolve(props.path) + if (process.platform === "win32") { + me.path = me._path = me.path.replace(/\?/g, "_") + if (me._path.length >= 260) { + // how DOES one create files on the moon? + // if the path has spaces in it, then UNC will fail. + me._swallowErrors = true + //if (me._path.indexOf(" ") === -1) { + me._path = "\\\\?\\" + me.path.replace(/\//g, "\\") + //} + } + } + me.basename = props.basename = path.basename(me.path) + me.dirname = props.dirname = path.dirname(me.path) + + // these have served their purpose, and are now just noisy clutter + props.parent = props.root = null + + // console.error("\n\n\n%s setting size to", props.path, props.size) + me.size = props.size + me.filter = typeof props.filter === "function" ? props.filter : null + if (props.sort === "alpha") props.sort = alphasort + + // start the ball rolling. + // this will stat the thing, and then call me._read() + // to start reading whatever it is. + // console.error("calling stat", props.path, currentStat) + me._stat(currentStat) +} + +function alphasort (a, b) { + return a === b ? 0 + : a.toLowerCase() > b.toLowerCase() ? 1 + : a.toLowerCase() < b.toLowerCase() ? -1 + : a > b ? 1 + : -1 +} + +Reader.prototype._stat = function (currentStat) { + var me = this + , props = me.props + , stat = props.follow ? "stat" : "lstat" + + // console.error("Reader._stat", me._path, currentStat) + if (currentStat) process.nextTick(statCb.bind(null, null, currentStat)) + else fs[stat](me._path, statCb) + + + function statCb (er, props_) { + // console.error("Reader._stat, statCb", me._path, props_, props_.nlink) + if (er) return me.error(er) + + Object.keys(props_).forEach(function (k) { + props[k] = props_[k] + }) + + // if it's not the expected size, then abort here. + if (undefined !== me.size && props.size !== me.size) { + return me.error("incorrect size") + } + me.size = props.size + + var type = getType(props) + // special little thing for handling hardlinks. + if (type !== "Directory" && props.nlink && props.nlink > 1) { + var k = props.dev + ":" + props.ino + // console.error("Reader has nlink", me._path, k) + if (hardLinks[k] === me._path || !hardLinks[k]) hardLinks[k] = me._path + else { + // switch into hardlink mode. + type = me.type = me.props.type = "Link" + me.Link = me.props.Link = true + me.linkpath = me.props.linkpath = hardLinks[k] + // console.error("Hardlink detected, switching mode", me._path, me.linkpath) + // Setting __proto__ would arguably be the "correct" + // approach here, but that just seems too wrong. + me._stat = me._read = LinkReader.prototype._read + } + } + + if (me.type && me.type !== type) { + me.error("Unexpected type: " + type) + } + + // if the filter doesn't pass, then just skip over this one. + // still have to emit end so that dir-walking can move on. + if (me.filter) { + var who = me._proxy || me + // special handling for ProxyReaders + if (!me.filter.call(who, who, props)) { + if (!me._disowned) { + me.abort() + me.emit("end") + me.emit("close") + } + return + } + } + + // last chance to abort or disown before the flow starts! + var events = ["_stat", "stat", "ready"] + var e = 0 + ;(function go () { + if (me._aborted) { + me.emit("end") + me.emit("close") + return + } + + if (me._paused) { + me.once("resume", go) + return + } + + var ev = events[e ++] + if (!ev) return me._read() + me.emit(ev, props) + go() + })() + } +} + +Reader.prototype.pipe = function (dest, opts) { + var me = this + if (typeof dest.add === "function") { + // piping to a multi-compatible, and we've got directory entries. + me.on("entry", function (entry) { + var ret = dest.add(entry) + if (false === ret) { + me.pause() + } + }) + } + + // console.error("R Pipe apply Stream Pipe") + return Stream.prototype.pipe.apply(this, arguments) +} + +Reader.prototype.pause = function (who) { + this._paused = true + who = who || this + this.emit("pause", who) + if (this._stream) this._stream.pause(who) +} + +Reader.prototype.resume = function (who) { + this._paused = false + who = who || this + this.emit("resume", who) + if (this._stream) this._stream.resume(who) + this._read() +} + +Reader.prototype._read = function () { + this.error("Cannot read unknown type: "+this.type) +} + diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/socket-reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/socket-reader.js new file mode 100644 index 000000000..e89c1731a --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/socket-reader.js @@ -0,0 +1,38 @@ +// Just get the stats, and then don't do anything. +// You can't really "read" from a socket. You "connect" to it. +// Mostly, this is here so that reading a dir with a socket in it +// doesn't blow up. + +module.exports = SocketReader + +var fs = require("graceful-fs") + , fstream = require("../fstream.js") + , inherits = require("inherits") + , mkdir = require("mkdirp") + , Reader = require("./reader.js") + +inherits(SocketReader, Reader) + +function SocketReader (props) { + var me = this + if (!(me instanceof SocketReader)) throw new Error( + "SocketReader must be called as constructor.") + + if (!(props.type === "Socket" && props.Socket)) { + throw new Error("Non-socket type "+ props.type) + } + + Reader.call(me, props) +} + +SocketReader.prototype._read = function () { + var me = this + if (me._paused) return + // basically just a no-op, since we got all the info we have + // from the _stat method + if (!me._ended) { + me.emit("end") + me.emit("close") + me._ended = true + } +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/writer.js new file mode 100644 index 000000000..5599fb222 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/lib/writer.js @@ -0,0 +1,389 @@ + +module.exports = Writer + +var fs = require("graceful-fs") + , inherits = require("inherits") + , rimraf = require("rimraf") + , mkdir = require("mkdirp") + , path = require("path") + , umask = process.platform === "win32" ? 0 : process.umask() + , getType = require("./get-type.js") + , Abstract = require("./abstract.js") + +// Must do this *before* loading the child classes +inherits(Writer, Abstract) + +Writer.dirmode = 0777 & (~umask) +Writer.filemode = 0666 & (~umask) + +var DirWriter = require("./dir-writer.js") + , LinkWriter = require("./link-writer.js") + , FileWriter = require("./file-writer.js") + , ProxyWriter = require("./proxy-writer.js") + +// props is the desired state. current is optionally the current stat, +// provided here so that subclasses can avoid statting the target +// more than necessary. +function Writer (props, current) { + var me = this + + if (typeof props === "string") { + props = { path: props } + } + + if (!props.path) me.error("Must provide a path", null, true) + + // polymorphism. + // call fstream.Writer(dir) to get a DirWriter object, etc. + var type = getType(props) + , ClassType = Writer + + switch (type) { + case "Directory": + ClassType = DirWriter + break + case "File": + ClassType = FileWriter + break + case "Link": + case "SymbolicLink": + ClassType = LinkWriter + break + case null: + // Don't know yet what type to create, so we wrap in a proxy. + ClassType = ProxyWriter + break + } + + if (!(me instanceof ClassType)) return new ClassType(props) + + // now get down to business. + + Abstract.call(me) + + // props is what we want to set. + // set some convenience properties as well. + me.type = props.type + me.props = props + me.depth = props.depth || 0 + me.clobber = false === props.clobber ? props.clobber : true + me.parent = props.parent || null + me.root = props.root || (props.parent && props.parent.root) || me + + me._path = me.path = path.resolve(props.path) + if (process.platform === "win32") { + me.path = me._path = me.path.replace(/\?/g, "_") + if (me._path.length >= 260) { + me._swallowErrors = true + me._path = "\\\\?\\" + me.path.replace(/\//g, "\\") + } + } + me.basename = path.basename(props.path) + me.dirname = path.dirname(props.path) + me.linkpath = props.linkpath || null + + props.parent = props.root = null + + // console.error("\n\n\n%s setting size to", props.path, props.size) + me.size = props.size + + if (typeof props.mode === "string") { + props.mode = parseInt(props.mode, 8) + } + + me.readable = false + me.writable = true + + // buffer until ready, or while handling another entry + me._buffer = [] + me.ready = false + + me.filter = typeof props.filter === "function" ? props.filter: null + + // start the ball rolling. + // this checks what's there already, and then calls + // me._create() to call the impl-specific creation stuff. + me._stat(current) +} + +// Calling this means that it's something we can't create. +// Just assert that it's already there, otherwise raise a warning. +Writer.prototype._create = function () { + var me = this + fs[me.props.follow ? "stat" : "lstat"](me._path, function (er, current) { + if (er) { + return me.warn("Cannot create " + me._path + "\n" + + "Unsupported type: "+me.type, "ENOTSUP") + } + me._finish() + }) +} + +Writer.prototype._stat = function (current) { + var me = this + , props = me.props + , stat = props.follow ? "stat" : "lstat" + , who = me._proxy || me + + if (current) statCb(null, current) + else fs[stat](me._path, statCb) + + function statCb (er, current) { + if (me.filter && !me.filter.call(who, who, current)) { + me._aborted = true + me.emit("end") + me.emit("close") + return + } + + // if it's not there, great. We'll just create it. + // if it is there, then we'll need to change whatever differs + if (er || !current) { + return create(me) + } + + me._old = current + var currentType = getType(current) + + // if it's a type change, then we need to clobber or error. + // if it's not a type change, then let the impl take care of it. + if (currentType !== me.type) { + return rimraf(me._path, function (er) { + if (er) return me.error(er) + me._old = null + create(me) + }) + } + + // otherwise, just handle in the app-specific way + // this creates a fs.WriteStream, or mkdir's, or whatever + create(me) + } +} + +function create (me) { + // console.error("W create", me._path, Writer.dirmode) + + // XXX Need to clobber non-dirs that are in the way, + // unless { clobber: false } in the props. + mkdir(path.dirname(me._path), Writer.dirmode, function (er, made) { + // console.error("W created", path.dirname(me._path), er) + if (er) return me.error(er) + + // later on, we have to set the mode and owner for these + me._madeDir = made + return me._create() + }) +} + +function endChmod (me, want, current, path, cb) { + var wantMode = want.mode + , chmod = want.follow || me.type !== "SymbolicLink" + ? "chmod" : "lchmod" + + if (!fs[chmod]) return cb() + if (typeof wantMode !== "number") return cb() + + var curMode = current.mode & 0777 + wantMode = wantMode & 0777 + if (wantMode === curMode) return cb() + + fs[chmod](path, wantMode, cb) +} + + +function endChown (me, want, current, path, cb) { + // Don't even try it unless root. Too easy to EPERM. + if (process.platform === "win32") return cb() + if (!process.getuid || !process.getuid() === 0) return cb() + if (typeof want.uid !== "number" && + typeof want.gid !== "number" ) return cb() + + if (current.uid === want.uid && + current.gid === want.gid) return cb() + + var chown = (me.props.follow || me.type !== "SymbolicLink") + ? "chown" : "lchown" + if (!fs[chown]) return cb() + + if (typeof want.uid !== "number") want.uid = current.uid + if (typeof want.gid !== "number") want.gid = current.gid + + fs[chown](path, want.uid, want.gid, cb) +} + +function endUtimes (me, want, current, path, cb) { + if (!fs.utimes || process.platform === "win32") return cb() + + var utimes = (want.follow || me.type !== "SymbolicLink") + ? "utimes" : "lutimes" + + if (utimes === "lutimes" && !fs[utimes]) { + utimes = "utimes" + } + + if (!fs[utimes]) return cb() + + var curA = current.atime + , curM = current.mtime + , meA = want.atime + , meM = want.mtime + + if (meA === undefined) meA = curA + if (meM === undefined) meM = curM + + if (!isDate(meA)) meA = new Date(meA) + if (!isDate(meM)) meA = new Date(meM) + + if (meA.getTime() === curA.getTime() && + meM.getTime() === curM.getTime()) return cb() + + fs[utimes](path, meA, meM, cb) +} + + +// XXX This function is beastly. Break it up! +Writer.prototype._finish = function () { + var me = this + + // console.error(" W Finish", me._path, me.size) + + // set up all the things. + // At this point, we're already done writing whatever we've gotta write, + // adding files to the dir, etc. + var todo = 0 + var errState = null + var done = false + + if (me._old) { + // the times will almost *certainly* have changed. + // adds the utimes syscall, but remove another stat. + me._old.atime = new Date(0) + me._old.mtime = new Date(0) + // console.error(" W Finish Stale Stat", me._path, me.size) + setProps(me._old) + } else { + var stat = me.props.follow ? "stat" : "lstat" + // console.error(" W Finish Stating", me._path, me.size) + fs[stat](me._path, function (er, current) { + // console.error(" W Finish Stated", me._path, me.size, current) + if (er) { + // if we're in the process of writing out a + // directory, it's very possible that the thing we're linking to + // doesn't exist yet (especially if it was intended as a symlink), + // so swallow ENOENT errors here and just soldier on. + if (er.code === "ENOENT" && + (me.type === "Link" || me.type === "SymbolicLink") && + process.platform === "win32") { + me.ready = true + me.emit("ready") + me.emit("end") + me.emit("close") + me.end = me._finish = function () {} + return + } else return me.error(er) + } + setProps(me._old = current) + }) + } + + return + + function setProps (current) { + todo += 3 + endChmod(me, me.props, current, me._path, next("chmod")) + endChown(me, me.props, current, me._path, next("chown")) + endUtimes(me, me.props, current, me._path, next("utimes")) + } + + function next (what) { + return function (er) { + // console.error(" W Finish", what, todo) + if (errState) return + if (er) { + er.fstream_finish_call = what + return me.error(errState = er) + } + if (--todo > 0) return + if (done) return + done = true + + // we may still need to set the mode/etc. on some parent dirs + // that were created previously. delay end/close until then. + if (!me._madeDir) return end() + else endMadeDir(me, me._path, end) + + function end (er) { + if (er) { + er.fstream_finish_call = "setupMadeDir" + return me.error(er) + } + // all the props have been set, so we're completely done. + me.emit("end") + me.emit("close") + } + } + } +} + +function endMadeDir (me, p, cb) { + var made = me._madeDir + // everything *between* made and path.dirname(me._path) + // needs to be set up. Note that this may just be one dir. + var d = path.dirname(p) + + endMadeDir_(me, d, function (er) { + if (er) return cb(er) + if (d === made) { + return cb() + } + endMadeDir(me, d, cb) + }) +} + +function endMadeDir_ (me, p, cb) { + var dirProps = {} + Object.keys(me.props).forEach(function (k) { + dirProps[k] = me.props[k] + + // only make non-readable dirs if explicitly requested. + if (k === "mode" && me.type !== "Directory") { + dirProps[k] = dirProps[k] | 0111 + } + }) + + var todo = 3 + , errState = null + fs.stat(p, function (er, current) { + if (er) return cb(errState = er) + endChmod(me, dirProps, current, p, next) + endChown(me, dirProps, current, p, next) + endUtimes(me, dirProps, current, p, next) + }) + + function next (er) { + if (errState) return + if (er) return cb(errState = er) + if (-- todo === 0) return cb() + } +} + +Writer.prototype.pipe = function () { + this.error("Can't pipe from writable stream") +} + +Writer.prototype.add = function () { + this.error("Cannot add to non-Directory type") +} + +Writer.prototype.write = function () { + return true +} + +function objectToString (d) { + return Object.prototype.toString.call(d) +} + +function isDate(d) { + return typeof d === 'object' && objectToString(d) === '[object Date]'; +} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/.npmignore b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/.npmignore similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/.npmignore rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/.npmignore diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/LICENSE diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/README.md rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/README.md diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/graceful-fs.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/graceful-fs.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/graceful-fs.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/package.json new file mode 100644 index 000000000..8cd0e1e77 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/package.json @@ -0,0 +1,45 @@ +{ + "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": "1.2.1", + "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", + "readme": "# graceful-fs\n\ngraceful-fs functions as a drop-in replacement for the fs module,\nmaking various improvements.\n\nThe improvements are meant to normalize behavior across different\nplatforms and environments, and to make filesystem access more\nresilient to errors.\n\n## Improvements over fs module\n\ngraceful-fs:\n\n* keeps track of how many file descriptors are open, and by default\n limits this to 1024. Any further requests to open a file are put in a\n queue until new slots become available. If 1024 turns out to be too\n much, it decreases the limit further.\n* fixes `lchmod` for Node versions prior to 0.6.2.\n* implements `fs.lutimes` if possible. Otherwise it becomes a noop.\n* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or\n `lchown` if the user isn't root.\n* makes `lchmod` and `lchown` become noops, if not available.\n* retries reading a file if `read` results in EAGAIN error.\n\nOn Windows, it retries renaming a file for up to one second if `EACCESS`\nor `EPERM` error occurs, likely because antivirus software has locked\nthe directory.\n\n## Configuration\n\nThe maximum number of open file descriptors that graceful-fs manages may\nbe adjusted by setting `fs.MAX_OPEN` to a different number. The default\nis 1024.\n", + "readmeFilename": "README.md", + "_id": "graceful-fs@1.2.1", + "_from": "graceful-fs@~1.2.0" +} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/test/open.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/test/open.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/test/open.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/graceful-fs/test/open.js diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/inherits/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/inherits/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/inherits/README.md rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/inherits/README.md diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/inherits/inherits.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/inherits/inherits.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/inherits/inherits.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/inherits/inherits.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/inherits/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/inherits/package.json new file mode 100644 index 000000000..a908c700e --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/node_modules/inherits/package.json @@ -0,0 +1,27 @@ +{ + "name": "inherits", + "description": "A tiny simple way to do classic inheritance in js", + "version": "1.0.0", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented" + ], + "main": "./inherits.js", + "repository": { + "type": "git", + "url": "https://github.com/isaacs/inherits" + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "readme": "A dead simple way to do inheritance in JS.\n\n var inherits = require(\"inherits\")\n\n function Animal () {\n this.alive = true\n }\n Animal.prototype.say = function (what) {\n console.log(what)\n }\n\n inherits(Dog, Animal)\n function Dog () {\n Dog.super.apply(this)\n }\n Dog.prototype.sniff = function () {\n this.say(\"sniff sniff\")\n }\n Dog.prototype.bark = function () {\n this.say(\"woof woof\")\n }\n\n inherits(Chihuahua, Dog)\n function Chihuahua () {\n Chihuahua.super.apply(this)\n }\n Chihuahua.prototype.bark = function () {\n this.say(\"yip yip\")\n }\n\n // also works\n function Cat () {\n Cat.super.apply(this)\n }\n Cat.prototype.hiss = function () {\n this.say(\"CHSKKSS!!\")\n }\n inherits(Cat, Animal, {\n meow: function () { this.say(\"miao miao\") }\n })\n Cat.prototype.purr = function () {\n this.say(\"purr purr\")\n }\n\n\n var c = new Chihuahua\n assert(c instanceof Chihuahua)\n assert(c instanceof Dog)\n assert(c instanceof Animal)\n\nThe actual function is laughably small. 10-lines small.\n", + "readmeFilename": "README.md", + "_id": "inherits@1.0.0", + "_from": "inherits@~1.0.0", + "scripts": {} +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/package.json new file mode 100644 index 000000000..177e36972 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/fstream/package.json @@ -0,0 +1,35 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "fstream", + "description": "Advanced file system stream things", + "version": "0.1.22", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/fstream.git" + }, + "main": "fstream.js", + "engines": { + "node": ">=0.6" + }, + "dependencies": { + "rimraf": "2", + "mkdirp": "0.3", + "graceful-fs": "~1.2.0", + "inherits": "~1.0.0" + }, + "devDependencies": { + "tap": "" + }, + "scripts": { + "test": "tap examples/*.js" + }, + "license": "BSD", + "readme": "Like FS streams, but with stat on them, and supporting directories and\nsymbolic links, as well as normal files. Also, you can use this to set\nthe stats on a file, even if you don't change its contents, or to create\na symlink, etc.\n\nSo, for example, you can \"write\" a directory, and it'll call `mkdir`. You\ncan specify a uid and gid, and it'll call `chown`. You can specify a\n`mtime` and `atime`, and it'll call `utimes`. You can call it a symlink\nand provide a `linkpath` and it'll call `symlink`.\n\nNote that it won't automatically resolve symbolic links. So, if you\ncall `fstream.Reader('/some/symlink')` then you'll get an object\nthat stats and then ends immediately (since it has no data). To follow\nsymbolic links, do this: `fstream.Reader({path:'/some/symlink', follow:\ntrue })`.\n\nThere are various checks to make sure that the bytes emitted are the\nsame as the intended size, if the size is set.\n\n## Examples\n\n```javascript\nfstream\n .Writer({ path: \"path/to/file\"\n , mode: 0755\n , size: 6\n })\n .write(\"hello\\n\")\n .end()\n```\n\nThis will create the directories if they're missing, and then write\n`hello\\n` into the file, chmod it to 0755, and assert that 6 bytes have\nbeen written when it's done.\n\n```javascript\nfstream\n .Writer({ path: \"path/to/file\"\n , mode: 0755\n , size: 6\n , flags: \"a\"\n })\n .write(\"hello\\n\")\n .end()\n```\n\nYou can pass flags in, if you want to append to a file.\n\n```javascript\nfstream\n .Writer({ path: \"path/to/symlink\"\n , linkpath: \"./file\"\n , SymbolicLink: true\n , mode: \"0755\" // octal strings supported\n })\n .end()\n```\n\nIf isSymbolicLink is a function, it'll be called, and if it returns\ntrue, then it'll treat it as a symlink. If it's not a function, then\nany truish value will make a symlink, or you can set `type:\n'SymbolicLink'`, which does the same thing.\n\nNote that the linkpath is relative to the symbolic link location, not\nthe parent dir or cwd.\n\n```javascript\nfstream\n .Reader(\"path/to/dir\")\n .pipe(fstream.Writer(\"path/to/other/dir\"))\n```\n\nThis will do like `cp -Rp path/to/dir path/to/other/dir`. If the other\ndir exists and isn't a directory, then it'll emit an error. It'll also\nset the uid, gid, mode, etc. to be identical. In this way, it's more\nlike `rsync -a` than simply a copy.\n", + "readmeFilename": "README.md", + "_id": "fstream@0.1.22", + "_from": "fstream@~0.1.19" +} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/.npmignore b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/.npmignore similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/.npmignore rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/.npmignore diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/.travis.yml b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/.travis.yml similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/.travis.yml rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/.travis.yml diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/LICENSE diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/README.md new file mode 100644 index 000000000..6e27df620 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/README.md @@ -0,0 +1,233 @@ +# Glob + +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. + +### 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.) +* `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. +* `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. **Note that this is different from the way that `**` is +handled by ruby's `Dir` class.** + +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 statCache object is 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/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/examples/g.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/examples/g.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/examples/g.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/examples/g.js diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/examples/usr-local.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/examples/usr-local.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/examples/usr-local.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/examples/usr-local.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/glob.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/glob.js new file mode 100644 index 000000000..891c88360 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/glob.js @@ -0,0 +1,643 @@ +// 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.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 + + 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.statCache[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) { + 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) + + // 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] + if (typeof pn === "string") { + var found = entries.indexOf(pn) !== -1 + entries = found ? entries[pn] : [] + } else { + var rawGlob = pattern[n]._glob + , dotOk = this.dot || rawGlob.charAt(0) === "." + + entries = entries.filter(function (e) { + return (e.charAt(0) !== "." || dotOk) && + (typeof pattern[n] === "string" && e === pattern[n] || + 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) + }) + +} + +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) + } + this.log('stat', [this.cwd, f, '=', abs]) + 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) + } + + if (this.statCache.hasOwnProperty(f)) { + var exists = this.statCache[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)) + } + + if (this.sync) { + var er, stat + 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 + } + + if (er || !stat) { + exists = false + } else { + exists = stat.isDirectory() ? 2 : 1 + } + this.statCache[f] = this.statCache[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) + } + + this.log('readdir', [this.cwd, f, abs]) + 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) + } + + if (this.statCache.hasOwnProperty(f)) { + var c = this.statCache[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.statCache[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.statCache[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.statCache[f] = 1 + return cb.call(this, er) + case "ENOENT": // not terribly unusual + case "ELOOP": + case "ENAMETOOLONG": + case "UNKNOWN": + this.statCache[f] = false + return cb.call(this, er) + default: // some unusual error. Treat as failure. + this.statCache[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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/graceful-fs/.npmignore b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/.npmignore similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/graceful-fs/.npmignore rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/.npmignore diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/LICENSE diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/graceful-fs/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/graceful-fs/README.md rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/README.md diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/graceful-fs/graceful-fs.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/graceful-fs.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/graceful-fs/graceful-fs.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/graceful-fs.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/package.json new file mode 100644 index 000000000..8cd0e1e77 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/package.json @@ -0,0 +1,45 @@ +{ + "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": "1.2.1", + "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", + "readme": "# graceful-fs\n\ngraceful-fs functions as a drop-in replacement for the fs module,\nmaking various improvements.\n\nThe improvements are meant to normalize behavior across different\nplatforms and environments, and to make filesystem access more\nresilient to errors.\n\n## Improvements over fs module\n\ngraceful-fs:\n\n* keeps track of how many file descriptors are open, and by default\n limits this to 1024. Any further requests to open a file are put in a\n queue until new slots become available. If 1024 turns out to be too\n much, it decreases the limit further.\n* fixes `lchmod` for Node versions prior to 0.6.2.\n* implements `fs.lutimes` if possible. Otherwise it becomes a noop.\n* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or\n `lchown` if the user isn't root.\n* makes `lchmod` and `lchown` become noops, if not available.\n* retries reading a file if `read` results in EAGAIN error.\n\nOn Windows, it retries renaming a file for up to one second if `EACCESS`\nor `EPERM` error occurs, likely because antivirus software has locked\nthe directory.\n\n## Configuration\n\nThe maximum number of open file descriptors that graceful-fs manages may\nbe adjusted by setting `fs.MAX_OPEN` to a different number. The default\nis 1024.\n", + "readmeFilename": "README.md", + "_id": "graceful-fs@1.2.1", + "_from": "graceful-fs@~1.2.0" +} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/graceful-fs/test/open.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/test/open.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/graceful-fs/test/open.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/graceful-fs/test/open.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/inherits/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/inherits/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/inherits/README.md rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/inherits/README.md diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/inherits/inherits.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/inherits/inherits.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/inherits/inherits.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/inherits/inherits.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/inherits/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/inherits/package.json new file mode 100644 index 000000000..ada613725 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/inherits/package.json @@ -0,0 +1,26 @@ +{ + "name": "inherits", + "description": "A tiny simple way to do classic inheritance in js", + "version": "1.0.0", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented" + ], + "main": "./inherits.js", + "repository": { + "type": "git", + "url": "https://github.com/isaacs/inherits" + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "readme": "A dead simple way to do inheritance in JS.\n\n var inherits = require(\"inherits\")\n\n function Animal () {\n this.alive = true\n }\n Animal.prototype.say = function (what) {\n console.log(what)\n }\n\n inherits(Dog, Animal)\n function Dog () {\n Dog.super.apply(this)\n }\n Dog.prototype.sniff = function () {\n this.say(\"sniff sniff\")\n }\n Dog.prototype.bark = function () {\n this.say(\"woof woof\")\n }\n\n inherits(Chihuahua, Dog)\n function Chihuahua () {\n Chihuahua.super.apply(this)\n }\n Chihuahua.prototype.bark = function () {\n this.say(\"yip yip\")\n }\n\n // also works\n function Cat () {\n Cat.super.apply(this)\n }\n Cat.prototype.hiss = function () {\n this.say(\"CHSKKSS!!\")\n }\n inherits(Cat, Animal, {\n meow: function () { this.say(\"miao miao\") }\n })\n Cat.prototype.purr = function () {\n this.say(\"purr purr\")\n }\n\n\n var c = new Chihuahua\n assert(c instanceof Chihuahua)\n assert(c instanceof Dog)\n assert(c instanceof Animal)\n\nThe actual function is laughably small. 10-lines small.\n", + "readmeFilename": "README.md", + "_id": "inherits@1.0.0", + "_from": "inherits@1" +} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/LICENSE diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/README.md rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/README.md diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/minimatch.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/minimatch.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/minimatch.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/minimatch.js diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/.npmignore b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.npmignore similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/.npmignore rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.npmignore diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/AUTHORS b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/AUTHORS similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/AUTHORS rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/AUTHORS diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/LICENSE diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/README.md rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/README.md diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json new file mode 100644 index 000000000..111e5d7c2 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json @@ -0,0 +1,59 @@ +{ + "name": "lru-cache", + "description": "A cache object that deletes the least-recently-used items.", + "version": "2.3.0", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me" + }, + "scripts": { + "test": "tap test --gc" + }, + "main": "lib/lru-cache.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-lru-cache.git" + }, + "devDependencies": { + "tap": "", + "weak": "" + }, + "license": { + "type": "MIT", + "url": "http://github.com/isaacs/node-lru-cache/raw/master/LICENSE" + }, + "contributors": [ + { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me" + }, + { + "name": "Carlos Brito Lage", + "email": "carlos@carloslage.net" + }, + { + "name": "Marko Mikulicic", + "email": "marko.mikulicic@isti.cnr.it" + }, + { + "name": "Trent Mick", + "email": "trentm@gmail.com" + }, + { + "name": "Kevin O'Hara", + "email": "kevinohara80@gmail.com" + }, + { + "name": "Marco Rogers", + "email": "marco.rogers@gmail.com" + }, + { + "name": "Jesse Dailey", + "email": "jesse.dailey@gmail.com" + } + ], + "readme": "# lru cache\n\nA cache object that deletes the least-recently-used items.\n\n## Usage:\n\n```javascript\nvar LRU = require(\"lru-cache\")\n , options = { max: 500\n , length: function (n) { return n * 2 }\n , dispose: function (key, n) { n.close() }\n , maxAge: 1000 * 60 * 60 }\n , cache = LRU(options)\n , otherCache = LRU(50) // sets just the max size\n\ncache.set(\"key\", \"value\")\ncache.get(\"key\") // \"value\"\n\ncache.reset() // empty the cache\n```\n\nIf you put more stuff in it, then items will fall out.\n\nIf you try to put an oversized thing in it, then it'll fall out right\naway.\n\n## Options\n\n* `max` The maximum size of the cache, checked by applying the length\n function to all values in the cache. Not setting this is kind of\n silly, since that's the whole purpose of this lib, but it defaults\n to `Infinity`.\n* `maxAge` Maximum age in ms. Items are not pro-actively pruned out\n as they age, but if you try to get an item that is too old, it'll\n drop it and return undefined instead of giving it to you.\n* `length` Function that is used to calculate the length of stored\n items. If you're storing strings or buffers, then you probably want\n to do something like `function(n){return n.length}`. The default is\n `function(n){return 1}`, which is fine if you want to store `n`\n like-sized things.\n* `dispose` Function that is called on items when they are dropped\n from the cache. This can be handy if you want to close file\n descriptors or do other cleanup tasks when items are no longer\n accessible. Called with `key, value`. It's called *before*\n actually removing the item from the internal cache, so if you want\n to immediately put it back in, you'll have to do that in a\n `nextTick` or `setTimeout` callback or it won't do anything.\n* `stale` By default, if you set a `maxAge`, it'll only actually pull\n stale items out of the cache when you `get(key)`. (That is, it's\n not pre-emptively doing a `setTimeout` or anything.) If you set\n `stale:true`, it'll return the stale value before deleting it. If\n you don't set this, then it'll return `undefined` when you try to\n get a stale entry, as if it had already been deleted.\n\n## API\n\n* `set(key, value)`\n* `get(key) => value`\n\n Both of these will update the \"recently used\"-ness of the key.\n They do what you think.\n\n* `peek(key)`\n\n Returns the key value (or `undefined` if not found) without\n updating the \"recently used\"-ness of the key.\n\n (If you find yourself using this a lot, you *might* be using the\n wrong sort of data structure, but there are some use cases where\n it's handy.)\n\n* `del(key)`\n\n Deletes a key out of the cache.\n\n* `reset()`\n\n Clear the cache entirely, throwing away all values.\n\n* `has(key)`\n\n Check if a key is in the cache, without updating the recent-ness\n or deleting it for being stale.\n\n* `forEach(function(value,key,cache), [thisp])`\n\n Just like `Array.prototype.forEach`. Iterates over all the keys\n in the cache, in order of recent-ness. (Ie, more recently used\n items are iterated over first.)\n\n* `keys()`\n\n Return an array of the keys in the cache.\n\n* `values()`\n\n Return an array of the values in the cache.\n", + "readmeFilename": "README.md", + "_id": "lru-cache@2.3.0", + "_from": "lru-cache@2" +} diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/s.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/s.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/s.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/s.js diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/test/basic.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/basic.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/test/basic.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/basic.js diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/test/foreach.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/foreach.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/test/foreach.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/foreach.js diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/node_modules/sigmund/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/node_modules/sigmund/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/LICENSE diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/sigmund/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/sigmund/README.md rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/README.md diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/sigmund/bench.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/bench.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/sigmund/bench.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/bench.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json new file mode 100644 index 000000000..92a63e961 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json @@ -0,0 +1,38 @@ +{ + "name": "sigmund", + "version": "1.0.0", + "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" + }, + "keywords": [ + "object", + "signature", + "key", + "data", + "psychoanalysis" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "BSD", + "readme": "# sigmund\n\nQuick and dirty signatures for Objects.\n\nThis is like a much faster `deepEquals` comparison, which returns a\nstring key suitable for caches and the like.\n\n## Usage\n\n```javascript\nfunction doSomething (someObj) {\n var key = sigmund(someObj, maxDepth) // max depth defaults to 10\n var cached = cache.get(key)\n if (cached) return cached)\n\n var result = expensiveCalculation(someObj)\n cache.set(key, result)\n return result\n}\n```\n\nThe resulting key will be as unique and reproducible as calling\n`JSON.stringify` or `util.inspect` on the object, but is much faster.\nIn order to achieve this speed, some differences are glossed over.\nFor example, the object `{0:'foo'}` will be treated identically to the\narray `['foo']`.\n\nAlso, just as there is no way to summon the soul from the scribblings\nof a cocain-addled psychoanalyst, there is no way to revive the object\nfrom the signature string that sigmund gives you. In fact, it's\nbarely even readable.\n\nAs with `sys.inspect` and `JSON.stringify`, larger objects will\nproduce larger signature strings.\n\nBecause sigmund is a bit less strict than the more thorough\nalternatives, the strings will be shorter, and also there is a\nslightly higher chance for collisions. For example, these objects\nhave the same signature:\n\n var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]}\n var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']}\n\nLike a good Freudian, sigmund is most effective when you already have\nsome understanding of what you're looking for. It can help you help\nyourself, but you must be willing to do some work as well.\n\nCycles are handled, and cyclical objects are silently omitted (though\nthe key is included in the signature output.)\n\nThe second argument is the maximum depth, which defaults to 10,\nbecause that is the maximum object traversal depth covered by most\ninsurance carriers.\n", + "readmeFilename": "README.md", + "_id": "sigmund@1.0.0", + "_from": "sigmund@~1.0.0" +} diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/sigmund/sigmund.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/sigmund.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/sigmund/sigmund.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/sigmund.js diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/sigmund/test/basic.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/test/basic.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/node_modules/sigmund/test/basic.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/node_modules/sigmund/test/basic.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/package.json new file mode 100644 index 000000000..480a1cd58 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/package.json @@ -0,0 +1,36 @@ +{ + "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.12", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "test": "tap test" + }, + "engines": { + "node": "*" + }, + "dependencies": { + "lru-cache": "2", + "sigmund": "~1.0.0" + }, + "devDependencies": { + "tap": "" + }, + "license": { + "type": "MIT", + "url": "http://github.com/isaacs/minimatch/raw/master/LICENSE" + }, + "readme": "# minimatch\n\nA minimal matching utility.\n\n[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch)\n\n\nThis is the matching library used internally by npm.\n\nEventually, it will replace the C binding in node-glob.\n\nIt works by converting glob expressions into JavaScript `RegExp`\nobjects.\n\n## Usage\n\n```javascript\nvar minimatch = require(\"minimatch\")\n\nminimatch(\"bar.foo\", \"*.foo\") // true!\nminimatch(\"bar.foo\", \"*.bar\") // false!\n```\n\n## Features\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\n### Comparisons to other fnmatch/glob implementations\n\nWhile strict compliance with the existing standards is a worthwhile\ngoal, some discrepancies exist between minimatch 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. **Note that this is different from the way that `**` is\nhandled by ruby's `Dir` class.**\n\nIf an escaped pattern has no matches, and the `nonull` flag is set,\nthen minimatch.match returns the pattern as-provided, rather than\ninterpreting the character escapes. For example,\n`minimatch.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\n## Minimatch Class\n\nCreate a minimatch object by instanting the `minimatch.Minimatch` class.\n\n```javascript\nvar Minimatch = require(\"minimatch\").Minimatch\nvar mm = new Minimatch(pattern, options)\n```\n\n### Properties\n\n* `pattern` The original pattern the minimatch object represents.\n* `options` The options supplied to the constructor.\n* `set` A 2-dimensional array of regexp or string expressions.\n Each row in the\n array corresponds to a brace-expanded pattern. Each item in the row\n corresponds to a single path-part. For example, the pattern\n `{a,b/c}/d` would expand to a set of patterns like:\n\n [ [ a, d ]\n , [ b, c, d ] ]\n\n If a portion of the pattern doesn't have any \"magic\" in it\n (that is, it's something like `\"foo\"` rather than `fo*o?`), then it\n will be left as a string rather than converted to a regular\n expression.\n\n* `regexp` Created by the `makeRe` method. A single regular expression\n expressing the entire pattern. This is useful in cases where you wish\n to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.\n* `negate` True if the pattern is negated.\n* `comment` True if the pattern is a comment.\n* `empty` True if the pattern is `\"\"`.\n\n### Methods\n\n* `makeRe` Generate the `regexp` member if necessary, and return it.\n Will return `false` if the pattern is invalid.\n* `match(fname)` Return true if the filename matches the pattern, or\n false otherwise.\n* `matchOne(fileArray, patternArray, partial)` Take a `/`-split\n filename, and match it against a single row in the `regExpSet`. This\n method is mainly for internal use, but is exposed so that it can be\n used by a glob-walker that needs to avoid excessive filesystem calls.\n\nAll other methods are internal, and will be called as necessary.\n\n## Functions\n\nThe top-level exported function has a `cache` property, which is an LRU\ncache set to store 100 items. So, calling these methods repeatedly\nwith the same pattern and options will use the same Minimatch object,\nsaving the cost of parsing it multiple times.\n\n### minimatch(path, pattern, options)\n\nMain export. Tests a path against the pattern using the options.\n\n```javascript\nvar isJS = minimatch(file, \"*.js\", { matchBase: true })\n```\n\n### minimatch.filter(pattern, options)\n\nReturns a function that tests its\nsupplied argument, suitable for use with `Array.filter`. Example:\n\n```javascript\nvar javascripts = fileList.filter(minimatch.filter(\"*.js\", {matchBase: true}))\n```\n\n### minimatch.match(list, pattern, options)\n\nMatch against the list of\nfiles, in the style of fnmatch or glob. If nothing is matched, and\noptions.nonull is set, then return a list containing the pattern itself.\n\n```javascript\nvar javascripts = minimatch.match(fileList, \"*.js\", {matchBase: true}))\n```\n\n### minimatch.makeRe(pattern, options)\n\nMake a regular expression object from the pattern.\n\n## Options\n\nAll options are `false` by default.\n\n### debug\n\nDump a ton of stuff to stderr.\n\n### nobrace\n\nDo not expand `{a,b}` and `{1..3}` brace sets.\n\n### noglobstar\n\nDisable `**` matching against multiple folder names.\n\n### dot\n\nAllow patterns to match filenames starting with a period, even if\nthe pattern does not explicitly have a period in that spot.\n\nNote that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`\nis set.\n\n### noext\n\nDisable \"extglob\" style patterns like `+(a|b)`.\n\n### nocase\n\nPerform a case-insensitive match.\n\n### nonull\n\nWhen a match is not found by `minimatch.match`, return a list containing\nthe pattern itself. When set, an empty list is returned if there are\nno matches.\n\n### matchBase\n\nIf set, then patterns without slashes will be matched\nagainst the basename of the path if it contains slashes. For example,\n`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.\n\n### nocomment\n\nSuppress the behavior of treating `#` at the start of a pattern as a\ncomment.\n\n### nonegate\n\nSuppress the behavior of treating a leading `!` character as negation.\n\n### flipNegate\n\nReturns from negate expressions the same as if they were not negated.\n(Ie, true on a hit, false on a miss.)\n", + "readmeFilename": "README.md", + "_id": "minimatch@0.2.12", + "_from": "minimatch@~0.2.11" +} diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/test/basic.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/test/basic.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/test/basic.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/test/basic.js diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/test/brace-expand.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/test/brace-expand.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/test/brace-expand.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/test/brace-expand.js diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/test/caching.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/test/caching.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/test/caching.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/test/caching.js diff --git a/node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/test/defaults.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/test/defaults.js similarity index 100% rename from node/node_modules/grunt/node_modules/glob-whatev/node_modules/minimatch/test/defaults.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/node_modules/minimatch/test/defaults.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/package.json new file mode 100644 index 000000000..b7200ddb3 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/package.json @@ -0,0 +1,36 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "name": "glob", + "description": "a little globber", + "version": "3.1.21", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-glob.git" + }, + "main": "glob.js", + "engines": { + "node": "*" + }, + "dependencies": { + "minimatch": "~0.2.11", + "graceful-fs": "~1.2.0", + "inherits": "1" + }, + "devDependencies": { + "tap": "~0.4.0", + "mkdirp": "0", + "rimraf": "1" + }, + "scripts": { + "test": "tap test/*.js" + }, + "license": "BSD", + "readme": "# Glob\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\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* `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* `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. **Note that this is different from the way that `**` is\nhandled by ruby's `Dir` class.**\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 statCache object is reused between glob calls.\n\nUsers are thus advised not to use a glob result as a\nguarantee of filesystem state in the face of rapid changes.\nFor the vast majority of operations, this is never a problem.\n", + "readmeFilename": "README.md", + "_id": "glob@3.1.21", + "_from": "glob@~3.1.14" +} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/00-setup.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/00-setup.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/00-setup.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/00-setup.js diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/bash-comparison.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/bash-comparison.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/bash-comparison.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/bash-comparison.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/bash-results.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/bash-results.json new file mode 100644 index 000000000..c227449b6 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/bash-results.json @@ -0,0 +1,348 @@ +{ + "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/mark.js", + "./test/nocase-nomagic.js", + "./test/pause-resume.js", + "./test/root-nomount.js", + "./test/root.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/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/cwd-test.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/cwd-test.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/cwd-test.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/cwd-test.js diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/mark.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/mark.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/mark.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/mark.js diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/nocase-nomagic.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/nocase-nomagic.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/nocase-nomagic.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/nocase-nomagic.js diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/pause-resume.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/pause-resume.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/pause-resume.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/pause-resume.js diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/root-nomount.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/root-nomount.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/root-nomount.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/root-nomount.js diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/root.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/root.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/root.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/root.js diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/zz-cleanup.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/zz-cleanup.js similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/test/zz-cleanup.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/glob/test/zz-cleanup.js diff --git a/node/node_modules/grunt/node_modules/connect/node_modules/cookie/.npmignore b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/.git_ignore similarity index 100% rename from node/node_modules/grunt/node_modules/connect/node_modules/cookie/.npmignore rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/.git_ignore diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/.gitmodules b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/.gitmodules new file mode 100644 index 000000000..6bfdc18eb --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/.gitmodules @@ -0,0 +1,3 @@ +[submodule "test/spec"] + path = test/spec + url = https://github.com/mustache/spec.git diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/LICENSE new file mode 100644 index 000000000..4947287f7 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/LICENSE @@ -0,0 +1,177 @@ + + 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 \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/Makefile b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/Makefile new file mode 100644 index 000000000..43ed5e8eb --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/Makefile @@ -0,0 +1,60 @@ +REPO = git@github.com:twitter/hogan.js.git +BUILD := build +VERSION = ${shell node -e 'console.log(JSON.parse(require("fs").readFileSync("package.json").toString()).version);'} + +# +# Run command line tests +# +test: + @ node test/run.js test/index.html + +# +# Run Mustache spec tests +# +spec: + @ node test/spec.js + +# +# Run benchmark +# +benchmark: + @ node benchmark/console/index.js + +clean: + @ rm -rf dist/* +# +# Make a new version of Hogan from the current dev version. +# +release: clean + @ echo "Creating a new version of Hogan." + @ node tools/release.js + @ mkdir -p web/builds/$(VERSION) + @ cp dist/*.* web/builds/$(VERSION)/. +# +# Make the gh-pages website +# +# This target builds the hogan.js github website using hogan.js. +# +# cd into build/gh-pages to check in the new site. +# +GH_PAGES = $(BUILD)/gh-pages +web: | pages + @cp -R web/* $(GH_PAGES) + @@ node tools/web_templates.js + @echo + @echo "Website built in $(GH_PAGES)." + +# +# Checkout the gh-pages branch. +# +pages: | $(BUILD) + @if [ ! -d "$(GH_PAGES)" ]; then \ + git clone -b gh-pages $(REPO) $(GH_PAGES); \ + rm -rf $(GH_PAGES)/*; \ + fi; + @mkdir -p $(GH_PAGES)/images + +$(BUILD): + mkdir -p $(BUILD) + +.PHONY: test spec benchmark web release diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/README.md new file mode 100644 index 000000000..1fa3e433f --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/README.md @@ -0,0 +1,93 @@ +## Hogan.js - A mustache compiler. + +[Hogan.js](http://twitter.github.com/hogan.js/) is a compiler for the +[Mustache](http://mustache.github.com/) templating language. For information +on Mustache, see the [manpage](http://mustache.github.com/mustache.5.html) and +the [spec](https://github.com/mustache/spec). + +## Basics + +Hogan compiles templates to HoganTemplate objects, which have a render method. + +```js +var data = { + screenName: "dhg", +}; + +var template = Hogan.compile("Follow @{{screenName}}."); +var output = template.render(data); + +// prints "Follow @dhg." +console.log(output); +``` + +## Features + +Hogan is fast--try it on your workload. + +Hogan has separate scanning, parsing and code generation phases. This way it's +possible to add new features without touching the scanner at all, and many +different code generation techniques can be tried without changing the parser. + +Hogan exposes scan and parse methods. These can be useful for +pre-processing templates on the server. + +```js +var text = "{{^check}}{{#i18n}}No{{/i18n}}{{/check}}"; +text += "{{#check}}{{#i18n}}Yes{{/i18n}}{{/check}}"; +var tree = Hogan.parse(Hogan.scan(text)); + +// outputs "# check" +console.log(tree[0].tag + " " + tree[0].name); + +// outputs "Yes" +console.log(tree[1].nodes[0].nodes[0]); +``` + +It's also possible to use HoganTemplate objects without the Hogan compiler +present. That means you can pre-compile your templates on the server, and +avoid shipping the compiler. However, the optional lambda features from the +Mustache spec do require the compiler to be present. + +## Why Hogan.js? + +Why another templating library? + +Hogan.js was written to meet three templating library requirements: good +performance, standalone template objects, and a parser API. + +## Issues + +Have a bug? Please create an issue here on GitHub! + +https://github.com/twitter/hogan.js/issues + +## Versioning + +For transparency and insight into our release cycle, releases will be numbered with the follow format: + +`..` + +And constructed with the following guidelines: + +* Breaking backwards compatibility bumps the major +* New additions without breaking backwards compatibility bumps the minor +* Bug fixes and misc changes bump the patch + +For more information on semantic versioning, please visit http://semver.org/. + +## Authors + +**Robert Sayre** + ++ http://github.com/sayrer + +**Jacob Thornton** + ++ http://github.com/fat + +## License + +Copyright 2011 Twitter, Inc. + +Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0 \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/bin/hulk b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/bin/hulk new file mode 100755 index 000000000..2b5065550 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/bin/hulk @@ -0,0 +1,93 @@ +#!/usr/bin/env node + +/* + * Copyright 2011 Twitter, 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. + */ + +var hogan = require('../lib/hogan.js'), + path = require('path'), + fs = require('fs'); + +var specials = ['/', '.', '*', '+', '?', '|','(', ')', '[', ']', '{', '}', '\\'], + specialsRegExp = new RegExp('(\\' + specials.join('|\\') + ')', 'g'), + templates; + + +// Escape special regexp characters +function esc(text) { + return text.replace(specialsRegExp, '\\$1'); +} + + +// Check for dirs and correct ext (<3 for windows) +function extractFiles(args) { + var usage = 'USAGE: hulk ./templates/*.mustaches\n' + + 'NOTE: hulk supports the "*" wildcard and allows you to target specific extensions too', + files = []; + + if (!args.length) { + console.log(usage); + process.exit(-1); + } + + args.forEach(function (arg) { + + if (/\*/.test(arg)) { + arg = arg.split('*'); + return files = files.concat( + fs.readdirSync(arg[0] || '.') + .map(function (f) { + return new RegExp(esc(arg[1]) + '$').test(f) && path.join(arg[0], f); + }) + .filter(function (f) { + return f; + }) + ); + } + + files.push(arg); + + }) + + return files; +} + + +// Remove utf-8 byte order mark, http://en.wikipedia.org/wiki/Byte_order_mark +function removeByteOrderMark(text) { + if (text.charCodeAt(0) === 0xfeff) { + return text.substring(1); + } + return text; +} + + +// Write a template foreach file that matches template extension +templates = extractFiles(process.argv.slice(2)) + .map(function (file) { + var openedFile = fs.readFileSync(file, 'utf-8'), name; + if (!openedFile) return; + name = path.basename(file).replace(/\..*$/, ''); + openedFile = removeByteOrderMark(openedFile.trim()); + return 'templates.' + name + ' = new Hogan.Template(' + hogan.compile(openedFile, { asString: 1 }) + ');'; + }) + .filter(function (t) { + return t; + }); + + +// Output templates +if (!templates.length) return; +console.log('var templates = {};'); +console.log(templates.join('\n')); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/lib/compiler.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/lib/compiler.js new file mode 100644 index 000000000..f72a0b26a --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/lib/compiler.js @@ -0,0 +1,344 @@ +/* + * Copyright 2011 Twitter, 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. + */ + +(function (Hogan) { + // Setup regex assignments + // remove whitespace according to Mustache spec + var rIsWhitespace = /\S/, + rQuot = /\"/g, + rNewline = /\n/g, + rCr = /\r/g, + rSlash = /\\/g, + tagTypes = { + '#': 1, '^': 2, '/': 3, '!': 4, '>': 5, + '<': 6, '=': 7, '_v': 8, '{': 9, '&': 10 + }; + + Hogan.scan = function scan(text, delimiters) { + var len = text.length, + IN_TEXT = 0, + IN_TAG_TYPE = 1, + IN_TAG = 2, + state = IN_TEXT, + tagType = null, + tag = null, + buf = '', + tokens = [], + seenTag = false, + i = 0, + lineStart = 0, + otag = '{{', + ctag = '}}'; + + function addBuf() { + if (buf.length > 0) { + tokens.push(new String(buf)); + buf = ''; + } + } + + function lineIsWhitespace() { + var isAllWhitespace = true; + for (var j = lineStart; j < tokens.length; j++) { + isAllWhitespace = + (tokens[j].tag && tagTypes[tokens[j].tag] < tagTypes['_v']) || + (!tokens[j].tag && tokens[j].match(rIsWhitespace) === null); + if (!isAllWhitespace) { + return false; + } + } + + return isAllWhitespace; + } + + function filterLine(haveSeenTag, noNewLine) { + addBuf(); + + if (haveSeenTag && lineIsWhitespace()) { + for (var j = lineStart, next; j < tokens.length; j++) { + if (!tokens[j].tag) { + if ((next = tokens[j+1]) && next.tag == '>') { + // set indent to token value + next.indent = tokens[j].toString() + } + tokens.splice(j, 1); + } + } + } else if (!noNewLine) { + tokens.push({tag:'\n'}); + } + + seenTag = false; + lineStart = tokens.length; + } + + function changeDelimiters(text, index) { + var close = '=' + ctag, + closeIndex = text.indexOf(close, index), + delimiters = trim( + text.substring(text.indexOf('=', index) + 1, closeIndex) + ).split(' '); + + otag = delimiters[0]; + ctag = delimiters[1]; + + return closeIndex + close.length - 1; + } + + if (delimiters) { + delimiters = delimiters.split(' '); + otag = delimiters[0]; + ctag = delimiters[1]; + } + + for (i = 0; i < len; i++) { + if (state == IN_TEXT) { + if (tagChange(otag, text, i)) { + --i; + addBuf(); + state = IN_TAG_TYPE; + } else { + if (text.charAt(i) == '\n') { + filterLine(seenTag); + } else { + buf += text.charAt(i); + } + } + } else if (state == IN_TAG_TYPE) { + i += otag.length - 1; + tag = tagTypes[text.charAt(i + 1)]; + tagType = tag ? text.charAt(i + 1) : '_v'; + if (tagType == '=') { + i = changeDelimiters(text, i); + state = IN_TEXT; + } else { + if (tag) { + i++; + } + state = IN_TAG; + } + seenTag = i; + } else { + if (tagChange(ctag, text, i)) { + tokens.push({tag: tagType, n: trim(buf), otag: otag, ctag: ctag, + i: (tagType == '/') ? seenTag - ctag.length : i + otag.length}); + buf = ''; + i += ctag.length - 1; + state = IN_TEXT; + if (tagType == '{') { + if (ctag == '}}') { + i++; + } else { + cleanTripleStache(tokens[tokens.length - 1]); + } + } + } else { + buf += text.charAt(i); + } + } + } + + filterLine(seenTag, true); + + return tokens; + } + + function cleanTripleStache(token) { + if (token.n.substr(token.n.length - 1) === '}') { + token.n = token.n.substring(0, token.n.length - 1); + } + } + + function trim(s) { + if (s.trim) { + return s.trim(); + } + + return s.replace(/^\s*|\s*$/g, ''); + } + + function tagChange(tag, text, index) { + if (text.charAt(index) != tag.charAt(0)) { + return false; + } + + for (var i = 1, l = tag.length; i < l; i++) { + if (text.charAt(index + i) != tag.charAt(i)) { + return false; + } + } + + return true; + } + + function buildTree(tokens, kind, stack, customTags) { + var instructions = [], + opener = null, + token = null; + + while (tokens.length > 0) { + token = tokens.shift(); + if (token.tag == '#' || token.tag == '^' || isOpener(token, customTags)) { + stack.push(token); + token.nodes = buildTree(tokens, token.tag, stack, customTags); + instructions.push(token); + } else if (token.tag == '/') { + if (stack.length === 0) { + throw new Error('Closing tag without opener: /' + token.n); + } + opener = stack.pop(); + if (token.n != opener.n && !isCloser(token.n, opener.n, customTags)) { + throw new Error('Nesting error: ' + opener.n + ' vs. ' + token.n); + } + opener.end = token.i; + return instructions; + } else { + instructions.push(token); + } + } + + if (stack.length > 0) { + throw new Error('missing closing tag: ' + stack.pop().n); + } + + return instructions; + } + + function isOpener(token, tags) { + for (var i = 0, l = tags.length; i < l; i++) { + if (tags[i].o == token.n) { + token.tag = '#'; + return true; + } + } + } + + function isCloser(close, open, tags) { + for (var i = 0, l = tags.length; i < l; i++) { + if (tags[i].c == close && tags[i].o == open) { + return true; + } + } + } + + Hogan.generate = function (tree, text, options) { + var code = 'var _=this;_.b(i=i||"");' + walk(tree) + 'return _.fl();'; + if (options.asString) { + return 'function(c,p,i){' + code + ';}'; + } + + return new Hogan.Template(new Function('c', 'p', 'i', code), text, Hogan, options); + } + + function esc(s) { + return s.replace(rSlash, '\\\\') + .replace(rQuot, '\\\"') + .replace(rNewline, '\\n') + .replace(rCr, '\\r'); + } + + function chooseMethod(s) { + return (~s.indexOf('.')) ? 'd' : 'f'; + } + + function walk(tree) { + var code = ''; + for (var i = 0, l = tree.length; i < l; i++) { + var tag = tree[i].tag; + if (tag == '#') { + code += section(tree[i].nodes, tree[i].n, chooseMethod(tree[i].n), + tree[i].i, tree[i].end, tree[i].otag + " " + tree[i].ctag); + } else if (tag == '^') { + code += invertedSection(tree[i].nodes, tree[i].n, + chooseMethod(tree[i].n)); + } else if (tag == '<' || tag == '>') { + code += partial(tree[i]); + } else if (tag == '{' || tag == '&') { + code += tripleStache(tree[i].n, chooseMethod(tree[i].n)); + } else if (tag == '\n') { + code += text('"\\n"' + (tree.length-1 == i ? '' : ' + i')); + } else if (tag == '_v') { + code += variable(tree[i].n, chooseMethod(tree[i].n)); + } else if (tag === undefined) { + code += text('"' + esc(tree[i]) + '"'); + } + } + return code; + } + + function section(nodes, id, method, start, end, tags) { + return 'if(_.s(_.' + method + '("' + esc(id) + '",c,p,1),' + + 'c,p,0,' + start + ',' + end + ',"' + tags + '")){' + + '_.rs(c,p,' + + 'function(c,p,_){' + + walk(nodes) + + '});c.pop();}'; + } + + function invertedSection(nodes, id, method) { + return 'if(!_.s(_.' + method + '("' + esc(id) + '",c,p,1),c,p,1,0,0,"")){' + + walk(nodes) + + '};'; + } + + function partial(tok) { + return '_.b(_.rp("' + esc(tok.n) + '",c,p,"' + (tok.indent || '') + '"));'; + } + + function tripleStache(id, method) { + return '_.b(_.t(_.' + method + '("' + esc(id) + '",c,p,0)));'; + } + + function variable(id, method) { + return '_.b(_.v(_.' + method + '("' + esc(id) + '",c,p,0)));'; + } + + function text(id) { + return '_.b(' + id + ');'; + } + + Hogan.parse = function(tokens, text, options) { + options = options || {}; + return buildTree(tokens, '', [], options.sectionTags || []); + }, + + Hogan.cache = {}; + + Hogan.compile = function(text, options) { + // options + // + // asString: false (default) + // + // sectionTags: [{o: '_foo', c: 'foo'}] + // An array of object with o and c fields that indicate names for custom + // section tags. The example above allows parsing of {{_foo}}{{/foo}}. + // + // delimiters: A string that overrides the default delimiters. + // Example: "<% %>" + // + options = options || {}; + + var key = text + '||' + !!options.asString; + + var t = this.cache[key]; + + if (t) { + return t; + } + + t = this.generate(this.parse(this.scan(text, options.delimiters), text, options), text, options); + return this.cache[key] = t; + }; +})(typeof exports !== 'undefined' ? exports : Hogan); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/lib/hogan.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/lib/hogan.js new file mode 100644 index 000000000..f0119b529 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/lib/hogan.js @@ -0,0 +1,20 @@ +/* + * Copyright 2011 Twitter, 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. + */ + +// This file is for use with Node.js. See dist/ for browser files. + +var Hogan = require('./compiler'); +Hogan.Template = require('./template').Template; +module.exports = Hogan; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/lib/template.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/lib/template.js new file mode 100644 index 000000000..c28ce44ec --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/lib/template.js @@ -0,0 +1,241 @@ +/* + * Copyright 2011 Twitter, 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. + */ + +var Hogan = {}; + +(function (Hogan, useArrayBuffer) { + Hogan.Template = function (renderFunc, text, compiler, options) { + this.r = renderFunc || this.r; + this.c = compiler; + this.options = options; + this.text = text || ''; + this.buf = (useArrayBuffer) ? [] : ''; + } + + Hogan.Template.prototype = { + // render: replaced by generated code. + r: function (context, partials, indent) { return ''; }, + + // variable escaping + v: hoganEscape, + + // triple stache + t: coerceToString, + + render: function render(context, partials, indent) { + return this.ri([context], partials || {}, indent); + }, + + // render internal -- a hook for overrides that catches partials too + ri: function (context, partials, indent) { + return this.r(context, partials, indent); + }, + + // tries to find a partial in the curent scope and render it + rp: function(name, context, partials, indent) { + var partial = partials[name]; + + if (!partial) { + return ''; + } + + if (this.c && typeof partial == 'string') { + partial = this.c.compile(partial, this.options); + } + + return partial.ri(context, partials, indent); + }, + + // render a section + rs: function(context, partials, section) { + var tail = context[context.length - 1]; + + if (!isArray(tail)) { + section(context, partials, this); + return; + } + + for (var i = 0; i < tail.length; i++) { + context.push(tail[i]); + section(context, partials, this); + context.pop(); + } + }, + + // maybe start a section + s: function(val, ctx, partials, inverted, start, end, tags) { + var pass; + + if (isArray(val) && val.length === 0) { + return false; + } + + if (typeof val == 'function') { + val = this.ls(val, ctx, partials, inverted, start, end, tags); + } + + pass = (val === '') || !!val; + + if (!inverted && pass && ctx) { + ctx.push((typeof val == 'object') ? val : ctx[ctx.length - 1]); + } + + return pass; + }, + + // find values with dotted names + d: function(key, ctx, partials, returnFound) { + var names = key.split('.'), + val = this.f(names[0], ctx, partials, returnFound), + cx = null; + + if (key === '.' && isArray(ctx[ctx.length - 2])) { + return ctx[ctx.length - 1]; + } + + for (var i = 1; i < names.length; i++) { + if (val && typeof val == 'object' && names[i] in val) { + cx = val; + val = val[names[i]]; + } else { + val = ''; + } + } + + if (returnFound && !val) { + return false; + } + + if (!returnFound && typeof val == 'function') { + ctx.push(cx); + val = this.lv(val, ctx, partials); + ctx.pop(); + } + + return val; + }, + + // find values with normal names + f: function(key, ctx, partials, returnFound) { + var val = false, + v = null, + found = false; + + for (var i = ctx.length - 1; i >= 0; i--) { + v = ctx[i]; + if (v && typeof v == 'object' && key in v) { + val = v[key]; + found = true; + break; + } + } + + if (!found) { + return (returnFound) ? false : ""; + } + + if (!returnFound && typeof val == 'function') { + val = this.lv(val, ctx, partials); + } + + return val; + }, + + // higher order templates + ho: function(val, cx, partials, text, tags) { + var compiler = this.c; + var options = this.options; + options.delimiters = tags; + var text = val.call(cx, text); + text = (text == null) ? String(text) : text.toString(); + this.b(compiler.compile(text, options).render(cx, partials)); + return false; + }, + + // template result buffering + b: (useArrayBuffer) ? function(s) { this.buf.push(s); } : + function(s) { this.buf += s; }, + fl: (useArrayBuffer) ? function() { var r = this.buf.join(''); this.buf = []; return r; } : + function() { var r = this.buf; this.buf = ''; return r; }, + + // lambda replace section + ls: function(val, ctx, partials, inverted, start, end, tags) { + var cx = ctx[ctx.length - 1], + t = null; + + if (!inverted && this.c && val.length > 0) { + return this.ho(val, cx, partials, this.text.substring(start, end), tags); + } + + t = val.call(cx); + + if (typeof t == 'function') { + if (inverted) { + return true; + } else if (this.c) { + return this.ho(t, cx, partials, this.text.substring(start, end), tags); + } + } + + return t; + }, + + // lambda replace variable + lv: function(val, ctx, partials) { + var cx = ctx[ctx.length - 1]; + var result = val.call(cx); + + if (typeof result == 'function') { + result = coerceToString(result.call(cx)); + if (this.c && ~result.indexOf("{\u007B")) { + return this.c.compile(result, this.options).render(cx, partials); + } + } + + return coerceToString(result); + } + + }; + + var rAmp = /&/g, + rLt = //g, + rApos =/\'/g, + rQuot = /\"/g, + hChars =/[&<>\"\']/; + + + function coerceToString(val) { + return String((val === null || val === undefined) ? '' : val); + } + + function hoganEscape(str) { + str = coerceToString(str); + return hChars.test(str) ? + str + .replace(rAmp,'&') + .replace(rLt,'<') + .replace(rGt,'>') + .replace(rApos,''') + .replace(rQuot, '"') : + str; + } + + var isArray = Array.isArray || function(a) { + return Object.prototype.toString.call(a) === '[object Array]'; + }; + +})(typeof exports !== 'undefined' ? exports : Hogan); + diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/package.json new file mode 100644 index 000000000..f59e4f342 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/package.json @@ -0,0 +1,36 @@ +{ + "name": "hogan.js", + "description": "A mustache compiler.", + "version": "2.0.0", + "keywords": [ + "mustache", + "template" + ], + "main": "./lib/hogan.js", + "homepage": "http://twitter.github.com/hogan.js/", + "author": { + "name": "Twitter Inc." + }, + "repository": { + "type": "git", + "url": "https://github.com/twitter/hogan.js.git" + }, + "licenses": [ + { + "type": "Apache-2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0" + } + ], + "devDependencies": { + "uglify-js": "*", + "jsdom": "0.2.10", + "step": "0.0.5" + }, + "bin": { + "hulk": "./bin/hulk" + }, + "readme": "## Hogan.js - A mustache compiler.\n\n[Hogan.js](http://twitter.github.com/hogan.js/) is a compiler for the\n[Mustache](http://mustache.github.com/) templating language. For information\non Mustache, see the [manpage](http://mustache.github.com/mustache.5.html) and\nthe [spec](https://github.com/mustache/spec).\n\n## Basics\n\nHogan compiles templates to HoganTemplate objects, which have a render method.\n\n```js\nvar data = {\n screenName: \"dhg\",\n};\n\nvar template = Hogan.compile(\"Follow @{{screenName}}.\");\nvar output = template.render(data);\n\n// prints \"Follow @dhg.\"\nconsole.log(output);\n```\n\n## Features\n\nHogan is fast--try it on your workload.\n\nHogan has separate scanning, parsing and code generation phases. This way it's\npossible to add new features without touching the scanner at all, and many\ndifferent code generation techniques can be tried without changing the parser.\n\nHogan exposes scan and parse methods. These can be useful for\npre-processing templates on the server.\n\n```js\nvar text = \"{{^check}}{{#i18n}}No{{/i18n}}{{/check}}\";\ntext += \"{{#check}}{{#i18n}}Yes{{/i18n}}{{/check}}\";\nvar tree = Hogan.parse(Hogan.scan(text));\n\n// outputs \"# check\"\nconsole.log(tree[0].tag + \" \" + tree[0].name);\n\n// outputs \"Yes\"\nconsole.log(tree[1].nodes[0].nodes[0]);\n```\n\nIt's also possible to use HoganTemplate objects without the Hogan compiler\npresent. That means you can pre-compile your templates on the server, and\navoid shipping the compiler. However, the optional lambda features from the\nMustache spec do require the compiler to be present.\n\n## Why Hogan.js?\n\nWhy another templating library?\n\nHogan.js was written to meet three templating library requirements: good\nperformance, standalone template objects, and a parser API.\n\n## Issues\n\nHave a bug? Please create an issue here on GitHub!\n\nhttps://github.com/twitter/hogan.js/issues\n\n## Versioning\n\nFor transparency and insight into our release cycle, releases will be numbered with the follow format:\n\n`..`\n\nAnd constructed with the following guidelines:\n\n* Breaking backwards compatibility bumps the major\n* New additions without breaking backwards compatibility bumps the minor\n* Bug fixes and misc changes bump the patch\n\nFor more information on semantic versioning, please visit http://semver.org/.\n\n## Authors\n\n**Robert Sayre**\n\n+ http://github.com/sayrer\n\n**Jacob Thornton**\n\n+ http://github.com/fat\n\n## License\n\nCopyright 2011 Twitter, Inc.\n\nLicensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0", + "readmeFilename": "README.md", + "_id": "hogan.js@2.0.0", + "_from": "hogan.js@~2.0.0" +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/test/html/list.html b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/test/html/list.html new file mode 100644 index 000000000..9bb653a3b --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/test/html/list.html @@ -0,0 +1,8 @@ +
    +
  • +
  • +
  • +
  • +
  • +
  • +
\ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/test/index.html b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/test/index.html new file mode 100644 index 000000000..7f63ab29b --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/test/index.html @@ -0,0 +1,21 @@ + + + Hogan.js Test Suite + + + + + + + + + + +

Hogan.js

+

+
+

+
    +
    + + diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/test/index.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/test/index.js new file mode 100644 index 000000000..1ac75943b --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/test/index.js @@ -0,0 +1,814 @@ +/* + * Copyright 2011 Twitter, 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. + */ + +var is = strictEqual; + +test("Scan Text No Tags", function() { + var text = "

    hi

    "; + var tokens = Hogan.scan(text); + is(tokens.length, 1, "One token"); + is(tokens[0]+'', text, "text is equal to first token"); +}); + +test("Scan One Tag", function() { + var text = "{{hmm}}"; + var tokens = Hogan.scan(text); + is(tokens.length, 1, "One token"); + is(tokens[0].n, "hmm", "First token content is variable name."); +}); + +test("Scan Multiple Tags", function() { + var text = "asdf{{hmm}}asdf2{{hmm2}}asdf3"; + var tokens = Hogan.scan(text); + is(tokens.length, 5, "3 text tokens, 2 tag tokens."); + is(tokens[0]+'', "asdf", "first token is text"); + is(tokens[1].n, "hmm", "second token is tag"); + is(tokens[1].tag, "_v", "second token is a variable"); + is(tokens[2]+'', "asdf2", "third token is text"); + is(tokens[3].n, "hmm2", "fourth token is tag"); + is(tokens[3].tag, "_v", "fourth token is a variable"); + is(tokens[4]+'', "asdf3", "Fifth token is text"); +}); + +test("Scan Section Open", function() { + var text = "{{#hmm}}"; + var tokens = Hogan.scan(text); + is(tokens.length, 1, "One token"); + is(tokens[0].n, "hmm", "First token content is variable name."); + is(tokens[0].tag, "#", "First token is a section."); +}); + +test("Scan Section Close", function() { + var text = "{{/hmm}}"; + var tokens = Hogan.scan(text); + is(tokens.length, 1, "One token"); + is(tokens[0].n, "hmm", "First token content is variable name."); + is(tokens[0].tag, "/", "First token is a section."); +}); + +test("Scan Section", function() { + var text = "{{#hmm}}{{/hmm}}"; + var tokens = Hogan.scan(text); + is(tokens.length, 2, "One token"); + is(tokens[0].n, "hmm", "First token content is variable name."); + is(tokens[0].tag, "#", "First token is a section."); + is(tokens[1].n, "hmm", "Second token content is variable name."); + is(tokens[1].tag, "/", "Second token is a section."); +}); + +test("Scan Section In Content", function() { + var text = "abc{{#hmm}}def{{/hmm}}ghi"; + var tokens = Hogan.scan(text); + is(tokens.length, 5, "3 text tokens, 2 tag tokens."); + is(tokens[0]+'', "abc", "first token is text"); + is(tokens[1].n, "hmm", "second token is tag"); + is(tokens[1].tag, "#", "second token is a variable"); + is(tokens[2]+'', "def", "third token is text"); + is(tokens[3].n, "hmm", "fourth token is tag"); + is(tokens[3].tag, "/", "fourth token is a variable"); + is(tokens[4]+'', "ghi", "Fifth token is text"); +}); + +test("Scan Negative Section", function() { + var text = "{{^hmm}}{{/hmm}}"; + var tokens = Hogan.scan(text); + is(tokens.length, 2, "One token"); + is(tokens[0].n, "hmm", "First token content is variable name."); + is(tokens[0].tag, "^", "First token is a negative section."); + is(tokens[1].n, "hmm", "First token content is variable name."); + is(tokens[1].tag, "/", "Second token is a section."); +}); + +test("Scan Partial", function() { + var text = "{{>hmm}}"; + var tokens = Hogan.scan(text); + is(tokens.length, 1, "One token"); + is(tokens[0].n, "hmm", "First token content is variable name."); + is(tokens[0].tag, ">", "First token is a partial."); +}); + +test("Scan Backward Partial", function() { + var text = "{{
    \' \" &"}); + is(s, "< > <div> ' " &", "input correctly escaped."); + + var ec ={ "'": "'", '"': """, "<": "<", ">": ">", "&": "&"} + for (var char in ec) { + var s = t.render({foo: char + " just me"}); + is(s, ec[char] + " just me", "input correctly escaped."); + } +}); + +test("Mustache Injection", function() { + var text = "{{foo}}"; + var t = Hogan.compile(text); + s = t.render({foo:"{{{<42}}}"}) + is(s, "{{{<42}}}", "Can't inject mustache"); +}); + +test("Triple Stache", function() { + var text = "{{{foo}}}"; + var t = Hogan.compile(text); + var s = t.render({foo: "< >
    \' \" &"}); + is(s, "< >
    \' \" &", "input correctly not-escaped."); +}); + +test("Amp No Escaping", function() { + var text = "{{&foo}}"; + var t = Hogan.compile(text); + var s = t.render({foo: "< >
    \' \" &"}); + is(s, "< >
    \' \" &", "input correctly not-escaped."); +}); + +test("Partial", function() { + var partialText = "this is text from the partial--the magic number {{foo}} is from a variable"; + var p = Hogan.compile(partialText); + + var text = "This template contains a partial ({{>testPartial}})." + var t = Hogan.compile(text); + + var s = t.render({foo: 42}, {testPartial: p}); + is(s, "This template contains a partial (this is text from the partial--the magic number 42 is from a variable).", "partials work"); +}); + +test("Nested Partials", function() { + var partialText = "this is text from the partial--the magic number {{foo}} is from a variable"; + var p = Hogan.compile(partialText); + + var partialText2 = "This template contains a partial ({{>testPartial}})." + var p2 = Hogan.compile(partialText2); + + var text = "This template contains a partial that contains a partial [{{>testPartial2}}]." + var t = Hogan.compile(text); + + var s = t.render({foo: 42}, {testPartial: p, testPartial2: p2}); + is(s, "This template contains a partial that contains a partial [This template contains a partial (this is text from the partial--the magic number 42 is from a variable).].", "nested partials work"); +}); + +test("Negative Section", function() { + var text = "This template {{^foo}}BOO {{/foo}}contains an inverted section." + var t = Hogan.compile(text); + var s = t.render(); + is(s, "This template BOO contains an inverted section.", "inverted sections with no context work"); + + s = t.render({foo:[]}); + is(s, "This template BOO contains an inverted section.", "inverted sections with empty list context work"); + + s = t.render({ foo:false }); + is(s, "This template BOO contains an inverted section.", "inverted sections with false context work"); + + s = t.render({foo:''}); + is(s, "This template contains an inverted section.", "inverted sections with empty string context work"); + + s = t.render({foo:true}); + is(s, "This template contains an inverted section.", "inverted sections with true context work"); + + s = t.render({foo: function() { return false; }}); + is(s, "This template BOO contains an inverted section.", "inverted sections with false returning method in context work"); +}); + +test("Section Elision", function() { + var text = "This template {{#foo}}BOO {{/foo}}contains a section." + var t = Hogan.compile(text); + var s = t.render(); + is(s, "This template contains a section.", "sections with no context work"); + + s = t.render({foo:[]}); + is(s, "This template contains a section.", "sections with empty list context work"); + + s = t.render({foo:false}); + is(s, "This template contains a section.", "sections with false context work"); +}); + +test("Section Object Context", function() { + var text = "This template {{#foo}}{{bar}} {{/foo}}contains a section." + var t = Hogan.compile(text); + var s = t.render({foo:{bar:42}}); + is(s, "This template 42 contains a section.", "sections with object context work"); +}); + +test("Section Array Context", function() { + var text = "This template {{#foo}}{{bar}} {{/foo}}contains a section." + var t = Hogan.compile(text); + var s = t.render({foo:[{bar:42}, {bar:43}, {bar:44}]}); + is(s, "This template 42 43 44 contains a section.", "sections with object ctx and array values work"); +}); + +test("Falsy Variable No Render", function() { + var text = "I ({{cannot}}) be seen!"; + var t = Hogan.compile(text); + var s = t.render(); + is(s, "I () be seen!", "missing value doesn't render."); +}); + +test("Undefined Return Value From Lambda", function() { + var text = "abc{{foo}}def"; + var t = Hogan.compile(text); + var context = { + foo: function(s) { + return undefined; + } + } + var s = t.render(context); + is(s, "abcdef", "deal with undefined return values from lambdas.") +}); + +test("Section Extensions", function() { + var text = "Test {{_//|__foo}}bar{{/foo}}"; + var options = {sectionTags:[{o:'_//|__foo', c:'foo'}]}; + var tree = Hogan.parse(Hogan.scan(text), text, options); + is(tree[1].tag, "#", "_//|__foo node transformed to section"); + is(tree[1].n, "_//|__foo", "_//|__foo node transformed to section"); + + var t = Hogan.compile(text, options ); + var s = t.render({'_//|__foo':true}); + is(s, "Test bar", "Custom sections work"); +}); + +test("Misnested Section Extensions", function() { + var text = "Test {{__foo}}bar{{/bar}}"; + var options = {sectionTags:[{o:'__foo', c:'foo'}, {o:'__bar', c:'bar'}]}; + raises(function() { + var tree = Hogan.parse(Hogan.scan(text), text, options); + }, "Nesting error: __foo vs. bar", "Error is generated"); +}); + +test("Section Extensions In Higher Order Sections", function() { + var text = "Test{{_foo}}bar{{/foo}}"; + var options = {sectionTags:[{o:'_foo', c:'foo'}, {o:'_baz', c:'baz'}]}; + var t = Hogan.compile(text, options); + var context = { + "_foo": function (s) { + return "{{_baz}}" + s + "{{/baz}}"; + } + } + var s = t.render(context); + is(s, "Test", "unprocessed test"); +}); + +test("Section Extensions In Lambda Replace Variable", function() { + var text = "Test{{foo}}"; + var options = {sectionTags:[{o:'_baz', c:'baz'}]}; + var t = Hogan.compile(text, options); + var context = { + "foo": function () { + return function() { "{{_baz}}" + s + "{{/baz}}"; }; + } + } + var s = t.render(context); + is(s, "Test", "unprocessed test"); +}); + +test("Mustache not reprocessed for method calls in interpolations", function() { + var text = "text with {{foo}} inside"; + var t = Hogan.compile(text); + var context = { + foo: function() { + return "no processing of {{tags}}"; + } + } + var s = t.render(context); + is(s, "text with no processing of {{tags}} inside", "method calls should not be processed as mustache."); + + var text = "text with {{{foo}}} inside"; + var t = Hogan.compile(text); + var s = t.render(context); + is(s, "text with no processing of {{tags}} inside", "method calls should not be processed as mustache in triple staches."); +}); + +test("Mustache is reprocessed for lambdas in interpolations", function() { + var text = "text with {{foo}} inside"; + var t = Hogan.compile(text); + var context = { + bar: "42", + foo: function() { + return function() { + return "processing of {{bar}}"; + }; + } + }; + var s = t.render(context); + is(s, "text with processing of 42 inside", "the return value of lambdas should be processed mustache."); +}); + +test("Nested Section", function() { + var text = "{{#foo}}{{#bar}}{{baz}}{{/bar}}{{/foo}}"; + var t = Hogan.compile(text); + var s = t.render({foo: 42, bar: 42, baz:42}); + is(s, "42", "can reach up context stack"); +}); + +test("Dotted Names", function() { + var text = '"{{person.name}}" == "{{#person}}{{name}}{{/person}}"'; + var t = Hogan.compile(text); + var s = t.render({person:{name:'Joe'}}); + is(s, '"Joe" == "Joe"', "dotted names work"); +}); + +test("Implicit Iterator", function() { + var text = '{{#stuff}} {{.}} {{/stuff}}'; + var t = Hogan.compile(text); + var s = t.render({stuff:[42,43,44]}); + is(s, " 42 43 44 ", "implicit iterators work"); +}); + +test("Partials And Delimiters", function() { + var text = '{{>include}}*\n{{= | | =}}\n*|>include|'; + var partialText = ' .{{value}}. '; + var partial = Hogan.compile(partialText); + var t = Hogan.compile(text); + var s = t.render({value:"yes"}, {'include':partial}); + is(s, " .yes. *\n* .yes. ", "partials work around delimiters"); +}); + +test("String Partials", function() { + var text = "foo{{>mypartial}}baz"; + var partialText = " bar "; + var t = Hogan.compile(text); + var s = t.render({}, {'mypartial': partialText}); + is(s, "foo bar baz", "string partial works."); +}); + +test("Missing Partials", function() { + var text = "foo{{>mypartial}} bar"; + var t = Hogan.compile(text); + var s = t.render({}); + is(s, "foo bar", "missing partial works."); +}); + +test("Indented Standalone Comment", function() { + var text = 'Begin.\n {{! Indented Comment Block! }}\nEnd.'; + var t = Hogan.compile(text); + var s = t.render(); + is(s, 'Begin.\nEnd.', "Standalone comment blocks are removed."); +}); + +test("New Line Between Delimiter Changes", function() { + var data = { section: true, data: 'I got interpolated.' }; + var text = '\n{{#section}}\n {{data}}\n |data|\n{{/section}}x\n\n{{= | | =}}\n|#section|\n {{data}}\n |data|\n|/section|'; + var t = Hogan.compile(text); + var s = t.render(data); + is(s, '\n I got interpolated.\n |data|\nx\n\n {{data}}\n I got interpolated.\n', 'render correct') +}); + +test("Mustache JS Apostrophe", function() { + var text = '{{apos}}{{control}}'; + var t = Hogan.compile(text); + var s = t.render({'apos':"'", 'control':"X"}); + is(s, ''X', 'Apostrophe is escaped.'); +}); + +test("Mustache JS Array Of Implicit Partials", function() { + var text = 'Here is some stuff!\n{{#numbers}}\n{{>partial}}\n{{/numbers}}\n'; + var partialText = '{{.}}\n'; + var t = Hogan.compile(text); + var s = t.render({numbers:[1,2,3,4]}, {partial: partialText}); + is(s, 'Here is some stuff!\n1\n2\n3\n4\n', 'Partials with implicit iterators work.'); +}); + +test("Mustache JS Array Of Partials", function() { + var text = 'Here is some stuff!\n{{#numbers}}\n{{>partial}}\n{{/numbers}}\n'; + var partialText = '{{i}}\n'; + var t = Hogan.compile(text); + var s = t.render({numbers:[{i:1},{i:2},{i:3},{i:4}]}, {partial: partialText}); + is(s, 'Here is some stuff!\n1\n2\n3\n4\n', 'Partials with arrays work.'); +}); + +test("Mustache JS Array Of Strings", function() { + var text = '{{#strings}}{{.}} {{/strings}}'; + var t = Hogan.compile(text); + var s = t.render({strings:['foo', 'bar', 'baz']}); + is(s, 'foo bar baz ', 'array of strings works with implicit iterators.'); +}); + +test("Mustache JS Undefined String", function() { + var text = 'foo{{bar}}baz'; + var t = Hogan.compile(text); + var s = t.render({bar:undefined}); + is(s, 'foobaz', 'undefined value does not render.'); +}); + +test("Mustache JS Undefined Triple Stache", function() { + var text = 'foo{{{bar}}}baz'; + var t = Hogan.compile(text); + var s = t.render({bar:undefined}); + is(s, 'foobaz', 'undefined value does not render in triple stache.'); +}); + +test("Mustache JS Null String", function() { + var text = 'foo{{bar}}baz'; + var t = Hogan.compile(text); + var s = t.render({bar:null}); + is(s, 'foobaz', 'undefined value does not render.'); +}); + +test("Mustache JS Null Triple Stache", function() { + var text = 'foo{{{bar}}}baz'; + var t = Hogan.compile(text); + var s = t.render({bar:null}); + is(s, 'foobaz', 'undefined value does not render in triple stache.'); +}); + +test("Mustache JS Triple Stache Alt Delimiter", function() { + var text = '{{=<% %>=}}<% foo %> {{foo}} <%{bar}%> {{{bar}}}'; + var t = Hogan.compile(text); + var s = t.render({foo:'yeah', bar:'hmm'}); + is(s, 'yeah {{foo}} hmm {{{bar}}}', 'triple stache inside alternate delimiter works.'); +}); + +/* Safety tests */ + +test("Updates object state", function() { + var text = '{{foo}} {{bar}} {{foo}}'; + var t = Hogan.compile(text); + var s = t.render({foo: 1, bar: function() { this.foo++; return 42; } }); + is(s, '1 42 2'); +}); + +/* shootout benchmark tests */ + +test("Shoot Out String", function() { + var text = "Hello World!"; + var expected = "Hello World!" + var t = Hogan.compile(text) + var s = t.render({}) + is(s, expected, "Shootout String compiled correctly"); +}); + +test("Shoot Out Replace", function() { + var text = "Hello {{name}}! You have {{count}} new messages."; + var expected = "Hello Mick! You have 30 new messages."; + var t = Hogan.compile(text) + var s = t.render({ name: "Mick", count: 30 }) + is(s, expected, "Shootout Replace compiled correctly"); +}); + +test("Shoot Out Array", function() { + var text = "{{#names}}{{name}}{{/names}}"; + var expected = "MoeLarryCurlyShemp"; + var t = Hogan.compile(text); + var s = t.render({ names: [{name: "Moe"}, {name: "Larry"}, {name: "Curly"}, {name: "Shemp"}] }) + is(s, expected, "Shootout Array compiled correctly"); +}); + +test("Shoot Out Object", function() { + var text = "{{#person}}{{name}}{{age}}{{/person}}"; + var expected = "Larry45"; + var t = Hogan.compile(text) + var s = t.render({ person: { name: "Larry", age: 45 } }) + is(s, expected, "Shootout Object compiled correctly"); +}); + +test("Shoot Out Partial", function() { + var text = "{{#peeps}}{{>replace}}{{/peeps}}"; + var t = Hogan.compile(text); + var partial = Hogan.compile(" Hello {{name}}! You have {{count}} new messages."); + var s = t.render({ peeps: [{name: "Moe", count: 15}, {name: "Larry", count: 5}, {name: "Curly", count: 2}] }, { replace: partial }); + var expected = " Hello Moe! You have 15 new messages. Hello Larry! You have 5 new messages. Hello Curly! You have 2 new messages."; + is(s, expected, "Shootout Partial compiled correctly"); +}); + +test("Shoot Out Recurse", function() { + var text = "{{name}}{{#kids}}{{>recursion}}{{/kids}}"; + var t = Hogan.compile(text); + var partial = Hogan.compile("{{name}}{{#kids}}{{>recursion}}{{/kids}}"); + var s = t.render({ + name: '1', + kids: [ + { + name: '1.1', + kids: [ + { name: '1.1.1', kids: [] } + ] + } + ] + }, { recursion: partial }); + var expected = "11.11.1.1"; + is(s, expected, "Shootout Recurse compiled correctly"); +}); + +test("Shoot Out Filter", function() { + var text = "{{#filter}}foo {{bar}}{{/filter}}"; + var t = Hogan.compile(text); + var s = t.render({ + filter: function() { + return function(text) { + return text.toUpperCase() + "{{bar}}"; + } + }, + bar: "bar" + }); + var expected = "FOO bar" + is(s, expected, "Shootout Filter compiled correctly"); +}); + +test("Shoot Out Complex", function() { + var text = + "

    {{header}}

    " + + "{{#hasItems}}" + + "
    " + + "{{/hasItems}}" + + "{{^hasItems}}" + + "

    The list is empty.

    " + + "{{/hasItems}}"; + + var expected = "

    Colors

    "; + var t = Hogan.compile(text) + var s = t.render({ + header: function() { + return "Colors"; + }, + items: [ + {name: "red", current: true, url: "#Red"}, + {name: "green", current: false, url: "#Green"}, + {name: "blue", current: false, url: "#Blue"} + ], + hasItems: function() { + return this.items.length !== 0; + }, + empty: function() { + return this.items.length === 0; + } + }) + + is(s, expected, "Shootout Complex compiled correctly"); +}); + +$.each(['list'], function(i, name) { + return; + asyncTest("Render Output: " + name, function() { + $.when( + $.get('./templates/' + name + '.mustache'), + $.get('./html/' + name + '.html') + ).done(function(tmpl, html) { + var r = Hogan.compile(tmpl[0]).render({}); + is(r, html[0], name + ': should correctly render html'); + }) + .fail(function() { ok(false, 'file missing'); }) + .always(function() { start(); }); + }); +}); + +test("Default Render Impl", function() { + var ht = new Hogan.Template(); + is(ht.render() === '', true, 'default renderImpl returns an array.'); +}); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/test/jquery.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/test/jquery.js new file mode 100644 index 000000000..8ccd0ea78 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/test/jquery.js @@ -0,0 +1,9266 @@ +/*! + * jQuery JavaScript Library v1.7.1 + * http://jquery.com/ + * + * Copyright 2011, John Resig + * Dual licensed under the MIT or GPL Version 2 licenses. + * http://jquery.org/license + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * + * Date: Mon Nov 21 21:11:03 2011 -0500 + */ +(function( window, undefined ) { + +// Use the correct document accordingly with window argument (sandbox) +var document = window.document, + navigator = window.navigator, + location = window.location; +var jQuery = (function() { + +// Define a local copy of jQuery +var jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // A central reference to the root jQuery(document) + rootjQuery, + + // A simple way to check for HTML strings or ID strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + + // Check if a string has a non-whitespace character in it + rnotwhite = /\S/, + + // Used for trimming whitespace + trimLeft = /^\s+/, + trimRight = /\s+$/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, + rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + + // Useragent RegExp + rwebkit = /(webkit)[ \/]([\w.]+)/, + ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/, + rmsie = /(msie) ([\w.]+)/, + rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/, + + // Matches dashed string for camelizing + rdashAlpha = /-([a-z]|[0-9])/ig, + rmsPrefix = /^-ms-/, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return ( letter + "" ).toUpperCase(); + }, + + // Keep a UserAgent string for use with jQuery.browser + userAgent = navigator.userAgent, + + // For matching the engine and version of the browser + browserMatch, + + // The deferred used on DOM ready + readyList, + + // The ready event handler + DOMContentLoaded, + + // Save a reference to some core methods + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + push = Array.prototype.push, + slice = Array.prototype.slice, + trim = String.prototype.trim, + indexOf = Array.prototype.indexOf, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), or $(undefined) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // The body element only exists once, optimize finding it + if ( selector === "body" && !context && document.body ) { + this.context = document; + this[0] = document.body; + this.selector = selector; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + // Are we dealing with HTML string or an ID? + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = quickExpr.exec( selector ); + } + + // Verify a match, and that no context was specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + doc = ( context ? context.ownerDocument || context : document ); + + // If a single string is passed in and it's a single tag + // just do a createElement and skip the rest + ret = rsingleTag.exec( selector ); + + if ( ret ) { + if ( jQuery.isPlainObject( context ) ) { + selector = [ document.createElement( ret[1] ) ]; + jQuery.fn.attr.call( selector, context, true ); + + } else { + selector = [ doc.createElement( ret[1] ) ]; + } + + } else { + ret = jQuery.buildFragment( [ match[1] ], [ doc ] ); + selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes; + } + + return jQuery.merge( this, selector ); + + // HANDLE: $("#id") + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.7.1", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return slice.call( this, 0 ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + // Build a new jQuery matched element set + var ret = this.constructor(); + + if ( jQuery.isArray( elems ) ) { + push.apply( ret, elems ); + + } else { + jQuery.merge( ret, elems ); + } + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Attach the listeners + jQuery.bindReady(); + + // Add the callback + readyList.add( fn ); + + return this; + }, + + eq: function( i ) { + i = +i; + return i === -1 ? + this.slice( i ) : + this.slice( i, i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ), + "slice", slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + // Either a released hold or an DOMready/load event and not yet ready + if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.fireWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger( "ready" ).off( "ready" ); + } + } + }, + + bindReady: function() { + if ( readyList ) { + return; + } + + readyList = jQuery.Callbacks( "once memory" ); + + // Catch cases where $(document).ready() is called after the + // browser event has already occurred. + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + return setTimeout( jQuery.ready, 1 ); + } + + // Mozilla, Opera and webkit nightlies currently support this event + if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else if ( document.attachEvent ) { + // ensure firing before onload, + // maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var toplevel = false; + + try { + toplevel = window.frameElement == null; + } catch(e) {} + + if ( document.documentElement.doScroll && toplevel ) { + doScrollCheck(); + } + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + // A crude way of determining if an object is a window + isWindow: function( obj ) { + return obj && typeof obj === "object" && "setInterval" in obj; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + for ( var name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + parseJSON: function( data ) { + if ( typeof data !== "string" || !data ) { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + + } + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && rnotwhite.test( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase(); + }, + + // args is for internal usage only + each: function( object, callback, args ) { + var name, i = 0, + length = object.length, + isObj = length === undefined || jQuery.isFunction( object ); + + if ( args ) { + if ( isObj ) { + for ( name in object ) { + if ( callback.apply( object[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( object[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in object ) { + if ( callback.call( object[ name ], name, object[ name ] ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) { + break; + } + } + } + } + + return object; + }, + + // Use native String.trim function wherever possible + trim: trim ? + function( text ) { + return text == null ? + "" : + trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + text.toString().replace( trimLeft, "" ).replace( trimRight, "" ); + }, + + // results is for internal usage only + makeArray: function( array, results ) { + var ret = results || []; + + if ( array != null ) { + // The window, strings (and functions) also have 'length' + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + var type = jQuery.type( array ); + + if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) { + push.call( ret, array ); + } else { + jQuery.merge( ret, array ); + } + } + + return ret; + }, + + inArray: function( elem, array, i ) { + var len; + + if ( array ) { + if ( indexOf ) { + return indexOf.call( array, elem, i ); + } + + len = array.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in array && array[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var i = first.length, + j = 0; + + if ( typeof second.length === "number" ) { + for ( var l = second.length; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var ret = [], retVal; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( var i = 0, length = elems.length; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, key, ret = [], + i = 0, + length = elems.length, + // jquery objects are treated as arrays + isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( key in elems ) { + value = callback( elems[ key ], key, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + if ( typeof context === "string" ) { + var tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + var args = slice.call( arguments, 2 ), + proxy = function() { + return fn.apply( context, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; + + return proxy; + }, + + // Mutifunctional method to get and set values to a collection + // The value/s can optionally be executed if it's a function + access: function( elems, key, value, exec, fn, pass ) { + var length = elems.length; + + // Setting many attributes + if ( typeof key === "object" ) { + for ( var k in key ) { + jQuery.access( elems, k, key[k], exec, fn, value ); + } + return elems; + } + + // Setting one attribute + if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = !pass && exec && jQuery.isFunction(value); + + for ( var i = 0; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + + return elems; + } + + // Getting an attribute + return length ? fn( elems[0], key ) : undefined; + }, + + now: function() { + return ( new Date() ).getTime(); + }, + + // Use of jQuery.browser is frowned upon. + // More details: http://docs.jquery.com/Utilities/jQuery.browser + uaMatch: function( ua ) { + ua = ua.toLowerCase(); + + var match = rwebkit.exec( ua ) || + ropera.exec( ua ) || + rmsie.exec( ua ) || + ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) || + []; + + return { browser: match[1] || "", version: match[2] || "0" }; + }, + + sub: function() { + function jQuerySub( selector, context ) { + return new jQuerySub.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySub, this ); + jQuerySub.superclass = this; + jQuerySub.fn = jQuerySub.prototype = this(); + jQuerySub.fn.constructor = jQuerySub; + jQuerySub.sub = this.sub; + jQuerySub.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { + context = jQuerySub( context ); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); + }; + jQuerySub.fn.init.prototype = jQuerySub.fn; + var rootjQuerySub = jQuerySub(document); + return jQuerySub; + }, + + browser: {} +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +browserMatch = jQuery.uaMatch( userAgent ); +if ( browserMatch.browser ) { + jQuery.browser[ browserMatch.browser ] = true; + jQuery.browser.version = browserMatch.version; +} + +// Deprecated, use jQuery.browser.webkit instead +if ( jQuery.browser.webkit ) { + jQuery.browser.safari = true; +} + +// IE doesn't match non-breaking spaces with \s +if ( rnotwhite.test( "\xA0" ) ) { + trimLeft = /^[\s\xA0]+/; + trimRight = /[\s\xA0]+$/; +} + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); + +// Cleanup functions for the document ready method +if ( document.addEventListener ) { + DOMContentLoaded = function() { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + }; + +} else if ( document.attachEvent ) { + DOMContentLoaded = function() { + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( document.readyState === "complete" ) { + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }; +} + +// The DOM ready check for Internet Explorer +function doScrollCheck() { + if ( jQuery.isReady ) { + return; + } + + try { + // If IE is used, use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + document.documentElement.doScroll("left"); + } catch(e) { + setTimeout( doScrollCheck, 1 ); + return; + } + + // and execute any waiting functions + jQuery.ready(); +} + +return jQuery; + +})(); + + +// String to Object flags format cache +var flagsCache = {}; + +// Convert String-formatted flags into Object-formatted ones and store in cache +function createFlags( flags ) { + var object = flagsCache[ flags ] = {}, + i, length; + flags = flags.split( /\s+/ ); + for ( i = 0, length = flags.length; i < length; i++ ) { + object[ flags[i] ] = true; + } + return object; +} + +/* + * Create a callback list using the following parameters: + * + * flags: an optional list of space-separated flags that will change how + * the callback list behaves + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible flags: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( flags ) { + + // Convert flags from String-formatted to Object-formatted + // (we check in cache first) + flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {}; + + var // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = [], + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Add one or several callbacks to the list + add = function( args ) { + var i, + length, + elem, + type, + actual; + for ( i = 0, length = args.length; i < length; i++ ) { + elem = args[ i ]; + type = jQuery.type( elem ); + if ( type === "array" ) { + // Inspect recursively + add( elem ); + } else if ( type === "function" ) { + // Add if not in unique mode and callback is not in + if ( !flags.unique || !self.has( elem ) ) { + list.push( elem ); + } + } + } + }, + // Fire callbacks + fire = function( context, args ) { + args = args || []; + memory = !flags.memory || [ context, args ]; + firing = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) { + memory = true; // Mark as halted + break; + } + } + firing = false; + if ( list ) { + if ( !flags.once ) { + if ( stack && stack.length ) { + memory = stack.shift(); + self.fireWith( memory[ 0 ], memory[ 1 ] ); + } + } else if ( memory === true ) { + self.disable(); + } else { + list = []; + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + var length = list.length; + add( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away, unless previous + // firing was halted (stopOnFalse) + } else if ( memory && memory !== true ) { + firingStart = length; + fire( memory[ 0 ], memory[ 1 ] ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + var args = arguments, + argIndex = 0, + argLength = args.length; + for ( ; argIndex < argLength ; argIndex++ ) { + for ( var i = 0; i < list.length; i++ ) { + if ( args[ argIndex ] === list[ i ] ) { + // Handle firingIndex and firingLength + if ( firing ) { + if ( i <= firingLength ) { + firingLength--; + if ( i <= firingIndex ) { + firingIndex--; + } + } + } + // Remove the element + list.splice( i--, 1 ); + // If we have some unicity property then + // we only need to do this once + if ( flags.unique ) { + break; + } + } + } + } + } + return this; + }, + // Control if a given callback is in the list + has: function( fn ) { + if ( list ) { + var i = 0, + length = list.length; + for ( ; i < length; i++ ) { + if ( fn === list[ i ] ) { + return true; + } + } + } + return false; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory || memory === true ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( stack ) { + if ( firing ) { + if ( !flags.once ) { + stack.push( [ context, args ] ); + } + } else if ( !( flags.once && memory ) ) { + fire( context, args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!memory; + } + }; + + return self; +}; + + + + +var // Static reference to slice + sliceDeferred = [].slice; + +jQuery.extend({ + + Deferred: function( func ) { + var doneList = jQuery.Callbacks( "once memory" ), + failList = jQuery.Callbacks( "once memory" ), + progressList = jQuery.Callbacks( "memory" ), + state = "pending", + lists = { + resolve: doneList, + reject: failList, + notify: progressList + }, + promise = { + done: doneList.add, + fail: failList.add, + progress: progressList.add, + + state: function() { + return state; + }, + + // Deprecated + isResolved: doneList.fired, + isRejected: failList.fired, + + then: function( doneCallbacks, failCallbacks, progressCallbacks ) { + deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks ); + return this; + }, + always: function() { + deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments ); + return this; + }, + pipe: function( fnDone, fnFail, fnProgress ) { + return jQuery.Deferred(function( newDefer ) { + jQuery.each( { + done: [ fnDone, "resolve" ], + fail: [ fnFail, "reject" ], + progress: [ fnProgress, "notify" ] + }, function( handler, data ) { + var fn = data[ 0 ], + action = data[ 1 ], + returned; + if ( jQuery.isFunction( fn ) ) { + deferred[ handler ](function() { + returned = fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); + } + }); + } else { + deferred[ handler ]( newDefer[ action ] ); + } + }); + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + if ( obj == null ) { + obj = promise; + } else { + for ( var key in promise ) { + obj[ key ] = promise[ key ]; + } + } + return obj; + } + }, + deferred = promise.promise({}), + key; + + for ( key in lists ) { + deferred[ key ] = lists[ key ].fire; + deferred[ key + "With" ] = lists[ key ].fireWith; + } + + // Handle state + deferred.done( function() { + state = "resolved"; + }, failList.disable, progressList.lock ).fail( function() { + state = "rejected"; + }, doneList.disable, progressList.lock ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( firstParam ) { + var args = sliceDeferred.call( arguments, 0 ), + i = 0, + length = args.length, + pValues = new Array( length ), + count = length, + pCount = length, + deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ? + firstParam : + jQuery.Deferred(), + promise = deferred.promise(); + function resolveFunc( i ) { + return function( value ) { + args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + if ( !( --count ) ) { + deferred.resolveWith( deferred, args ); + } + }; + } + function progressFunc( i ) { + return function( value ) { + pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value; + deferred.notifyWith( promise, pValues ); + }; + } + if ( length > 1 ) { + for ( ; i < length; i++ ) { + if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) { + args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) ); + } else { + --count; + } + } + if ( !count ) { + deferred.resolveWith( deferred, args ); + } + } else if ( deferred !== firstParam ) { + deferred.resolveWith( deferred, length ? [ firstParam ] : [] ); + } + return promise; + } +}); + + + + +jQuery.support = (function() { + + var support, + all, + a, + select, + opt, + input, + marginDiv, + fragment, + tds, + events, + eventName, + i, + isSupported, + div = document.createElement( "div" ), + documentElement = document.documentElement; + + // Preliminary tests + div.setAttribute("className", "t"); + div.innerHTML = "
    a"; + + all = div.getElementsByTagName( "*" ); + a = div.getElementsByTagName( "a" )[ 0 ]; + + // Can't get basic test support + if ( !all || !all.length || !a ) { + return {}; + } + + // First batch of supports tests + select = document.createElement( "select" ); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName( "input" )[ 0 ]; + + support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: ( div.firstChild.nodeType === 3 ), + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: ( a.getAttribute("href") === "/a" ), + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.55/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: ( input.value === "on" ), + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // Tests for enctype support on a form(#6743) + enctype: !!document.createElement("form").enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", + + // Will be defined later + submitBubbles: true, + changeBubbles: true, + focusinBubbles: false, + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent( "onclick", function() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + support.noCloneEvent = false; + }); + div.cloneNode( true ).fireEvent( "onclick" ); + } + + // Check if a radio maintains its value + // after being appended to the DOM + input = document.createElement("input"); + input.value = "t"; + input.setAttribute("type", "radio"); + support.radioValue = input.value === "t"; + + input.setAttribute("checked", "checked"); + div.appendChild( input ); + fragment = document.createDocumentFragment(); + fragment.appendChild( div.lastChild ); + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + fragment.removeChild( input ); + fragment.appendChild( div ); + + div.innerHTML = ""; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. For more + // info see bug #3333 + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + if ( window.getComputedStyle ) { + marginDiv = document.createElement( "div" ); + marginDiv.style.width = "0"; + marginDiv.style.marginRight = "0"; + div.style.width = "2px"; + div.appendChild( marginDiv ); + support.reliableMarginRight = + ( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0; + } + + // Technique from Juriy Zaytsev + // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( div.attachEvent ) { + for( i in { + submit: 1, + change: 1, + focusin: 1 + }) { + eventName = "on" + i; + isSupported = ( eventName in div ); + if ( !isSupported ) { + div.setAttribute( eventName, "return;" ); + isSupported = ( typeof div[ eventName ] === "function" ); + } + support[ i + "Bubbles" ] = isSupported; + } + } + + fragment.removeChild( div ); + + // Null elements to avoid leaks in IE + fragment = select = opt = marginDiv = div = input = null; + + // Run tests that need a body at doc ready + jQuery(function() { + var container, outer, inner, table, td, offsetSupport, + conMarginTop, ptlm, vb, style, html, + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + conMarginTop = 1; + ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;"; + vb = "visibility:hidden;border:0;"; + style = "style='" + ptlm + "border:5px solid #000;padding:0;'"; + html = "
    " + + "" + + "
    "; + + container = document.createElement("div"); + container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px"; + body.insertBefore( container, body.firstChild ); + + // Construct the test element + div = document.createElement("div"); + container.appendChild( div ); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + div.innerHTML = "
    t
    "; + tds = div.getElementsByTagName( "td" ); + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE <= 8 fail this test) + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Figure out if the W3C box model works as expected + div.innerHTML = ""; + div.style.width = div.style.paddingLeft = "1px"; + jQuery.boxModel = support.boxModel = div.offsetWidth === 2; + + if ( typeof div.style.zoom !== "undefined" ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.style.display = "inline"; + div.style.zoom = 1; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 ); + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = ""; + div.innerHTML = "
    "; + support.shrinkWrapBlocks = ( div.offsetWidth !== 2 ); + } + + div.style.cssText = ptlm + vb; + div.innerHTML = html; + + outer = div.firstChild; + inner = outer.firstChild; + td = outer.nextSibling.firstChild.firstChild; + + offsetSupport = { + doesNotAddBorder: ( inner.offsetTop !== 5 ), + doesAddBorderForTableAndCells: ( td.offsetTop === 5 ) + }; + + inner.style.position = "fixed"; + inner.style.top = "20px"; + + // safari subtracts parent border width here which is 5px + offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 ); + inner.style.position = inner.style.top = ""; + + outer.style.overflow = "hidden"; + outer.style.position = "relative"; + + offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 ); + offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop ); + + body.removeChild( container ); + div = container = null; + + jQuery.extend( support, offsetSupport ); + }); + + return support; +})(); + + + + +var rbrace = /^(?:\{.*\}|\[.*\])$/, + rmultiDash = /([A-Z])/g; + +jQuery.extend({ + cache: {}, + + // Please use with caution + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var privateCache, thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey, + isEvents = name === "events"; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ internalKey ] = id = ++jQuery.uuid; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + privateCache = thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Users should not attempt to inspect the internal events object using jQuery.data, + // it is undocumented and subject to change. But does anyone listen? No. + if ( isEvents && !thisCache[ name ] ) { + return privateCache.events; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, l, + + // Reference to internal data cache key + internalKey = jQuery.expando, + + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + + // See jQuery.data for more information + id = isNode ? elem[ internalKey ] : internalKey; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split( " " ); + } + } + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject(cache[ id ]) ) { + return; + } + } + + // Browsers that fail expando deletion also refuse to delete expandos on + // the window, but it will allow it on all other JS objects; other browsers + // don't care + // Ensure that `cache` is not a window object #10080 + if ( jQuery.support.deleteExpando || !cache.setInterval ) { + delete cache[ id ]; + } else { + cache[ id ] = null; + } + + // We destroyed the cache and need to eliminate the expando on the node to avoid + // false lookups in the cache for entries that no longer exist + if ( isNode ) { + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( jQuery.support.deleteExpando ) { + delete elem[ internalKey ]; + } else if ( elem.removeAttribute ) { + elem.removeAttribute( internalKey ); + } else { + elem[ internalKey ] = null; + } + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + if ( elem.nodeName ) { + var match = jQuery.noData[ elem.nodeName.toLowerCase() ]; + + if ( match ) { + return !(match === true || elem.getAttribute("classid") !== match); + } + } + + return true; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var parts, attr, name, + data = null; + + if ( typeof key === "undefined" ) { + if ( this.length ) { + data = jQuery.data( this[0] ); + + if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) { + attr = this[0].attributes; + for ( var i = 0, l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.substring(5) ); + + dataAttr( this[0], name, data[ name ] ); + } + } + jQuery._data( this[0], "parsedAttrs", true ); + } + } + + return data; + + } else if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + parts = key.split("."); + parts[1] = parts[1] ? "." + parts[1] : ""; + + if ( value === undefined ) { + data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]); + + // Try to fetch any internally stored data first + if ( data === undefined && this.length ) { + data = jQuery.data( this[0], key ); + data = dataAttr( this[0], key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + + } else { + return this.each(function() { + var self = jQuery( this ), + args = [ parts[0], value ]; + + self.triggerHandler( "setData" + parts[1] + "!", args ); + jQuery.data( this, key, value ); + self.triggerHandler( "changeData" + parts[1] + "!", args ); + }); + } + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + jQuery.isNumeric( data ) ? parseFloat( data ) : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + for ( var name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + + + + +function handleQueueMarkDefer( elem, type, src ) { + var deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + defer = jQuery._data( elem, deferDataKey ); + if ( defer && + ( src === "queue" || !jQuery._data(elem, queueDataKey) ) && + ( src === "mark" || !jQuery._data(elem, markDataKey) ) ) { + // Give room for hard-coded callbacks to fire first + // and eventually mark/queue something else on the element + setTimeout( function() { + if ( !jQuery._data( elem, queueDataKey ) && + !jQuery._data( elem, markDataKey ) ) { + jQuery.removeData( elem, deferDataKey, true ); + defer.fire(); + } + }, 0 ); + } +} + +jQuery.extend({ + + _mark: function( elem, type ) { + if ( elem ) { + type = ( type || "fx" ) + "mark"; + jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 ); + } + }, + + _unmark: function( force, elem, type ) { + if ( force !== true ) { + type = elem; + elem = force; + force = false; + } + if ( elem ) { + type = type || "fx"; + var key = type + "mark", + count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 ); + if ( count ) { + jQuery._data( elem, key, count ); + } else { + jQuery.removeData( elem, key, true ); + handleQueueMarkDefer( elem, type, "mark" ); + } + } + }, + + queue: function( elem, type, data ) { + var q; + if ( elem ) { + type = ( type || "fx" ) + "queue"; + q = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !q || jQuery.isArray(data) ) { + q = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + q.push( data ); + } + } + return q || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + fn = queue.shift(), + hooks = {}; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + } + + if ( fn ) { + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + jQuery._data( elem, type + ".run", hooks ); + fn.call( elem, function() { + jQuery.dequeue( elem, type ); + }, hooks ); + } + + if ( !queue.length ) { + jQuery.removeData( elem, type + "queue " + type + ".run", true ); + handleQueueMarkDefer( elem, type, "queue" ); + } + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + } + + if ( data === undefined ) { + return jQuery.queue( this[0], type ); + } + return this.each(function() { + var queue = jQuery.queue( this, type, data ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, object ) { + if ( typeof type !== "string" ) { + object = type; + type = undefined; + } + type = type || "fx"; + var defer = jQuery.Deferred(), + elements = this, + i = elements.length, + count = 1, + deferDataKey = type + "defer", + queueDataKey = type + "queue", + markDataKey = type + "mark", + tmp; + function resolve() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + } + while( i-- ) { + if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) || + ( jQuery.data( elements[ i ], queueDataKey, undefined, true ) || + jQuery.data( elements[ i ], markDataKey, undefined, true ) ) && + jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) { + count++; + tmp.add( resolve ); + } + } + resolve(); + return defer.promise(); + } +}); + + + + +var rclass = /[\n\t\r]/g, + rspace = /\s+/, + rreturn = /\r/g, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea)?$/i, + rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute, + nodeHook, boolHook, fixSpecified; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.attr ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, name, value, true, jQuery.prop ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classNames, i, l, elem, + setClass, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call(this, j, this.className) ); + }); + } + + if ( value && typeof value === "string" ) { + classNames = value.split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className && classNames.length === 1 ) { + elem.className = value; + + } else { + setClass = " " + elem.className + " "; + + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { + setClass += classNames[ c ] + " "; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classNames, i, l, elem, className, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call(this, j, this.className) ); + }); + } + + if ( (value && typeof value === "string") || value === undefined ) { + classNames = ( value || "" ).split( rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 && elem.className ) { + if ( value ) { + className = (" " + elem.className + " ").replace( rclass, " " ); + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + className = className.replace(" " + classNames[ c ] + " ", " "); + } + elem.className = jQuery.trim( className ); + + } else { + elem.className = ""; + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.split( rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space seperated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var hooks, ret, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var self = jQuery(this), val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, i, max, option, + index = elem.selectedIndex, + values = [], + options = elem.options, + one = elem.type === "select-one"; + + // Nothing was selected + if ( index < 0 ) { + return null; + } + + // Loop through all the selected options + i = one ? index : 0; + max = one ? index + 1 : options.length; + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Don't return options that are disabled or in a disabled optgroup + if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && + (!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + // Fixes Bug #2551 -- select.val() broken in IE after form.reset() + if ( one && !values.length && options.length ) { + return jQuery( options[ index ] ).val(); + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + attrFn: { + val: true, + css: true, + html: true, + text: true, + data: true, + width: true, + height: true, + offset: true + }, + + attr: function( elem, name, value, pass ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( pass && name in jQuery.attrFn ) { + return jQuery( elem )[ name ]( value ); + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + + } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, "" + value ); + return value; + } + + } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret === null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var propName, attrNames, name, l, + i = 0; + + if ( value && elem.nodeType === 1 ) { + attrNames = value.toLowerCase().split( rspace ); + l = attrNames.length; + + for ( ; i < l; i++ ) { + name = attrNames[ i ]; + + if ( name ) { + propName = jQuery.propFix[ name ] || name; + + // See #9699 for explanation of this approach (setting first, then removal) + jQuery.attr( elem, name, "" ); + elem.removeAttribute( getSetAttribute ? name : propName ); + + // Set corresponding property to false for boolean attributes + if ( rboolean.test( name ) && propName in elem ) { + elem[ propName ] = false; + } + } + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to it's default in case type is set after value + // This is for element creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }, + // Use the value property for back compat + // Use the nodeHook for button elements in IE6/7 (#1954) + value: { + get: function( elem, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set: function( elem, value, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional) +jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex; + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + // Align boolean attributes with corresponding properties + // Fall back to attribute presence where some booleans are not supported + var attrNode, + property = jQuery.prop( elem, name ); + return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + var propName; + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + // value is true since we know at this point it's type boolean and not false + // Set boolean attributes to the same name and set the DOM property + propName = jQuery.propFix[ name ] || name; + if ( propName in elem ) { + // Only set the IDL specifically if it already exists on the element + elem[ propName ] = true; + } + + elem.setAttribute( name, name.toLowerCase() ); + } + return name; + } +}; + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + fixSpecified = { + name: true, + id: true + }; + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret; + ret = elem.getAttributeNode( name ); + return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ? + ret.nodeValue : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + ret = document.createAttribute( name ); + elem.setAttributeNode( ret ); + } + return ( ret.nodeValue = value + "" ); + } + }; + + // Apply the nodeHook to tabindex + jQuery.attrHooks.tabindex.set = nodeHook.set; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + if ( value === "" ) { + value = "false"; + } + nodeHook.set( elem, value, name ); + } + }; +} + + +// Some attributes require a special call on IE +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret === null ? undefined : ret; + } + }); + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Normalize to lowercase since IE uppercases css property names + return elem.style.cssText.toLowerCase() || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = "" + value ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); + + + + +var rformElems = /^(?:textarea|input|select)$/i, + rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/, + rhoverHack = /\bhover(\.\S+)?\b/, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/, + quickParse = function( selector ) { + var quick = rquickIs.exec( selector ); + if ( quick ) { + // 0 1 2 3 + // [ _, tag, id, class ] + quick[1] = ( quick[1] || "" ).toLowerCase(); + quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" ); + } + return quick; + }, + quickIs = function( elem, m ) { + var attrs = elem.attributes || {}; + return ( + (!m[1] || elem.nodeName.toLowerCase() === m[1]) && + (!m[2] || (attrs.id || {}).value === m[2]) && + (!m[3] || m[3].test( (attrs[ "class" ] || {}).value )) + ); + }, + hoverHack = function( events ) { + return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); + }; + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + add: function( elem, types, handler, data, selector ) { + + var elemData, eventHandle, events, + t, tns, type, namespaces, handleObj, + handleObjIn, quick, handlers, special; + + // Don't attach events to noData or text/comment nodes (allow plain objects tho) + if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + events = elemData.events; + if ( !events ) { + elemData.events = events = {}; + } + eventHandle = elemData.handle; + if ( !eventHandle ) { + elemData.handle = eventHandle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = jQuery.trim( hoverHack(types) ).split( " " ); + for ( t = 0; t < types.length; t++ ) { + + tns = rtypenamespace.exec( types[t] ) || []; + type = tns[1]; + namespaces = ( tns[2] || "" ).split( "." ).sort(); + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: tns[1], + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + quick: quickParse( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + handlers = events[ type ]; + if ( !handlers ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var elemData = jQuery.hasData( elem ) && jQuery._data( elem ), + t, tns, type, origType, namespaces, origCount, + j, events, special, handle, eventType, handleObj; + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = jQuery.trim( hoverHack( types || "" ) ).split(" "); + for ( t = 0; t < types.length; t++ ) { + tns = rtypenamespace.exec( types[t] ) || []; + type = origType = tns[1]; + namespaces = tns[2]; + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector? special.delegateType : special.bindType ) || type; + eventType = events[ type ] || []; + origCount = eventType.length; + namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + + // Remove matching events + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !namespaces || namespaces.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + eventType.splice( j--, 1 ); + + if ( handleObj.selector ) { + eventType.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( eventType.length === 0 && origCount !== eventType.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + handle = elemData.handle; + if ( handle ) { + handle.elem = null; + } + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery.removeData( elem, [ "events", "handle" ], true ); + } + }, + + // Events that are safe to short-circuit if no handlers are attached. + // Native DOM events should not be added, they may have inline handlers. + customEvent: { + "getData": true, + "setData": true, + "changeData": true + }, + + trigger: function( event, data, elem, onlyHandlers ) { + // Don't do events on text and comment nodes + if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { + return; + } + + // Event object or event type + var type = event.type || event, + namespaces = [], + cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType; + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "!" ) >= 0 ) { + // Exclusive events trigger only for the exact event (no namespaces) + type = type.slice(0, -1); + exclusive = true; + } + + if ( type.indexOf( "." ) >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + + if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { + // No jQuery handlers for this event type, and it can't have inline handlers + return; + } + + // Caller can pass in an Event, Object, or just an event type string + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + new jQuery.Event( type, event ) : + // Just the event type (string) + new jQuery.Event( type ); + + event.type = type; + event.isTrigger = true; + event.exclusive = exclusive; + event.namespace = namespaces.join( "." ); + event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null; + ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; + + // Handle a global trigger + if ( !elem ) { + + // TODO: Stop taunting the data cache; remove global events and always attach to document + cache = jQuery.cache; + for ( i in cache ) { + if ( cache[ i ].events && cache[ i ].events[ type ] ) { + jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); + } + } + return; + } + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data != null ? jQuery.makeArray( data ) : []; + data.unshift( event ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + eventPath = [[ elem, special.bindType || type ]]; + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; + old = null; + for ( ; cur; cur = cur.parentNode ) { + eventPath.push([ cur, bubbleType ]); + old = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( old && old === elem.ownerDocument ) { + eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); + } + } + + // Fire handlers on the event path + for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { + + cur = eventPath[i][0]; + event.type = eventPath[i][1]; + + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + // Note that this is a bare JS function and not a jQuery handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + // IE<9 dies on focus/blur to hidden element (#1486) + if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + old = elem[ ontype ]; + + if ( old ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( old ) { + elem[ ontype ] = old; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event || window.event ); + + var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), + delegateCount = handlers.delegateCount, + args = [].slice.call( arguments, 0 ), + run_all = !event.exclusive && !event.namespace, + handlerQueue = [], + i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Determine handlers that should run if there are delegated events + // Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861) + if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) { + + // Pregenerate a single jQuery object for reuse with .is() + jqcur = jQuery(this); + jqcur.context = this.ownerDocument || this; + + for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { + selMatch = {}; + matches = []; + jqcur[0] = cur; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + sel = handleObj.selector; + + if ( selMatch[ sel ] === undefined ) { + selMatch[ sel ] = ( + handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel ) + ); + } + if ( selMatch[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, matches: matches }); + } + } + } + + // Add the remaining (directly-bound) handlers + if ( handlers.length > delegateCount ) { + handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); + } + + // Run delegates first; they may want to stop propagation beneath us + for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { + matched = handlerQueue[ i ]; + event.currentTarget = matched.elem; + + for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { + handleObj = matched.matches[ j ]; + + // Triggered event must either 1) be non-exclusive and have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { + + event.data = handleObj.data; + event.handleObj = handleObj; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + return event.result; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** + props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, + originalEvent = event, + fixHook = jQuery.event.fixHooks[ event.type ] || {}, + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = jQuery.Event( originalEvent ); + + for ( i = copy.length; i; ) { + prop = copy[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Target should not be a text node (#504, Safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8) + if ( event.metaKey === undefined ) { + event.metaKey = event.ctrlKey; + } + + return fixHook.filter? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + ready: { + // Make sure the ready event is setup + setup: jQuery.bindReady + }, + + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + + focus: { + delegateType: "focusin" + }, + blur: { + delegateType: "focusout" + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +// Some plugins are using, but it's undocumented/deprecated and will be removed. +// The 1.7 special event interface should provide all the hooks needed now. +jQuery.event.handle = jQuery.event.dispatch; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + if ( elem.detachEvent ) { + elem.detachEvent( "on" + type, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var target = this, + related = event.relatedTarget, + handleObj = event.handleObj, + selector = handleObj.selector, + ret; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !form._submit_attached ) { + jQuery.event.add( form, "submit._submit", function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + }); + form._submit_attached = true; + } + }); + // return undefined since we don't need an event listener + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + jQuery.event.simulate( "change", this, event, true ); + } + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + elem._change_attached = true; + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on.call( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + var handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( var type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + live: function( types, data, fn ) { + jQuery( this.context ).on( types, this.selector, data, fn ); + return this; + }, + die: function( types, fn ) { + jQuery( this.context ).off( types, this.selector || "**", fn ); + return this; + }, + + delegate: function( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate: function( selector, types, fn ) { + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + if ( this[0] ) { + return jQuery.event.trigger( type, data, this[0], true ); + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + guid = fn.guid || jQuery.guid++, + i = 0, + toggler = function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + }; + + // link all the functions, so any of them can unbind this click handler + toggler.guid = guid; + while ( i < args.length ) { + args[ i++ ].guid = guid; + } + + return this.click( toggler ); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; + + if ( jQuery.attrFn ) { + jQuery.attrFn[ name ] = true; + } + + if ( rkeyEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; + } + + if ( rmouseEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; + } +}); + + + +/*! + * Sizzle CSS Selector Engine + * Copyright 2011, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + expando = "sizcache" + (Math.random() + '').replace('.', ''), + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true, + rBackslash = /\\/g, + rReturn = /\r\n/g, + rNonWord = /\W/; + +// Here we check if the JavaScript engine is using some sort of +// optimization where it does not always call our comparision +// function. If that is the case, discard the hasDuplicate value. +// Thus far that includes Google Chrome. +[0, 0].sort(function() { + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function( selector, context, results, seed ) { + results = results || []; + context = context || document; + + var origContext = context; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var m, set, checkSet, extra, ret, cur, pop, i, + prune = true, + contextXML = Sizzle.isXML( context ), + parts = [], + soFar = selector; + + // Reset the position of the chunker regexp (start from head) + do { + chunker.exec( "" ); + m = chunker.exec( soFar ); + + if ( m ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + } while ( m ); + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context, seed ); + + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) { + selector += parts.shift(); + } + + set = posProcess( selector, set, seed ); + } + } + + } else { + // Take a shortcut and set the context if the root selector is an ID + // (but not if it'll be faster if the inner selector is an ID) + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + + ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? + Sizzle.filter( ret.expr, ret.set )[0] : + ret.set[0]; + } + + if ( context ) { + ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + + set = ret.expr ? + Sizzle.filter( ret.expr, ret.set ) : + ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray( set ); + + } else { + prune = false; + } + + while ( parts.length ) { + cur = parts.pop(); + pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + Sizzle.error( cur || selector ); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + + } else if ( context && context.nodeType === 1 ) { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + + } else { + for ( i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function( results ) { + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[ i - 1 ] ) { + results.splice( i--, 1 ); + } + } + } + } + + return results; +}; + +Sizzle.matches = function( expr, set ) { + return Sizzle( expr, null, null, set ); +}; + +Sizzle.matchesSelector = function( node, expr ) { + return Sizzle( expr, null, null, [node] ).length > 0; +}; + +Sizzle.find = function( expr, context, isXML ) { + var set, i, len, match, type, left; + + if ( !expr ) { + return []; + } + + for ( i = 0, len = Expr.order.length; i < len; i++ ) { + type = Expr.order[i]; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + left = match[1]; + match.splice( 1, 1 ); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace( rBackslash, "" ); + set = Expr.find[ type ]( match, context, isXML ); + + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = typeof context.getElementsByTagName !== "undefined" ? + context.getElementsByTagName( "*" ) : + []; + } + + return { set: set, expr: expr }; +}; + +Sizzle.filter = function( expr, set, inplace, not ) { + var match, anyFound, + type, found, item, filter, left, + i, pass, + old = expr, + result = [], + curLoop = set, + isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); + + while ( expr && set.length ) { + for ( type in Expr.filter ) { + if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { + filter = Expr.filter[ type ]; + left = match[1]; + + anyFound = false; + + match.splice(1,1); + + if ( left.substr( left.length - 1 ) === "\\" ) { + continue; + } + + if ( curLoop === result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + pass = not ^ found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + + } else { + curLoop[i] = false; + } + + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + // Improper expression + if ( expr === old ) { + if ( anyFound == null ) { + Sizzle.error( expr ); + + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Utility function for retreiving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +var getText = Sizzle.getText = function( elem ) { + var i, node, + nodeType = elem.nodeType, + ret = ""; + + if ( nodeType ) { + if ( nodeType === 1 || nodeType === 9 ) { + // Use textContent || innerText for elements + if ( typeof elem.textContent === 'string' ) { + return elem.textContent; + } else if ( typeof elem.innerText === 'string' ) { + // Replace IE's carriage returns + return elem.innerText.replace( rReturn, '' ); + } else { + // Traverse it's children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + } else { + + // If no nodeType, this is expected to be an array + for ( i = 0; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + if ( node.nodeType !== 8 ) { + ret += getText( node ); + } + } + } + return ret; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + + match: { + ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/ + }, + + leftMatch: {}, + + attrMap: { + "class": "className", + "for": "htmlFor" + }, + + attrHandle: { + href: function( elem ) { + return elem.getAttribute( "href" ); + }, + type: function( elem ) { + return elem.getAttribute( "type" ); + } + }, + + relative: { + "+": function(checkSet, part){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !rNonWord.test( part ), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag ) { + part = part.toLowerCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + + ">": function( checkSet, part ) { + var elem, + isPartStr = typeof part === "string", + i = 0, + l = checkSet.length; + + if ( isPartStr && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false; + } + } + + } else { + for ( ; i < l; i++ ) { + elem = checkSet[i]; + + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + + "": function(checkSet, part, isXML){ + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML ); + }, + + "~": function( checkSet, part, isXML ) { + var nodeCheck, + doneName = done++, + checkFn = dirCheck; + + if ( typeof part === "string" && !rNonWord.test( part ) ) { + part = part.toLowerCase(); + nodeCheck = part; + checkFn = dirNodeCheck; + } + + checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML ); + } + }, + + find: { + ID: function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + }, + + NAME: function( match, context ) { + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], + results = context.getElementsByName( match[1] ); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + + TAG: function( match, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( match[1] ); + } + } + }, + preFilter: { + CLASS: function( match, curLoop, inplace, result, not, isXML ) { + match = " " + match[1].replace( rBackslash, "" ) + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) { + if ( !inplace ) { + result.push( elem ); + } + + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + + ID: function( match ) { + return match[1].replace( rBackslash, "" ); + }, + + TAG: function( match, curLoop ) { + return match[1].replace( rBackslash, "" ).toLowerCase(); + }, + + CHILD: function( match ) { + if ( match[1] === "nth" ) { + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + match[2] = match[2].replace(/^\+|\s*/g, ''); + + // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6' + var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec( + match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + // calculate the numbers (first)n+(last) including if they are negative + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + // TODO: Move to normal caching system + match[0] = done++; + + return match; + }, + + ATTR: function( match, curLoop, inplace, result, not, isXML ) { + var name = match[1] = match[1].replace( rBackslash, "" ); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + // Handle if an un-quoted value was used + match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" ); + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + + PSEUDO: function( match, curLoop, inplace, result, not ) { + if ( match[1] === "not" ) { + // If we're dealing with a complex expression, or a simple one + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + + if ( !inplace ) { + result.push.apply( result, ret ); + } + + return false; + } + + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + + POS: function( match ) { + match.unshift( true ); + + return match; + } + }, + + filters: { + enabled: function( elem ) { + return elem.disabled === false && elem.type !== "hidden"; + }, + + disabled: function( elem ) { + return elem.disabled === true; + }, + + checked: function( elem ) { + return elem.checked === true; + }, + + selected: function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + parent: function( elem ) { + return !!elem.firstChild; + }, + + empty: function( elem ) { + return !elem.firstChild; + }, + + has: function( elem, i, match ) { + return !!Sizzle( match[3], elem ).length; + }, + + header: function( elem ) { + return (/h\d/i).test( elem.nodeName ); + }, + + text: function( elem ) { + var attr = elem.getAttribute( "type" ), type = elem.type; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null ); + }, + + radio: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type; + }, + + checkbox: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type; + }, + + file: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "file" === elem.type; + }, + + password: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "password" === elem.type; + }, + + submit: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "submit" === elem.type; + }, + + image: function( elem ) { + return elem.nodeName.toLowerCase() === "input" && "image" === elem.type; + }, + + reset: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && "reset" === elem.type; + }, + + button: function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && "button" === elem.type || name === "button"; + }, + + input: function( elem ) { + return (/input|select|textarea|button/i).test( elem.nodeName ); + }, + + focus: function( elem ) { + return elem === elem.ownerDocument.activeElement; + } + }, + setFilters: { + first: function( elem, i ) { + return i === 0; + }, + + last: function( elem, i, match, array ) { + return i === array.length - 1; + }, + + even: function( elem, i ) { + return i % 2 === 0; + }, + + odd: function( elem, i ) { + return i % 2 === 1; + }, + + lt: function( elem, i, match ) { + return i < match[3] - 0; + }, + + gt: function( elem, i, match ) { + return i > match[3] - 0; + }, + + nth: function( elem, i, match ) { + return match[3] - 0 === i; + }, + + eq: function( elem, i, match ) { + return match[3] - 0 === i; + } + }, + filter: { + PSEUDO: function( elem, match, i, array ) { + var name = match[1], + filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0; + + } else if ( name === "not" ) { + var not = match[3]; + + for ( var j = 0, l = not.length; j < l; j++ ) { + if ( not[j] === elem ) { + return false; + } + } + + return true; + + } else { + Sizzle.error( name ); + } + }, + + CHILD: function( elem, match ) { + var first, last, + doneName, parent, cache, + count, diff, + type = match[1], + node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + + case "nth": + first = match[2]; + last = match[3]; + + if ( first === 1 && last === 0 ) { + return true; + } + + doneName = match[0]; + parent = elem.parentNode; + + if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) { + count = 0; + + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + + parent[ expando ] = doneName; + } + + diff = elem.nodeIndex - last; + + if ( first === 0 ) { + return diff === 0; + + } else { + return ( diff % first === 0 && diff / first >= 0 ); + } + } + }, + + ID: function( elem, match ) { + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + + TAG: function( elem, match ) { + return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match; + }, + + CLASS: function( elem, match ) { + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + + ATTR: function( elem, match ) { + var name = match[1], + result = Sizzle.attr ? + Sizzle.attr( elem, name ) : + Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + !type && Sizzle.attr ? + result != null : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value !== check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + + POS: function( elem, match, i, array ) { + var name = match[2], + filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS, + fescape = function(all, num){ + return "\\" + (num - 0 + 1); + }; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) ); +} + +var makeArray = function( array, results ) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +// Perform a simple check to determine if the browser is capable of +// converting a NodeList to an array using builtin methods. +// Also verifies that the returned array holds DOM nodes +// (which is not the case in the Blackberry browser) +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType; + +// Provide a fallback method if it does not work +} catch( e ) { + makeArray = function( array, results ) { + var i = 0, + ret = results || []; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + + } else { + if ( typeof array.length === "number" ) { + for ( var l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + + } else { + for ( ; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder, siblingCheck; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + return a.compareDocumentPosition ? -1 : 1; + } + + return a.compareDocumentPosition(b) & 4 ? -1 : 1; + }; + +} else { + sortOrder = function( a, b ) { + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; + } + + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // If the nodes are siblings (or identical) we can do a quick check + if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + + siblingCheck = function( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; + }; +} + +// Check to see if the browser returns elements by name when +// querying by getElementById (and provide a workaround) +(function(){ + // We're going to inject a fake input element with a specified name + var form = document.createElement("div"), + id = "script" + (new Date()).getTime(), + root = document.documentElement; + + form.innerHTML = ""; + + // Inject it into the root element, check its status, and remove it quickly + root.insertBefore( form, root.firstChild ); + + // The workaround has to do additional checks after a getElementById + // Which slows things down for other browsers (hence the branching) + if ( document.getElementById( id ) ) { + Expr.find.ID = function( match, context, isXML ) { + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + + return m ? + m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? + [m] : + undefined : + []; + } + }; + + Expr.filter.ID = function( elem, match ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + + // release memory in IE + root = form = null; +})(); + +(function(){ + // Check to see if the browser returns only elements + // when doing getElementsByTagName("*") + + // Create a fake element + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + // Make sure no comments are found + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function( match, context ) { + var results = context.getElementsByTagName( match[1] ); + + // Filter out possible comments + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + // Check to see if an attribute returns normalized href attributes + div.innerHTML = ""; + + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + + Expr.attrHandle.href = function( elem ) { + return elem.getAttribute( "href", 2 ); + }; + } + + // release memory in IE + div = null; +})(); + +if ( document.querySelectorAll ) { + (function(){ + var oldSizzle = Sizzle, + div = document.createElement("div"), + id = "__sizzle__"; + + div.innerHTML = "

    "; + + // Safari can't handle uppercase or unicode characters when + // in quirks mode. + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function( query, context, extra, seed ) { + context = context || document; + + // Only use querySelectorAll on non-XML documents + // (ID selectors don't work in non-HTML documents) + if ( !seed && !Sizzle.isXML(context) ) { + // See if we find a selector to speed up + var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query ); + + if ( match && (context.nodeType === 1 || context.nodeType === 9) ) { + // Speed-up: Sizzle("TAG") + if ( match[1] ) { + return makeArray( context.getElementsByTagName( query ), extra ); + + // Speed-up: Sizzle(".CLASS") + } else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) { + return makeArray( context.getElementsByClassName( match[2] ), extra ); + } + } + + if ( context.nodeType === 9 ) { + // Speed-up: Sizzle("body") + // The body element only exists once, optimize finding it + if ( query === "body" && context.body ) { + return makeArray( [ context.body ], extra ); + + // Speed-up: Sizzle("#ID") + } else if ( match && match[3] ) { + var elem = context.getElementById( match[3] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id === match[3] ) { + return makeArray( [ elem ], extra ); + } + + } else { + return makeArray( [], extra ); + } + } + + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(qsaError) {} + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + var oldContext = context, + old = context.getAttribute( "id" ), + nid = old || id, + hasParent = context.parentNode, + relativeHierarchySelector = /^\s*[+~]/.test( query ); + + if ( !old ) { + context.setAttribute( "id", nid ); + } else { + nid = nid.replace( /'/g, "\\$&" ); + } + if ( relativeHierarchySelector && hasParent ) { + context = context.parentNode; + } + + try { + if ( !relativeHierarchySelector || hasParent ) { + return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra ); + } + + } catch(pseudoError) { + } finally { + if ( !old ) { + oldContext.removeAttribute( "id" ); + } + } + } + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + // release memory in IE + div = null; + })(); +} + +(function(){ + var html = document.documentElement, + matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector; + + if ( matches ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9 fails this) + var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ), + pseudoWorks = false; + + try { + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( document.documentElement, "[test!='']:sizzle" ); + + } catch( pseudoError ) { + pseudoWorks = true; + } + + Sizzle.matchesSelector = function( node, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); + + if ( !Sizzle.isXML( node ) ) { + try { + if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) { + var ret = matches.call( node, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || !disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9, so check for that + node.document && node.document.nodeType !== 11 ) { + return ret; + } + } + } catch(e) {} + } + + return Sizzle(expr, null, null, [node]).length > 0; + }; + } +})(); + +(function(){ + var div = document.createElement("div"); + + div.innerHTML = "
    "; + + // Opera can't find a second classname (in 9.6) + // Also, make sure that getElementsByClassName actually exists + if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) { + return; + } + + // Safari caches class attributes, doesn't catch changes (in 3.2) + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) { + return; + } + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function( match, context, isXML ) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + // release memory in IE + div = null; +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( elem.nodeName.toLowerCase() === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + + if ( elem ) { + var match = false; + + elem = elem[dir]; + + while ( elem ) { + if ( elem[ expando ] === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem[ expando ] = doneName; + elem.sizset = i; + } + + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} + +if ( document.documentElement.contains ) { + Sizzle.contains = function( a, b ) { + return a !== b && (a.contains ? a.contains(b) : true); + }; + +} else if ( document.documentElement.compareDocumentPosition ) { + Sizzle.contains = function( a, b ) { + return !!(a.compareDocumentPosition(b) & 16); + }; + +} else { + Sizzle.contains = function() { + return false; + }; +} + +Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement; + + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +var posProcess = function( selector, context, seed ) { + var match, + tmpSet = [], + later = "", + root = context.nodeType ? [context] : context; + + // Position selectors must be done after the filter + // And so must :not(positional) so we move all PSEUDOs to the end + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } + + selector = Expr.relative[selector] ? selector + "*" : selector; + + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet, seed ); + } + + return Sizzle.filter( later, tmpSet ); +}; + +// EXPOSE +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +Sizzle.selectors.attrMap = {}; +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.filters; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})(); + + +var runtil = /Until$/, + rparentsprev = /^(?:parents|prevUntil|prevAll)/, + // Note: This RegExp should be improved, or likely pulled from Sizzle + rmultiselector = /,/, + isSimple = /^.[^:#\[\.,]*$/, + slice = Array.prototype.slice, + POS = jQuery.expr.match.POS, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var self = this, + i, l; + + if ( typeof selector !== "string" ) { + return jQuery( selector ).filter(function() { + for ( i = 0, l = self.length; i < l; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }); + } + + var ret = this.pushStack( "", "find", selector ), + length, n, r; + + for ( i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( n = length; n < ret.length; n++ ) { + for ( r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var targets = jQuery( target ); + return this.filter(function() { + for ( var i = 0, l = targets.length; i < l; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // If this is a positional selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + POS.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var ret = [], i, l, cur = this[0]; + + // Array (deprecated as of jQuery 1.7) + if ( jQuery.isArray( selectors ) ) { + var level = 1; + + while ( cur && cur.ownerDocument && cur !== context ) { + for ( i = 0; i < selectors.length; i++ ) { + + if ( jQuery( cur ).is( selectors[ i ] ) ) { + ret.push({ selector: selectors[ i ], elem: cur, level: level }); + } + } + + cur = cur.parentNode; + level++; + } + + return ret; + } + + // String + var pos = POS.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( i = 0, l = this.length; i < l; i++ ) { + cur = this[i]; + + while ( cur ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + + } else { + cur = cur.parentNode; + if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) { + break; + } + } + } + } + + ret = ret.length > 1 ? jQuery.unique( ret ) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + andSelf: function() { + return this.add( this.prevObject ); + } +}); + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return jQuery.nth( elem, 2, "nextSibling" ); + }, + prev: function( elem ) { + return jQuery.nth( elem, 2, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( elem.parentNode.firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.makeArray( elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, slice.call( arguments ).join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + nth: function( cur, result, dir, elem ) { + result = result || 1; + var num = 0; + + for ( ; cur; cur = cur[dir] ) { + if ( cur.nodeType === 1 && ++num === result ) { + break; + } + } + + return cur; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} + + + + +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, + rtagName = /<([\w:]+)/, + rtbody = /", "" ], + legend: [ 1, "
    ", "
    " ], + thead: [ 1, "", "
    " ], + tr: [ 2, "", "
    " ], + td: [ 3, "", "
    " ], + col: [ 2, "", "
    " ], + area: [ 1, "", "" ], + _default: [ 0, "", "" ] + }, + safeFragment = createSafeFragment( document ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE can't serialize and +
    +
    +
    +
    + + +
    +

    Templates

    +

    + Hogan.js was developed against the mustache test suite, so everything that holds true for templates as specified here, is also the case for hogan.js. +

    +

    + That means you get variables, sections, lambdas, partials, filters, and everything else you've come to expect from mustache templating - only much, much faster. +

    +
    +
    + +
    +
    +
    +
    + + +
    +

    Compiling

    +

    + Use hogan.compile() to precompile your templates into vanilla JS. +

    +

    + It's best to serve your templates precompiled whenever you can (rather than the raw templates), as parsing is the most time consuming operation. +

    +

    +

    +
    +
    + +
    +
    +
    +
    + + +
    +

    Rendering

    +

    + Once compiled, call the render() method with a context and optional partials object. +

    +

    + If supplying partials, you can compile them ahead of time, or pass string templates.

    +

    +

    +
    +
    + +
    + + + + + +
    + + + + + diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/web/stylesheets/layout.css b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/web/stylesheets/layout.css new file mode 100755 index 000000000..20e20cffb --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/web/stylesheets/layout.css @@ -0,0 +1,206 @@ + +/* #Reset & Basics (Inspired by E. Meyers) +================================================== */ + html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { + margin: 0; + padding: 0; + border: 0; + font-size: 100%; + font: inherit; + vertical-align: baseline; } + article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section { + display: block; } + body { + line-height: 1; } + ol, ul { + list-style: none; } + blockquote, q { + quotes: none; } + blockquote:before, blockquote:after, + q:before, q:after { + content: ''; + content: none; } + table { + border-collapse: collapse; + border-spacing: 0; } + + +/* #Basic Styles +================================================== */ + body { + background: #fff; + font: 14px/24px "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif; + color: #000; + -webkit-font-smoothing: antialiased; /* Fix for webkit rendering */ + -webkit-text-size-adjust: 100%; + } + a { + color: #999113; + text-decoration: none; + } + a:hover { + color: #7b750e; + text-decoration: underline; + } + + +/* #Typography +================================================== */ + h1, h2, h3, h4, h5, h6 { + font-weight: bold; } + h1 a, h2 a, h3 a, h4 a, h5 a, h6 a { font-weight: inherit; } + h1 { font-size: 75px; line-height: 80px; margin-bottom: 14px;} + h2 { font-size: 35px; line-height: 40px; margin-bottom: 10px; } + h3 { font-size: 28px; line-height: 34px; margin-bottom: 8px; } + h4 { font-size: 21px; line-height: 30px; margin-bottom: 4px; } + h5 { font-size: 17px; line-height: 24px; } + h6 { font-size: 14px; line-height: 21px; } + p { margin-bottom: 22px; } + + +/* #Main styles +================================================== */ + +/* Hogan Hero */ +.hogan-hero { + position: relative; + background: #333; /* Old browsers */ + background: -moz-radial-gradient(center, ellipse cover, #333 0%, #000 100%); /* FF3.6+ */ + background: -webkit-gradient(radial, center center, 0px, center center, 100%, color-stop(0%,#333), color-stop(100%,#000)); /* Chrome,Safari4+ */ + background: -webkit-radial-gradient(center, ellipse cover, #333 0%,#000 100%); /* Chrome10+,Safari5.1+ */ + background: -o-radial-gradient(center, ellipse cover, #333 0%,#000 100%); /* Opera 12+ */ + background: -ms-radial-gradient(center, ellipse cover, #333 0%,#000 100%); /* IE10+ */ + background: radial-gradient(center, ellipse cover, #333 0%,#000 100%); /* W3C */ + filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#333', endColorstr='#000',GradientType=1 ); /* IE6-9 fallback on horizontal gradient */ +} +.hogan-hero .container { + padding: 180px 0; +} +.hogan-hero h1 { + letter-spacing: -3px; + color: #fff; + position: relative; + margin-bottom: 5px; +} +.hogan-hero h3 { + max-width: 650px; + margin-bottom: 20px; + color: #fff; +} +.hogan-hero .noise, +.hogan-hero .stripes { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; +} +.hogan-hero .noise { + background: url(../images/noise.png) repeat; +} +.hogan-hero .stripes { + background: url(../images/stripes.png) repeat; +} + +/* Primary content container */ +.primary.container { + padding-top: 100px; +} + +/*Hogan divider */ +.hogan-divider { + padding-top: 60px; + border-bottom: 1px solid #ddd; + margin-bottom: 60px; + clear: both; + position: relative; +} +.hogan-icon { + width: 40px; + height: 30px; + position: absolute; + left: 50%; + top: 46px; + margin-left: -20px; + background: url('../images/small-hogan-icon.png') white no-repeat center center; +} + +/* Button style */ +.button { + display: inline-block; + cursor: pointer; + background: #dfd52e; + border-radius: 3px; + margin-bottom: 20px; + color: #000; + text-transform: uppercase; + text-decoration: none; + font-size: 15px; + padding: 0 34px; + line-height: 46px; + font-weight: bold; + -webkit-transition: background-color .3s ease-in-out; + -moz-transition: background-color .3s ease-in-out; + -o-transition: background-color .3s ease-in-out; + transition: background-color .3s ease-in-out; + +} +.button:hover { + text-decoration: inherit; + color: inherit; + background-color: #f5e810; +} + +/* Hogan footer */ +.hogan-footer { + border-top: 1px solid #ddd; + margin-top: 60px; + padding: 20px 0 40px; + color: #999; + font-size: 12px; +} +.hogan-footer .copyright { + float: left; +} +.hogan-footer .colophon { + float: right; +} + +pre, code { + background: #F8F8FF; + border: 1px solid #DDD; + padding: 5px 10px; + margin-bottom: 20px; + font-family: courier; + overflow: hidden; +} + +pre code { + border: 0; + padding: 0; + margin-bottom: 0; +} + + +/* #Media Queries +================================================== */ + + /* Smaller than standard 960 (devices and browsers) */ + @media only screen and (max-width: 959px) {} + + /* Tablet Portrait size to standard 960 (devices and browsers) */ + @media only screen and (min-width: 768px) and (max-width: 959px) {} + + /* All Mobile Sizes (devices and browser) */ + @media only screen and (max-width: 767px) { + .hogan-hero .container { + padding: 100px 0; + } + } + + /* Mobile Landscape Size to Tablet Portrait (devices and browsers) */ + @media only screen and (min-width: 480px) and (max-width: 767px) {} + + /* Mobile Portrait Size to Mobile Landscape Size (devices and browsers) */ + @media only screen and (max-width: 479px) {} + diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/web/stylesheets/skeleton.css b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/web/stylesheets/skeleton.css new file mode 100755 index 000000000..d0264a40b --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/web/stylesheets/skeleton.css @@ -0,0 +1,236 @@ +/* +* Skeleton V1.1 +* Copyright 2011, Dave Gamache +* www.getskeleton.com +* Free to use under the MIT license. +* http://www.opensource.org/licenses/mit-license.php +* 8/17/2011 +*/ + + +/* Table of Contents +================================================== + #Base 960 Grid + #Tablet (Portrait) + #Mobile (Portrait) + #Mobile (Landscape) + #Clearing */ + + + +/* #Base 960 Grid +================================================== */ + + .container { position: relative; width: 960px; margin: 0 auto; padding: 0; } + .column, .columns { float: left; display: inline; margin-left: 10px; margin-right: 10px; } + .row { margin-bottom: 20px; } + + /* Nested Column Classes */ + .column.alpha, .columns.alpha { margin-left: 0; } + .column.omega, .columns.omega { margin-right: 0; } + + /* Base Grid */ + .container .one.column { width: 40px; } + .container .two.columns { width: 100px; } + .container .three.columns { width: 160px; } + .container .four.columns { width: 220px; } + .container .five.columns { width: 280px; } + .container .six.columns { width: 340px; } + .container .seven.columns { width: 400px; } + .container .eight.columns { width: 460px; } + .container .nine.columns { width: 520px; } + .container .ten.columns { width: 580px; } + .container .eleven.columns { width: 640px; } + .container .twelve.columns { width: 700px; } + .container .thirteen.columns { width: 760px; } + .container .fourteen.columns { width: 820px; } + .container .fifteen.columns { width: 880px; } + .container .sixteen.columns { width: 940px; } + + .container .one-third.column { width: 300px; } + .container .two-thirds.column { width: 620px; } + + /* Offsets */ + .container .offset-by-one { padding-left: 60px; } + .container .offset-by-two { padding-left: 120px; } + .container .offset-by-three { padding-left: 180px; } + .container .offset-by-four { padding-left: 240px; } + .container .offset-by-five { padding-left: 300px; } + .container .offset-by-six { padding-left: 360px; } + .container .offset-by-seven { padding-left: 420px; } + .container .offset-by-eight { padding-left: 480px; } + .container .offset-by-nine { padding-left: 540px; } + .container .offset-by-ten { padding-left: 600px; } + .container .offset-by-eleven { padding-left: 660px; } + .container .offset-by-twelve { padding-left: 720px; } + .container .offset-by-thirteen { padding-left: 780px; } + .container .offset-by-fourteen { padding-left: 840px; } + .container .offset-by-fifteen { padding-left: 900px; } + + + +/* #Tablet (Portrait) +================================================== */ + + /* Note: Design for a width of 768px */ + + @media only screen and (min-width: 768px) and (max-width: 959px) { + .container { width: 768px; } + .container .column, + .container .columns { margin-left: 10px; margin-right: 10px; } + .column.alpha, .columns.alpha { margin-left: 0; margin-right: 10px; } + .column.omega, .columns.omega { margin-right: 0; margin-left: 10px; } + + .container .one.column { width: 28px; } + .container .two.columns { width: 76px; } + .container .three.columns { width: 124px; } + .container .four.columns { width: 172px; } + .container .five.columns { width: 220px; } + .container .six.columns { width: 268px; } + .container .seven.columns { width: 316px; } + .container .eight.columns { width: 364px; } + .container .nine.columns { width: 412px; } + .container .ten.columns { width: 460px; } + .container .eleven.columns { width: 508px; } + .container .twelve.columns { width: 556px; } + .container .thirteen.columns { width: 604px; } + .container .fourteen.columns { width: 652px; } + .container .fifteen.columns { width: 700px; } + .container .sixteen.columns { width: 748px; } + + .container .one-third.column { width: 236px; } + .container .two-thirds.column { width: 492px; } + + /* Offsets */ + .container .offset-by-one { padding-left: 48px; } + .container .offset-by-two { padding-left: 96px; } + .container .offset-by-three { padding-left: 144px; } + .container .offset-by-four { padding-left: 192px; } + .container .offset-by-five { padding-left: 240px; } + .container .offset-by-six { padding-left: 288px; } + .container .offset-by-seven { padding-left: 336px; } + .container .offset-by-eight { padding-left: 348px; } + .container .offset-by-nine { padding-left: 432px; } + .container .offset-by-ten { padding-left: 480px; } + .container .offset-by-eleven { padding-left: 528px; } + .container .offset-by-twelve { padding-left: 576px; } + .container .offset-by-thirteen { padding-left: 624px; } + .container .offset-by-fourteen { padding-left: 672px; } + .container .offset-by-fifteen { padding-left: 720px; } + } + + +/* #Mobile (Portrait) +================================================== */ + + /* Note: Design for a width of 320px */ + + @media only screen and (max-width: 767px) { + .container { width: 300px; } + .columns, .column { margin: 0; } + + .container .one.column, + .container .two.columns, + .container .three.columns, + .container .four.columns, + .container .five.columns, + .container .six.columns, + .container .seven.columns, + .container .eight.columns, + .container .nine.columns, + .container .ten.columns, + .container .eleven.columns, + .container .twelve.columns, + .container .thirteen.columns, + .container .fourteen.columns, + .container .fifteen.columns, + .container .sixteen.columns, + .container .one-third.column, + .container .two-thirds.column { width: 300px; } + + /* Offsets */ + .container .offset-by-one, + .container .offset-by-two, + .container .offset-by-three, + .container .offset-by-four, + .container .offset-by-five, + .container .offset-by-six, + .container .offset-by-seven, + .container .offset-by-eight, + .container .offset-by-nine, + .container .offset-by-ten, + .container .offset-by-eleven, + .container .offset-by-twelve, + .container .offset-by-thirteen, + .container .offset-by-fourteen, + .container .offset-by-fifteen { padding-left: 0; } + + } + + +/* #Mobile (Landscape) +================================================== */ + + /* Note: Design for a width of 480px */ + + @media only screen and (min-width: 480px) and (max-width: 767px) { + .container { width: 420px; } + .columns, .column { margin: 0; } + + .container .one.column, + .container .two.columns, + .container .three.columns, + .container .four.columns, + .container .five.columns, + .container .six.columns, + .container .seven.columns, + .container .eight.columns, + .container .nine.columns, + .container .ten.columns, + .container .eleven.columns, + .container .twelve.columns, + .container .thirteen.columns, + .container .fourteen.columns, + .container .fifteen.columns, + .container .sixteen.columns, + .container .one-third.column, + .container .two-thirds.column { width: 420px; } + } + + +/* #Clearing +================================================== */ + + /* Self Clearing Goodness */ + .container:after { content: "\0020"; display: block; height: 0; clear: both; visibility: hidden; } + + /* Use clearfix class on parent to clear nested columns, + or wrap each row of columns in a
    */ + .clearfix:before, + .clearfix:after, + .row:before, + .row:after { + content: '\0020'; + display: block; + overflow: hidden; + visibility: hidden; + width: 0; + height: 0; } + .row:after, + .clearfix:after { + clear: both; } + .row, + .clearfix { + zoom: 1; } + + /* You can also use a
    to clear columns */ + .clear { + clear: both; + display: block; + overflow: hidden; + visibility: hidden; + width: 0; + height: 0; + } + + diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/wrappers/amd.js.mustache b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/wrappers/amd.js.mustache new file mode 100644 index 000000000..d91ef77ca --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/wrappers/amd.js.mustache @@ -0,0 +1,21 @@ +/* + * Copyright 2011 Twitter, 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. + */ + +{{{template}}} +{{{compiler}}} + +if (typeof define === 'function' && define.amd) { + define(Hogan); +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/wrappers/common.js.mustache b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/wrappers/common.js.mustache new file mode 100644 index 000000000..e823e83a0 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/wrappers/common.js.mustache @@ -0,0 +1,21 @@ +/* + * Copyright 2011 Twitter, 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. + */ + +{{{template}}} +{{{compiler}}} + +if (typeof module !== 'undefined' && module.exports) { + module.exports = Hogan; +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/wrappers/js.mustache b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/wrappers/js.mustache new file mode 100644 index 000000000..9f311f08d --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/wrappers/js.mustache @@ -0,0 +1,17 @@ +/* + * Copyright 2011 Twitter, 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. + */ + +{{{template}}} +{{{compiler}}} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/wrappers/mustache.js.mustache b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/wrappers/mustache.js.mustache new file mode 100644 index 000000000..d3a3d70df --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/hogan.js/wrappers/mustache.js.mustache @@ -0,0 +1,64 @@ +/* + * Copyright 2011 Twitter, 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. + */ + +// A wrapper for compatibility with Mustache.js, quirks and all + +{{{template}}} +{{{compiler}}} + +var Mustache = (function (Hogan) { + + // Mustache.js has non-spec partial context behavior + function mustachePartial(name, context, partials, indent) { + var partialScope = this.f(name, context, partials, 0); + var cx = context; + if (partialScope) { + cx = cx.concat(partialScope); + } + + return Hogan.Template.prototype.rp.call(this, name, cx, partials, indent); + } + + var HoganTemplateWrapper = function(renderFunc, text, compiler){ + this.rp = mustachePartial; + Hogan.Template.call(this, renderFunc, text, compiler); + }; + HoganTemplateWrapper.prototype = Hogan.Template.prototype; + + // Add a wrapper for Hogan's generate method. Mustache and Hogan keep + // separate caches, and Mustache returns wrapped templates. + var wrapper; + var HoganWrapper = function(){ + this.cache = {}; + this.generate = function(code, text, options) { + return new HoganTemplateWrapper(new Function('c', 'p', 'i', code), text, wrapper); + } + }; + HoganWrapper.prototype = Hogan; + wrapper = new HoganWrapper(); + + return { + to_html: function(text, data, partials, sendFun) { + var template = wrapper.compile(text); + var result = template.render(data, partials); + if (!sendFun) { + return result; + } + + sendFun(result); + } + } + +})(Hogan); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/LICENSE.txt b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/LICENSE.txt new file mode 100644 index 000000000..cc082396c --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright 2012-2013 The Dojo Foundation +Based on Underscore.js 1.4.3, copyright 2009-2013 Jeremy Ashkenas, +DocumentCloud Inc. + +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/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/README.md new file mode 100644 index 000000000..6181c7790 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/README.md @@ -0,0 +1,276 @@ +# Lo-Dash v1.0.1 +[![build status](https://secure.travis-ci.org/bestiejs/lodash.png)](http://travis-ci.org/bestiejs/lodash) + +An alternative to Underscore.js, delivering consistency, [customization](https://github.com/bestiejs/lodash#custom-builds), [performance](http://lodash.com/benchmarks), and [extra features](https://github.com/bestiejs/lodash#features). + +## Download + +* Lo-Dash builds (for modern environments):
    +[Development](https://raw.github.com/bestiejs/lodash/v1.0.1/dist/lodash.js) and +[Production](https://raw.github.com/bestiejs/lodash/v1.0.1/dist/lodash.min.js) + +* Lo-Dash compatibility builds (for legacy and modern environments):
    +[Development](https://raw.github.com/bestiejs/lodash/v1.0.1/dist/lodash.compat.js) and +[Production](https://raw.github.com/bestiejs/lodash/v1.0.1/dist/lodash.compat.min.js) + +* Underscore compatibility builds:
    +[Development](https://raw.github.com/bestiejs/lodash/v1.0.1/dist/lodash.underscore.js) and +[Production](https://raw.github.com/bestiejs/lodash/v1.0.1/dist/lodash.underscore.min.js) + +* CDN copies of ≤ v1.0.1’s builds are available on [cdnjs](http://cdnjs.com/) thanks to [CloudFlare](http://www.cloudflare.com/):
    +[Lo-Dash dev](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.0.1/lodash.js), +[Lo-Dash prod](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.0.1/lodash.min.js),
    +[Lo-Dash compat-dev](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.0.1/lodash.compat.js), +[Lo-Dash compat-prod](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.0.1/lodash.compat.min.js),
    +[Underscore compat-dev](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.0.1/lodash.underscore.js), and +[Underscore compat-prod](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.0.1/lodash.underscore.min.js) + +* For optimal file size, [create a custom build](https://github.com/bestiejs/lodash#custom-builds) with only the features you need + +## Dive in + +We’ve got [API docs](http://lodash.com/docs), [benchmarks](http://lodash.com/benchmarks), and [unit tests](http://lodash.com/tests). + +For a list of upcoming features, check out our [roadmap](https://github.com/bestiejs/lodash/wiki/Roadmap). + +## Resources + +For more information check out these articles, screencasts, and other videos over Lo-Dash: + + * Posts + - [Say “Hello” to Lo-Dash](http://kitcambridge.be/blog/say-hello-to-lo-dash/) + + * Videos + - [Introducing Lo-Dash](https://vimeo.com/44154599) + - [Lo-Dash optimizations and custom builds](https://vimeo.com/44154601) + - [Lo-Dash’s origin and why it’s a better utility belt](https://vimeo.com/44154600) + - [Unit testing in Lo-Dash](https://vimeo.com/45865290) + - [Lo-Dash’s approach to native method use](https://vimeo.com/48576012) + - [CascadiaJS: Lo-Dash for a better utility belt](http://www.youtube.com/watch?v=dpPy4f_SeEk) + +## Features + + * AMD loader support ([RequireJS](http://requirejs.org/), [curl.js](https://github.com/cujojs/curl), etc.) + * [_(…)](http://lodash.com/docs#_) supports intuitive chaining + * [_.at](http://lodash.com/docs#at) for cherry-picking collection values + * [_.bindKey](http://lodash.com/docs#bindKey) for binding [*“lazy”* defined](http://michaux.ca/articles/lazy-function-definition-pattern) methods + * [_.cloneDeep](http://lodash.com/docs#cloneDeep) for deep cloning arrays and objects + * [_.contains](http://lodash.com/docs#contains) accepts a `fromIndex` argument + * [_.forEach](http://lodash.com/docs#forEach) is chainable and supports exiting iteration early + * [_.forIn](http://lodash.com/docs#forIn) for iterating over an object’s own and inherited properties + * [_.forOwn](http://lodash.com/docs#forOwn) for iterating over an object’s own properties + * [_.isPlainObject](http://lodash.com/docs#isPlainObject) checks if values are created by the `Object` constructor + * [_.merge](http://lodash.com/docs#merge) for a deep [_.extend](http://lodash.com/docs#extend) + * [_.partial](http://lodash.com/docs#partial) and [_.partialRight](http://lodash.com/docs#partialRight) for partial application without `this` binding + * [_.template](http://lodash.com/docs#template) supports [*“imports”* options](http://lodash.com/docs#templateSettings_imports), [ES6 template delimiters](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6), and [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * [_.where](http://lodash.com/docs#where) supports deep object comparisons + * [_.clone](http://lodash.com/docs#clone), [_.omit](http://lodash.com/docs#omit), [_.pick](http://lodash.com/docs#pick), + [and more…](http://lodash.com/docs "_.assign, _.cloneDeep, _.first, _.initial, _.isEqual, _.last, _.merge, _.rest") accept `callback` and `thisArg` arguments + * [_.contains](http://lodash.com/docs#contains), [_.size](http://lodash.com/docs#size), [_.toArray](http://lodash.com/docs#toArray), + [and more…](http://lodash.com/docs "_.at, _.countBy, _.every, _.filter, _.find, _.forEach, _.groupBy, _.invoke, _.map, _.max, _.min, _.pluck, _.reduce, _.reduceRight, _.reject, _.shuffle, _.some, _.sortBy, _.where") accept strings + * [_.filter](http://lodash.com/docs#filter), [_.find](http://lodash.com/docs#find), [_.map](http://lodash.com/docs#map), + [and more…](http://lodash.com/docs "_.countBy, _.every, _.first, _.groupBy, _.initial, _.last, _.max, _.min, _.reject, _.rest, _.some, _.sortBy, _.sortedIndex, _.uniq") support *“_.pluck”* and *“_.where”* `callback` shorthands + +## Support + +Lo-Dash has been tested in at least Chrome 5~24, Firefox 1~18, IE 6-10, Opera 9.25-12, Safari 3-6, Node.js 0.4.8-0.8.20, Narwhal 0.3.2, PhantomJS 1.8.1, RingoJS 0.9, and Rhino 1.7RC5. + +## Custom builds + +Custom builds make it easy to create lightweight versions of Lo-Dash containing only the methods you need. +To top it off, we handle all method dependency and alias mapping for you. + + * Backbone builds, with only methods required by Backbone, may be created using the `backbone` modifier argument. +```bash +lodash backbone +``` + + * CSP builds, supporting default [Content Security Policy](https://dvcs.w3.org/hg/content-security-policy/raw-file/tip/csp-specification.dev.html) restrictions, may be created using the `csp` modifier argument. + The `csp` modifier is an alais of the `mobile` modifier. Lo-Dash may be used in Chrome extensions by using either the `csp`, `mobile`, or `underscore` build and using precompiled templates, or loading Lo-Dash in a [sandbox](http://developer.chrome.com/stable/extensions/sandboxingEval.html). +```bash +lodash csp +``` + + * Legacy builds, tailored for older environments without [ES5 support](http://es5.github.com/), may be created using the `legacy` modifier argument. +```bash +lodash legacy +``` + + * Modern builds, tailored for newer environments with ES5 support, may be created using the `modern` modifier argument. +```bash +lodash modern +``` + + * Mobile builds, without method compilation and most bug fixes for old browsers, may be created using the `mobile` modifier argument. +```bash +lodash mobile +``` + + * Strict builds, with `_.bindAll`, `_.defaults`, and `_.extend` in [strict mode](http://es5.github.com/#C), may be created using the `strict` modifier argument. +```bash +lodash strict +``` + + * Underscore builds, tailored for projects already using Underscore, may be created using the `underscore` modifier argument. +```bash +lodash underscore +``` + +Custom builds may be created using the following commands: + + * Use the `category` argument to pass comma separated categories of methods to include in the build.
    + Valid categories (case-insensitive) are *“arrays”*, *“chaining”*, *“collections”*, *“functions”*, *“objects”*, and *“utilities”*. +```bash +lodash category=collections,functions +lodash category="collections, functions" +``` + + * Use the `exports` argument to pass comma separated names of ways to export the `LoDash` function.
    + Valid exports are *“amd”*, *“commonjs”*, *“global”*, *“node”*, and *“none”*. +```bash +lodash exports=amd,commonjs,node +lodash exports="amd, commonjs, node" +``` + + * Use the `iife` argument to specify code to replace the immediately-invoked function expression that wraps Lo-Dash. +```bash +lodash iife="!function(window,undefined){%output%}(this)" +``` + + * Use the `include` argument to pass comma separated method/category names to include in the build. +```bash +lodash include=each,filter,map +lodash include="each, filter, map" +``` + + * Use the `minus` argument to pass comma separated method/category names to remove from those included in the build. +```bash +lodash underscore minus=result,shuffle +lodash underscore minus="result, shuffle" +``` + + * Use the `plus` argument to pass comma separated method/category names to add to those included in the build. +```bash +lodash backbone plus=random,template +lodash backbone plus="random, template" +``` + + * Use the `template` argument to pass the file path pattern used to match template files to precompile. +```bash +lodash template="./*.jst" +``` + + * Use the `settings` argument to pass the template settings used when precompiling templates. +```bash +lodash settings="{interpolate:/\{\{([\s\S]+?)\}\}/g}" +``` + + * Use the `moduleId` argument to specify the AMD module ID of Lo-Dash, which defaults to “lodash”, used by precompiled templates. +```bash +lodash moduleId="underscore" +``` + +All arguments, except `legacy` with `csp`, `mobile`, `modern`, or `underscore`, may be combined.
    +Unless specified by `-o` or `--output`, all files created are saved to the current working directory. + +The following options are also supported: + + * `-c`, `--stdout` ......... Write output to standard output + * `-d`, `--debug` ........... Write only the non-minified development output + * `-h`, `--help` ............. Display help information + * `-m`, `--minify` ......... Write only the minified production output + * `-o`, `--output` ......... Write output to a given path/filename + * `-p`, `--source-map` .. Generate a source map for the minified output, using an optional source map URL + * `-s`, `--silent` ......... Skip status updates normally logged to the console + * `-V`, `--version` ....... Output current version of Lo-Dash + +The `lodash` command-line utility is available when Lo-Dash is installed as a global package (i.e. `npm install -g lodash`). + +## Installation and usage + +In browsers: + +```html + +``` + +Using [`npm`](http://npmjs.org/): + +```bash +npm install lodash + +npm install -g lodash +npm link lodash +``` + +To avoid potential issues, update `npm` before installing Lo-Dash: + +```bash +npm install npm -g +``` + +In [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/): + +```js +var _ = require('lodash'); + +// or as a drop-in replacement for Underscore +var _ = require('lodash/lodash.underscore'); +``` + +**Note:** If Lo-Dash is installed globally, run [`npm link lodash`](http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/) in your project’s root directory before requiring it. + +In [RingoJS v0.7.0-](http://ringojs.org/): + +```js +var _ = require('lodash')._; +``` + +In [Rhino](http://www.mozilla.org/rhino/): + +```js +load('lodash.js'); +``` + +In an AMD loader like [RequireJS](http://requirejs.org/): + +```js +require({ + 'paths': { + 'underscore': 'path/to/lodash' + } +}, +['underscore'], function(_) { + console.log(_.VERSION); +}); +``` + +## Release Notes + +### v1.0.1 + + * Add support for specifying source map URLs in `-p`/`--source-map` build options + * Ensured the second argument passed to `_.assign` is not treated as a `callback` + * Ensured `-p`/`--source-map` build options correctly set the `sourceMappingURL` + * Made `-p`/`--source-map` build options set source map *“sources”* keys based on the builds performed + * Made `_.defer` use `setImmediate`, in Node.js, when available + * Made `_.where` search arrays for values regardless of their index position + * Removed dead code from `_.template` + +The full changelog is available [here](https://github.com/bestiejs/lodash/wiki/Changelog). + +## BestieJS + +Lo-Dash is part of the BestieJS *“Best in Class”* module collection. This means we promote solid browser/environment support, ES5 precedents, unit testing, and plenty of documentation. + +## Author + +* [John-David Dalton](http://allyoucanleet.com/) + [![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") + +## Contributors + +* [Kit Cambridge](http://kitcambridge.github.com/) + [![twitter/kitcambridge](http://gravatar.com/avatar/6662a1d02f351b5ef2f8b4d815804661?s=70)](https://twitter.com/kitcambridge "Follow @kitcambridge on Twitter") +* [Mathias Bynens](http://mathiasbynens.be/) + [![twitter/mathias](http://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/build.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/build.js new file mode 100755 index 000000000..4e34c827d --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/build.js @@ -0,0 +1,2509 @@ +#!/usr/bin/env node +;(function() { + 'use strict'; + + /** Load modules */ + var fs = require('fs'), + path = require('path'), + vm = require('vm'), + minify = require(path.join(__dirname, 'build', 'minify.js')), + _ = require(path.join(__dirname, 'lodash.js')); + + /** The current working directory */ + var cwd = process.cwd(); + + /** Used for array method references */ + var arrayRef = []; + + /** Shortcut used to push arrays of values to an array */ + var push = arrayRef.push; + + /** Shortcut used to convert array-like objects to arrays */ + var slice = arrayRef.slice; + + /** Shortcut to the `stdout` object */ + var stdout = process.stdout; + + /** Used to associate aliases with their real names */ + var aliasToRealMap = { + 'all': 'every', + 'any': 'some', + 'collect': 'map', + 'detect': 'find', + 'drop': 'rest', + 'each': 'forEach', + 'extend': 'assign', + 'foldl': 'reduce', + 'foldr': 'reduceRight', + 'head': 'first', + 'include': 'contains', + 'inject': 'reduce', + 'methods': 'functions', + 'select': 'filter', + 'tail': 'rest', + 'take': 'first', + 'unique': 'uniq' + }; + + /** Used to associate real names with their aliases */ + var realToAliasMap = { + 'assign': ['extend'], + 'contains': ['include'], + 'every': ['all'], + 'filter': ['select'], + 'find': ['detect'], + 'first': ['head', 'take'], + 'forEach': ['each'], + 'functions': ['methods'], + 'map': ['collect'], + 'reduce': ['foldl', 'inject'], + 'reduceRight': ['foldr'], + 'rest': ['drop', 'tail'], + 'some': ['any'], + 'uniq': ['unique'] + }; + + /** Used to track function dependencies */ + var dependencyMap = { + 'after': [], + 'assign': ['isArray', 'forEach', 'forOwn'], + 'at': ['isString'], + 'bind': ['isFunction', 'isObject'], + 'bindAll': ['bind', 'functions'], + 'bindKey': ['isFunction', 'isObject'], + 'clone': ['assign', 'forEach', 'forOwn', 'isArray', 'isObject'], + 'cloneDeep': ['clone'], + 'compact': [], + 'compose': [], + 'contains': ['indexOf', 'isString'], + 'countBy': ['forEach', 'identity', 'isEqual', 'keys'], + 'debounce': [], + 'defaults': ['isArray', 'forEach', 'forOwn'], + 'defer': ['bind'], + 'delay': [], + 'difference': ['indexOf'], + 'escape': [], + 'every': ['identity', 'isArray', 'isEqual', 'keys'], + 'filter': ['identity', 'isArray', 'isEqual', 'keys'], + 'find': ['forEach', 'identity', 'isEqual', 'keys'], + 'first': [], + 'flatten': ['isArray'], + 'forEach': ['identity', 'isArguments', 'isArray', 'isString'], + 'forIn': ['identity', 'isArguments'], + 'forOwn': ['identity', 'isArguments'], + 'functions': ['forIn', 'isFunction'], + 'groupBy': ['forEach', 'identity', 'isEqual', 'keys'], + 'has': [], + 'identity': [], + 'indexOf': ['sortedIndex'], + 'initial': [], + 'intersection': ['indexOf'], + 'invert': ['keys'], + 'invoke': ['forEach'], + 'isArguments': [], + 'isArray': [], + 'isBoolean': [], + 'isDate': [], + 'isElement': [], + 'isEmpty': ['forOwn', 'isArguments', 'isFunction'], + 'isEqual': ['forIn', 'isArguments', 'isFunction'], + 'isFinite': [], + 'isFunction': [], + 'isNaN': ['isNumber'], + 'isNull': [], + 'isNumber': [], + 'isObject': [], + 'isPlainObject': ['forIn', 'isArguments', 'isFunction'], + 'isRegExp': [], + 'isString': [], + 'isUndefined': [], + 'keys': ['forOwn', 'isArguments', 'isObject'], + 'last': [], + 'lastIndexOf': [], + 'map': ['identity', 'isArray', 'isEqual', 'keys'], + 'max': ['isArray', 'isEqual', 'isString', 'keys'], + 'memoize': [], + 'merge': ['forEach', 'forOwn', 'isArray', 'isObject', 'isPlainObject'], + 'min': ['isArray', 'isEqual', 'isString', 'keys'], + 'mixin': ['forEach', 'forOwn', 'functions'], + 'noConflict': [], + 'object': [], + 'omit': ['forIn', 'indexOf'], + 'once': [], + 'pairs': ['keys'], + 'partial': ['isFunction', 'isObject'], + 'partialRight': ['isFunction', 'isObject'], + 'pick': ['forIn', 'isObject'], + 'pluck': ['map'], + 'random': [], + 'range': [], + 'reduce': ['identity', 'isArray', 'isEqual', 'keys'], + 'reduceRight': ['forEach', 'identity', 'isEqual', 'isString', 'keys'], + 'reject': ['filter', 'identity', 'isEqual', 'keys'], + 'rest': [], + 'result': ['isFunction'], + 'shuffle': ['forEach'], + 'size': ['keys'], + 'some': ['identity', 'isArray', 'isEqual', 'keys'], + 'sortBy': ['forEach', 'identity', 'isEqual', 'keys'], + 'sortedIndex': ['identity', 'isEqual', 'keys'], + 'tap': ['mixin'], + 'template': ['defaults', 'escape', 'keys', 'values'], + 'throttle': [], + 'times': [], + 'toArray': ['isString', 'values'], + 'unescape': [], + 'union': ['uniq'], + 'uniq': ['indexOf', 'isEqual', 'keys'], + 'uniqueId': [], + 'value': ['mixin'], + 'values': ['keys'], + 'where': ['filter'], + 'without': ['indexOf'], + 'wrap': [], + 'zip': ['max', 'pluck'], + + // method used by the `backbone` and `underscore` builds + 'chain': ['mixin'], + 'findWhere': ['where'] + }; + + /** Used to inline `iteratorTemplate` */ + var iteratorOptions = [ + 'args', + 'arrays', + 'bottom', + 'firstArg', + 'hasDontEnumBug', + 'hasEnumPrototype', + 'isKeysFast', + 'loop', + 'nonEnumArgs', + 'noCharByIndex', + 'shadowed', + 'top', + 'useHas' + ]; + + /** List of all Lo-Dash methods */ + var allMethods = _.keys(dependencyMap); + + /** List of Backbone's Lo-Dash dependencies */ + var backboneDependencies = [ + 'bind', + 'bindAll', + 'chain', + 'clone', + 'contains', + 'countBy', + 'defaults', + 'escape', + 'every', + 'extend', + 'filter', + 'find', + 'first', + 'forEach', + 'groupBy', + 'has', + 'indexOf', + 'initial', + 'invoke', + 'isArray', + 'isEmpty', + 'isEqual', + 'isFunction', + 'isObject', + 'isRegExp', + 'isString', + 'keys', + 'last', + 'lastIndexOf', + 'map', + 'max', + 'min', + 'mixin', + 'once', + 'pick', + 'reduce', + 'reduceRight', + 'reject', + 'rest', + 'result', + 'shuffle', + 'size', + 'some', + 'sortBy', + 'sortedIndex', + 'toArray', + 'uniqueId', + 'value', + 'without' + ]; + + /** List of methods used by Underscore */ + var underscoreMethods = _.without.apply(_, [allMethods].concat([ + 'at', + 'bindKey', + 'cloneDeep', + 'forIn', + 'forOwn', + 'isPlainObject', + 'merge', + 'partialRight' + ])); + + /** List of ways to export the `lodash` function */ + var exportsAll = [ + 'amd', + 'commonjs', + 'global', + 'node' + ]; + + /*--------------------------------------------------------------------------*/ + + /** + * Adds support for Underscore style chaining to the `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function addChainMethods(source) { + // add `_.chain` + source = source.replace(matchFunction(source, 'tap'), function(match) { + return [ + '', + ' /**', + ' * Creates a `lodash` object that wraps the given `value`.', + ' *', + ' * @static', + ' * @memberOf _', + ' * @category Chaining', + ' * @param {Mixed} value The value to wrap.', + ' * @returns {Object} Returns the wrapper object.', + ' * @example', + ' *', + ' * var stooges = [', + " * { 'name': 'moe', 'age': 40 },", + " * { 'name': 'larry', 'age': 50 },", + " * { 'name': 'curly', 'age': 60 }", + ' * ];', + ' *', + ' * var youngest = _.chain(stooges)', + ' * .sortBy(function(stooge) { return stooge.age; })', + " * .map(function(stooge) { return stooge.name + ' is ' + stooge.age; })", + ' * .first();', + " * // => 'moe is 40'", + ' */', + ' function chain(value) {', + ' value = new lodash(value);', + ' value.__chain__ = true;', + ' return value;', + ' }', + '', + match + ].join('\n'); + }); + + // add `wrapperChain` + source = source.replace(matchFunction(source, 'wrapperToString'), function(match) { + return [ + '', + ' /**', + ' * Enables method chaining on the wrapper object.', + ' *', + ' * @name chain', + ' * @memberOf _', + ' * @category Chaining', + ' * @returns {Mixed} Returns the wrapper object.', + ' * @example', + ' *', + ' * var sum = _([1, 2, 3])', + ' * .chain()', + ' * .reduce(function(sum, num) { return sum + num; })', + ' * .value()', + ' * // => 6`', + ' */', + ' function wrapperChain() {', + ' this.__chain__ = true;', + ' return this;', + ' }', + '', + match + ].join('\n'); + }); + + // add `lodash.chain` assignment + source = source.replace(getMethodAssignments(source), function(match) { + return match.replace(/^(?: *\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/\n)?( *)lodash\.VERSION *=/m, '$1lodash.chain = chain;\n\n$&'); + }); + + // add `lodash.prototype.chain` assignment + source = source.replace(/^( *)lodash\.prototype\.value *=.+\n/m, '$1lodash.prototype.chain = wrapperChain;\n$&'); + + // remove `lodash.prototype.toString` and `lodash.prototype.valueOf` assignments + source = source.replace(/^ *lodash\.prototype\.(?:toString|valueOf) *=.+\n/gm, ''); + + // remove `lodash.prototype` batch method assignments + source = source.replace(/(?:\s*\/\/.*)*\n( *)forOwn\(lodash, *function\(func, *methodName\)[\s\S]+?\n\1}.+/g, ''); + + // move `mixin(lodash)` to after the method assignments + source = source.replace(/(?:\s*\/\/.*)*\s*mixin\(lodash\).+/, ''); + source = source.replace(getMethodAssignments(source), function(match) { + return match + [ + '', + '', + ' // add functions to `lodash.prototype`', + ' mixin(lodash);' + ].join('\n'); + }); + + // add `__chain__` checks to `_.mixin` + source = source.replace(matchFunction(source, 'mixin'), function(match) { + return match.replace(/^( *)return new lodash.+/m, function() { + var indent = arguments[1]; + return indent + [ + '', + 'var result = func.apply(lodash, args);', + 'if (this.__chain__) {', + ' result = new lodash(result);', + ' result.__chain__ = true;', + '}', + 'return result;' + ].join('\n' + indent); + }); + }); + + // replace wrapper `Array` method assignments + source = source.replace(/^(?: *\/\/.*\n)*( *)each\(\['[\s\S]+?\n\1}$/m, function() { + return [ + ' // add `Array` mutator functions to the wrapper', + " each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {", + ' var func = arrayRef[methodName];', + ' lodash.prototype[methodName] = function() {', + ' var value = this.__wrapped__;', + ' func.apply(value, arguments);', + '', + ' // avoid array-like object bugs with `Array#shift` and `Array#splice`', + ' // in Firefox < 10 and IE < 9', + ' if (hasObjectSpliceBug && value.length === 0) {', + ' delete value[0];', + ' }', + ' return this;', + ' };', + ' });', + '', + ' // add `Array` accessor functions to the wrapper', + " each(['concat', 'join', 'slice'], function(methodName) {", + ' var func = arrayRef[methodName];', + ' lodash.prototype[methodName] = function() {', + ' var value = this.__wrapped__,', + ' result = func.apply(value, arguments);', + '', + ' if (this.__chain__) {', + ' result = new lodash(result);', + ' result.__chain__ = true;', + ' }', + ' return result;', + ' };', + ' });' + ].join('\n'); + }); + + return source; + } + + /** + * Adds build `commands` to the copyright/license header of the `source`. + * + * @private + * @param {String} source The source to process. + * @param {Array} [commands=[]] An array of commands. + * @returns {String} Returns the modified source. + */ + function addCommandsToHeader(source, commands) { + return source.replace(/(\/\**\n)( \*)( *@license[\s*]+)( *Lo-Dash [\w.-]+)(.*)/, function() { + // remove `node path/to/build.js` from `commands` + if (commands[0] == 'node') { + commands.splice(0, 2); + } + // add quotes to commands with spaces or equals signs + commands = _.map(commands, function(command) { + var separator = (command.match(/[= ]/) || [''])[0]; + if (separator) { + var pair = command.split(separator); + command = pair[0] + separator + '"' + pair[1] + '"'; + } + // escape newlines, carriage returns, multi-line comment end tokens + command = command + .replace(/\n/g, '\\n') + .replace(/\r/g, '\\r') + .replace(/\*\//g, '*\\/'); + + return command; + }); + // add build commands to copyright/license header + var parts = slice.call(arguments, 1); + return ( + parts[0] + + parts[1] + + parts[2] + parts[3] + ' (Custom Build)' + parts[4] + '\n' + + parts[1] + ' Build: `lodash ' + commands.join(' ') + '`' + ); + }); + } + + /** + * Compiles template files matched by the given file path `pattern` into a + * single source, extending `_.templates` with precompiled templates named after + * each template file's basename. + * + * @private + * @param {String} [pattern='/*.jst'] The file path pattern. + * @param {Object} options The options object. + * @returns {String} Returns the compiled source. + */ + function buildTemplate(pattern, options) { + pattern || (pattern = path.join(cwd, '*.jst')); + + var directory = path.dirname(pattern); + + var source = [ + ';(function(window) {', + " var freeExports = typeof exports == 'object' && exports;", + '', + " var freeModule = typeof module == 'object' && module && module.exports == freeExports && module;", + '', + " var freeGlobal = typeof global == 'object' && global;", + ' if (freeGlobal.global === freeGlobal) {', + ' window = freeGlobal;', + ' }', + '', + ' var templates = {},', + ' _ = window._;', + '' + ]; + + // convert to a regexp + pattern = RegExp( + path.basename(pattern) + .replace(/[.+?^=!:${}()|[\]\/\\]/g, '\\$&') + .replace(/\*/g, '.*?') + '$' + ); + + fs.readdirSync(directory).forEach(function(filename) { + var filePath = path.join(directory, filename); + if (pattern.test(filename)) { + var text = fs.readFileSync(filePath, 'utf8'), + precompiled = getFunctionSource(_.template(text, null, options)), + prop = filename.replace(/\..*$/, ''); + + source.push(" templates['" + prop.replace(/['\n\r\t]/g, '\\$&') + "'] = " + precompiled + ';', ''); + } + }); + + source.push( + " if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {", + " define(['" + options.moduleId + "'], function(lodash) {", + ' _ = lodash;', + ' lodash.templates = lodash.extend(lodash.templates || {}, templates);', + ' });', + " } else if (freeExports) {", + " if (freeModule) {", + ' (freeModule.exports = templates).templates = templates;', + ' } else {', + ' freeExports.templates = templates;', + ' }', + ' } else if (_) {', + ' _.templates = _.extend(_.templates || {}, templates);', + ' }', + '}(this));' + ); + + return source.join('\n'); + } + + /** + * Capitalizes a given string. + * + * @private + * @param {String} string The string to capitalize. + * @returns {String} Returns the capitalized string. + */ + function capitalize(string) { + return string[0].toUpperCase() + string.toLowerCase().slice(1); + } + + /** + * Removes unnecessary comments, whitespace, and pseudo private properties. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function cleanupSource(source) { + return source + // remove pseudo private properties + .replace(/(?:(?:\s*\/\/.*)*\s*lodash\._[^=]+=.+\n)+/g, '\n') + // remove lines with just whitespace and semicolons + .replace(/^ *;\n/gm, '') + // consolidate multiple newlines + .replace(/\n{3,}/g, '\n\n') + // consolidate consecutive horizontal rule comment separators + .replace(/(?:\s*\/\*-+\*\/\s*){2,}/g, function(separators) { + return separators.match(/^\s*/)[0] + separators.slice(separators.lastIndexOf('/*')); + }); + } + + /** + * Writes the help message to standard output. + * + * @private + */ + function displayHelp() { + console.log([ + '', + ' Commands:', + '', + ' lodash backbone Build with only methods required by Backbone', + ' lodash csp Build supporting default Content Security Policy restrictions', + ' lodash legacy Build tailored for older environments without ES5 support', + ' lodash modern Build tailored for newer environments with ES5 support', + ' lodash mobile Build without method compilation and most bug fixes for old browsers', + ' lodash strict Build with `_.assign`, `_.bindAll`, & `_.defaults` in strict mode', + ' lodash underscore Build tailored for projects already using Underscore', + ' lodash include=... Comma separated method/category names to include in the build', + ' lodash minus=... Comma separated method/category names to remove from those included in the build', + ' lodash plus=... Comma separated method/category names to add to those included in the build', + ' lodash category=... Comma separated categories of methods to include in the build (case-insensitive)', + ' (i.e. “arrays”, “chaining”, “collections”, “functions”, “objects”, and “utilities”)', + ' lodash exports=... Comma separated names of ways to export the `lodash` function', + ' (i.e. “amd”, “commonjs”, “global”, “node”, and “none”)', + ' lodash iife=... Code to replace the immediately-invoked function expression that wraps Lo-Dash', + ' (e.g. `lodash iife="!function(window,undefined){%output%}(this)"`)', + '', + ' lodash template=... File path pattern used to match template files to precompile', + ' (e.g. `lodash template=./*.jst`)', + ' lodash settings=... Template settings used when precompiling templates', + ' (e.g. `lodash settings="{interpolate:/{{([\\s\\S]+?)}}/g}"`)', + ' lodash moduleId=... The AMD module ID of Lo-Dash, which defaults to “lodash”, used by precompiled templates', + '', + ' All arguments, except `legacy` with `csp`, `mobile`, `modern`, or `underscore`, may be combined.', + ' Unless specified by `-o` or `--output`, all files created are saved to the current working directory.', + '', + ' Options:', + '', + ' -c, --stdout Write output to standard output', + ' -d, --debug Write only the non-minified development output', + ' -h, --help Display help information', + ' -m, --minify Write only the minified production output', + ' -o, --output Write output to a given path/filename', + ' -p, --source-map Generate a source map for the minified output, using an optional source map URL', + ' -s, --silent Skip status updates normally logged to the console', + ' -V, --version Output current version of Lo-Dash', + '' + ].join('\n')); + } + + /** + * Gets the aliases associated with a given function name. + * + * @private + * @param {String} methodName The name of the method to get aliases for. + * @returns {Array} Returns an array of aliases. + */ + function getAliases(methodName) { + return realToAliasMap[methodName] || []; + } + + /** + * Gets the category of the given method name. + * + * @private + * @param {String} source The source to inspect. + * @param {String} methodName The method name. + * @returns {String} Returns the method name's category. + */ + function getCategory(source, methodName) { + var result = /@category +(\w+)/.exec(matchFunction(source, methodName)); + return result ? result[1] : ''; + } + + /** + * Gets an array of category dependencies for a given category. + * + * @private + * @param {String} source The source to inspect. + * @param {String} category The category. + * @returns {Array} Returns an array of cetegory dependants. + */ + function getCategoryDependencies(source, category) { + var methods = _.uniq(getMethodsByCategory(source, category).reduce(function(result, methodName) { + push.apply(result, getDependencies(methodName)); + return result; + }, [])); + + var categories = _.uniq(methods.map(function(methodName) { + return getCategory(source, methodName); + })); + + return categories.filter(function(other) { + return other != category; + }); + } + + /** + * Gets an array of depenants for a method by a given name. + * + * @private + * @param {String} methodName The method name. + * @returns {Array} Returns an array of method dependants. + */ + function getDependants(methodName) { + // iterate over the `dependencyMap`, adding the names of methods that + // have `methodName` as a dependency + return _.reduce(dependencyMap, function(result, dependencies, otherName) { + if (_.contains(dependencies, methodName)) { + result.push(otherName); + } + return result; + }, []); + } + + /** + * Gets an array of dependencies for a given method name. If passed an array + * of dependencies it will return an array containing the given dependencies + * plus any additional detected sub-dependencies. + * + * @private + * @param {Array|String} methodName A single method name or array of + * dependencies to query. + * @returns {Array} Returns an array of method dependencies. + */ + function getDependencies(methodName) { + var dependencies = Array.isArray(methodName) ? methodName : dependencyMap[methodName]; + if (!dependencies) { + return []; + } + // recursively accumulate the dependencies of the `methodName` function, and + // the dependencies of its dependencies, and so on + return _.uniq(dependencies.reduce(function(result, otherName) { + result.push.apply(result, getDependencies(otherName).concat(otherName)); + return result; + }, [])); + } + + /** + * Gets the formatted source of the given function. + * + * @private + * @param {Function} func The function to process. + * @returns {String} Returns the formatted source. + */ + function getFunctionSource(func) { + var source = func.source || (func + ''); + + // format leading whitespace + return source.replace(/\n(?:.*)/g, function(match, index) { + match = match.slice(1); + return ( + match == '}' && source.indexOf('}', index + 2) < 0 ? '\n ' : '\n ' + ) + match; + }); + } + + /** + * Gets the `_.isArguments` fallback from `source`. + * + * @private + * @param {String} source The source to inspect. + * @returns {String} Returns the `isArguments` fallback. + */ + function getIsArgumentsFallback(source) { + return (source.match(/(?:\s*\/\/.*)*\n( *)if *\((?:noArgsClass|!isArguments)[\s\S]+?};\n\1}/) || [''])[0]; + } + + /** + * Gets the `_.isFunction` fallback from `source`. + * + * @private + * @param {String} source The source to inspect. + * @returns {String} Returns the `isFunction` fallback. + */ + function getIsFunctionFallback(source) { + return (source.match(/(?:\s*\/\/.*)*\n( *)if *\(isFunction\(\/x\/[\s\S]+?};\n\1}/) || [''])[0]; + } + + /** + * Gets the `iteratorTemplate` from `source`. + * + * @private + * @param {String} source The source to inspect. + * @returns {String} Returns the `iteratorTemplate`. + */ + function getIteratorTemplate(source) { + return (source.match(/^( *)var iteratorTemplate *= *[\s\S]+?\n\1.+?;\n/m) || [''])[0]; + } + + /** + * Gets the Lo-Dash method assignments snippet from `source`. + * + * @private + * @param {String} source The source to inspect. + * @returns {String} Returns the method assignments snippet. + */ + function getMethodAssignments(source) { + return (source.match(/\/\*-+\*\/\n(?:\s*\/\/.*)*\s*lodash\.\w+ *=[\s\S]+?lodash\.VERSION *=.+/) || [''])[0]; + } + + /** + * Gets the names of methods in `source` belonging to the given `category`. + * + * @private + * @param {String} source The source to inspect. + * @param {String} category The category to filter by. + * @returns {Array} Returns a new array of method names belonging to the given category. + */ + function getMethodsByCategory(source, category) { + return allMethods.filter(function(methodName) { + return getCategory(source, methodName) == category; + }); + } + + /** + * Gets the real name, not alias, of a given method name. + * + * @private + * @param {String} methodName The name of the method to resolve. + * @returns {String} Returns the real method name. + */ + function getRealName(methodName) { + return aliasToRealMap[methodName] || methodName; + } + + /** + * Determines if all functions of the given names have been removed from `source`. + * + * @private + * @param {String} source The source to inspect. + * @param {String} [funcName1, funcName2, ...] The names of functions to check. + * @returns {Boolean} Returns `true` if all functions have been removed, else `false`. + */ + function isRemoved(source) { + return slice.call(arguments, 1).every(function(funcName) { + return !matchFunction(source, funcName); + }); + } + + /** + * Searches `source` for a `funcName` function declaration, expression, or + * assignment and returns the matched snippet. + * + * @private + * @param {String} source The source to inspect. + * @param {String} funcName The name of the function to match. + * @returns {String} Returns the matched function snippet. + */ + function matchFunction(source, funcName) { + var result = source.match(RegExp( + // match multi-line comment block (could be on a single line) + '(?:\\n +/\\*[^*]*\\*+(?:[^/][^*]*\\*+)*/\\n)?' + + // begin non-capturing group + '( *)(?:' + + // match a function declaration + 'function ' + funcName + '\\b[\\s\\S]+?\\n\\1}|' + + // match a variable declaration with function expression + 'var ' + funcName + ' *=.*?function[\\s\\S]+?\\n\\1};' + + // end non-capturing group + ')\\n' + )); + + // match variables that are explicitly defined as functions + result || (result = source.match(RegExp( + // match multi-line comment block + '(?:\\n +/\\*[^*]*\\*+(?:[^/][^*]*\\*+)*/)?\\n' + + // match simple variable declarations and those with `createIterator` + ' *var ' + funcName + ' *=(?:.+?|.*?createIterator\\([\\s\\S]+?\\));\\n' + ))); + + return /@type +Function|function\s*\w*\(/.test(result) ? result[0] : ''; + } + + /** + * Converts a comma separated options string into an array. + * + * @private + * @param {String} value The option to convert. + * @returns {Array} Returns the new converted array. + */ + function optionToArray(value) { + return value.match(/\w+=(.*)$/)[1].split(/, */); + } + + /** + * Converts a comma separated options string into an array containing + * only real method names. + * + * @private + * @param {String} source The source to inspect. + * @param {String} value The option to convert. + * @returns {Array} Returns the new converted array. + */ + function optionToMethodsArray(source, value) { + var methodNames = optionToArray(value); + + // convert categories to method names + methodNames.forEach(function(category) { + push.apply(methodNames, getMethodsByCategory(source, category)); + }); + + // convert aliases to real method names + methodNames = methodNames.map(getRealName); + + // remove nonexistent and duplicate method names + return _.uniq(_.intersection(allMethods, methodNames)); + } + + /** + * Removes all `argsAreObjects` references from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeArgsAreObjects(source) { + source = removeVar(source, 'argsAreObjects'); + + // remove `argsAreObjects` from `_.isArray` + source = source.replace(matchFunction(source, 'isArray'), function(match) { + return match.replace(/\(argsAreObjects && *([^)]+)\)/g, '$1'); + }); + + // remove `argsAreObjects` from `_.isEqual` + source = source.replace(matchFunction(source, 'isEqual'), function(match) { + return match.replace(/!argsAreObjects[^:]+:\s*/g, ''); + }); + + return source; + } + + /** + * Removes the all references to `varName` from `createIterator` in `source`. + * + * @private + * @param {String} source The source to process. + * @param {String} varName The name of the variable to remove. + * @returns {String} Returns the modified source. + */ + function removeFromCreateIterator(source, varName) { + var snippet = matchFunction(source, 'createIterator'); + if ( snippet) { + // remove data object property assignment + var modified = snippet.replace(RegExp("^ *'" + varName + "': *" + varName + '.+\\n', 'm'), ''); + source = source.replace(snippet, modified); + + // clip at the `factory` assignment + snippet = modified.match(/Function\([\s\S]+$/)[0]; + + modified = snippet + .replace(RegExp('\\b' + varName + '\\b,? *', 'g'), '') + .replace(/, *',/, "',") + .replace(/,\s*\)/, ')') + + source = source.replace(snippet, modified); + } + return source; + } + + /** + * Removes the `funcName` function declaration, expression, or assignment and + * associated code from `source`. + * + * @private + * @param {String} source The source to process. + * @param {String} funcName The name of the function to remove. + * @returns {String} Returns the modified source. + */ + function removeFunction(source, funcName) { + // remove function + var snippet = matchFunction(source, funcName); + if (snippet) { + source = source.replace(snippet, ''); + } + // grab the method assignments snippet + snippet = getMethodAssignments(source); + + // remove assignment and aliases + var modified = getAliases(funcName).concat(funcName).reduce(function(result, otherName) { + return result.replace(RegExp('(?:\\n *//.*\\s*)* *lodash\\.' + otherName + ' *= *.+\\n'), ''); + }, snippet); + + // replace with the modified snippet + source = source.replace(snippet, modified); + + return removeFromCreateIterator(source, funcName); + } + + /** + * Removes all `hasDontEnumBug` references from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeHasDontEnumBug(source) { + source = removeFromCreateIterator(source, 'hasDontEnumBug'); + source = removeFromCreateIterator(source, 'shadowed'); + + // remove `hasDontEnumBug` declaration and assignment + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *var hasDontEnumBug\b.*|.+?hasDontEnumBug *=.+/g, ''); + + // remove `shadowed` variable + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *var shadowed[\s\S]+?;\n/, ''); + + // remove `hasDontEnumBug` from `iteratorTemplate` + source = source.replace(getIteratorTemplate(source), function(match) { + return match.replace(/(?: *\/\/.*\n)* *["']( *)<% *if *\(hasDontEnumBug[\s\S]+?["']\1<% *} *%>.+/, ''); + }); + + return source; + } + + /** + * Removes all `hasEnumPrototype` references from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeHasEnumPrototype(source) { + source = removeFromCreateIterator(source, 'hasEnumPrototype'); + + // remove `hasEnumPrototype` declaration and assignment + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *var hasEnumPrototype\b.*|.+?hasEnumPrototype *=.+/g, ''); + + // remove `hasEnumPrototype` from `_.keys` + source = source.replace(matchFunction(source, 'keys'), function(match) { + return match + .replace(/\(hasEnumPrototype[^)]+\)(?:\s*\|\|\s*)?/, '') + .replace(/\s*if *\(\s*\)[^}]+}/, ''); + }); + + // remove `hasEnumPrototype` from `iteratorTemplate` + source = source.replace(getIteratorTemplate(source), function(match) { + return match + .replace(/(?: *\/\/.*\n)* *["'] *(?:<% *)?if *\(hasEnumPrototype *(?:&&|\))[\s\S]+?<% *} *(?:%>|["']).+/g, '') + .replace(/hasEnumPrototype *\|\|\s*/g, ''); + }); + + return source; + } + + /** + * Removes the `_.isArguments` fallback from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeIsArgumentsFallback(source) { + return source.replace(getIsArgumentsFallback(source), ''); + } + + /** + * Removes the `_.isFunction` fallback from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeIsFunctionFallback(source) { + return source.replace(getIsFunctionFallback(source), ''); + } + + /** + * Removes all `iteratesOwnLast` references from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeIteratesOwnLast(source) { + // remove `iteratesOwnLast` declaration and assignment + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *var iteratesOwnLast\b.*|.+?iteratesOwnLast *=.+/g, ''); + + // remove `iteratesOwnLast` from `shimIsPlainObject` + source = source.replace(matchFunction(source, 'shimIsPlainObject'), function(match) { + return match.replace(/(?:\s*\/\/.*)*\n( *)if *\(iteratesOwnLast[\s\S]+?\n\1}/, ''); + }); + + return source; + } + + /** + * Removes the `Object.keys` object iteration optimization from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeKeysOptimization(source) { + source = removeVar(source, 'isKeysFast'); + + // remove optimized branch in `iteratorTemplate` + source = source.replace(getIteratorTemplate(source), function(match) { + return match.replace(/(?: *\/\/.*\n)* *["']( *)<% *if *\(isKeysFast[\s\S]+?["']\1<% *} *else *{ *%>.+\n([\s\S]+?) *["']\1<% *} *%>.+/, "'\\n' +\n$2"); + }); + + return source; + } + + /** + * Removes all `noArgsClass` references from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeNoArgsClass(source) { + source = removeVar(source, 'noArgsClass'); + + // replace `noArgsClass` in the `_.isArguments` fallback + source = source.replace(getIsArgumentsFallback(source), function(match) { + return match.replace(/noArgsClass/g, '!isArguments(arguments)'); + }); + + // remove `noArgsClass` from `_.isEmpty` + source = source.replace(matchFunction(source, 'isEmpty'), function(match) { + return match.replace(/ *\|\|\s*\(noArgsClass *&&[^)]+?\)\)/g, ''); + }); + + return source; + } + + /** + * Removes all `noCharByIndex` references from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeNoCharByIndex(source) { + source = removeVar(source, 'noCharByIndex'); + + // remove `noCharByIndex` from `_.at` + source = source.replace(matchFunction(source, 'at'), function(match) { + return match.replace(/^ *if *\(noCharByIndex[^}]+}\n/m, ''); + }); + + // remove `noCharByIndex` from `_.reduceRight` + source = source.replace(matchFunction(source, 'reduceRight'), function(match) { + return match.replace(/}\s*else if *\(noCharByIndex[^}]+/, ''); + }); + + // remove `noCharByIndex` from `_.toArray` + source = source.replace(matchFunction(source, 'toArray'), function(match) { + return match.replace(/noCharByIndex[^:]+:/, ''); + }); + + // `noCharByIndex` from `iteratorTemplate` + source = source.replace(getIteratorTemplate(source), function(match) { + return match + .replace(/'if *\(<%= *arrays *%>[^']*/, '$&\\n') + .replace(/(?: *\/\/.*\n)* *["']( *)<% *if *\(noCharByIndex[\s\S]+?["']\1<% *} *%>.+/, ''); + }); + + return source; + } + + /** + * Removes all `nonEnumArgs` references from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeNonEnumArgs(source) { + source = removeFromCreateIterator(source, 'nonEnumArgs'); + + // remove `nonEnumArgs` declaration and assignment + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *var nonEnumArgs\b.*|.+?nonEnumArgs *=.+/g, ''); + + // remove `nonEnumArgs` from `_.keys` + source = source.replace(matchFunction(source, 'keys'), function(match) { + return match + .replace(/(?:\s*\|\|\s*)?\(nonEnumArgs[^)]+\)\)/, '') + .replace(/\s*if *\(\s*\)[^}]+}/, ''); + }); + + // remove `nonEnumArgs` from `iteratorTemplate` + source = source.replace(getIteratorTemplate(source), function(match) { + return match + .replace(/(?: *\/\/.*\n)*( *["'] *)<% *} *else *if *\(nonEnumArgs[\s\S]+?(\1<% *} *%>.+)/, '$2') + .replace(/ *\|\|\s*nonEnumArgs/, ''); + }); + + return source; + } + + /** + * Removes all `noNodeClass` references from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeNoNodeClass(source) { + // remove `noNodeClass` assignment + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *try *{(?:\s*\/\/.*)*\n *var noNodeClass[\s\S]+?catch[^}]+}\n/, ''); + + // remove `noNodeClass` from `shimIsPlainObject` + source = source.replace(matchFunction(source, 'shimIsPlainObject'), function(match) { + return match.replace(/ *&& *\(!noNodeClass[\s\S]+?\)\)/, ''); + }); + + // remove `noNodeClass` from `_.clone` + source = source.replace(matchFunction(source, 'clone'), function(match) { + return match.replace(/ *\|\|\s*\(noNodeClass[\s\S]+?\)\)/, ''); + }); + + // remove `noNodeClass` from `_.isEqual` + source = source.replace(matchFunction(source, 'isEqual'), function(match) { + return match.replace(/ *\|\|\s*\(noNodeClass[\s\S]+?\)\)\)/, ''); + }); + + return source; + } + + /** + * Removes all `hasObjectSpliceByg` references from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeHasObjectSpliceBug(source) { + return removeVar(source, 'hasObjectSpliceBug') + // remove `hasObjectSpliceBug` fix from the `Array` function mixins + .replace(/(?:\s*\/\/.*)*\n( *)if *\(hasObjectSpliceBug[\s\S]+?(?:{\s*}|\n\1})/, ''); + } + + /** + * Removes the `setImmediate` fork of `_.defer`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeSetImmediate(source) { + return source.replace(/(?:\s*\/\/.*)*\n( *)if *\(isV8 *&& *freeModule[\s\S]+?\n\1}/, ''); + } + + /** + * Removes a given variable from `source`. + * + * @private + * @param {String} source The source to process. + * @param {String} varName The name of the variable to remove. + * @returns {String} Returns the modified source. + */ + function removeVar(source, varName) { + // simplify `cloneableClasses`, `ctorByClass`, or `hasObjectSpliceBug` + if (/^(?:cloneableClasses|ctorByClass|hasObjectSpliceBug)$/.test(varName)) { + source = source.replace(RegExp('(var ' + varName + ' *=)[\\s\\S]+?\\n\\n'), '$1=null;\n\n'); + } + source = source.replace(RegExp( + // match multi-line comment block + '(?:\\n +/\\*[^*]*\\*+(?:[^/][^*]*\\*+)*/)?\\n' + + // match a variable declaration that's not part of a declaration list + '( *)var ' + varName + ' *= *(?:.+?(?:;|&&\\n[^;]+;)|(?:\\w+\\(|{)[\\s\\S]+?\\n\\1.+?;)\\n|' + + // match a variable in a declaration list + '\\n +' + varName + ' *=.+?,' + ), ''); + + // remove a varaible at the start of a variable declaration list + source = source.replace(RegExp('(var +)' + varName + ' *=.+?,\\s+'), '$1'); + + // remove a variable at the end of a variable declaration list + source = source.replace(RegExp(',\\s*' + varName + ' *=.+?;'), ';'); + + return removeFromCreateIterator(source, varName); + } + + /** + * Replaces the `funcName` function body in `source` with `funcValue`. + * + * @private + * @param {String} source The source to inspect. + * @param {String} varName The name of the function to replace. + * @returns {String} Returns the modified source. + */ + function replaceFunction(source, funcName, funcValue) { + var match = matchFunction(source, funcName); + if (match) { + // clip snippet after the JSDoc comment block + match = match.replace(/^\s*(?:\/\/.*|\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)\n/, ''); + source = source.replace(match, function() { + return funcValue.trimRight() + '\n'; + }); + } + return source; + } + + /** + * Replaces the `varName` variable declaration value in `source` with `varValue`. + * + * @private + * @param {String} source The source to inspect. + * @param {String} varName The name of the variable to replace. + * @returns {String} Returns the modified source. + */ + function replaceVar(source, varName, varValue) { + // replace a variable that's not part of a declaration list + var result = source.replace(RegExp( + '(( *)var ' + varName + ' *= *)' + + '(?:.+?;|(?:Function\\(.+?|.*?[^,])\\n[\\s\\S]+?\\n\\2.+?;)\\n' + ), function(match, captured) { + return captured + varValue + ';\n'; + }); + + if (source == result) { + // replace a varaible at the start or middle of a declaration list + result = source.replace(RegExp('((?:var|\\n) +' + varName + ' *=).+?,'), function(match, captured) { + return captured + ' ' + varValue + ','; + }); + } + if (source == result) { + // replace a variable at the end of a variable declaration list + result = source.replace(RegExp('(,\\s*' + varName + ' *=).+?;'), function(match, captured) { + return captured + ' ' + varValue + ';'; + }); + } + return result; + } + + /** + * Hard-codes the `strict` template option value for `iteratorTemplate`. + * + * @private + * @param {String} source The source to process. + * @param {Boolean} value The value to set. + * @returns {String} Returns the modified source. + */ + function setUseStrictOption(source, value) { + // inject or remove the "use strict" directive + source = source.replace(/^([\s\S]*?function[^{]+{)(?:\s*'use strict';)?/, '$1' + (value ? "\n 'use strict';" : '')); + + // replace `strict` branch in `iteratorTemplate` with hard-coded option + source = source.replace(getIteratorTemplate(source), function(match) { + return match.replace(/(template\()(?:\s*"'use strict.+)?/, '$1' + (value ? '\n "\'use strict\';\\n" +' : '')); + }); + + return source; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a debug and/or minified build, executing the `callback` for each. + * The `callback` is invoked with two arguments; (filePath, outputSource). + * + * Note: For a list of commands see `displayHelp()` or run `lodash --help`. + * + * @param {Array} [options=[]] An array of commands. + * @param {Function} callback The function called per build. + */ + function build(options, callback) { + options || (options = []); + + // the debug version of `source` + var debugSource; + + // used to specify the source map URL + var sourceMapURL; + + // used to report invalid command-line arguments + var invalidArgs = _.reject(options.slice(options[0] == 'node' ? 2 : 0), function(value, index, options) { + if (/^(?:-o|--output)$/.test(options[index - 1]) || + /^(?:category|exclude|exports|iife|include|moduleId|minus|plus|settings|template)=.*$/.test(value)) { + return true; + } + var result = [ + 'backbone', + 'csp', + 'legacy', + 'mobile', + 'modern', + 'modularize', + 'strict', + 'underscore', + '-c', '--stdout', + '-d', '--debug', + '-h', '--help', + '-m', '--minify', + '-o', '--output', + '-p', '--source-map', + '-s', '--silent', + '-V', '--version' + ].indexOf(value) > -1; + + if (!result && /^(?:-p|--source-map)$/.test(options[index - 1])) { + result = true; + sourceMapURL = value; + } + return result; + }); + + // report invalid arguments + if (invalidArgs.length) { + console.log( + '\n' + + 'Invalid argument' + (invalidArgs.length > 1 ? 's' : '') + + ' passed: ' + invalidArgs.join(', ') + ); + displayHelp(); + return; + } + + // display help message + if (_.find(options, function(arg) { + return /^(?:-h|--help)$/.test(arg); + })) { + displayHelp(); + return; + } + + // display `lodash.VERSION` + if (_.find(options, function(arg) { + return /^(?:-V|--version)$/.test(arg); + })) { + console.log(_.VERSION); + return; + } + + /*------------------------------------------------------------------------*/ + + // backup `dependencyMap` to restore later + var dependencyBackup = _.cloneDeep(dependencyMap); + + // used to specify a custom IIFE to wrap Lo-Dash + var iife = options.reduce(function(result, value) { + var match = value.match(/iife=(.*)/); + return match ? match[1] : result; + }, null); + + // the path to the source file + var filePath = path.join(__dirname, 'lodash.js'); + + // flag to specify a Backbone build + var isBackbone = options.indexOf('backbone') > -1; + + // flag to specify a Content Security Policy build + var isCSP = options.indexOf('csp') > -1 || options.indexOf('CSP') > -1; + + // flag to specify only creating the debug build + var isDebug = options.indexOf('-d') > -1 || options.indexOf('--debug') > -1; + + // flag to indicate that a custom IIFE was specified + var isIIFE = typeof iife == 'string'; + + // flag to specify creating a source map for the minified source + var isMapped = options.indexOf('-p') > -1 || options.indexOf('--source-map') > -1; + + // flag to specify only creating the minified build + var isMinify = options.indexOf('-m') > -1 || options.indexOf('--minify') > -1; + + // flag to specify a mobile build + var isMobile = isCSP || options.indexOf('mobile') > -1; + + // flag to specify a modern build + var isModern = isMobile || options.indexOf('modern') > -1; + + // flag to specify a modularize build + var isModularize = options.indexOf('modularize') > -1; + + // flag to specify writing output to standard output + var isStdOut = options.indexOf('-c') > -1 || options.indexOf('--stdout') > -1; + + // flag to specify skipping status updates normally logged to the console + var isSilent = isStdOut || options.indexOf('-s') > -1 || options.indexOf('--silent') > -1; + + // flag to specify `_.assign`, `_.bindAll`, and `_.defaults` are + // constructed using the "use strict" directive + var isStrict = options.indexOf('strict') > -1; + + // flag to specify an Underscore build + var isUnderscore = isBackbone || options.indexOf('underscore') > -1; + + // flag to specify a legacy build + var isLegacy = !(isModern || isUnderscore) && options.indexOf('legacy') > -1; + + // used to specify methods of specific categories + var categories = options.reduce(function(result, value) { + return /category/.test(value) ? optionToArray(value) : result; + }, []); + + // used to specify the ways to export the `lodash` function + var exportsOptions = options.reduce(function(result, value) { + return /exports/.test(value) ? optionToArray(value).sort() : result; + }, isUnderscore + ? ['commonjs', 'global', 'node'] + : exportsAll.slice() + ); + + // used to specify the AMD module ID of Lo-Dash used by precompiled templates + var moduleId = options.reduce(function(result, value) { + var match = value.match(/moduleId=(.*)/); + return match ? match[1] : result; + }, 'lodash'); + + // used to specify the output path for builds + var outputPath = options.reduce(function(result, value, index) { + if (/-o|--output/.test(value)) { + result = options[index + 1]; + result = path.join(fs.realpathSync(path.dirname(result)), path.basename(result)); + } + return result; + }, ''); + + // used to match external template files to precompile + var templatePattern = options.reduce(function(result, value) { + var match = value.match(/template=(.+)$/); + return match + ? path.join(fs.realpathSync(path.dirname(match[1])), path.basename(match[1])) + : result; + }, ''); + + // used when precompiling template files + var templateSettings = options.reduce(function(result, value) { + var match = value.match(/settings=(.+)$/); + return match + ? _.assign(result, Function('return {' + match[1].replace(/^{|}$/g, '') + '}')()) + : result; + }, _.assign(_.clone(_.templateSettings), { + 'moduleId': moduleId + })); + + // flag to specify a template build + var isTemplate = !!templatePattern; + + // the lodash.js source + var source = fs.readFileSync(filePath, 'utf8'); + + // flag to specify replacing Lo-Dash's `_.clone` with Underscore's + var useUnderscoreClone = isUnderscore; + + // flags to specify exposing Lo-Dash methods in an Underscore build + var exposeAssign = !isUnderscore, + exposeForIn = !isUnderscore, + exposeForOwn = !isUnderscore, + exposeIsPlainObject = !isUnderscore; + + // flags to specify export options + var isAMD = exportsOptions.indexOf('amd') > -1, + isCommonJS = exportsOptions.indexOf('commonjs') > -1, + isGlobal = exportsOptions.indexOf('global') > -1, + isNode = exportsOptions.indexOf('node') > -1; + + /*------------------------------------------------------------------------*/ + + // names of methods to include in the build + var buildMethods = !isTemplate && (function() { + var result; + + var includeMethods = options.reduce(function(accumulator, value) { + return /include/.test(value) + ? _.union(accumulator, optionToMethodsArray(source, value)) + : accumulator; + }, []); + + var minusMethods = options.reduce(function(accumulator, value) { + return /exclude|minus/.test(value) + ? _.union(accumulator, optionToMethodsArray(source, value)) + : accumulator; + }, []); + + var plusMethods = options.reduce(function(accumulator, value) { + return /plus/.test(value) + ? _.union(accumulator, optionToMethodsArray(source, value)) + : accumulator; + }, []); + + // set flags to include Lo-Dash's methods if explicitly requested + if (isUnderscore) { + var methods = _.without.apply(_, [_.union(includeMethods, plusMethods)].concat(minusMethods)); + exposeAssign = methods.indexOf('assign') > -1; + exposeForIn = methods.indexOf('forIn') > -1; + exposeForOwn = methods.indexOf('forOwn') > -1; + exposeIsPlainObject = methods.indexOf('isPlainObject') > -1; + + methods = _.without.apply(_, [plusMethods].concat(minusMethods)); + useUnderscoreClone = methods.indexOf('clone') < 0; + } + // update dependencies + if (isLegacy) { + dependencyMap.defer = _.without(dependencyMap.defer, 'bind'); + } + if (isUnderscore) { + dependencyMap.contains = _.without(dependencyMap.contains, 'isString'); + dependencyMap.countBy = _.without(dependencyMap.countBy, 'isEqual', 'keys'); + dependencyMap.every = _.without(dependencyMap.every, 'isEqual', 'keys'); + dependencyMap.filter = _.without(dependencyMap.filter, 'isEqual'); + dependencyMap.find = _.without(dependencyMap.find, 'isEqual', 'keys'); + dependencyMap.groupBy = _.without(dependencyMap.groupBy, 'isEqual', 'keys'); + dependencyMap.isEqual = _.without(dependencyMap.isEqual, 'forIn', 'isArguments'); + dependencyMap.isEmpty = ['isArray', 'isString']; + dependencyMap.map = _.without(dependencyMap.map, 'isEqual', 'keys'); + dependencyMap.max = _.without(dependencyMap.max, 'isEqual', 'isString', 'keys'); + dependencyMap.min = _.without(dependencyMap.min, 'isEqual', 'isString', 'keys'); + dependencyMap.pick = _.without(dependencyMap.pick, 'forIn', 'isObject'); + dependencyMap.reduce = _.without(dependencyMap.reduce, 'isEqual', 'keys'); + dependencyMap.reject = _.without(dependencyMap.reject, 'isEqual', 'keys'); + dependencyMap.some = _.without(dependencyMap.some, 'isEqual', 'keys'); + dependencyMap.sortBy = _.without(dependencyMap.sortBy, 'isEqual', 'keys'); + dependencyMap.sortedIndex = _.without(dependencyMap.sortedIndex, 'isEqual', 'keys'); + dependencyMap.template = _.without(dependencyMap.template, 'keys', 'values'); + dependencyMap.uniq = _.without(dependencyMap.uniq, 'isEqual', 'keys'); + dependencyMap.where.push('find', 'isEmpty'); + + if (useUnderscoreClone) { + dependencyMap.clone = _.without(dependencyMap.clone, 'forEach', 'forOwn'); + } + } + if (isModern || isUnderscore) { + dependencyMap.reduceRight = _.without(dependencyMap.reduceRight, 'isEqual', 'isString'); + } + + // add method names explicitly + if (includeMethods.length) { + result = getDependencies(includeMethods); + } + // add method names required by Backbone and Underscore builds + if (isBackbone && !result) { + result = getDependencies(backboneDependencies); + } + else if (isUnderscore && !result) { + result = getDependencies(underscoreMethods); + } + // add method names by category + if (categories.length) { + result = _.union(result || [], getDependencies(categories.reduce(function(accumulator, category) { + // resolve method names belonging to each category (case-insensitive) + return accumulator.concat(getMethodsByCategory(source, capitalize(category))); + }, []))); + } + if (!result) { + result = allMethods.slice(); + } + if (plusMethods.length) { + result = _.union(result, getDependencies(plusMethods)); + } + if (minusMethods.length) { + result = _.without.apply(_, [result].concat(minusMethods, getDependants(minusMethods))); + } + return result; + }()); + + /*------------------------------------------------------------------------*/ + + // load customized Lo-Dash module + var lodash = !isTemplate && (function() { + var context = vm.createContext({ + 'clearTimeout': clearTimeout, + 'console': console, + 'setTimeout': setTimeout + }); + + source = setUseStrictOption(source, isStrict); + + if (isLegacy) { + _.each(['getPrototypeOf', 'isBindFast', 'isKeysFast', 'nativeBind', 'nativeIsArray', 'nativeKeys'], function(varName) { + source = replaceVar(source, varName, 'false'); + }); + + source = replaceVar(source, 'noArgsClass', 'true'); + source = removeKeysOptimization(source); + } + if (isMobile || isUnderscore) { + source = removeKeysOptimization(source); + } + if (isModern || isUnderscore) { + source = removeHasDontEnumBug(source); + source = removeHasEnumPrototype(source); + source = removeIteratesOwnLast(source); + source = removeNoCharByIndex(source); + source = removeNoNodeClass(source); + + if (!isMobile) { + source = removeNonEnumArgs(source); + } + } + if (isModern) { + // remove `_.isPlainObject` fallback + source = source.replace(matchFunction(source, 'isPlainObject'), function(match) { + return match.replace(/!getPrototypeOf.+?: */, ''); + }); + } + if (isUnderscore) { + // replace `_.assign` + source = replaceFunction(source, 'assign', [ + ' function assign(object) {', + ' if (!object) {', + ' return object;', + ' }', + ' for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {', + ' var iterable = arguments[argsIndex];', + ' if (iterable) {', + ' for (var key in iterable) {', + ' object[key] = iterable[key];', + ' }', + ' }', + ' }', + ' return object;', + ' }' + ].join('\n')); + + // replace `_.clone` + if (useUnderscoreClone) { + source = replaceFunction(source, 'clone', [ + ' function clone(value) {', + ' return isObject(value)', + ' ? (isArray(value) ? slice(value) : assign({}, value))', + ' : value', + ' }' + ].join('\n')); + } + + // replace `_.contains` + source = replaceFunction(source, 'contains', [ + ' function contains(collection, target) {', + ' var length = collection ? collection.length : 0,', + ' result = false;', + " if (typeof length == 'number') {", + ' result = indexOf(collection, target) > -1;', + ' } else {', + ' each(collection, function(value) {', + ' return (result = value === target) && indicatorObject;', + ' });', + ' }', + ' return result;', + ' }' + ].join('\n')); + + // replace `_.defaults` + source = replaceFunction(source, 'defaults', [ + ' function defaults(object) {', + ' if (!object) {', + ' return object;', + ' }', + ' for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {', + ' var iterable = arguments[argsIndex];', + ' if (iterable) {', + ' for (var key in iterable) {', + ' if (object[key] == null) {', + ' object[key] = iterable[key];', + ' }', + ' }', + ' }', + ' }', + ' return object;', + ' }' + ].join('\n')); + + // replace `_.difference` + source = replaceFunction(source, 'difference', [ + ' function difference(array) {', + ' var index = -1,', + ' length = array.length,', + ' flattened = concat.apply(arrayRef, arguments),', + ' result = [];', + '', + ' while (++index < length) {', + ' var value = array[index]', + ' if (indexOf(flattened, value, length) < 0) {', + ' result.push(value);', + ' }', + ' }', + ' return result', + ' }' + ].join('\n')); + + // replace `_.intersection` + source = replaceFunction(source, 'intersection', [ + ' function intersection(array) {', + ' var args = arguments,', + ' argsLength = args.length,', + ' index = -1,', + ' length = array ? array.length : 0,', + ' result = [];', + '', + ' outer:', + ' while (++index < length) {', + ' var value = array[index];', + ' if (indexOf(result, value) < 0) {', + ' var argsIndex = argsLength;', + ' while (--argsIndex) {', + ' if (indexOf(args[argsIndex], value) < 0) {', + ' continue outer;', + ' }', + ' }', + ' result.push(value);', + ' }', + ' }', + ' return result;', + ' }' + ].join('\n')); + + // replace `_.isEmpty` + source = replaceFunction(source, 'isEmpty', [ + ' function isEmpty(value) {', + ' if (!value) {', + ' return true;', + ' }', + ' if (isArray(value) || isString(value)) {', + ' return !value.length;', + ' }', + ' for (var key in value) {', + ' if (hasOwnProperty.call(value, key)) {', + ' return false;', + ' }', + ' }', + ' return true;', + ' }' + ].join('\n')); + + // replace `_.isEqual` + source = replaceFunction(source, 'isEqual', [ + ' function isEqual(a, b, stackA, stackB) {', + ' if (a === b) {', + ' return a !== 0 || (1 / a == 1 / b);', + ' }', + ' var type = typeof a,', + ' otherType = typeof b;', + '', + ' if (a === a &&', + " (!a || (type != 'function' && type != 'object')) &&", + " (!b || (otherType != 'function' && otherType != 'object'))) {", + ' return false;', + ' }', + ' if (a == null || b == null) {', + ' return a === b;', + ' }', + ' var className = toString.call(a),', + ' otherClass = toString.call(b);', + '', + ' if (className != otherClass) {', + ' return false;', + ' }', + ' switch (className) {', + ' case boolClass:', + ' case dateClass:', + ' return +a == +b;', + '', + ' case numberClass:', + ' return a != +a', + ' ? b != +b', + ' : (a == 0 ? (1 / a == 1 / b) : a == +b);', + '', + ' case regexpClass:', + ' case stringClass:', + " return a == b + '';", + ' }', + ' var isArr = className == arrayClass;', + ' if (!isArr) {', + ' if (a.__wrapped__ || b.__wrapped__) {', + ' return isEqual(a.__wrapped__ || a, b.__wrapped__ || b, stackA, stackB);', + ' }', + ' if (className != objectClass) {', + ' return false;', + ' }', + ' var ctorA = a.constructor,', + ' ctorB = b.constructor;', + '', + ' if (ctorA != ctorB && !(', + ' isFunction(ctorA) && ctorA instanceof ctorA &&', + ' isFunction(ctorB) && ctorB instanceof ctorB', + ' )) {', + ' return false;', + ' }', + ' }', + ' stackA || (stackA = []);', + ' stackB || (stackB = []);', + '', + ' var length = stackA.length;', + ' while (length--) {', + ' if (stackA[length] == a) {', + ' return stackB[length] == b;', + ' }', + ' }', + ' var result = true,', + ' size = 0;', + '', + ' stackA.push(a);', + ' stackB.push(b);', + '', + ' if (isArr) {', + ' size = b.length;', + ' result = size == a.length;', + '', + ' if (result) {', + ' while (size--) {', + ' if (!(result = isEqual(a[size], b[size], stackA, stackB))) {', + ' break;', + ' }', + ' }', + ' }', + ' return result;', + ' }', + ' forIn(b, function(value, key, b) {', + ' if (hasOwnProperty.call(b, key)) {', + ' size++;', + ' return !(result = hasOwnProperty.call(a, key) && isEqual(a[key], value, stackA, stackB)) && indicatorObject;', + ' }', + ' });', + '', + ' if (result) {', + ' forIn(a, function(value, key, a) {', + ' if (hasOwnProperty.call(a, key)) {', + ' return !(result = --size > -1) && indicatorObject;', + ' }', + ' });', + ' }', + ' return result;', + ' }' + ].join('\n')); + + // replace `_.omit` + source = replaceFunction(source, 'omit', [ + ' function omit(object) {', + ' var props = concat.apply(arrayRef, arguments),', + ' result = {};', + '', + ' forIn(object, function(value, key) {', + ' if (indexOf(props, key, 1) < 0) {', + ' result[key] = value;', + ' }', + ' });', + ' return result;', + ' }' + ].join('\n')); + + // replace `_.pick` + source = replaceFunction(source, 'pick', [ + ' function pick(object) {', + ' var index = 0,', + ' props = concat.apply(arrayRef, arguments),', + ' length = props.length,', + ' result = {};', + '', + ' while (++index < length) {', + ' var prop = props[index];', + ' if (prop in object) {', + ' result[prop] = object[prop];', + ' }', + ' }', + ' return result;', + ' }' + ].join('\n')); + + // replace `_.result` + source = replaceFunction(source, 'result', [ + ' function result(object, property) {', + ' var value = object ? object[property] : null;', + ' return isFunction(value) ? object[property]() : value;', + ' }' + ].join('\n')); + + // replace `_.template` + source = replaceFunction(source, 'template', [ + ' function template(text, data, options) {', + " text || (text = '');", + ' options = defaults({}, options, lodash.templateSettings);', + '', + ' var index = 0,', + ' source = "__p += \'",', + ' variable = options.variable;', + '', + ' var reDelimiters = RegExp(', + " (options.escape || reNoMatch).source + '|' +", + " (options.interpolate || reNoMatch).source + '|' +", + " (options.evaluate || reNoMatch).source + '|$'", + " , 'g');", + '', + ' text.replace(reDelimiters, function(match, escapeValue, interpolateValue, evaluateValue, offset) {', + ' source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);', + ' if (escapeValue) {', + ' source += "\' +\\n_.escape(" + escapeValue + ") +\\n\'";', + ' }', + ' if (evaluateValue) {', + ' source += "\';\\n" + evaluateValue + ";\\n__p += \'";', + ' }', + ' if (interpolateValue) {', + ' source += "\' +\\n((__t = (" + interpolateValue + ")) == null ? \'\' : __t) +\\n\'";', + ' }', + ' index = offset + match.length;', + ' return match;', + ' });', + '', + ' source += "\';\\n";', + ' if (!variable) {', + " variable = 'obj';", + " source = 'with (' + variable + ' || {}) {\\n' + source + '\\n}\\n';", + ' }', + " source = 'function(' + variable + ') {\\n' +", + ' "var __t, __p = \'\', __j = Array.prototype.join;\\n" +', + ' "function print() { __p += __j.call(arguments, \'\') }\\n" +', + ' source +', + " 'return __p\\n}';", + '', + ' try {', + " var result = Function('_', 'return ' + source)(lodash);", + ' } catch(e) {', + ' e.source = source;', + ' throw e;', + ' }', + ' if (data) {', + ' return result(data);', + ' }', + ' result.source = source;', + ' return result;', + ' }' + ].join('\n')); + + // replace `_.uniq` + source = replaceFunction(source, 'uniq', [ + ' function uniq(array, isSorted, callback, thisArg) {', + ' var index = -1,', + ' length = array ? array.length : 0,', + ' result = [],', + ' seen = result;', + '', + " if (typeof isSorted == 'function') {", + ' thisArg = callback;', + ' callback = isSorted;', + ' isSorted = false;', + ' }', + ' if (callback) {', + ' seen = [];', + ' callback = createCallback(callback, thisArg);', + ' }', + ' while (++index < length) {', + ' var value = array[index],', + ' computed = callback ? callback(value, index, array) : value;', + '', + ' if (isSorted', + ' ? !index || seen[seen.length - 1] !== computed', + ' : indexOf(seen, computed) < 0', + ' ) {', + ' if (callback) {', + ' seen.push(computed);', + ' }', + ' result.push(value);', + ' }', + ' }', + ' return result;', + ' }' + ].join('\n')); + + // replace `_.uniqueId` + source = replaceFunction(source, 'uniqueId', [ + ' function uniqueId(prefix) {', + " var id = ++idCounter + '';", + ' return prefix ? prefix + id : id;', + ' }' + ].join('\n')); + + // replace `_.where` + source = replaceFunction(source, 'where', [ + ' function where(collection, properties, first) {', + ' return (first && isEmpty(properties))', + ' ? null', + ' : (first ? find : filter)(collection, properties);', + ' }' + ].join('\n')); + + // replace `_.without` + source = replaceFunction(source, 'without', [ + ' function without(array) {', + ' var index = -1,', + ' length = array.length,', + ' result = [];', + '', + ' while (++index < length) {', + ' var value = array[index]', + ' if (indexOf(arguments, value, 1) < 0) {', + ' result.push(value);', + ' }', + ' }', + ' return result', + ' }' + ].join('\n')); + + // add `_.findWhere` + source = source.replace(matchFunction(source, 'find'), function (match) { + return match + [ + '', + ' function findWhere(object, properties) {', + ' return where(object, properties, true);', + ' }', + '' + ].join('\n') + }); + + source = source.replace(getMethodAssignments(source), function(match) { + return match.replace(/^( *)lodash.find *=.+/m, '$&\n$1lodash.findWhere = findWhere;'); + }); + + // add Underscore style chaining + source = addChainMethods(source); + + // remove `_.templateSettings.imports assignment + source = source.replace(/,[^']*'imports':[^}]+}/, ''); + + // remove large array optimizations + source = removeFunction(source, 'cachedContains'); + source = removeVar(source, 'largeArraySize'); + + // remove `_.isEqual` use from `createCallback` + source = source.replace(matchFunction(source, 'createCallback'), function(match) { + return match.replace(/isEqual\(([^,]+), *([^,]+)[^)]+\)/, '$1 === $2'); + }); + + // remove conditional `charCodeCallback` use from `_.max` and `_.min` + _.each(['max', 'min'], function(methodName) { + source = source.replace(matchFunction(source, methodName), function(match) { + return match.replace(/!callback *&& *isString\(collection\)[\s\S]+?: */g, ''); + }); + }); + + // remove unneeded variables + if (useUnderscoreClone) { + source = removeVar(source, 'cloneableClasses'); + source = removeVar(source, 'ctorByClass'); + } + // remove unused features from `createBound` + if (buildMethods.indexOf('partial') < 0 && buildMethods.indexOf('partialRight') < 0) { + source = source.replace(matchFunction(source, 'createBound'), function(match) { + return match + .replace(/, *right[^)]*/, '') + .replace(/(function createBound\([^{]+{)[\s\S]+?(\n *function bound)/, '$1$2') + .replace(/thisBinding *=[^}]+}/, 'thisBinding = thisArg;\n') + .replace(/\(args *=.+/, 'partialArgs.concat(slice(args))'); + }); + } + } + vm.runInContext(source, context); + return context._; + }()); + + /*------------------------------------------------------------------------*/ + + if (isTemplate) { + source = buildTemplate(templatePattern, templateSettings); + } + else { + // remove methods from the build + allMethods.forEach(function(otherName) { + if (!_.contains(buildMethods, otherName)) { + source = removeFunction(source, otherName); + } + }); + + // remove `isArguments` fallback before `isArguments` is transformed by + // other parts of the build process + if (isRemoved(source, 'isArguments')) { + source = removeIsArgumentsFallback(source); + } + + // remove `iteratorTemplate` dependency checks from `_.template` + source = source.replace(matchFunction(source, 'template'), function(match) { + return match + .replace(/iteratorTemplate *&& */g, '') + .replace(/iteratorTemplate *\? *([^:]+?) *:[^,;]+/g, '$1'); + }); + + /*----------------------------------------------------------------------*/ + + if (isLegacy) { + source = removeSetImmediate(source); + + _.each(['isBindFast', 'isV8', 'nativeBind', 'nativeIsArray', 'nativeKeys', 'reNative'], function(varName) { + source = removeVar(source, varName); + }); + + // remove native `Function#bind` branch in `_.bind` + source = source.replace(matchFunction(source, 'bind'), function(match) { + return match.replace(/(?:\s*\/\/.*)*\s*return isBindFast[^:]+:\s*/, 'return '); + }); + + // remove native `Array.isArray` branch in `_.isArray` + source = source.replace(matchFunction(source, 'isArray'), function(match) { + return match.replace(/nativeIsArray * \|\|\s*/, ''); + }); + + // replace `_.keys` with `shimKeys` + if (!isRemoved(source, 'keys')) { + source = source.replace( + matchFunction(source, 'keys').replace(/[\s\S]+?var keys *= */, ''), + matchFunction(source, 'shimKeys').replace(/[\s\S]+?function shimKeys/, 'function').replace(/}\n$/, '};\n') + ); + + source = removeFunction(source, 'shimKeys'); + } + // replace `_.isArguments` with fallback + if (!isRemoved(source, 'isArguments')) { + source = source.replace( + matchFunction(source, 'isArguments').replace(/[\s\S]+?function isArguments/, ''), + getIsArgumentsFallback(source).match(/isArguments *= *function([\s\S]+?) *};/)[1] + ' }\n' + ); + + source = removeIsArgumentsFallback(source); + } + } + if (isModern) { + source = removeArgsAreObjects(source); + source = removeHasObjectSpliceBug(source); + source = removeIsArgumentsFallback(source); + } + if (isModern || isUnderscore) { + source = removeNoArgsClass(source); + source = removeNoNodeClass(source); + } + if (isMobile || isUnderscore) { + source = removeVar(source, 'iteratorTemplate'); + + // inline all functions defined with `createIterator` + _.functions(lodash).forEach(function(methodName) { + // strip leading underscores to match pseudo private functions + var reFunc = RegExp('(\\bvar ' + methodName.replace(/^_/, '') + ' *= *)createIterator\\(((?:{|[a-zA-Z])[\\s\\S]+?)\\);\\n'); + if (reFunc.test(source)) { + // extract, format, and inject the compiled function's source code + source = source.replace(reFunc, function(match, captured) { + return captured + getFunctionSource(lodash[methodName]) + ';\n'; + }); + } + }); + } + if (isUnderscore) { + // remove `_.assign`, `_.forIn`, `_.forOwn`, and `_.isPlainObject` assignments + (function() { + var snippet = getMethodAssignments(source), + modified = snippet; + + if (!exposeAssign) { + modified = modified.replace(/^(?: *\/\/.*\s*)* *lodash\.assign *= *.+\n/m, ''); + } + if (!exposeForIn) { + modified = modified.replace(/^(?: *\/\/.*\s*)* *lodash\.forIn *= *.+\n/m, ''); + } + if (!exposeForOwn) { + modified = modified.replace(/^(?: *\/\/.*\s*)* *lodash\.forOwn *= *.+\n/m, ''); + } + if (!exposeIsPlainObject) { + modified = modified.replace(/^(?: *\/\/.*\s*)* *lodash\.isPlainObject *= *.+\n/m, ''); + } + source = source.replace(snippet, modified); + }()); + + // remove `thisArg` from unexposed `forIn` and `forOwn` + _.each([ + { 'methodName': 'forIn', 'flag': exposeForIn }, + { 'methodName': 'forOwn', 'flag': exposeForOwn } + ], function(data) { + if (!data.flag) { + source = source.replace(matchFunction(source, data.methodName), function(match) { + return match + .replace(/(callback), *thisArg/g, '$1') + .replace(/^( *)callback *=.+/m, '$1callback || (callback = identity);') + }); + } + }); + + // remove chainability from `each` and `_.forEach` + _.each(['each', 'forEach'], function(methodName) { + source = source.replace(matchFunction(source, methodName), function(match) { + return match.replace(/\n *return .+?([};\s]+)$/, '$1'); + }); + }); + + // unexpose "exit early" feature of `each`, `_.forEach`, `_.forIn`, and `_.forOwn` + _.each(['each', 'forEach', 'forIn', 'forOwn'], function(methodName) { + source = source.replace(matchFunction(source, methodName), function(match) { + return match.replace(/=== *false\)/g, '=== indicatorObject)'); + }); + }); + + // modify `_.every`, `_.find`, `_.isEqual`, and `_.some` to use the private `indicatorObject` + _.each(['every', 'isEqual'], function(methodName) { + source = source.replace(matchFunction(source, methodName), function(match) { + return match.replace(/\(result *= *(.+?)\);/g, '!(result = $1) && indicatorObject;'); + }); + }); + + source = source.replace(matchFunction(source, 'find'), function(match) { + return match.replace(/return false/, 'return indicatorObject'); + }); + + source = source.replace(matchFunction(source, 'some'), function(match) { + return match.replace(/!\(result *= *(.+?)\);/, '(result = $1) && indicatorObject;'); + }); + } + if (!(isMobile || isUnderscore)) { + // inline `iteratorTemplate` template + source = source.replace(getIteratorTemplate(source), function() { + var snippet = getFunctionSource(lodash._iteratorTemplate); + + // prepend data object references to property names to avoid having to + // use a with-statement + iteratorOptions.forEach(function(property) { + snippet = snippet.replace(RegExp('([^\\w.])\\b' + property + '\\b', 'g'), '$1obj.' + property); + }); + + // remove unnecessary code + snippet = snippet + .replace(/var __t.+/, "var __p = '';") + .replace(/function print[^}]+}/, '') + .replace(/'(?:\\n|\s)+'/g, "''") + .replace(/__p *\+= *' *';/g, '') + .replace(/(__p *\+= *)' *' *\+/g, '$1') + .replace(/({) *;|; *(})/g, '$1$2') + .replace(/\(\(__t *= *\( *([^)]+) *\)\) *== *null *\? *'' *: *__t\)/g, '($1)'); + + // remove the with-statement + snippet = snippet.replace(/ *with *\(.+?\) *{/, '\n').replace(/}([^}]*}[^}]*$)/, '$1'); + + // minor cleanup + snippet = snippet + .replace(/obj *\|\|\s*\(obj *= *{}\);/, '') + .replace(/var __p = '';\s*__p \+=/, 'var __p ='); + + // remove comments, including sourceURLs + snippet = snippet.replace(/\s*\/\/.*(?:\n|$)/g, ''); + + return ' var iteratorTemplate = ' + snippet + ';\n'; + }); + } + } + + /*------------------------------------------------------------------------*/ + + // customize Lo-Dash's IIFE + (function() { + if (isIIFE) { + var token = '%output%', + index = iife.indexOf(token); + + source = source.match(/^\/\**[\s\S]+?\*\/\n/) + + iife.slice(0, index) + + source.replace(/^[\s\S]+?\(function[^{]+?{|}\(this\)\)[;\s]*$/g, '') + + iife.slice(index + token.length); + } + }()); + + /*------------------------------------------------------------------------*/ + + // customize Lo-Dash's export bootstrap + (function() { + if (!isAMD) { + source = source.replace(/(?: *\/\/.*\n)*( *)if *\(typeof +define[\s\S]+?else /, '$1'); + } + if (!isNode) { + source = source.replace(/(?: *\/\/.*\n)*( *)if *\(freeModule[\s\S]+?else *{([\s\S]+?\n)\1}\n/, '$1$2'); + } + if (!isCommonJS) { + source = source.replace(/(?: *\/\/.*\n)*(?:( *)else *{)?\s*freeExports\.\w+ *=[\s\S]+?(?:\n\1})?\n/, ''); + } + if (!isGlobal) { + source = source.replace(/(?:( *)(})? *else(?: *if *\(_\))? *{)?(?:\s*\/\/.*)*\s*(?:window\._|_\.templates) *=[\s\S]+?(?:\n\1})?\n/g, '$1$2\n'); + } + // remove `if (freeExports) {...}` if it's empty + if (isAMD && isGlobal) { + source = source.replace(/(?: *\/\/.*\n)* *(?:else )?if *\(freeExports\) *{\s*}\n/, ''); + } else { + source = source.replace(/(?: *\/\/.*\n)* *(?:else )?if *\(freeExports\) *{\s*}(?:\s*else *{([\s\S]+?) *})?\n/, '$1\n'); + } + }()); + + /*------------------------------------------------------------------------*/ + + if (!isTemplate) { + // modify/remove references to removed methods/variables + if (isRemoved(source, 'invert')) { + source = replaceVar(source, 'htmlUnescapes', "{'&':'&','<':'<','>':'>','"':'\"',''':\"'\"}"); + } + if (isRemoved(source, 'isArguments')) { + source = replaceVar(source, 'noArgsClass', 'false'); + } + if (isRemoved(source, 'isFunction')) { + source = removeIsFunctionFallback(source); + } + if (isRemoved(source, 'mixin')) { + source = removeHasObjectSpliceBug(source); + + // simplify the `lodash` function + source = replaceFunction(source, 'lodash', [ + ' function lodash() {', + ' // no operation performed', + ' }' + ].join('\n')); + + // remove all `lodash.prototype` additions + source = source + .replace(/(?:\s*\/\/.*)*\n( *)forOwn\(lodash, *function\(func, *methodName\)[\s\S]+?\n\1}.+/g, '') + .replace(/(?:\s*\/\/.*)*\n( *)each\(\['[\s\S]+?\n\1}.+/g, '') + .replace(/(?:\s*\/\/.*)*\s*lodash\.prototype.+\n/g, '') + .replace(/(?:\s*\/\/.*)*\s*mixin\(lodash\).+\n/, ''); + } + // remove functions, variables, and snippets that the minifier may miss + if (isRemoved(source, 'clone')) { + source = removeVar(source, 'cloneableClasses'); + source = removeVar(source, 'ctorByClass'); + } + if (isRemoved(source, 'isArray')) { + source = removeVar(source, 'nativeIsArray'); + } + if (isRemoved(source, 'isPlainObject')) { + source = removeVar(source, 'getPrototypeOf'); + source = removeIteratesOwnLast(source); + } + if (isRemoved(source, 'keys')) { + source = removeFunction(source, 'shimKeys'); + } + if (isRemoved(source, 'template')) { + // remove `templateSettings` assignment + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *lodash\.templateSettings[\s\S]+?};\n/, ''); + } + if (isRemoved(source, 'isArguments', 'isEmpty')) { + source = removeNoArgsClass(source); + } + if (isRemoved(source, 'clone', 'isEqual', 'isPlainObject')) { + source = removeNoNodeClass(source); + } + if ((source.match(/\bcreateIterator\b/g) || []).length < 2) { + source = removeFunction(source, 'createIterator'); + source = removeVar(source, 'defaultsIteratorOptions'); + source = removeVar(source, 'eachIteratorOptions'); + source = removeVar(source, 'forOwnIteratorOptions'); + source = removeVar(source, 'templateIterator'); + source = removeHasDontEnumBug(source); + source = removeHasEnumPrototype(source); + } + if (isRemoved(source, 'createIterator', 'bind', 'keys')) { + source = removeSetImmediate(source); + source = removeVar(source, 'isBindFast'); + source = removeVar(source, 'isV8'); + source = removeVar(source, 'nativeBind'); + } + if (isRemoved(source, 'createIterator', 'keys')) { + source = removeVar(source, 'nativeKeys'); + source = removeKeysOptimization(source); + source = removeNonEnumArgs(source); + } + if (!source.match(/var (?:hasDontEnumBug|hasEnumPrototype|iteratesOwnLast|nonEnumArgs)\b/g)) { + // remove IIFE used to assign `hasDontEnumBug`, `hasEnumPrototype`, `iteratesOwnLast`, and `nonEnumArgs` + source = source.replace(/^ *\(function\(\) *{[\s\S]+?}\(1\)\);\n/m, ''); + } + } + if ((source.match(/\bfreeModule\b/g) || []).length < 2) { + source = removeVar(source, 'freeModule'); + } + if ((source.match(/\bfreeExports\b/g) || []).length < 2) { + source = removeVar(source, 'freeExports'); + } + + debugSource = cleanupSource(source); + source = cleanupSource(source); + + /*------------------------------------------------------------------------*/ + + // flag to track if `outputPath` has been used by `callback` + var outputUsed = false; + + // flag to specify creating a custom build + var isCustom = ( + isLegacy || isMapped || isModern || isStrict || isUnderscore || outputPath || + /(?:category|exclude|exports|iife|include|minus|plus)=/.test(options) || + !_.isEqual(exportsOptions, exportsAll) + ); + + // used as the basename of the output path + var basename = outputPath + ? path.basename(outputPath, '.js') + : 'lodash' + (isTemplate ? '.template' : isCustom ? '.custom' : ''); + + // restore `dependencyMap` + dependencyMap = dependencyBackup; + + // output debug build + if (!isMinify && (isCustom || isDebug || isTemplate)) { + if (isCustom) { + debugSource = addCommandsToHeader(debugSource, options); + } + if (isDebug && isStdOut) { + stdout.write(debugSource); + callback({ + 'source': debugSource + }); + } + else if (!isStdOut) { + filePath = outputPath || path.join(cwd, basename + '.js'); + outputUsed = true; + callback({ + 'source': debugSource, + 'outputPath': filePath + }); + } + } + // begin the minification process + if (!isDebug) { + if (outputPath && outputUsed) { + outputPath = path.join(path.dirname(outputPath), path.basename(outputPath, '.js') + '.min.js'); + } else if (!outputPath) { + outputPath = path.join(cwd, basename + '.min.js'); + } + minify(source, { + 'filePath': filePath, + 'isMapped': isMapped, + 'isSilent': isSilent, + 'isTemplate': isTemplate, + 'modes': isIIFE && ['simple', 'hybrid'], + 'outputPath': outputPath, + 'sourceMapURL': sourceMapURL, + 'onComplete': function(data) { + if (isCustom) { + data.source = addCommandsToHeader(data.source, options); + } + if (isStdOut) { + stdout.write(data.source); + callback(data); + } else { + callback(data); + } + } + }); + } + } + + /*--------------------------------------------------------------------------*/ + + // expose `build` + if (module != require.main) { + module.exports = build; + } + else { + // or invoked directly + build(process.argv, function(data) { + var outputPath = data.outputPath, + sourceMap = data.sourceMap; + + if (outputPath) { + fs.writeFileSync(outputPath, data.source, 'utf8'); + if (sourceMap) { + fs.writeFileSync(path.join(path.dirname(outputPath), path.basename(outputPath, '.js') + '.map'), sourceMap, 'utf8'); + } + } + }); + } +}()); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/build/minify.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/build/minify.js new file mode 100755 index 000000000..2250669ee --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/build/minify.js @@ -0,0 +1,753 @@ +#!/usr/bin/env node +;(function() { + 'use strict'; + + /** Load Node modules */ + var fs = require('fs'), + https = require('https'), + path = require('path'), + spawn = require('child_process').spawn, + zlib = require('zlib'), + tar = require('../vendor/tar/tar.js'), + _ = require('../lodash.js'); + + /** Load other modules */ + var preprocess = require('./pre-compile.js'), + postprocess = require('./post-compile.js'); + + /** The Git object ID of `closure-compiler.tar.gz` */ + var closureId = '23cf67d0f0b979d97631fc108a2a43bb82225994'; + + /** The Git object ID of `uglifyjs.tar.gz` */ + var uglifyId = 'a934fb18f8fa2768c6a68de44b6e035fe96a268b'; + + /** The path of the directory that is the base of the repository */ + var basePath = fs.realpathSync(path.join(__dirname, '..')); + + /** The path of the `vendor` directory */ + var vendorPath = path.join(basePath, 'vendor'); + + /** The path to the Closure Compiler `.jar` */ + var closurePath = path.join(vendorPath, 'closure-compiler', 'compiler.jar'); + + /** The path to the UglifyJS module */ + var uglifyPath = path.join(vendorPath, 'uglifyjs', 'tools', 'node.js'); + + /** The Closure Compiler command-line options */ + var closureOptions = ['--warning_level=QUIET']; + + /** The media type for raw blob data */ + var mediaType = 'application/vnd.github.v3.raw'; + + /** Used to reference parts of the blob href */ + var location = (function() { + var host = 'api.github.com', + origin = 'https://api.github.com', + pathname = '/repos/bestiejs/lodash/git/blobs'; + + return { + 'host': host, + 'href': origin + pathname, + 'origin': origin, + 'pathname': pathname + }; + }()); + + /** The Closure Compiler optimization modes */ + var optimizationModes = { + 'simple': 'SIMPLE_OPTIMIZATIONS', + 'advanced': 'ADVANCED_OPTIMIZATIONS' + }; + + /** Reassign `existsSync` for older versions of Node */ + fs.existsSync || (fs.existsSync = path.existsSync); + + /*--------------------------------------------------------------------------*/ + + /** + * Minifies a given Lo-Dash `source` and invokes the `options.onComplete` + * callback when finished. The `onComplete` callback is invoked with one + * argument; (outputSource). + * + * @param {Array|String} [source=''] The source to minify or array of commands. + * -o, --output - Write output to a given path/filename. + * -s, --silent - Skip status updates normally logged to the console. + * -t, --template - Applies template specific minifier options. + * + * @param {Object} [options={}] The options object. + * outputPath - Write output to a given path/filename. + * isSilent - Skip status updates normally logged to the console. + * isTemplate - Applies template specific minifier options. + * onComplete - The function called once minification has finished. + */ + function minify(source, options) { + // used to specify the source map URL + var sourceMapURL; + + // used to specify the default minifer modes + var modes = ['simple', 'advanced', 'hybrid']; + + source || (source = ''); + options || (options = {}); + + // juggle arguments + if (Array.isArray(source)) { + // convert commands to an options object + options = source; + + // used to report invalid command-line arguments + var invalidArgs = _.reject(options.slice(options[0] == 'node' ? 2 : 0), function(value, index, options) { + if (/^(?:-o|--output)$/.test(options[index - 1]) || + /^modes=.*$/.test(value)) { + return true; + } + var result = [ + '-o', '--output', + '-p', '--source-map', + '-s', '--silent', + '-t', '--template' + ].indexOf(value) > -1; + + if (!result && /^(?:-p|--source-map)$/.test(options[index - 1])) { + result = true; + sourceMapURL = value; + } + return result; + }); + + // report invalid arguments + if (invalidArgs.length) { + console.log( + '\n' + + 'Invalid argument' + (invalidArgs.length > 1 ? 's' : '') + + ' passed: ' + invalidArgs.join(', ') + ); + return; + } + var filePath = options[options.length - 1], + isMapped = options.indexOf('-p') > -1 || options.indexOf('--source-map') > -1, + isSilent = options.indexOf('-s') > -1 || options.indexOf('--silent') > -1, + isTemplate = options.indexOf('-t') > -1 || options.indexOf('--template') > -1, + outputPath = path.join(path.dirname(filePath), path.basename(filePath, '.js') + '.min.js'); + + modes = options.reduce(function(result, value) { + var match = value.match(/modes=(.*)$/); + return match ? match[1].split(/, */) : result; + }, modes); + + outputPath = options.reduce(function(result, value, index) { + if (/-o|--output/.test(value)) { + result = options[index + 1]; + result = path.join(fs.realpathSync(path.dirname(result)), path.basename(result)); + } + return result; + }, outputPath); + + options = { + 'filePath': filePath, + 'isMapped': isMapped, + 'isSilent': isSilent, + 'isTemplate': isTemplate, + 'modes': modes, + 'outputPath': outputPath, + 'sourceMapURL': sourceMapURL + }; + + source = fs.readFileSync(filePath, 'utf8'); + } + + modes = options.modes || modes; + if (options.isMapped) { + modes = modes.filter(function(mode) { + return mode != 'hybrid'; + }); + } + if (options.isTemplate) { + modes = modes.filter(function(mode) { + return mode != 'advanced'; + }); + } + options.modes = modes; + + // fetch the Closure Compiler + getDependency({ + 'id': 'closure-compiler', + 'hashId': closureId, + 'path': vendorPath, + 'title': 'the Closure Compiler', + 'onComplete': function(exception) { + var error = exception; + + // fetch UglifyJS + getDependency({ + 'id': 'uglifyjs', + 'hashId': uglifyId, + 'title': 'UglifyJS', + 'path': vendorPath, + 'onComplete': function(exception) { + error || (error = exception); + if (!error) { + new Minify(source, options); + } + } + }); + } + }); + } + + /** + * The Minify constructor used to keep state of each `minify` invocation. + * + * @private + * @constructor + * @param {String} source The source to minify. + * @param {Object} options The options object. + * outputPath - Write output to a given path/filename. + * isSilent - Skip status updates normally logged to the console. + * isTemplate - Applies template specific minifier options. + * onComplete - The function called once minification has finished. + */ + function Minify(source, options) { + // juggle arguments + if (typeof source == 'object' && source) { + options = source || options; + source = options.source || ''; + } + this.compiled = { 'simple': {}, 'advanced': {} }; + this.hybrid = { 'simple': {}, 'advanced': {} }; + this.uglified = {}; + + this.filePath = options.filePath; + this.isMapped = !!options.isMapped; + this.isSilent = !!options.isSilent; + this.isTemplate = !!options.isTemplate; + this.outputPath = options.outputPath; + this.sourceMapURL = options.sourceMapURL; + + var modes = this.modes = options.modes; + source = this.source = preprocess(source, options); + + this.onComplete = options.onComplete || function(data) { + var outputPath = this.outputPath, + sourceMap = data.sourceMap; + + fs.writeFileSync(outputPath, data.source, 'utf8'); + if (sourceMap) { + fs.writeFileSync(getMapPath(outputPath), sourceMap, 'utf8'); + } + }; + + // begin the minification process + if (modes.indexOf('simple') > -1) { + closureCompile.call(this, source, 'simple', onClosureSimpleCompile.bind(this)); + } else if (modes.indexOf('advanced') > -1) { + onClosureSimpleGzip.call(this); + } else { + onClosureAdvancedGzip.call(this); + } + } + + /*--------------------------------------------------------------------------*/ + + /** + * Fetches a required `.tar.gz` dependency with the given Git object ID from + * the Lo-Dash repo on GitHub. The object ID may be obtained by running + * `git hash-object path/to/dependency.tar.gz`. + * + * @private + * @param {Object} options The options object. + * id - The Git object ID of the `.tar.gz` file. + * onComplete - The function called once the extraction has finished. + * path - The path of the extraction directory. + * title - The dependency's title used in status updates logged to the console. + */ + function getDependency(options) { + options || (options = {}); + + var ran, + destPath = options.path, + hashId = options.hashId, + id = options.id, + onComplete = options.onComplete, + title = options.title; + + // exit early if dependency exists + if (fs.existsSync(path.join(destPath, id))) { + onComplete(); + return; + } + var callback = function(exception) { + if (ran) { + return; + } + if (exception) { + console.error([ + 'There was a problem installing ' + title + '.', + 'Try running the command as root, via `sudo`, or manually install by running:', + '', + "curl -H 'Accept: " + mediaType + "' " + location.href + '/' + hashId + " | tar xvz -C '" + destPath + "'", + '' + ].join('\n')); + } + ran = true; + process.removeListener('uncaughtException', callback); + onComplete(exception); + }; + + console.log('Downloading ' + title + '...'); + process.on('uncaughtException', callback); + + https.get({ + 'host': location.host, + 'path': location.pathname + '/' + hashId, + 'headers': { + // By default, all GitHub blob API endpoints return a JSON document + // containing Base64-encoded blob data. Overriding the `Accept` header + // with the GitHub raw media type returns the blob data directly. + // See http://developer.github.com/v3/media/. + 'Accept': mediaType + } + }, function(response) { + var decompressor = zlib.createUnzip(), + parser = new tar.Extract({ 'path': destPath }); + + parser.on('end', callback); + response.pipe(decompressor).pipe(parser); + }); + } + + /** + * Resolves the source map path from the given output path. + * + * @private + * @param {String} outputPath The output path. + * @returns {String} Returns the source map path. + */ + function getMapPath(outputPath) { + return path.join(path.dirname(outputPath), path.basename(outputPath, '.js') + '.map'); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Compresses a `source` string using the Closure Compiler. Yields the + * minified result, and any exceptions encountered, to a `callback` function. + * + * @private + * @param {String} source The JavaScript source to minify. + * @param {String} mode The optimization mode. + * @param {Function} callback The function called once the process has completed. + */ + function closureCompile(source, mode, callback) { + var filePath = this.filePath, + isAdvanced = mode == 'advanced', + isMapped = this.isMapped, + options = closureOptions.slice(), + outputPath = this.outputPath, + mapPath = getMapPath(outputPath), + sourceMapURL = this.sourceMapURL || path.basename(mapPath); + + // remove copyright header to make other modifications easier + var license = (/^(?:\s*\/\/.*\s*|\s*\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/\s*)*/.exec(source) || [''])[0]; + if (license) { + source = source.replace(license, ''); + } + + var hasIIFE = /^;?\(function[^{]+{\s*/.test(source), + isStrict = hasIIFE && /^;?\(function[^{]+{\s*["']use strict["']/.test(source); + + // to avoid stripping the IIFE, convert it to a function call + if (hasIIFE && isAdvanced) { + source = source + .replace(/\(function/, '__iife__$&') + .replace(/\(this\)\)([\s;]*(\n\/\/.+)?)$/, ', this)$1'); + } + + options.push('--compilation_level=' + optimizationModes[mode]); + if (isMapped) { + options.push('--create_source_map=' + mapPath, '--source_map_format=V3'); + } + + var compiler = spawn('java', ['-jar', closurePath].concat(options)); + if (!this.isSilent) { + console.log('Compressing ' + path.basename(outputPath, '.js') + ' using the Closure Compiler (' + mode + ')...'); + } + + var error = ''; + compiler.stderr.on('data', function(data) { + error += data; + }); + + var output = ''; + compiler.stdout.on('data', function(data) { + output += data; + }); + + compiler.on('exit', function(status) { + // `status` contains the process exit code + if (status) { + var exception = new Error(error); + exception.status = status; + } + // restore IIFE and move exposed vars inside the IIFE + if (hasIIFE && isAdvanced) { + output = output + .replace(/__iife__\(/, '(') + .replace(/,\s*this\)([\s;]*(\n\/\/.+)?)$/, '(this))$1') + .replace(/^((?:var (?:\w+=(?:!0|!1|null)[,;])+)?)([\s\S]*?function[^{]+{)/, '$2$1'); + } + // inject "use strict" directive + if (isStrict) { + output = output.replace(/^[\s\S]*?function[^{]+{/, '$&"use strict";'); + } + // restore copyright header + if (license) { + output = license + output; + } + if (isMapped) { + var mapOutput = fs.readFileSync(mapPath, 'utf8'); + fs.unlinkSync(mapPath); + output = output.replace(/[\s;]*$/, '\n/*\n//@ sourceMappingURL=' + sourceMapURL) + '\n*/'; + + mapOutput = JSON.parse(mapOutput); + mapOutput.file = path.basename(outputPath); + mapOutput.sources = [path.basename(filePath)]; + mapOutput = JSON.stringify(mapOutput, null, 2); + } + callback(exception, output, mapOutput); + }); + + // proxy the standard input to the Closure Compiler + compiler.stdin.end(source); + } + + /** + * Compresses a `source` string using UglifyJS. Yields the result to a + * `callback` function. This function is synchronous; the `callback` is used + * for symmetry. + * + * @private + * @param {String} source The JavaScript source to minify. + * @param {String} label The label to log. + * @param {Function} callback The function called once the process has completed. + */ + function uglify(source, label, callback) { + if (!this.isSilent) { + console.log('Compressing ' + path.basename(this.outputPath, '.js') + ' using ' + label + '...'); + } + try { + var uglifyJS = require(uglifyPath); + + // 1. parse + var toplevel = uglifyJS.parse(source); + + // 2. compress + // enable unsafe comparisons + toplevel.figure_out_scope(); + toplevel = toplevel.transform(uglifyJS.Compressor({ + 'comparisons': false, + 'unsafe_comps': true, + 'warnings': false + })); + + // 3. mangle + // excluding the `define` function exposed by AMD loaders + toplevel.figure_out_scope(); + toplevel.compute_char_frequency(); + toplevel.mangle_names({ + 'except': ['define'] + }); + + // 4. output + // restrict lines to 500 characters for consistency with the Closure Compiler + var stream = uglifyJS.OutputStream({ + 'ascii_only': true, + 'comments': /@cc_on|@license|@preserve/i, + 'max_line_len': 500, + }); + + toplevel.print(stream); + } + catch(e) { + var exception = e; + } + callback(exception, stream && String(stream)); + } + + /*--------------------------------------------------------------------------*/ + + /** + * The Closure Compiler callback for simple optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {String} result The resulting minified source. + * @param {String} map The source map output. + */ + function onClosureSimpleCompile(exception, result, map) { + if (exception) { + throw exception; + } + result = postprocess(result); + + var simple = this.compiled.simple; + simple.source = result; + simple.sourceMap = map; + zlib.gzip(result, onClosureSimpleGzip.bind(this)); + } + + /** + * The Closure Compiler `gzip` callback for simple optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {Buffer} result The resulting gzipped source. + */ + function onClosureSimpleGzip(exception, result) { + if (exception) { + throw exception; + } + if (result != null) { + if (!this.isSilent) { + console.log('Done. Size: %d bytes.', result.length); + } + this.compiled.simple.gzip = result; + } + // compile the source using advanced optimizations + if (this.modes.indexOf('advanced') > -1) { + closureCompile.call(this, this.source, 'advanced', onClosureAdvancedCompile.bind(this)); + } else { + onClosureAdvancedGzip.call(this); + } + } + + /** + * The Closure Compiler callback for advanced optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {String} result The resulting minified source. + * @param {String} map The source map output. + */ + function onClosureAdvancedCompile(exception, result, map) { + if (exception) { + throw exception; + } + result = postprocess(result); + + var advanced = this.compiled.advanced; + advanced.source = result; + advanced.sourceMap = map; + zlib.gzip(result, onClosureAdvancedGzip.bind(this)); + } + + /** + * The Closure Compiler `gzip` callback for advanced optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {Buffer} result The resulting gzipped source. + */ + function onClosureAdvancedGzip(exception, result) { + if (exception) { + throw exception; + } + if (result != null) { + if (!this.isSilent) { + console.log('Done. Size: %d bytes.', result.length); + } + this.compiled.advanced.gzip = result; + } + // minify the source using UglifyJS + if (!this.isMapped) { + uglify.call(this, this.source, 'UglifyJS', onUglify.bind(this)); + } else { + onComplete.call(this); + } + } + + /** + * The UglifyJS callback. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {String} result The resulting minified source. + */ + function onUglify(exception, result) { + if (exception) { + throw exception; + } + result = postprocess(result); + this.uglified.source = result; + zlib.gzip(result, onUglifyGzip.bind(this)); + } + + /** + * The UglifyJS `gzip` callback. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {Buffer} result The resulting gzipped source. + */ + function onUglifyGzip(exception, result) { + if (exception) { + throw exception; + } + if (result != null) { + if (!this.isSilent) { + console.log('Done. Size: %d bytes.', result.length); + } + this.uglified.gzip = result; + } + // minify the already Closure Compiler simple optimized source using UglifyJS + var modes = this.modes; + if (modes.indexOf('hybrid') > -1) { + if (modes.indexOf('simple') > -1) { + uglify.call(this, this.compiled.simple.source, 'hybrid (simple)', onSimpleHybrid.bind(this)); + } else if (modes.indexOf('advanced') > -1) { + onSimpleHybridGzip.call(this); + } + } else { + onComplete.call(this); + } + } + + /** + * The hybrid callback for simple optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {String} result The resulting minified source. + */ + function onSimpleHybrid(exception, result) { + if (exception) { + throw exception; + } + result = postprocess(result); + this.hybrid.simple.source = result; + zlib.gzip(result, onSimpleHybridGzip.bind(this)); + } + + /** + * The hybrid `gzip` callback for simple optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {Buffer} result The resulting gzipped source. + */ + function onSimpleHybridGzip(exception, result) { + if (exception) { + throw exception; + } + if (result != null) { + if (!this.isSilent) { + console.log('Done. Size: %d bytes.', result.length); + } + this.hybrid.simple.gzip = result; + } + // minify the already Closure Compiler advance optimized source using UglifyJS + if (this.modes.indexOf('advanced') > -1) { + uglify.call(this, this.compiled.advanced.source, 'hybrid (advanced)', onAdvancedHybrid.bind(this)); + } else { + onComplete.call(this); + } + } + + /** + * The hybrid callback for advanced optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {String} result The resulting minified source. + */ + function onAdvancedHybrid(exception, result) { + if (exception) { + throw exception; + } + result = postprocess(result); + this.hybrid.advanced.source = result; + zlib.gzip(result, onAdvancedHybridGzip.bind(this)); + } + + /** + * The hybrid `gzip` callback for advanced optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {Buffer} result The resulting gzipped source. + */ + function onAdvancedHybridGzip(exception, result) { + if (exception) { + throw exception; + } + if (result != null) { + if (!this.isSilent) { + console.log('Done. Size: %d bytes.', result.length); + } + this.hybrid.advanced.gzip = result; + } + // finish by choosing the smallest compressed file + onComplete.call(this); + } + + /** + * The callback executed after the source is minified and gzipped. + * + * @private + */ + function onComplete() { + var compiledSimple = this.compiled.simple, + compiledAdvanced = this.compiled.advanced, + uglified = this.uglified, + hybridSimple = this.hybrid.simple, + hybridAdvanced = this.hybrid.advanced; + + var objects = [ + compiledSimple, + compiledAdvanced, + uglified, + hybridSimple, + hybridAdvanced + ]; + + var gzips = objects + .map(function(data) { return data.gzip; }) + .filter(Boolean); + + // select the smallest gzipped file and use its minified counterpart as the + // official minified release (ties go to the Closure Compiler) + var min = gzips.reduce(function(min, gzip) { + var length = gzip.length; + return min > length ? length : min; + }, Infinity); + + // pass the minified source to the "onComplete" callback + objects.some(function(data) { + var gzip = data.gzip; + if (gzip && gzip.length == min) { + data.outputPath = this.outputPath; + this.onComplete(data); + return true; + } + }, this); + } + + /*--------------------------------------------------------------------------*/ + + // expose `minify` + if (module != require.main) { + module.exports = minify; + } + else { + // read the Lo-Dash source file from the first argument if the script + // was invoked directly (e.g. `node minify.js source.js`) and write to + // `.min.js` + (function() { + var options = process.argv; + if (options.length < 3) { + return; + } + minify(options); + }()); + } +}()); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/build/post-compile.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/build/post-compile.js new file mode 100644 index 000000000..db56866f8 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/build/post-compile.js @@ -0,0 +1,79 @@ +#!/usr/bin/env node +;(function() { + 'use strict'; + + /** The Node filesystem module */ + var fs = require('fs'); + + /** The minimal license/copyright template */ + var licenseTemplate = [ + '/**', + ' * @license', + ' * Lo-Dash <%= VERSION %> lodash.com/license', + ' * Underscore.js 1.4.4 underscorejs.org/LICENSE', + ' */' + ].join('\n'); + + /*--------------------------------------------------------------------------*/ + + /** + * Post-process a given minified Lo-Dash `source`, preparing it for + * deployment. + * + * @param {String} source The source to process. + * @returns {String} Returns the processed source. + */ + function postprocess(source) { + // remove copyright header + source = source.replace(/^\/\**[\s\S]+?\*\/\n/, ''); + + // correct overly aggressive Closure Compiler advanced optimizations + source = source + .replace(/prototype\s*=\s*{\s*valueOf\s*:\s*1\s*}/, 'prototype={valueOf:1,y:1}') + .replace(/(document[^&]+&&)\s*(?:\w+|!\d)/, '$1!({toString:0}+"")'); + + // flip `typeof` expressions to help optimize Safari and + // correct the AMD module definition for AMD build optimizers + // (e.g. from `"number" == typeof x` to `typeof x == "number") + source = source.replace(/(\w)?("[^"]+")\s*([!=]=)\s*(typeof(?:\s*\([^)]+\)|\s+[.\w]+(?!\[)))/g, function(match, other, type, equality, expression) { + return (other ? other + ' ' : '') + expression + equality + type; + }); + + // add trailing semicolon + if (source) { + source = source.replace(/[\s;]*?(\s*\/\/.*\s*|\s*\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/\s*)*$/, ';$1'); + } + // exit early if version snippet isn't found + var snippet = /VERSION\s*[=:]\s*([\'"])(.*?)\1/.exec(source); + if (!snippet) { + return source; + } + // add new copyright header + var version = snippet[2]; + source = licenseTemplate.replace('<%= VERSION %>', version) + '\n;' + source; + + return source; + } + + /*--------------------------------------------------------------------------*/ + + // expose `postprocess` + if (module != require.main) { + module.exports = postprocess; + } + else { + // read the Lo-Dash source file from the first argument if the script + // was invoked directly (e.g. `node post-compile.js source.js`) and write to + // the same file + (function() { + var options = process.argv; + if (options.length < 3) { + return; + } + var filePath = options[options.length - 1], + source = fs.readFileSync(filePath, 'utf8'); + + fs.writeFileSync(filePath, postprocess(source), 'utf8'); + }()); + } +}()); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/build/pre-compile.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/build/pre-compile.js new file mode 100644 index 000000000..94e1011b3 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/build/pre-compile.js @@ -0,0 +1,382 @@ +#!/usr/bin/env node +;(function() { + 'use strict'; + + /** The Node filesystem module */ + var fs = require('fs'); + + /** Used to minify variables embedded in compiled strings */ + var compiledVars = [ + 'args', + 'argsIndex', + 'argsLength', + 'callback', + 'collection', + 'createCallback', + 'ctor', + 'guard', + 'hasOwnProperty', + 'index', + 'isArguments', + 'isArray', + 'isString', + 'iterable', + 'length', + 'nativeKeys', + 'object', + 'objectTypes', + 'ownIndex', + 'ownProps', + 'result', + 'skipProto', + 'source', + 'thisArg' + ]; + + /** Used to minify `compileIterator` option properties */ + var iteratorOptions = [ + 'args', + 'arrays', + 'bottom', + 'firstArg', + 'hasDontEnumBug', + 'hasEnumPrototype', + 'isKeysFast', + 'loop', + 'nonEnumArgs', + 'noCharByIndex', + 'shadowed', + 'top', + 'useHas' + ]; + + /** Used to minify variables and string values to a single character */ + var minNames = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); + minNames.push.apply(minNames, minNames.map(function(value) { + return value + value; + })); + + /** Used to protect the specified properties from getting minified */ + var propWhitelist = [ + '_', + '__wrapped__', + 'after', + 'all', + 'amd', + 'any', + 'assign', + 'at', + 'attachEvent', + 'bind', + 'bindAll', + 'bindKey', + 'clearTimeout', + 'clone', + 'cloneDeep', + 'collect', + 'compact', + 'compose', + 'contains', + 'countBy', + 'criteria', + 'debounce', + 'defaults', + 'defer', + 'delay', + 'detect', + 'difference', + 'drop', + 'each', + 'environment', + 'escape', + 'evaluate', + 'every', + 'exports', + 'extend', + 'filter', + 'find', + 'first', + 'flatten', + 'foldl', + 'foldr', + 'forEach', + 'forIn', + 'forOwn', + 'functions', + 'global', + 'groupBy', + 'has', + 'head', + 'imports', + 'identity', + 'include', + 'index', + 'indexOf', + 'initial', + 'inject', + 'interpolate', + 'intersection', + 'invert', + 'invoke', + 'isArguments', + 'isArray', + 'isBoolean', + 'isDate', + 'isElement', + 'isEmpty', + 'isEqual', + 'isEqual', + 'isFinite', + 'isFinite', + 'isFunction', + 'isNaN', + 'isNull', + 'isNumber', + 'isObject', + 'isPlainObject', + 'isRegExp', + 'isString', + 'isUndefined', + 'keys', + 'last', + 'lastIndexOf', + 'map', + 'max', + 'memoize', + 'merge', + 'methods', + 'min', + 'mixin', + 'noConflict', + 'object', + 'omit', + 'once', + 'opera', + 'pairs', + 'partial', + 'partialRight', + 'pick', + 'pluck', + 'random', + 'range', + 'reduce', + 'reduceRight', + 'reject', + 'rest', + 'result', + 'select', + 'setImmediate', + 'setTimeout', + 'shuffle', + 'size', + 'some', + 'sortBy', + 'sortedIndex', + 'source', + 'tail', + 'take', + 'tap', + 'template', + 'templateSettings', + 'throttle', + 'times', + 'toArray', + 'unescape', + 'union', + 'uniq', + 'unique', + 'uniqueId', + 'value', + 'values', + 'variable', + 'VERSION', + 'where', + 'without', + 'wrap', + 'zip', + + // properties used by the `backbone` and `underscore` builds + '__chain__', + 'chain', + 'findWhere' + ]; + + /*--------------------------------------------------------------------------*/ + + /** + * Pre-process a given Lo-Dash `source`, preparing it for minification. + * + * @param {String} [source=''] The source to process. + * @param {Object} [options={}] The options object. + * @returns {String} Returns the processed source. + */ + function preprocess(source, options) { + source || (source = ''); + options || (options = {}); + + // remove unrecognized JSDoc tags so the Closure Compiler won't complain + source = source.replace(/@(?:alias|category)\b.*/g, ''); + + if (options.isTemplate) { + return source; + } + // add brackets to whitelisted properties so the Closure Compiler won't mung them + // http://code.google.com/closure/compiler/docs/api-tutorial3.html#export + source = source.replace(RegExp('\\.(' + propWhitelist.join('|') + ')\\b', 'g'), function(match, prop) { + return "['" + prop.replace(/['\n\r\t]/g, '\\$&') + "']"; + }); + + // remove brackets from `_.escape()` in `_.template` + source = source.replace(/__e *= *_\['escape']/g, '__e=_.escape'); + + // remove brackets from `collection.indexOf` in `_.contains` + source = source.replace("collection['indexOf'](target)", 'collection.indexOf(target)'); + + // remove brackets from `result[length].value` in `_.sortBy` + source = source.replace("result[length]['value']", 'result[length].value'); + + // remove whitespace from string literals + source = source.replace(/^([ "'\w]+:)? *"[^"\\\n]*(?:\\.[^"\\\n]*)*"|'[^'\\\n]*(?:\\.[^'\\\n]*)*'/gm, function(string, captured) { + // remove object literal property name + if (/:$/.test(captured)) { + string = string.slice(captured.length); + } + // avoids removing the '\n' of the `stringEscapes` object + string = string.replace(/\[object |delete |else (?!{)|function | in |return\s+[\w"']|throw |typeof |use strict|var |@ |(["'])\\n\1|\\\\n|\\n|\s+/g, function(match) { + return match == false || match == '\\n' ? '' : match; + }); + // prepend object literal property name + return (captured || '') + string; + }); + + // remove whitespace from `_.template` related regexes + source = source.replace(/reEmptyString\w+ *=.+/g, function(match) { + return match.replace(/ |\\n/g, ''); + }); + + // remove newline from double-quoted strings in `_.template` + source = source + .replace('"__p += \'"', '"__p+=\'"') + .replace('"\';\n"', '"\';"') + + // remove debug sourceURL use in `_.template` + source = source.replace(/(?:\s*\/\/.*\n)* *var sourceURL[^;]+;|\+ *sourceURL/g, ''); + + // minify internal properties used by 'compareAscending' and `_.sortBy` + (function() { + var properties = ['criteria', 'index', 'value'], + snippets = source.match(/( +)function (?:compareAscending|sortBy)\b[\s\S]+?\n\1}/g); + + if (!snippets) { + return; + } + snippets.forEach(function(snippet) { + var modified = snippet; + + // minify properties + properties.forEach(function(property, index) { + var minName = minNames[index], + reBracketProp = RegExp("\\['(" + property + ")'\\]", 'g'), + reDotProp = RegExp('\\.' + property + '\\b', 'g'), + rePropColon = RegExp("([^?\\s])\\s*([\"'])?\\b" + property + "\\2 *:", 'g'); + + modified = modified + .replace(reBracketProp, "['" + minName + "']") + .replace(reDotProp, "['" + minName + "']") + .replace(rePropColon, "$1'" + minName + "':"); + }); + + // replace with modified snippet + source = source.replace(snippet, modified); + }); + }()); + + // minify all compilable snippets + var snippets = source.match( + RegExp([ + // match the `iteratorTemplate` + '( +)var iteratorTemplate\\b[\\s\\S]+?\\n\\1}', + // match methods created by `createIterator` calls + 'createIterator\\((?:{|[a-zA-Z]+)[\\s\\S]+?\\);\\n', + // match variables storing `createIterator` options + '( +)var [a-zA-Z]+IteratorOptions\\b[\\s\\S]+?\\n\\2}', + // match the the `createIterator` function + '( +)function createIterator\\b[\\s\\S]+?\\n\\3}' + ].join('|'), 'g') + ); + + // exit early if no compilable snippets + if (!snippets) { + return source; + } + + snippets.forEach(function(snippet, index) { + var isCreateIterator = /function createIterator\b/.test(snippet), + isIteratorTemplate = /var iteratorTemplate\b/.test(snippet), + modified = snippet; + + // add brackets to iterator option properties so the Closure Compiler won't mung them + modified = modified.replace(RegExp('\\.(' + iteratorOptions.join('|') + ')\\b', 'g'), function(match, prop) { + return "['" + prop.replace(/['\n\r\t]/g, '\\$&') + "']"; + }); + + if (isCreateIterator) { + // clip before the `factory` call to avoid minifying its arguments + source = source.replace(snippet, modified); + snippet = modified = modified.replace(/return factory\([\s\S]+$/, ''); + } + // minify `createIterator` option property names + iteratorOptions.forEach(function(property, index) { + var minName = minNames[index]; + + // minify variables in `iteratorTemplate` or property names in everything else + modified = isIteratorTemplate + ? modified.replace(RegExp('\\b' + property + '\\b', 'g'), minName) + : modified.replace(RegExp("'" + property + "'", 'g'), "'" + minName + "'"); + }); + + // minify snippet variables / arguments + compiledVars.forEach(function(variable, index) { + var minName = minNames[index]; + + // ensure properties in compiled strings aren't minified + modified = modified.replace(RegExp('([^.]\\b)' + variable + '\\b(?!\' *[\\]:])', 'g'), '$1' + minName); + + // correct `typeof` values + if (/^(?:boolean|function|object|number|string|undefined)$/.test(variable)) { + modified = modified.replace(RegExp("(typeof [^']+')" + minName + "'", 'g'), '$1' + variable + "'"); + } + }); + + // replace with modified snippet + source = source.replace(snippet, modified); + }); + + return source; + } + + /*--------------------------------------------------------------------------*/ + + // expose `preprocess` + if (module != require.main) { + module.exports = preprocess; + } + else { + // read the Lo-Dash source file from the first argument if the script + // was invoked directly (e.g. `node pre-compile.js source.js`) and write to + // the same file + (function() { + var options = process.argv; + if (options.length < 3) { + return; + } + var filePath = options[options.length - 1], + isTemplate = options.indexOf('-t') > -1 || options.indexOf('--template') > -1, + source = fs.readFileSync(filePath, 'utf8'); + + fs.writeFileSync(filePath, preprocess(source, { + 'isTemplate': isTemplate + }), 'utf8'); + }()); + } +}()); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/dist/lodash.compat.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/dist/lodash.compat.js new file mode 100644 index 000000000..37ebc920b --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/dist/lodash.compat.js @@ -0,0 +1,5152 @@ +/** + * @license + * Lo-Dash 1.0.1 (Custom Build) + * Build: `lodash -o ./dist/lodash.compat.js` + * Copyright 2012-2013 The Dojo Foundation + * Based on Underscore.js 1.4.4 + * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. + * Available under MIT license + */ +;(function(window, undefined) { + + /** Detect free variable `exports` */ + var freeExports = typeof exports == 'object' && exports; + + /** Detect free variable `module` */ + var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; + + /** Detect free variable `global` and use it as `window` */ + var freeGlobal = typeof global == 'object' && global; + if (freeGlobal.global === freeGlobal) { + window = freeGlobal; + } + + /** Used for array and object method references */ + var arrayRef = [], + objectRef = {}; + + /** Used to generate unique IDs */ + var idCounter = 0; + + /** Used internally to indicate various things */ + var indicatorObject = objectRef; + + /** Used by `cachedContains` as the default size when optimizations are enabled for large arrays */ + var largeArraySize = 30; + + /** Used to restore the original `_` reference in `noConflict` */ + var oldDash = window._; + + /** Used to match HTML entities */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g; + + /** Used to match empty string literals in compiled template source */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match regexp flags from their coerced string values */ + var reFlags = /\w*$/; + + /** Used to detect if a method is native */ + var reNative = RegExp('^' + + (objectRef.valueOf + '') + .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + .replace(/valueOf|for [^\]]+/g, '.+?') + '$' + ); + + /** + * Used to match ES6 template delimiters + * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6 + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match "interpolate" template delimiters */ + var reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to ensure capturing order of template delimiters */ + var reNoMatch = /($^)/; + + /** Used to match HTML characters */ + var reUnescapedHtml = /[&<>"']/g; + + /** Used to match unescaped characters in compiled string literals */ + var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; + + /** Used to fix the JScript [[DontEnum]] bug */ + var shadowed = [ + 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', + 'toLocaleString', 'toString', 'valueOf' + ]; + + /** Used to make template sourceURLs easier to identify */ + var templateCounter = 0; + + /** Native method shortcuts */ + var ceil = Math.ceil, + concat = arrayRef.concat, + floor = Math.floor, + getPrototypeOf = reNative.test(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, + hasOwnProperty = objectRef.hasOwnProperty, + push = arrayRef.push, + toString = objectRef.toString; + + /* Native method shortcuts for methods with the same name as other `lodash` methods */ + var nativeBind = reNative.test(nativeBind = slice.bind) && nativeBind, + nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray, + nativeIsFinite = window.isFinite, + nativeIsNaN = window.isNaN, + nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys, + nativeMax = Math.max, + nativeMin = Math.min, + nativeRandom = Math.random; + + /** `Object#toString` result shortcuts */ + var argsClass = '[object Arguments]', + arrayClass = '[object Array]', + boolClass = '[object Boolean]', + dateClass = '[object Date]', + funcClass = '[object Function]', + numberClass = '[object Number]', + objectClass = '[object Object]', + regexpClass = '[object RegExp]', + stringClass = '[object String]'; + + /** Detect various environments */ + var isIeOpera = !!window.attachEvent, + isV8 = nativeBind && !/\n|true/.test(nativeBind + isIeOpera); + + /* Detect if `Function#bind` exists and is inferred to be fast (all but V8) */ + var isBindFast = nativeBind && !isV8; + + /* Detect if `Object.keys` exists and is inferred to be fast (IE, Opera, V8) */ + var isKeysFast = nativeKeys && (isIeOpera || isV8); + + /** + * Detect the JScript [[DontEnum]] bug: + * + * In IE < 9 an objects own properties, shadowing non-enumerable ones, are + * made non-enumerable as well. + */ + var hasDontEnumBug; + + /** + * Detect if a `prototype` properties are enumerable by default: + * + * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 + * (if the prototype or a property on the prototype has been set) + * incorrectly sets a function's `prototype` property [[Enumerable]] + * value to `true`. + */ + var hasEnumPrototype; + + /** Detect if own properties are iterated after inherited properties (IE < 9) */ + var iteratesOwnLast; + + /** + * Detect if `Array#shift` and `Array#splice` augment array-like objects + * incorrectly: + * + * Firefox < 10, IE compatibility mode, and IE < 9 have buggy Array `shift()` + * and `splice()` functions that fail to remove the last element, `value[0]`, + * of array-like objects even though the `length` property is set to `0`. + * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()` + * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9. + */ + var hasObjectSpliceBug = (hasObjectSpliceBug = { '0': 1, 'length': 1 }, + arrayRef.splice.call(hasObjectSpliceBug, 0, 1), hasObjectSpliceBug[0]); + + /** Detect if `arguments` object indexes are non-enumerable (Firefox < 4, IE < 9, PhantomJS, Safari < 5.1) */ + var nonEnumArgs = true; + + (function() { + var props = []; + function ctor() { this.x = 1; } + ctor.prototype = { 'valueOf': 1, 'y': 1 }; + for (var prop in new ctor) { props.push(prop); } + for (prop in arguments) { nonEnumArgs = !prop; } + + hasDontEnumBug = !/valueOf/.test(props); + hasEnumPrototype = ctor.propertyIsEnumerable('prototype'); + iteratesOwnLast = props[0] != 'x'; + }(1)); + + /** Detect if `arguments` objects are `Object` objects (all but Opera < 10.5) */ + var argsAreObjects = arguments.constructor == Object; + + /** Detect if `arguments` objects [[Class]] is unresolvable (Firefox < 4, IE < 9) */ + var noArgsClass = !isArguments(arguments); + + /** + * Detect lack of support for accessing string characters by index: + * + * IE < 8 can't access characters by index and IE 8 can only access + * characters by index on string literals. + */ + var noCharByIndex = ('x'[0] + Object('x')[0]) != 'xx'; + + /** + * Detect if a DOM node's [[Class]] is unresolvable (IE < 9) + * and that the JS engine won't error when attempting to coerce an object to + * a string without a `toString` function. + */ + try { + var noNodeClass = toString.call(document) == objectClass && !({ 'toString': 0 } + ''); + } catch(e) { } + + /** Used to identify object classifications that `_.clone` supports */ + var cloneableClasses = {}; + cloneableClasses[funcClass] = false; + cloneableClasses[argsClass] = cloneableClasses[arrayClass] = + cloneableClasses[boolClass] = cloneableClasses[dateClass] = + cloneableClasses[numberClass] = cloneableClasses[objectClass] = + cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; + + /** Used to lookup a built-in constructor by [[Class]] */ + var ctorByClass = {}; + ctorByClass[arrayClass] = Array; + ctorByClass[boolClass] = Boolean; + ctorByClass[dateClass] = Date; + ctorByClass[objectClass] = Object; + ctorByClass[numberClass] = Number; + ctorByClass[regexpClass] = RegExp; + ctorByClass[stringClass] = String; + + /** Used to determine if values are of the language type Object */ + var objectTypes = { + 'boolean': false, + 'function': true, + 'object': true, + 'number': false, + 'string': false, + 'undefined': false + }; + + /** Used to escape characters for inclusion in compiled string literals */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\t': 't', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a `lodash` object, that wraps the given `value`, to enable method + * chaining. + * + * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: + * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, + * and `unshift` + * + * The chainable wrapper functions are: + * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, `compose`, + * `concat`, `countBy`, `debounce`, `defaults`, `defer`, `delay`, `difference`, + * `filter`, `flatten`, `forEach`, `forIn`, `forOwn`, `functions`, `groupBy`, + * `initial`, `intersection`, `invert`, `invoke`, `keys`, `map`, `max`, `memoize`, + * `merge`, `min`, `object`, `omit`, `once`, `pairs`, `partial`, `partialRight`, + * `pick`, `pluck`, `push`, `range`, `reject`, `rest`, `reverse`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, + * `union`, `uniq`, `unshift`, `values`, `where`, `without`, `wrap`, and `zip` + * + * The non-chainable wrapper functions are: + * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `has`, `identity`, + * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, `isEmpty`, + * `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, `isObject`, + * `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, `lastIndexOf`, + * `mixin`, `noConflict`, `pop`, `random`, `reduce`, `reduceRight`, `result`, + * `shift`, `size`, `some`, `sortedIndex`, `template`, `unescape`, and `uniqueId` + * + * The wrapper functions `first` and `last` return wrapped values when `n` is + * passed, otherwise they return unwrapped values. + * + * @name _ + * @constructor + * @category Chaining + * @param {Mixed} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns a `lodash` instance. + */ + function lodash(value) { + // exit early if already wrapped, even if wrapped by a different `lodash` constructor + if (value && typeof value == 'object' && value.__wrapped__) { + return value; + } + // allow invoking `lodash` without the `new` operator + if (!(this instanceof lodash)) { + return new lodash(value); + } + this.__wrapped__ = value; + } + + /** + * By default, the template delimiters used by Lo-Dash are similar to those in + * embedded Ruby (ERB). Change the following template settings to use alternative + * delimiters. + * + * @static + * @memberOf _ + * @type Object + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'escape': /<%-([\s\S]+?)%>/g, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'evaluate': /<%([\s\S]+?)%>/g, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type RegExp + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type String + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type Object + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type Function + */ + '_': lodash + } + }; + + /*--------------------------------------------------------------------------*/ + + /** + * The template used to create iterator functions. + * + * @private + * @param {Obect} data The data object used to populate the text. + * @returns {String} Returns the interpolated text. + */ + var iteratorTemplate = function(obj) { + + var __p = 'var index, iterable = ' + + (obj.firstArg ) + + ', result = iterable;\nif (!iterable) return result;\n' + + (obj.top ) + + ';\n'; + if (obj.arrays) { + __p += 'var length = iterable.length; index = -1;\nif (' + + (obj.arrays ) + + ') { '; + if (obj.noCharByIndex) { + __p += '\n if (isString(iterable)) {\n iterable = iterable.split(\'\')\n } '; + } ; + __p += '\n while (++index < length) {\n ' + + (obj.loop ) + + '\n }\n}\nelse { '; + } else if (obj.nonEnumArgs) { + __p += '\n var length = iterable.length; index = -1;\n if (length && isArguments(iterable)) {\n while (++index < length) {\n index += \'\';\n ' + + (obj.loop ) + + '\n }\n } else { '; + } ; + + if (obj.hasEnumPrototype) { + __p += '\n var skipProto = typeof iterable == \'function\';\n '; + } ; + + if (obj.isKeysFast && obj.useHas) { + __p += '\n var ownIndex = -1,\n ownProps = objectTypes[typeof iterable] ? nativeKeys(iterable) : [],\n length = ownProps.length;\n\n while (++ownIndex < length) {\n index = ownProps[ownIndex];\n '; + if (obj.hasEnumPrototype) { + __p += 'if (!(skipProto && index == \'prototype\')) {\n '; + } ; + __p += + (obj.loop ) + + ''; + if (obj.hasEnumPrototype) { + __p += '}\n'; + } ; + __p += ' } '; + } else { + __p += '\n for (index in iterable) {'; + if (obj.hasEnumPrototype || obj.useHas) { + __p += '\n if ('; + if (obj.hasEnumPrototype) { + __p += '!(skipProto && index == \'prototype\')'; + } if (obj.hasEnumPrototype && obj.useHas) { + __p += ' && '; + } if (obj.useHas) { + __p += 'hasOwnProperty.call(iterable, index)'; + } ; + __p += ') { '; + } ; + __p += + (obj.loop ) + + '; '; + if (obj.hasEnumPrototype || obj.useHas) { + __p += '\n }'; + } ; + __p += '\n } '; + } ; + + if (obj.hasDontEnumBug) { + __p += '\n\n var ctor = iterable.constructor;\n '; + for (var k = 0; k < 7; k++) { + __p += '\n index = \'' + + (obj.shadowed[k] ) + + '\';\n if ('; + if (obj.shadowed[k] == 'constructor') { + __p += '!(ctor && ctor.prototype === iterable) && '; + } ; + __p += 'hasOwnProperty.call(iterable, index)) {\n ' + + (obj.loop ) + + '\n } '; + } ; + + } ; + + if (obj.arrays || obj.nonEnumArgs) { + __p += '\n}'; + } ; + __p += + (obj.bottom ) + + ';\nreturn result'; + + + return __p + }; + + /** Reusable iterator options for `assign` and `defaults` */ + var defaultsIteratorOptions = { + 'args': 'object, source, guard', + 'top': + 'var args = arguments,\n' + + ' argsIndex = 0,\n' + + " argsLength = typeof guard == 'number' ? 2 : args.length;\n" + + 'while (++argsIndex < argsLength) {\n' + + ' iterable = args[argsIndex];\n' + + ' if (iterable && objectTypes[typeof iterable]) {', + 'loop': "if (typeof result[index] == 'undefined') result[index] = iterable[index]", + 'bottom': ' }\n}' + }; + + /** Reusable iterator options shared by `each`, `forIn`, and `forOwn` */ + var eachIteratorOptions = { + 'args': 'collection, callback, thisArg', + 'top': "callback = callback && typeof thisArg == 'undefined' ? callback : createCallback(callback, thisArg)", + 'arrays': "typeof length == 'number'", + 'loop': 'if (callback(iterable[index], index, collection) === false) return result' + }; + + /** Reusable iterator options for `forIn` and `forOwn` */ + var forOwnIteratorOptions = { + 'top': 'if (!objectTypes[typeof iterable]) return result;\n' + eachIteratorOptions.top, + 'arrays': false + }; + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a function optimized to search large arrays for a given `value`, + * starting at `fromIndex`, using strict equality for comparisons, i.e. `===`. + * + * @private + * @param {Array} array The array to search. + * @param {Mixed} value The value to search for. + * @param {Number} [fromIndex=0] The index to search from. + * @param {Number} [largeSize=30] The length at which an array is considered large. + * @returns {Boolean} Returns `true`, if `value` is found, else `false`. + */ + function cachedContains(array, fromIndex, largeSize) { + fromIndex || (fromIndex = 0); + + var length = array.length, + isLarge = (length - fromIndex) >= (largeSize || largeArraySize); + + if (isLarge) { + var cache = {}, + index = fromIndex - 1; + + while (++index < length) { + // manually coerce `value` to a string because `hasOwnProperty`, in some + // older versions of Firefox, coerces objects incorrectly + var key = array[index] + ''; + (hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = [])).push(array[index]); + } + } + return function(value) { + if (isLarge) { + var key = value + ''; + return hasOwnProperty.call(cache, key) && indexOf(cache[key], value) > -1; + } + return indexOf(array, value, fromIndex) > -1; + } + } + + /** + * Used by `_.max` and `_.min` as the default `callback` when a given + * `collection` is a string value. + * + * @private + * @param {String} value The character to inspect. + * @returns {Number} Returns the code unit of given character. + */ + function charAtCallback(value) { + return value.charCodeAt(0); + } + + /** + * Used by `sortBy` to compare transformed `collection` values, stable sorting + * them in ascending order. + * + * @private + * @param {Object} a The object to compare to `b`. + * @param {Object} b The object to compare to `a`. + * @returns {Number} Returns the sort order indicator of `1` or `-1`. + */ + function compareAscending(a, b) { + var ai = a.index, + bi = b.index; + + a = a.criteria; + b = b.criteria; + + // ensure a stable sort in V8 and other engines + // http://code.google.com/p/v8/issues/detail?id=90 + if (a !== b) { + if (a > b || typeof a == 'undefined') { + return 1; + } + if (a < b || typeof b == 'undefined') { + return -1; + } + } + return ai < bi ? -1 : 1; + } + + /** + * Creates a function that, when called, invokes `func` with the `this` binding + * of `thisArg` and prepends any `partialArgs` to the arguments passed to the + * bound function. + * + * @private + * @param {Function|String} func The function to bind or the method name. + * @param {Mixed} [thisArg] The `this` binding of `func`. + * @param {Array} partialArgs An array of arguments to be partially applied. + * @param {Object} [rightIndicator] Used to indicate partially applying arguments from the right. + * @returns {Function} Returns the new bound function. + */ + function createBound(func, thisArg, partialArgs, rightIndicator) { + var isFunc = isFunction(func), + isPartial = !partialArgs, + key = thisArg; + + // juggle arguments + if (isPartial) { + partialArgs = thisArg; + } + if (!isFunc) { + thisArg = func; + } + + function bound() { + // `Function#bind` spec + // http://es5.github.com/#x15.3.4.5 + var args = arguments, + thisBinding = isPartial ? this : thisArg; + + if (!isFunc) { + func = thisArg[key]; + } + if (partialArgs.length) { + args = args.length + ? (args = slice(args), rightIndicator ? args.concat(partialArgs) : partialArgs.concat(args)) + : partialArgs; + } + if (this instanceof bound) { + // ensure `new bound` is an instance of `bound` and `func` + noop.prototype = func.prototype; + thisBinding = new noop; + noop.prototype = null; + + // mimic the constructor's `return` behavior + // http://es5.github.com/#x13.2.2 + var result = func.apply(thisBinding, args); + return isObject(result) ? result : thisBinding; + } + return func.apply(thisBinding, args); + } + return bound; + } + + /** + * Produces a callback bound to an optional `thisArg`. If `func` is a property + * name, the created callback will return the property value for a given element. + * If `func` is an object, the created callback will return `true` for elements + * that contain the equivalent object properties, otherwise it will return `false`. + * + * @private + * @param {Mixed} [func=identity] The value to convert to a callback. + * @param {Mixed} [thisArg] The `this` binding of the created callback. + * @param {Number} [argCount=3] The number of arguments the callback accepts. + * @returns {Function} Returns a callback function. + */ + function createCallback(func, thisArg, argCount) { + if (func == null) { + return identity; + } + var type = typeof func; + if (type != 'function') { + if (type != 'object') { + return function(object) { + return object[func]; + }; + } + var props = keys(func); + return function(object) { + var length = props.length, + result = false; + while (length--) { + if (!(result = isEqual(object[props[length]], func[props[length]], indicatorObject))) { + break; + } + } + return result; + }; + } + if (typeof thisArg != 'undefined') { + if (argCount === 1) { + return function(value) { + return func.call(thisArg, value); + }; + } + if (argCount === 2) { + return function(a, b) { + return func.call(thisArg, a, b); + }; + } + if (argCount === 4) { + return function(accumulator, value, index, object) { + return func.call(thisArg, accumulator, value, index, object); + }; + } + return function(value, index, object) { + return func.call(thisArg, value, index, object); + }; + } + return func; + } + + /** + * Creates compiled iteration functions. + * + * @private + * @param {Object} [options1, options2, ...] The compile options object(s). + * arrays - A string of code to determine if the iterable is an array or array-like. + * useHas - A boolean to specify using `hasOwnProperty` checks in the object loop. + * args - A string of comma separated arguments the iteration function will accept. + * top - A string of code to execute before the iteration branches. + * loop - A string of code to execute in the object loop. + * bottom - A string of code to execute after the iteration branches. + * + * @returns {Function} Returns the compiled function. + */ + function createIterator() { + var data = { + // support properties + 'hasDontEnumBug': hasDontEnumBug, + 'hasEnumPrototype': hasEnumPrototype, + 'isKeysFast': isKeysFast, + 'nonEnumArgs': nonEnumArgs, + 'noCharByIndex': noCharByIndex, + 'shadowed': shadowed, + + // iterator options + 'arrays': 'isArray(iterable)', + 'bottom': '', + 'loop': '', + 'top': '', + 'useHas': true + }; + + // merge options into a template data object + for (var object, index = 0; object = arguments[index]; index++) { + for (var key in object) { + data[key] = object[key]; + } + } + var args = data.args; + data.firstArg = /^[^,]+/.exec(args)[0]; + + // create the function factory + var factory = Function( + 'createCallback, hasOwnProperty, isArguments, isArray, isString, ' + + 'objectTypes, nativeKeys', + 'return function(' + args + ') {\n' + iteratorTemplate(data) + '\n}' + ); + // return the compiled function + return factory( + createCallback, hasOwnProperty, isArguments, isArray, isString, + objectTypes, nativeKeys + ); + } + + /** + * A function compiled to iterate `arguments` objects, arrays, objects, and + * strings consistenly across environments, executing the `callback` for each + * element in the `collection`. The `callback` is bound to `thisArg` and invoked + * with three arguments; (value, index|key, collection). Callbacks may exit + * iteration early by explicitly returning `false`. + * + * @private + * @type Function + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|String} Returns `collection`. + */ + var each = createIterator(eachIteratorOptions); + + /** + * Used by `template` to escape characters for inclusion in compiled + * string literals. + * + * @private + * @param {String} match The matched character to escape. + * @returns {String} Returns the escaped character. + */ + function escapeStringChar(match) { + return '\\' + stringEscapes[match]; + } + + /** + * Used by `escape` to convert characters to HTML entities. + * + * @private + * @param {String} match The matched character to escape. + * @returns {String} Returns the escaped character. + */ + function escapeHtmlChar(match) { + return htmlEscapes[match]; + } + + /** + * Checks if `value` is a DOM node in IE < 9. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a DOM node, else `false`. + */ + function isNode(value) { + // IE < 9 presents DOM nodes as `Object` objects except they have `toString` + // methods that are `typeof` "string" and still can coerce nodes to strings + return typeof value.toString != 'function' && typeof (value + '') == 'string'; + } + + /** + * A no-operation function. + * + * @private + */ + function noop() { + // no operation performed + } + + /** + * Slices the `collection` from the `start` index up to, but not including, + * the `end` index. + * + * Note: This function is used, instead of `Array#slice`, to support node lists + * in IE < 9 and to ensure dense arrays are returned. + * + * @private + * @param {Array|Object|String} collection The collection to slice. + * @param {Number} start The start index. + * @param {Number} end The end index. + * @returns {Array} Returns the new array. + */ + function slice(array, start, end) { + start || (start = 0); + if (typeof end == 'undefined') { + end = array ? array.length : 0; + } + var index = -1, + length = end - start || 0, + result = Array(length < 0 ? 0 : length); + + while (++index < length) { + result[index] = array[start + index]; + } + return result; + } + + /** + * Used by `unescape` to convert HTML entities to characters. + * + * @private + * @param {String} match The matched character to unescape. + * @returns {String} Returns the unescaped character. + */ + function unescapeHtmlChar(match) { + return htmlUnescapes[match]; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Checks if `value` is an `arguments` object. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is an `arguments` object, else `false`. + * @example + * + * (function() { return _.isArguments(arguments); })(1, 2, 3); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + function isArguments(value) { + return toString.call(value) == argsClass; + } + // fallback for browsers that can't detect `arguments` objects by [[Class]] + if (noArgsClass) { + isArguments = function(value) { + return value ? hasOwnProperty.call(value, 'callee') : false; + }; + } + + /** + * Iterates over `object`'s own and inherited enumerable properties, executing + * the `callback` for each property. The `callback` is bound to `thisArg` and + * invoked with three arguments; (value, key, object). Callbacks may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * function Dog(name) { + * this.name = name; + * } + * + * Dog.prototype.bark = function() { + * alert('Woof, woof!'); + * }; + * + * _.forIn(new Dog('Dagny'), function(value, key) { + * alert(key); + * }); + * // => alerts 'name' and 'bark' (order is not guaranteed) + */ + var forIn = createIterator(eachIteratorOptions, forOwnIteratorOptions, { + 'useHas': false + }); + + /** + * Iterates over an object's own enumerable properties, executing the `callback` + * for each property. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, key, object). Callbacks may exit iteration early by explicitly + * returning `false`. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The object to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns `object`. + * @example + * + * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + * alert(key); + * }); + * // => alerts '0', '1', and 'length' (order is not guaranteed) + */ + var forOwn = createIterator(eachIteratorOptions, forOwnIteratorOptions); + + /** + * Checks if `value` is an array. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is an array, else `false`. + * @example + * + * (function() { return _.isArray(arguments); })(); + * // => false + * + * _.isArray([1, 2, 3]); + * // => true + */ + var isArray = nativeIsArray || function(value) { + // `instanceof` may cause a memory leak in IE 7 if `value` is a host object + // http://ajaxian.com/archives/working-aroung-the-instanceof-memory-leak + return (argsAreObjects && value instanceof Array) || toString.call(value) == arrayClass; + }; + + /** + * Creates an array composed of the own enumerable property names of `object`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns a new array of property names. + * @example + * + * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); + * // => ['one', 'two', 'three'] (order is not guaranteed) + */ + var keys = !nativeKeys ? shimKeys : function(object) { + if (!isObject(object)) { + return []; + } + if ((hasEnumPrototype && typeof object == 'function') || + (nonEnumArgs && object.length && isArguments(object))) { + return shimKeys(object); + } + return nativeKeys(object); + }; + + /** + * A fallback implementation of `isPlainObject` that checks if a given `value` + * is an object created by the `Object` constructor, assuming objects created + * by the `Object` constructor have no inherited enumerable properties and that + * there are no `Object.prototype` extensions. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if `value` is a plain object, else `false`. + */ + function shimIsPlainObject(value) { + // avoid non-objects and false positives for `arguments` objects + var result = false; + if (!(value && typeof value == 'object') || isArguments(value)) { + return result; + } + // check that the constructor is `Object` (i.e. `Object instanceof Object`) + var ctor = value.constructor; + if ((!isFunction(ctor) && (!noNodeClass || !isNode(value))) || ctor instanceof ctor) { + // IE < 9 iterates inherited properties before own properties. If the first + // iterated property is an object's own property then there are no inherited + // enumerable properties. + if (iteratesOwnLast) { + forIn(value, function(value, key, object) { + result = !hasOwnProperty.call(object, key); + return false; + }); + return result === false; + } + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + forIn(value, function(value, key) { + result = key; + }); + return result === false || hasOwnProperty.call(value, result); + } + return result; + } + + /** + * A fallback implementation of `Object.keys` that produces an array of the + * given object's own enumerable property names. + * + * @private + * @param {Object} object The object to inspect. + * @returns {Array} Returns a new array of property names. + */ + function shimKeys(object) { + var result = []; + forOwn(object, function(value, key) { + result.push(key); + }); + return result; + } + + /** + * Used to convert characters to HTML entities: + * + * Though the `>` character is escaped for symmetry, characters like `>` and `/` + * don't require escaping in HTML and have no special meaning unless they're part + * of a tag or an unquoted attribute value. + * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") + */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to convert HTML entities to characters */ + var htmlUnescapes = invert(htmlEscapes); + + /*--------------------------------------------------------------------------*/ + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object. Subsequent sources will overwrite propery assignments of previous + * sources. If a `callback` function is passed, it will be executed to produce + * the assigned values. The `callback` is bound to `thisArg` and invoked with + * two arguments; (objectValue, sourceValue). + * + * @static + * @memberOf _ + * @type Function + * @alias extend + * @category Objects + * @param {Object} object The destination object. + * @param {Object} [source1, source2, ...] The source objects. + * @param {Function} [callback] The function to customize assigning values. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the destination object. + * @example + * + * _.assign({ 'name': 'moe' }, { 'age': 40 }); + * // => { 'name': 'moe', 'age': 40 } + * + * var defaults = _.partialRight(_.assign, function(a, b) { + * return typeof a == 'undefined' ? b : a; + * }); + * + * var food = { 'name': 'apple' }; + * defaults(food, { 'name': 'banana', 'type': 'fruit' }); + * // => { 'name': 'apple', 'type': 'fruit' } + */ + var assign = createIterator(defaultsIteratorOptions, { + 'top': + defaultsIteratorOptions.top.replace(';', + ';\n' + + "if (argsLength > 3 && typeof args[argsLength - 2] == 'function') {\n" + + ' var callback = createCallback(args[--argsLength - 1], args[argsLength--], 2);\n' + + "} else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') {\n" + + ' callback = args[--argsLength];\n' + + '}' + ), + 'loop': 'result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]' + }); + + /** + * Creates a clone of `value`. If `deep` is `true`, nested objects will also + * be cloned, otherwise they will be assigned by reference. If a `callback` + * function is passed, it will be executed to produce the cloned values. If + * `callback` returns `undefined`, cloning will be handled by the method instead. + * The `callback` is bound to `thisArg` and invoked with one argument; (value). + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to clone. + * @param {Boolean} [deep=false] A flag to indicate a deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @param- {Array} [stackA=[]] Internally used to track traversed source objects. + * @param- {Array} [stackB=[]] Internally used to associate clones with source counterparts. + * @returns {Mixed} Returns the cloned `value`. + * @example + * + * var stooges = [ + * { 'name': 'moe', 'age': 40 }, + * { 'name': 'larry', 'age': 50 } + * ]; + * + * var shallow = _.clone(stooges); + * shallow[0] === stooges[0]; + * // => true + * + * var deep = _.clone(stooges, true); + * deep[0] === stooges[0]; + * // => false + * + * _.mixin({ + * 'clone': _.partialRight(_.clone, function(value) { + * return _.isElement(value) ? value.cloneNode(false) : undefined; + * }) + * }); + * + * var clone = _.clone(document.body); + * clone.childNodes.length; + * // => 0 + */ + function clone(value, deep, callback, thisArg, stackA, stackB) { + var result = value; + + // allows working with "Collections" methods without using their `callback` + // argument, `index|key`, for this method's `callback` + if (typeof deep == 'function') { + thisArg = callback; + callback = deep; + deep = false; + } + if (typeof callback == 'function') { + callback = typeof thisArg == 'undefined' ? callback : createCallback(callback, thisArg, 1); + result = callback(result); + + var done = typeof result != 'undefined'; + if (!done) { + result = value; + } + } + // inspect [[Class]] + var isObj = isObject(result); + if (isObj) { + var className = toString.call(result); + if (!cloneableClasses[className] || (noNodeClass && isNode(result))) { + return result; + } + var isArr = isArray(result); + } + // shallow clone + if (!isObj || !deep) { + return isObj && !done + ? (isArr ? slice(result) : assign({}, result)) + : result; + } + var ctor = ctorByClass[className]; + switch (className) { + case boolClass: + case dateClass: + return done ? result : new ctor(+result); + + case numberClass: + case stringClass: + return done ? result : new ctor(result); + + case regexpClass: + return done ? result : ctor(result.source, reFlags.exec(result)); + } + // check for circular references and return corresponding clone + stackA || (stackA = []); + stackB || (stackB = []); + + var length = stackA.length; + while (length--) { + if (stackA[length] == value) { + return stackB[length]; + } + } + // init cloned object + if (!done) { + result = isArr ? ctor(result.length) : {}; + + // add array properties assigned by `RegExp#exec` + if (isArr) { + if (hasOwnProperty.call(value, 'index')) { + result.index = value.index; + } + if (hasOwnProperty.call(value, 'input')) { + result.input = value.input; + } + } + } + // add the source value to the stack of traversed objects + // and associate it with its clone + stackA.push(value); + stackB.push(result); + + // recursively populate clone (susceptible to call stack limits) + (isArr ? forEach : forOwn)(done ? result : value, function(objValue, key) { + result[key] = clone(objValue, deep, callback, undefined, stackA, stackB); + }); + + return result; + } + + /** + * Creates a deep clone of `value`. If a `callback` function is passed, it will + * be executed to produce the cloned values. If `callback` returns the value it + * was passed, cloning will be handled by the method instead. The `callback` is + * bound to `thisArg` and invoked with one argument; (value). + * + * Note: This function is loosely based on the structured clone algorithm. Functions + * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and + * objects created by constructors other than `Object` are cloned to plain `Object` objects. + * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to deep clone. + * @param {Function} [callback] The function to customize cloning values. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the deep cloned `value`. + * @example + * + * var stooges = [ + * { 'name': 'moe', 'age': 40 }, + * { 'name': 'larry', 'age': 50 } + * ]; + * + * var deep = _.cloneDeep(stooges); + * deep[0] === stooges[0]; + * // => false + * + * var view = { + * 'label': 'docs', + * 'node': element + * }; + * + * var clone = _.cloneDeep(view, function(value) { + * return _.isElement(value) ? value.cloneNode(true) : value; + * }); + * + * clone.node == view.node; + * // => false + */ + function cloneDeep(value, callback, thisArg) { + return clone(value, true, callback, thisArg); + } + + /** + * Assigns own enumerable properties of source object(s) to the destination + * object for all destination properties that resolve to `undefined`. Once a + * property is set, additional defaults of the same property will be ignored. + * + * @static + * @memberOf _ + * @type Function + * @category Objects + * @param {Object} object The destination object. + * @param {Object} [source1, source2, ...] The source objects. + * @param- {Object} [guard] Internally used to allow working with `_.reduce` + * without using its callback's `key` and `object` arguments as sources. + * @returns {Object} Returns the destination object. + * @example + * + * var food = { 'name': 'apple' }; + * _.defaults(food, { 'name': 'banana', 'type': 'fruit' }); + * // => { 'name': 'apple', 'type': 'fruit' } + */ + var defaults = createIterator(defaultsIteratorOptions); + + /** + * Creates a sorted array of all enumerable properties, own and inherited, + * of `object` that have function values. + * + * @static + * @memberOf _ + * @alias methods + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns a new array of property names that have function values. + * @example + * + * _.functions(_); + * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] + */ + function functions(object) { + var result = []; + forIn(object, function(value, key) { + if (isFunction(value)) { + result.push(key); + } + }); + return result.sort(); + } + + /** + * Checks if the specified object `property` exists and is a direct property, + * instead of an inherited property. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to check. + * @param {String} property The property to check for. + * @returns {Boolean} Returns `true` if key is a direct property, else `false`. + * @example + * + * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); + * // => true + */ + function has(object, property) { + return object ? hasOwnProperty.call(object, property) : false; + } + + /** + * Creates an object composed of the inverted keys and values of the given `object`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to invert. + * @returns {Object} Returns the created inverted object. + * @example + * + * _.invert({ 'first': 'moe', 'second': 'larry' }); + * // => { 'moe': 'first', 'larry': 'second' } (order is not guaranteed) + */ + function invert(object) { + var index = -1, + props = keys(object), + length = props.length, + result = {}; + + while (++index < length) { + var key = props[index]; + result[object[key]] = key; + } + return result; + } + + /** + * Checks if `value` is a boolean value. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is a boolean value, else `false`. + * @example + * + * _.isBoolean(null); + * // => false + */ + function isBoolean(value) { + return value === true || value === false || toString.call(value) == boolClass; + } + + /** + * Checks if `value` is a date. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is a date, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + */ + function isDate(value) { + return value instanceof Date || toString.call(value) == dateClass; + } + + /** + * Checks if `value` is a DOM element. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + */ + function isElement(value) { + return value ? value.nodeType === 1 : false; + } + + /** + * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a + * length of `0` and objects with no own enumerable properties are considered + * "empty". + * + * @static + * @memberOf _ + * @category Objects + * @param {Array|Object|String} value The value to inspect. + * @returns {Boolean} Returns `true`, if the `value` is empty, else `false`. + * @example + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({}); + * // => true + * + * _.isEmpty(''); + * // => true + */ + function isEmpty(value) { + var result = true; + if (!value) { + return result; + } + var className = toString.call(value), + length = value.length; + + if ((className == arrayClass || className == stringClass || + className == argsClass || (noArgsClass && isArguments(value))) || + (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { + return !length; + } + forOwn(value, function() { + return (result = false); + }); + return result; + } + + /** + * Performs a deep comparison between two values to determine if they are + * equivalent to each other. If `callback` is passed, it will be executed to + * compare values. If `callback` returns `undefined`, comparisons will be handled + * by the method instead. The `callback` is bound to `thisArg` and invoked with + * two arguments; (a, b). + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} a The value to compare. + * @param {Mixed} b The other value to compare. + * @param {Function} [callback] The function to customize comparing values. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @param- {Object} [stackA=[]] Internally used track traversed `a` objects. + * @param- {Object} [stackB=[]] Internally used track traversed `b` objects. + * @returns {Boolean} Returns `true`, if the values are equvalent, else `false`. + * @example + * + * var moe = { 'name': 'moe', 'age': 40 }; + * var copy = { 'name': 'moe', 'age': 40 }; + * + * moe == copy; + * // => false + * + * _.isEqual(moe, copy); + * // => true + * + * var words = ['hello', 'goodbye']; + * var otherWords = ['hi', 'goodbye']; + * + * _.isEqual(words, otherWords, function(a, b) { + * var reGreet = /^(?:hello|hi)$/i, + * aGreet = _.isString(a) && reGreet.test(a), + * bGreet = _.isString(b) && reGreet.test(b); + * + * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; + * }); + * // => true + */ + function isEqual(a, b, callback, thisArg, stackA, stackB) { + // used to indicate that when comparing objects, `a` has at least the properties of `b` + var whereIndicator = callback === indicatorObject; + if (callback && !whereIndicator) { + callback = typeof thisArg == 'undefined' ? callback : createCallback(callback, thisArg, 2); + var result = callback(a, b); + if (typeof result != 'undefined') { + return !!result; + } + } + // exit early for identical values + if (a === b) { + // treat `+0` vs. `-0` as not equal + return a !== 0 || (1 / a == 1 / b); + } + var type = typeof a, + otherType = typeof b; + + // exit early for unlike primitive values + if (a === a && + (!a || (type != 'function' && type != 'object')) && + (!b || (otherType != 'function' && otherType != 'object'))) { + return false; + } + // exit early for `null` and `undefined`, avoiding ES3's Function#call behavior + // http://es5.github.com/#x15.3.4.4 + if (a == null || b == null) { + return a === b; + } + // compare [[Class]] names + var className = toString.call(a), + otherClass = toString.call(b); + + if (className == argsClass) { + className = objectClass; + } + if (otherClass == argsClass) { + otherClass = objectClass; + } + if (className != otherClass) { + return false; + } + switch (className) { + case boolClass: + case dateClass: + // coerce dates and booleans to numbers, dates to milliseconds and booleans + // to `1` or `0`, treating invalid dates coerced to `NaN` as not equal + return +a == +b; + + case numberClass: + // treat `NaN` vs. `NaN` as equal + return a != +a + ? b != +b + // but treat `+0` vs. `-0` as not equal + : (a == 0 ? (1 / a == 1 / b) : a == +b); + + case regexpClass: + case stringClass: + // coerce regexes to strings (http://es5.github.com/#x15.10.6.4) + // treat string primitives and their corresponding object instances as equal + return a == b + ''; + } + var isArr = className == arrayClass; + if (!isArr) { + // unwrap any `lodash` wrapped values + if (a.__wrapped__ || b.__wrapped__) { + return isEqual(a.__wrapped__ || a, b.__wrapped__ || b, callback, thisArg, stackA, stackB); + } + // exit for functions and DOM nodes + if (className != objectClass || (noNodeClass && (isNode(a) || isNode(b)))) { + return false; + } + // in older versions of Opera, `arguments` objects have `Array` constructors + var ctorA = !argsAreObjects && isArguments(a) ? Object : a.constructor, + ctorB = !argsAreObjects && isArguments(b) ? Object : b.constructor; + + // non `Object` object instances with different constructors are not equal + if (ctorA != ctorB && !( + isFunction(ctorA) && ctorA instanceof ctorA && + isFunction(ctorB) && ctorB instanceof ctorB + )) { + return false; + } + } + // assume cyclic structures are equal + // the algorithm for detecting cyclic structures is adapted from ES 5.1 + // section 15.12.3, abstract operation `JO` (http://es5.github.com/#x15.12.3) + stackA || (stackA = []); + stackB || (stackB = []); + + var length = stackA.length; + while (length--) { + if (stackA[length] == a) { + return stackB[length] == b; + } + } + var size = 0; + result = true; + + // add `a` and `b` to the stack of traversed objects + stackA.push(a); + stackB.push(b); + + // recursively compare objects and arrays (susceptible to call stack limits) + if (isArr) { + length = a.length; + size = b.length; + + // compare lengths to determine if a deep comparison is necessary + result = size == a.length; + if (!result && !whereIndicator) { + return result; + } + // deep compare the contents, ignoring non-numeric properties + while (size--) { + var index = length, + value = b[size]; + + if (whereIndicator) { + while (index--) { + if ((result = isEqual(a[index], value, callback, thisArg, stackA, stackB))) { + break; + } + } + } else if (!(result = isEqual(a[size], value, callback, thisArg, stackA, stackB))) { + break; + } + } + return result; + } + // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` + // which, in this case, is more costly + forIn(b, function(value, key, b) { + if (hasOwnProperty.call(b, key)) { + // count the number of properties. + size++; + // deep compare each property value. + return (result = hasOwnProperty.call(a, key) && isEqual(a[key], value, callback, thisArg, stackA, stackB)); + } + }); + + if (result && !whereIndicator) { + // ensure both objects have the same number of properties + forIn(a, function(value, key, a) { + if (hasOwnProperty.call(a, key)) { + // `size` will be `-1` if `a` has more properties than `b` + return (result = --size > -1); + } + }); + } + return result; + } + + /** + * Checks if `value` is, or can be coerced to, a finite number. + * + * Note: This is not the same as native `isFinite`, which will return true for + * booleans and empty strings. See http://es5.github.com/#x15.1.2.5. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is finite, else `false`. + * @example + * + * _.isFinite(-101); + * // => true + * + * _.isFinite('10'); + * // => true + * + * _.isFinite(true); + * // => false + * + * _.isFinite(''); + * // => false + * + * _.isFinite(Infinity); + * // => false + */ + function isFinite(value) { + return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); + } + + /** + * Checks if `value` is a function. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + */ + function isFunction(value) { + return typeof value == 'function'; + } + // fallback for older versions of Chrome and Safari + if (isFunction(/x/)) { + isFunction = function(value) { + return value instanceof Function || toString.call(value) == funcClass; + }; + } + + /** + * Checks if `value` is the language type of Object. + * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(1); + * // => false + */ + function isObject(value) { + // check if the value is the ECMAScript language type of Object + // http://es5.github.com/#x8 + // and avoid a V8 bug + // http://code.google.com/p/v8/issues/detail?id=2291 + return value ? objectTypes[typeof value] : false; + } + + /** + * Checks if `value` is `NaN`. + * + * Note: This is not the same as native `isNaN`, which will return `true` for + * `undefined` and other values. See http://es5.github.com/#x15.1.2.4. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ + function isNaN(value) { + // `NaN` as a primitive is the only value that is not equal to itself + // (perform the [[Class]] check first to avoid errors with some host objects in IE) + return isNumber(value) && value != +value + } + + /** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(undefined); + * // => false + */ + function isNull(value) { + return value === null; + } + + /** + * Checks if `value` is a number. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is a number, else `false`. + * @example + * + * _.isNumber(8.4 * 5); + * // => true + */ + function isNumber(value) { + return typeof value == 'number' || toString.call(value) == numberClass; + } + + /** + * Checks if a given `value` is an object created by the `Object` constructor. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if `value` is a plain object, else `false`. + * @example + * + * function Stooge(name, age) { + * this.name = name; + * this.age = age; + * } + * + * _.isPlainObject(new Stooge('moe', 40)); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'name': 'moe', 'age': 40 }); + * // => true + */ + var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { + if (!(value && typeof value == 'object')) { + return false; + } + var valueOf = value.valueOf, + objProto = typeof valueOf == 'function' && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); + + return objProto + ? value == objProto || (getPrototypeOf(value) == objProto && !isArguments(value)) + : shimIsPlainObject(value); + }; + + /** + * Checks if `value` is a regular expression. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is a regular expression, else `false`. + * @example + * + * _.isRegExp(/moe/); + * // => true + */ + function isRegExp(value) { + return value instanceof RegExp || toString.call(value) == regexpClass; + } + + /** + * Checks if `value` is a string. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is a string, else `false`. + * @example + * + * _.isString('moe'); + * // => true + */ + function isString(value) { + return typeof value == 'string' || toString.call(value) == stringClass; + } + + /** + * Checks if `value` is `undefined`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true`, if the `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + */ + function isUndefined(value) { + return typeof value == 'undefined'; + } + + /** + * Recursively merges own enumerable properties of the source object(s), that + * don't resolve to `undefined`, into the destination object. Subsequent sources + * will overwrite propery assignments of previous sources. If a `callback` function + * is passed, it will be executed to produce the merged values of the destination + * and source properties. If `callback` returns `undefined`, merging will be + * handled by the method instead. The `callback` is bound to `thisArg` and + * invoked with two arguments; (objectValue, sourceValue). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The destination object. + * @param {Object} [source1, source2, ...] The source objects. + * @param {Function} [callback] The function to customize merging properties. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @param- {Object} [deepIndicator] Internally used to indicate that `stackA` + * and `stackB` are arrays of traversed objects instead of source objects. + * @param- {Array} [stackA=[]] Internally used to track traversed source objects. + * @param- {Array} [stackB=[]] Internally used to associate values with their + * source counterparts. + * @returns {Object} Returns the destination object. + * @example + * + * var names = { + * 'stooges': [ + * { 'name': 'moe' }, + * { 'name': 'larry' } + * ] + * }; + * + * var ages = { + * 'stooges': [ + * { 'age': 40 }, + * { 'age': 50 } + * ] + * }; + * + * _.merge(names, ages); + * // => { 'stooges': [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }] } + * + * var food = { + * 'fruits': ['apple'], + * 'vegetables': ['beet'] + * }; + * + * var otherFood = { + * 'fruits': ['banana'], + * 'vegetables': ['carrot'] + * }; + * + * _.merge(food, otherFood, function(a, b) { + * return _.isArray(a) ? a.concat(b) : undefined; + * }); + * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } + */ + function merge(object, source, deepIndicator) { + var args = arguments, + index = 0, + length = 2; + + if (!isObject(object)) { + return object; + } + if (deepIndicator === indicatorObject) { + var callback = args[3], + stackA = args[4], + stackB = args[5]; + } else { + stackA = []; + stackB = []; + + // allows working with `_.reduce` and `_.reduceRight` without + // using their `callback` arguments, `index|key` and `collection` + if (typeof deepIndicator != 'number') { + length = args.length; + } + if (length > 3 && typeof args[length - 2] == 'function') { + callback = createCallback(args[--length - 1], args[length--], 2); + } else if (length > 2 && typeof args[length - 1] == 'function') { + callback = args[--length]; + } + } + while (++index < length) { + (isArray(args[index]) ? forEach : forOwn)(args[index], function(source, key) { + var found, + isArr, + result = source, + value = object[key]; + + if (source && ((isArr = isArray(source)) || isPlainObject(source))) { + // avoid merging previously merged cyclic sources + var stackLength = stackA.length; + while (stackLength--) { + if ((found = stackA[stackLength] == source)) { + value = stackB[stackLength]; + break; + } + } + if (!found) { + value = isArr + ? (isArray(value) ? value : []) + : (isPlainObject(value) ? value : {}); + + if (callback) { + result = callback(value, source); + if (typeof result != 'undefined') { + value = result; + } + } + // add `source` and associated `value` to the stack of traversed objects + stackA.push(source); + stackB.push(value); + + // recursively merge objects and arrays (susceptible to call stack limits) + if (!callback) { + value = merge(value, source, indicatorObject, callback, stackA, stackB); + } + } + } + else { + if (callback) { + result = callback(value, source); + if (typeof result == 'undefined') { + result = source; + } + } + if (typeof result != 'undefined') { + value = result; + } + } + object[key] = value; + }); + } + return object; + } + + /** + * Creates a shallow clone of `object` excluding the specified properties. + * Property names may be specified as individual arguments or as arrays of + * property names. If a `callback` function is passed, it will be executed + * for each property in the `object`, omitting the properties `callback` + * returns truthy for. The `callback` is bound to `thisArg` and invoked + * with three arguments; (value, key, object). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The source object. + * @param {Function|String} callback|[prop1, prop2, ...] The properties to omit + * or the function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns an object without the omitted properties. + * @example + * + * _.omit({ 'name': 'moe', 'age': 40 }, 'age'); + * // => { 'name': 'moe' } + * + * _.omit({ 'name': 'moe', 'age': 40 }, function(value) { + * return typeof value == 'number'; + * }); + * // => { 'name': 'moe' } + */ + function omit(object, callback, thisArg) { + var isFunc = typeof callback == 'function', + result = {}; + + if (isFunc) { + callback = createCallback(callback, thisArg); + } else { + var props = concat.apply(arrayRef, arguments); + } + forIn(object, function(value, key, object) { + if (isFunc + ? !callback(value, key, object) + : indexOf(props, key, 1) < 0 + ) { + result[key] = value; + } + }); + return result; + } + + /** + * Creates a two dimensional array of the given object's key-value pairs, + * i.e. `[[key1, value1], [key2, value2]]`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns new array of key-value pairs. + * @example + * + * _.pairs({ 'moe': 30, 'larry': 40 }); + * // => [['moe', 30], ['larry', 40]] (order is not guaranteed) + */ + function pairs(object) { + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + var key = props[index]; + result[index] = [key, object[key]]; + } + return result; + } + + /** + * Creates a shallow clone of `object` composed of the specified properties. + * Property names may be specified as individual arguments or as arrays of property + * names. If `callback` is passed, it will be executed for each property in the + * `object`, picking the properties `callback` returns truthy for. The `callback` + * is bound to `thisArg` and invoked with three arguments; (value, key, object). + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The source object. + * @param {Array|Function|String} callback|[prop1, prop2, ...] The function called + * per iteration or properties to pick, either as individual arguments or arrays. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns an object composed of the picked properties. + * @example + * + * _.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name'); + * // => { 'name': 'moe' } + * + * _.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) { + * return key.charAt(0) != '_'; + * }); + * // => { 'name': 'moe' } + */ + function pick(object, callback, thisArg) { + var result = {}; + if (typeof callback != 'function') { + var index = 0, + props = concat.apply(arrayRef, arguments), + length = isObject(object) ? props.length : 0; + + while (++index < length) { + var key = props[index]; + if (key in object) { + result[key] = object[key]; + } + } + } else { + callback = createCallback(callback, thisArg); + forIn(object, function(value, key, object) { + if (callback(value, key, object)) { + result[key] = value; + } + }); + } + return result; + } + + /** + * Creates an array composed of the own enumerable property values of `object`. + * + * @static + * @memberOf _ + * @category Objects + * @param {Object} object The object to inspect. + * @returns {Array} Returns a new array of property values. + * @example + * + * _.values({ 'one': 1, 'two': 2, 'three': 3 }); + * // => [1, 2, 3] + */ + function values(object) { + var index = -1, + props = keys(object), + length = props.length, + result = Array(length); + + while (++index < length) { + result[index] = object[props[index]]; + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates an array of elements from the specified indexes, or keys, of the + * `collection`. Indexes may be specified as individual arguments or as arrays + * of indexes. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Array|Number|String} [index1, index2, ...] The indexes of + * `collection` to retrieve, either as individual arguments or arrays. + * @returns {Array} Returns a new array of elements corresponding to the + * provided indexes. + * @example + * + * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); + * // => ['a', 'c', 'e'] + * + * _.at(['moe', 'larry', 'curly'], 0, 2); + * // => ['moe', 'curly'] + */ + function at(collection) { + var index = -1, + props = concat.apply(arrayRef, slice(arguments, 1)), + length = props.length, + result = Array(length); + + if (noCharByIndex && isString(collection)) { + collection = collection.split(''); + } + while(++index < length) { + result[index] = collection[props[index]]; + } + return result; + } + + /** + * Checks if a given `target` element is present in a `collection` using strict + * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used + * as the offset from the end of the collection. + * + * @static + * @memberOf _ + * @alias include + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Mixed} target The value to check for. + * @param {Number} [fromIndex=0] The index to search from. + * @returns {Boolean} Returns `true` if the `target` element is found, else `false`. + * @example + * + * _.contains([1, 2, 3], 1); + * // => true + * + * _.contains([1, 2, 3], 1, 2); + * // => false + * + * _.contains({ 'name': 'moe', 'age': 40 }, 'moe'); + * // => true + * + * _.contains('curly', 'ur'); + * // => true + */ + function contains(collection, target, fromIndex) { + var index = -1, + length = collection ? collection.length : 0, + result = false; + + fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; + if (typeof length == 'number') { + result = (isString(collection) + ? collection.indexOf(target, fromIndex) + : indexOf(collection, target, fromIndex) + ) > -1; + } else { + each(collection, function(value) { + if (++index >= fromIndex) { + return !(result = value === target); + } + }); + } + return result; + } + + /** + * Creates an object composed of keys returned from running each element of the + * `collection` through the given `callback`. The corresponding value of each key + * is the number of times the key was returned by the `callback`. The `callback` + * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); + * // => { '4': 1, '6': 2 } + * + * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); + * // => { '4': 1, '6': 2 } + * + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + function countBy(collection, callback, thisArg) { + var result = {}; + callback = createCallback(callback, thisArg); + + forEach(collection, function(value, key, collection) { + key = callback(value, key, collection) + ''; + (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); + }); + return result; + } + + /** + * Checks if the `callback` returns a truthy value for **all** elements of a + * `collection`. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, index|key, collection). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias all + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Boolean} Returns `true` if all elements pass the callback check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var stooges = [ + * { 'name': 'moe', 'age': 40 }, + * { 'name': 'larry', 'age': 50 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.every(stooges, 'age'); + * // => true + * + * // using "_.where" callback shorthand + * _.every(stooges, { 'age': 50 }); + * // => false + */ + function every(collection, callback, thisArg) { + var result = true; + callback = createCallback(callback, thisArg); + + if (isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + if (!(result = !!callback(collection[index], index, collection))) { + break; + } + } + } else { + each(collection, function(value, index, collection) { + return (result = !!callback(value, index, collection)); + }); + } + return result; + } + + /** + * Examines each element in a `collection`, returning an array of all elements + * the `callback` returns truthy for. The `callback` is bound to `thisArg` and + * invoked with three arguments; (value, index|key, collection). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias select + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of elements that passed the callback check. + * @example + * + * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => [2, 4, 6] + * + * var food = [ + * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, + * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.filter(food, 'organic'); + * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }] + * + * // using "_.where" callback shorthand + * _.filter(food, { 'type': 'fruit' }); + * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }] + */ + function filter(collection, callback, thisArg) { + var result = []; + callback = createCallback(callback, thisArg); + + if (isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + if (callback(value, index, collection)) { + result.push(value); + } + } + } else { + each(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result.push(value); + } + }); + } + return result; + } + + /** + * Examines each element in a `collection`, returning the first that the `callback` + * returns truthy for. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, index|key, collection). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias detect + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the element that passed the callback check, + * else `undefined`. + * @example + * + * var even = _.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => 2 + * + * var food = [ + * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, + * { 'name': 'banana', 'organic': true, 'type': 'fruit' }, + * { 'name': 'beet', 'organic': false, 'type': 'vegetable' }, + * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } + * ]; + * + * // using "_.where" callback shorthand + * var veggie = _.find(food, { 'type': 'vegetable' }); + * // => { 'name': 'beet', 'organic': false, 'type': 'vegetable' } + * + * // using "_.pluck" callback shorthand + * var healthy = _.find(food, 'organic'); + * // => { 'name': 'banana', 'organic': true, 'type': 'fruit' } + */ + function find(collection, callback, thisArg) { + var result; + callback = createCallback(callback, thisArg); + + forEach(collection, function(value, index, collection) { + if (callback(value, index, collection)) { + result = value; + return false; + } + }); + return result; + } + + /** + * Iterates over a `collection`, executing the `callback` for each element in + * the `collection`. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, index|key, collection). Callbacks may exit iteration early + * by explicitly returning `false`. + * + * @static + * @memberOf _ + * @alias each + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array|Object|String} Returns `collection`. + * @example + * + * _([1, 2, 3]).forEach(alert).join(','); + * // => alerts each number and returns '1,2,3' + * + * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert); + * // => alerts each number value (order is not guaranteed) + */ + function forEach(collection, callback, thisArg) { + if (callback && typeof thisArg == 'undefined' && isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + if (callback(collection[index], index, collection) === false) { + break; + } + } + } else { + each(collection, callback, thisArg); + } + return collection; + } + + /** + * Creates an object composed of keys returned from running each element of the + * `collection` through the `callback`. The corresponding value of each key is + * an array of elements passed to `callback` that returned the key. The `callback` + * is bound to `thisArg` and invoked with three arguments; (value, index|key, collection). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false` + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); + * // => { '4': [4.2], '6': [6.1, 6.4] } + * + * // using "_.pluck" callback shorthand + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + function groupBy(collection, callback, thisArg) { + var result = {}; + callback = createCallback(callback, thisArg); + + forEach(collection, function(value, key, collection) { + key = callback(value, key, collection) + ''; + (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); + }); + return result; + } + + /** + * Invokes the method named by `methodName` on each element in the `collection`, + * returning an array of the results of each invoked method. Additional arguments + * will be passed to each invoked method. If `methodName` is a function, it will + * be invoked for, and `this` bound to, each element in the `collection`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|String} methodName The name of the method to invoke or + * the function invoked per iteration. + * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with. + * @returns {Array} Returns a new array of the results of each invoked method. + * @example + * + * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invoke([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + function invoke(collection, methodName) { + var args = slice(arguments, 2), + index = -1, + isFunc = typeof methodName == 'function', + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + forEach(collection, function(value) { + result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); + }); + return result; + } + + /** + * Creates an array of values by running each element in the `collection` + * through the `callback`. The `callback` is bound to `thisArg` and invoked with + * three arguments; (value, index|key, collection). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias collect + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of the results of each `callback` execution. + * @example + * + * _.map([1, 2, 3], function(num) { return num * 3; }); + * // => [3, 6, 9] + * + * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); + * // => [3, 6, 9] (order is not guaranteed) + * + * var stooges = [ + * { 'name': 'moe', 'age': 40 }, + * { 'name': 'larry', 'age': 50 } + * ]; + * + * // using "_.pluck" callback shorthand + * _.map(stooges, 'name'); + * // => ['moe', 'larry'] + */ + function map(collection, callback, thisArg) { + var index = -1, + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + callback = createCallback(callback, thisArg); + if (isArray(collection)) { + while (++index < length) { + result[index] = callback(collection[index], index, collection); + } + } else { + each(collection, function(value, key, collection) { + result[++index] = callback(value, key, collection); + }); + } + return result; + } + + /** + * Retrieves the maximum value of an `array`. If `callback` is passed, + * it will be executed for each value in the `array` to generate the + * criterion by which the value is ranked. The `callback` is bound to + * `thisArg` and invoked with three arguments; (value, index, collection). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * var stooges = [ + * { 'name': 'moe', 'age': 40 }, + * { 'name': 'larry', 'age': 50 } + * ]; + * + * _.max(stooges, function(stooge) { return stooge.age; }); + * // => { 'name': 'larry', 'age': 50 }; + * + * // using "_.pluck" callback shorthand + * _.max(stooges, 'age'); + * // => { 'name': 'larry', 'age': 50 }; + */ + function max(collection, callback, thisArg) { + var computed = -Infinity, + result = computed; + + if (!callback && isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + if (value > result) { + result = value; + } + } + } else { + callback = !callback && isString(collection) + ? charAtCallback + : createCallback(callback, thisArg); + + each(collection, function(value, index, collection) { + var current = callback(value, index, collection); + if (current > computed) { + computed = current; + result = value; + } + }); + } + return result; + } + + /** + * Retrieves the minimum value of an `array`. If `callback` is passed, + * it will be executed for each value in the `array` to generate the + * criterion by which the value is ranked. The `callback` is bound to `thisArg` + * and invoked with three arguments; (value, index, collection). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * var stooges = [ + * { 'name': 'moe', 'age': 40 }, + * { 'name': 'larry', 'age': 50 } + * ]; + * + * _.min(stooges, function(stooge) { return stooge.age; }); + * // => { 'name': 'moe', 'age': 40 }; + * + * // using "_.pluck" callback shorthand + * _.min(stooges, 'age'); + * // => { 'name': 'moe', 'age': 40 }; + */ + function min(collection, callback, thisArg) { + var computed = Infinity, + result = computed; + + if (!callback && isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + var value = collection[index]; + if (value < result) { + result = value; + } + } + } else { + callback = !callback && isString(collection) + ? charAtCallback + : createCallback(callback, thisArg); + + each(collection, function(value, index, collection) { + var current = callback(value, index, collection); + if (current < computed) { + computed = current; + result = value; + } + }); + } + return result; + } + + /** + * Retrieves the value of a specified property from all elements in the `collection`. + * + * @static + * @memberOf _ + * @type Function + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {String} property The property to pluck. + * @returns {Array} Returns a new array of property values. + * @example + * + * var stooges = [ + * { 'name': 'moe', 'age': 40 }, + * { 'name': 'larry', 'age': 50 } + * ]; + * + * _.pluck(stooges, 'name'); + * // => ['moe', 'larry'] + */ + var pluck = map; + + /** + * Reduces a `collection` to a value that is the accumulated result of running + * each element in the `collection` through the `callback`, where each successive + * `callback` execution consumes the return value of the previous execution. + * If `accumulator` is not passed, the first element of the `collection` will be + * used as the initial `accumulator` value. The `callback` is bound to `thisArg` + * and invoked with four arguments; (accumulator, value, index|key, collection). + * + * @static + * @memberOf _ + * @alias foldl, inject + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [accumulator] Initial value of the accumulator. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the accumulated value. + * @example + * + * var sum = _.reduce([1, 2, 3], function(sum, num) { + * return sum + num; + * }); + * // => 6 + * + * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { + * result[key] = num * 3; + * return result; + * }, {}); + * // => { 'a': 3, 'b': 6, 'c': 9 } + */ + function reduce(collection, callback, accumulator, thisArg) { + var noaccum = arguments.length < 3; + callback = createCallback(callback, thisArg, 4); + + if (isArray(collection)) { + var index = -1, + length = collection.length; + + if (noaccum) { + accumulator = collection[++index]; + } + while (++index < length) { + accumulator = callback(accumulator, collection[index], index, collection); + } + } else { + each(collection, function(value, index, collection) { + accumulator = noaccum + ? (noaccum = false, value) + : callback(accumulator, value, index, collection) + }); + } + return accumulator; + } + + /** + * This method is similar to `_.reduce`, except that it iterates over a + * `collection` from right to left. + * + * @static + * @memberOf _ + * @alias foldr + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function} [callback=identity] The function called per iteration. + * @param {Mixed} [accumulator] Initial value of the accumulator. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the accumulated value. + * @example + * + * var list = [[0, 1], [2, 3], [4, 5]]; + * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, callback, accumulator, thisArg) { + var iterable = collection, + length = collection ? collection.length : 0, + noaccum = arguments.length < 3; + + if (typeof length != 'number') { + var props = keys(collection); + length = props.length; + } else if (noCharByIndex && isString(collection)) { + iterable = collection.split(''); + } + callback = createCallback(callback, thisArg, 4); + forEach(collection, function(value, index, collection) { + index = props ? props[--length] : --length; + accumulator = noaccum + ? (noaccum = false, iterable[index]) + : callback(accumulator, iterable[index], index, collection); + }); + return accumulator; + } + + /** + * The opposite of `_.filter`, this method returns the elements of a + * `collection` that `callback` does **not** return truthy for. + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of elements that did **not** pass the + * callback check. + * @example + * + * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); + * // => [1, 3, 5] + * + * var food = [ + * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, + * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.reject(food, 'organic'); + * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }] + * + * // using "_.where" callback shorthand + * _.reject(food, { 'type': 'fruit' }); + * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }] + */ + function reject(collection, callback, thisArg) { + callback = createCallback(callback, thisArg); + return filter(collection, function(value, index, collection) { + return !callback(value, index, collection); + }); + } + + /** + * Creates an array of shuffled `array` values, using a version of the + * Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to shuffle. + * @returns {Array} Returns a new shuffled collection. + * @example + * + * _.shuffle([1, 2, 3, 4, 5, 6]); + * // => [4, 1, 6, 3, 5, 2] + */ + function shuffle(collection) { + var index = -1, + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + forEach(collection, function(value) { + var rand = floor(nativeRandom() * (++index + 1)); + result[index] = result[rand]; + result[rand] = value; + }); + return result; + } + + /** + * Gets the size of the `collection` by returning `collection.length` for arrays + * and array-like objects or the number of own enumerable properties for objects. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to inspect. + * @returns {Number} Returns `collection.length` or number of own enumerable properties. + * @example + * + * _.size([1, 2]); + * // => 2 + * + * _.size({ 'one': 1, 'two': 2, 'three': 3 }); + * // => 3 + * + * _.size('curly'); + * // => 5 + */ + function size(collection) { + var length = collection ? collection.length : 0; + return typeof length == 'number' ? length : keys(collection).length; + } + + /** + * Checks if the `callback` returns a truthy value for **any** element of a + * `collection`. The function returns as soon as it finds passing value, and + * does not iterate over the entire `collection`. The `callback` is bound to + * `thisArg` and invoked with three arguments; (value, index|key, collection). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias any + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Boolean} Returns `true` if any element passes the callback check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var food = [ + * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, + * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } + * ]; + * + * // using "_.pluck" callback shorthand + * _.some(food, 'organic'); + * // => true + * + * // using "_.where" callback shorthand + * _.some(food, { 'type': 'meat' }); + * // => false + */ + function some(collection, callback, thisArg) { + var result; + callback = createCallback(callback, thisArg); + + if (isArray(collection)) { + var index = -1, + length = collection.length; + + while (++index < length) { + if ((result = callback(collection[index], index, collection))) { + break; + } + } + } else { + each(collection, function(value, index, collection) { + return !(result = callback(value, index, collection)); + }); + } + return !!result; + } + + /** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in the `collection` through the `callback`. This method + * performs a stable sort, that is, it will preserve the original sort order of + * equal elements. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, index|key, collection). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a new array of sorted elements. + * @example + * + * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); + * // => [3, 1, 2] + * + * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); + * // => [3, 1, 2] + * + * // using "_.pluck" callback shorthand + * _.sortBy(['banana', 'strawberry', 'apple'], 'length'); + * // => ['apple', 'banana', 'strawberry'] + */ + function sortBy(collection, callback, thisArg) { + var index = -1, + length = collection ? collection.length : 0, + result = Array(typeof length == 'number' ? length : 0); + + callback = createCallback(callback, thisArg); + forEach(collection, function(value, key, collection) { + result[++index] = { + 'criteria': callback(value, key, collection), + 'index': index, + 'value': value + }; + }); + + length = result.length; + result.sort(compareAscending); + while (length--) { + result[length] = result[length].value; + } + return result; + } + + /** + * Converts the `collection` to an array. + * + * @static + * @memberOf _ + * @category Collections + * @param {Array|Object|String} collection The collection to convert. + * @returns {Array} Returns the new converted array. + * @example + * + * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); + * // => [2, 3, 4] + */ + function toArray(collection) { + if (collection && typeof collection.length == 'number') { + return noCharByIndex && isString(collection) + ? collection.split('') + : slice(collection); + } + return values(collection); + } + + /** + * Examines each element in a `collection`, returning an array of all elements + * that have the given `properties`. When checking `properties`, this method + * performs a deep comparison between values to determine if they are equivalent + * to each other. + * + * @static + * @memberOf _ + * @type Function + * @category Collections + * @param {Array|Object|String} collection The collection to iterate over. + * @param {Object} properties The object of property values to filter by. + * @returns {Array} Returns a new array of elements that have the given `properties`. + * @example + * + * var stooges = [ + * { 'name': 'moe', 'age': 40 }, + * { 'name': 'larry', 'age': 50 } + * ]; + * + * _.where(stooges, { 'age': 40 }); + * // => [{ 'name': 'moe', 'age': 40 }] + */ + var where = filter; + + /*--------------------------------------------------------------------------*/ + + /** + * Creates an array with all falsey values of `array` removed. The values + * `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to compact. + * @returns {Array} Returns a new filtered array. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ + function compact(array) { + var index = -1, + length = array ? array.length : 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result.push(value); + } + } + return result; + } + + /** + * Creates an array of `array` elements not present in the other arrays + * using strict equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to process. + * @param {Array} [array1, array2, ...] Arrays to check. + * @returns {Array} Returns a new array of `array` elements not present in the + * other arrays. + * @example + * + * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); + * // => [1, 3, 4] + */ + function difference(array) { + var index = -1, + length = array ? array.length : 0, + flattened = concat.apply(arrayRef, arguments), + contains = cachedContains(flattened, length), + result = []; + + while (++index < length) { + var value = array[index]; + if (!contains(value)) { + result.push(value); + } + } + return result; + } + + /** + * Gets the first element of the `array`. If a number `n` is passed, the first + * `n` elements of the `array` are returned. If a `callback` function is passed, + * the first elements the `callback` returns truthy for are returned. The `callback` + * is bound to `thisArg` and invoked with three arguments; (value, index, array). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias head, take + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|Number|String} [callback|n] The function called + * per element or the number of elements to return. If a property name or + * object is passed, it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the first element(s) of `array`. + * @example + * + * _.first([1, 2, 3]); + * // => 1 + * + * _.first([1, 2, 3], 2); + * // => [1, 2] + * + * _.first([1, 2, 3], function(num) { + * return num < 3; + * }); + * // => [1, 2] + * + * var food = [ + * { 'name': 'banana', 'organic': true }, + * { 'name': 'beet', 'organic': false }, + * ]; + * + * // using "_.pluck" callback shorthand + * _.first(food, 'organic'); + * // => [{ 'name': 'banana', 'organic': true }] + * + * var food = [ + * { 'name': 'apple', 'type': 'fruit' }, + * { 'name': 'banana', 'type': 'fruit' }, + * { 'name': 'beet', 'type': 'vegetable' } + * ]; + * + * // using "_.where" callback shorthand + * _.first(food, { 'type': 'fruit' }); + * // => [{ 'name': 'apple', 'type': 'fruit' }, { 'name': 'banana', 'type': 'fruit' }] + */ + function first(array, callback, thisArg) { + if (array) { + var n = 0, + length = array.length; + + if (typeof callback != 'number' && callback != null) { + var index = -1; + callback = createCallback(callback, thisArg); + while (++index < length && callback(array[index], index, array)) { + n++; + } + } else { + n = callback; + if (n == null || thisArg) { + return array[0]; + } + } + return slice(array, 0, nativeMin(nativeMax(0, n), length)); + } + } + + /** + * Flattens a nested array (the nesting can be to any depth). If `shallow` is + * truthy, `array` will only be flattened a single level. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to compact. + * @param {Boolean} shallow A flag to indicate only flattening a single level. + * @returns {Array} Returns a new flattened array. + * @example + * + * _.flatten([1, [2], [3, [[4]]]]); + * // => [1, 2, 3, 4]; + * + * _.flatten([1, [2], [3, [[4]]]], true); + * // => [1, 2, 3, [[4]]]; + */ + function flatten(array, shallow) { + var index = -1, + length = array ? array.length : 0, + result = []; + + while (++index < length) { + var value = array[index]; + + // recursively flatten arrays (susceptible to call stack limits) + if (isArray(value)) { + push.apply(result, shallow ? value : flatten(value)); + } else { + result.push(value); + } + } + return result; + } + + /** + * Gets the index at which the first occurrence of `value` is found using + * strict equality for comparisons, i.e. `===`. If the `array` is already + * sorted, passing `true` for `fromIndex` will run a faster binary search. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {Mixed} value The value to search for. + * @param {Boolean|Number} [fromIndex=0] The index to search from or `true` to + * perform a binary search on a sorted `array`. + * @returns {Number} Returns the index of the matched value or `-1`. + * @example + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2); + * // => 1 + * + * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 4 + * + * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); + * // => 2 + */ + function indexOf(array, value, fromIndex) { + var index = -1, + length = array ? array.length : 0; + + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0) - 1; + } else if (fromIndex) { + index = sortedIndex(array, value); + return array[index] === value ? index : -1; + } + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * Gets all but the last element of `array`. If a number `n` is passed, the + * last `n` elements are excluded from the result. If a `callback` function + * is passed, the last elements the `callback` returns truthy for are excluded + * from the result. The `callback` is bound to `thisArg` and invoked with three + * arguments; (value, index, array). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|Number|String} [callback|n=1] The function called + * per element or the number of elements to exclude. If a property name or + * object is passed, it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + * + * _.initial([1, 2, 3], 2); + * // => [1] + * + * _.initial([1, 2, 3], function(num) { + * return num > 1; + * }); + * // => [1] + * + * var food = [ + * { 'name': 'beet', 'organic': false }, + * { 'name': 'carrot', 'organic': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.initial(food, 'organic'); + * // => [{ 'name': 'beet', 'organic': false }] + * + * var food = [ + * { 'name': 'banana', 'type': 'fruit' }, + * { 'name': 'beet', 'type': 'vegetable' }, + * { 'name': 'carrot', 'type': 'vegetable' } + * ]; + * + * // using "_.where" callback shorthand + * _.initial(food, { 'type': 'vegetable' }); + * // => [{ 'name': 'banana', 'type': 'fruit' }] + */ + function initial(array, callback, thisArg) { + if (!array) { + return []; + } + var n = 0, + length = array.length; + + if (typeof callback != 'number' && callback != null) { + var index = length; + callback = createCallback(callback, thisArg); + while (index-- && callback(array[index], index, array)) { + n++; + } + } else { + n = (callback == null || thisArg) ? 1 : callback || n; + } + return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); + } + + /** + * Computes the intersection of all the passed-in arrays using strict equality + * for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} [array1, array2, ...] Arrays to process. + * @returns {Array} Returns a new array of unique elements that are present + * in **all** of the arrays. + * @example + * + * _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); + * // => [1, 2] + */ + function intersection(array) { + var args = arguments, + argsLength = args.length, + cache = { '0': {} }, + index = -1, + length = array ? array.length : 0, + isLarge = length >= 100, + result = [], + seen = result; + + outer: + while (++index < length) { + var value = array[index]; + if (isLarge) { + var key = value + ''; + var inited = hasOwnProperty.call(cache[0], key) + ? !(seen = cache[0][key]) + : (seen = cache[0][key] = []); + } + if (inited || indexOf(seen, value) < 0) { + if (isLarge) { + seen.push(value); + } + var argsIndex = argsLength; + while (--argsIndex) { + if (!(cache[argsIndex] || (cache[argsIndex] = cachedContains(args[argsIndex], 0, 100)))(value)) { + continue outer; + } + } + result.push(value); + } + } + return result; + } + + /** + * Gets the last element of the `array`. If a number `n` is passed, the last + * `n` elements of the `array` are returned. If a `callback` function is passed, + * the last elements the `callback` returns truthy for are returned. The `callback` + * is bound to `thisArg` and invoked with three arguments; (value, index, array). + * + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|Number|String} [callback|n] The function called + * per element or the number of elements to return. If a property name or + * object is passed, it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Mixed} Returns the last element(s) of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + * + * _.last([1, 2, 3], 2); + * // => [2, 3] + * + * _.last([1, 2, 3], function(num) { + * return num > 1; + * }); + * // => [2, 3] + * + * var food = [ + * { 'name': 'beet', 'organic': false }, + * { 'name': 'carrot', 'organic': true } + * ]; + * + * // using "_.pluck" callback shorthand + * _.last(food, 'organic'); + * // => [{ 'name': 'carrot', 'organic': true }] + * + * var food = [ + * { 'name': 'banana', 'type': 'fruit' }, + * { 'name': 'beet', 'type': 'vegetable' }, + * { 'name': 'carrot', 'type': 'vegetable' } + * ]; + * + * // using "_.where" callback shorthand + * _.last(food, { 'type': 'vegetable' }); + * // => [{ 'name': 'beet', 'type': 'vegetable' }, { 'name': 'carrot', 'type': 'vegetable' }] + */ + function last(array, callback, thisArg) { + if (array) { + var n = 0, + length = array.length; + + if (typeof callback != 'number' && callback != null) { + var index = length; + callback = createCallback(callback, thisArg); + while (index-- && callback(array[index], index, array)) { + n++; + } + } else { + n = callback; + if (n == null || thisArg) { + return array[length - 1]; + } + } + return slice(array, nativeMax(0, length - n)); + } + } + + /** + * Gets the index at which the last occurrence of `value` is found using strict + * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used + * as the offset from the end of the collection. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to search. + * @param {Mixed} value The value to search for. + * @param {Number} [fromIndex=array.length-1] The index to search from. + * @returns {Number} Returns the index of the matched value or `-1`. + * @example + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); + * // => 4 + * + * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var index = array ? array.length : 0; + if (typeof fromIndex == 'number') { + index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; + } + while (index--) { + if (array[index] === value) { + return index; + } + } + return -1; + } + + /** + * Creates an object composed from arrays of `keys` and `values`. Pass either + * a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`, or + * two arrays, one of `keys` and one of corresponding `values`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} keys The array of keys. + * @param {Array} [values=[]] The array of values. + * @returns {Object} Returns an object composed of the given keys and + * corresponding values. + * @example + * + * _.object(['moe', 'larry'], [30, 40]); + * // => { 'moe': 30, 'larry': 40 } + */ + function object(keys, values) { + var index = -1, + length = keys ? keys.length : 0, + result = {}; + + while (++index < length) { + var key = keys[index]; + if (values) { + result[key] = values[index]; + } else { + result[key[0]] = key[1]; + } + } + return result; + } + + /** + * Creates an array of numbers (positive and/or negative) progressing from + * `start` up to but not including `end`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Number} [start=0] The start of the range. + * @param {Number} end The end of the range. + * @param {Number} [step=1] The value to increment or descrement by. + * @returns {Array} Returns a new range array. + * @example + * + * _.range(10); + * // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + * + * _.range(1, 11); + * // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + * + * _.range(0, 30, 5); + * // => [0, 5, 10, 15, 20, 25] + * + * _.range(0, -10, -1); + * // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] + * + * _.range(0); + * // => [] + */ + function range(start, end, step) { + start = +start || 0; + step = +step || 1; + + if (end == null) { + end = start; + start = 0; + } + // use `Array(length)` so V8 will avoid the slower "dictionary" mode + // http://youtu.be/XAqIpGU8ZZk#t=17m25s + var index = -1, + length = nativeMax(0, ceil((end - start) / step)), + result = Array(length); + + while (++index < length) { + result[index] = start; + start += step; + } + return result; + } + + /** + * The opposite of `_.initial`, this method gets all but the first value of `array`. + * If a number `n` is passed, the first `n` values are excluded from the result. + * If a `callback` function is passed, the first elements the `callback` returns + * truthy for are excluded from the result. The `callback` is bound to `thisArg` + * and invoked with three arguments; (value, index, array). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias drop, tail + * @category Arrays + * @param {Array} array The array to query. + * @param {Function|Object|Number|String} [callback|n=1] The function called + * per element or the number of elements to exclude. If a property name or + * object is passed, it will be used to create a "_.pluck" or "_.where" + * style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a slice of `array`. + * @example + * + * _.rest([1, 2, 3]); + * // => [2, 3] + * + * _.rest([1, 2, 3], 2); + * // => [3] + * + * _.rest([1, 2, 3], function(num) { + * return num < 3; + * }); + * // => [3] + * + * var food = [ + * { 'name': 'banana', 'organic': true }, + * { 'name': 'beet', 'organic': false }, + * ]; + * + * // using "_.pluck" callback shorthand + * _.rest(food, 'organic'); + * // => [{ 'name': 'beet', 'organic': false }] + * + * var food = [ + * { 'name': 'apple', 'type': 'fruit' }, + * { 'name': 'banana', 'type': 'fruit' }, + * { 'name': 'beet', 'type': 'vegetable' } + * ]; + * + * // using "_.where" callback shorthand + * _.rest(food, { 'type': 'fruit' }); + * // => [{ 'name': 'beet', 'type': 'vegetable' }] + */ + function rest(array, callback, thisArg) { + if (typeof callback != 'number' && callback != null) { + var n = 0, + index = -1, + length = array ? array.length : 0; + + callback = createCallback(callback, thisArg); + while (++index < length && callback(array[index], index, array)) { + n++; + } + } else { + n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); + } + return slice(array, n); + } + + /** + * Uses a binary search to determine the smallest index at which the `value` + * should be inserted into `array` in order to maintain the sort order of the + * sorted `array`. If `callback` is passed, it will be executed for `value` and + * each element in `array` to compute their sort ranking. The `callback` is + * bound to `thisArg` and invoked with one argument; (value). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to iterate over. + * @param {Mixed} value The value to evaluate. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Number} Returns the index at which the value should be inserted + * into `array`. + * @example + * + * _.sortedIndex([20, 30, 50], 40); + * // => 2 + * + * // using "_.pluck" callback shorthand + * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); + * // => 2 + * + * var dict = { + * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } + * }; + * + * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + * return dict.wordToNumber[word]; + * }); + * // => 2 + * + * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + * return this.wordToNumber[word]; + * }, dict); + * // => 2 + */ + function sortedIndex(array, value, callback, thisArg) { + var low = 0, + high = array ? array.length : low; + + // explicitly reference `identity` for better inlining in Firefox + callback = callback ? createCallback(callback, thisArg, 1) : identity; + value = callback(value); + + while (low < high) { + var mid = (low + high) >>> 1; + callback(array[mid]) < value + ? low = mid + 1 + : high = mid; + } + return low; + } + + /** + * Computes the union of the passed-in arrays using strict equality for + * comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} [array1, array2, ...] Arrays to process. + * @returns {Array} Returns a new array of unique values, in order, that are + * present in one or more of the arrays. + * @example + * + * _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); + * // => [1, 2, 3, 101, 10] + */ + function union() { + return uniq(concat.apply(arrayRef, arguments)); + } + + /** + * Creates a duplicate-value-free version of the `array` using strict equality + * for comparisons, i.e. `===`. If the `array` is already sorted, passing `true` + * for `isSorted` will run a faster algorithm. If `callback` is passed, each + * element of `array` is passed through a callback` before uniqueness is computed. + * The `callback` is bound to `thisArg` and invoked with three arguments; (value, index, array). + * + * If a property name is passed for `callback`, the created "_.pluck" style + * callback will return the property value of the given element. + * + * If an object is passed for `callback`, the created "_.where" style callback + * will return `true` for elements that have the propeties of the given object, + * else `false`. + * + * @static + * @memberOf _ + * @alias unique + * @category Arrays + * @param {Array} array The array to process. + * @param {Boolean} [isSorted=false] A flag to indicate that the `array` is already sorted. + * @param {Function|Object|String} [callback=identity] The function called per + * iteration. If a property name or object is passed, it will be used to create + * a "_.pluck" or "_.where" style callback, respectively. + * @param {Mixed} [thisArg] The `this` binding of `callback`. + * @returns {Array} Returns a duplicate-value-free array. + * @example + * + * _.uniq([1, 2, 1, 3, 1]); + * // => [1, 2, 3] + * + * _.uniq([1, 1, 2, 2, 3], true); + * // => [1, 2, 3] + * + * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); }); + * // => [1, 2, 3] + * + * _.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math); + * // => [1, 2, 3] + * + * // using "_.pluck" callback shorthand + * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniq(array, isSorted, callback, thisArg) { + var index = -1, + length = array ? array.length : 0, + result = [], + seen = result; + + // juggle arguments + if (typeof isSorted == 'function') { + thisArg = callback; + callback = isSorted; + isSorted = false; + } + // init value cache for large arrays + var isLarge = !isSorted && length >= 75; + if (isLarge) { + var cache = {}; + } + if (callback) { + seen = []; + callback = createCallback(callback, thisArg); + } + while (++index < length) { + var value = array[index], + computed = callback ? callback(value, index, array) : value; + + if (isLarge) { + var key = computed + ''; + var inited = hasOwnProperty.call(cache, key) + ? !(seen = cache[key]) + : (seen = cache[key] = []); + } + if (isSorted + ? !index || seen[seen.length - 1] !== computed + : inited || indexOf(seen, computed) < 0 + ) { + if (callback || isLarge) { + seen.push(computed); + } + result.push(value); + } + } + return result; + } + + /** + * Creates an array with all occurrences of the passed values removed using + * strict equality for comparisons, i.e. `===`. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} array The array to filter. + * @param {Mixed} [value1, value2, ...] Values to remove. + * @returns {Array} Returns a new filtered array. + * @example + * + * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); + * // => [2, 3, 4] + */ + function without(array) { + var index = -1, + length = array ? array.length : 0, + contains = cachedContains(arguments, 1), + result = []; + + while (++index < length) { + var value = array[index]; + if (!contains(value)) { + result.push(value); + } + } + return result; + } + + /** + * Groups the elements of each array at their corresponding indexes. Useful for + * separate data sources that are coordinated through matching array indexes. + * For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix + * in a similar fashion. + * + * @static + * @memberOf _ + * @category Arrays + * @param {Array} [array1, array2, ...] Arrays to process. + * @returns {Array} Returns a new array of grouped elements. + * @example + * + * _.zip(['moe', 'larry'], [30, 40], [true, false]); + * // => [['moe', 30, true], ['larry', 40, false]] + */ + function zip(array) { + var index = -1, + length = array ? max(pluck(arguments, 'length')) : 0, + result = Array(length); + + while (++index < length) { + result[index] = pluck(arguments, index); + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a function that is restricted to executing `func` only after it is + * called `n` times. The `func` is executed with the `this` binding of the + * created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Number} n The number of times the function must be called before + * it is executed. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var renderNotes = _.after(notes.length, render); + * _.forEach(notes, function(note) { + * note.asyncSave({ 'success': renderNotes }); + * }); + * // `renderNotes` is run once, after all notes have saved + */ + function after(n, func) { + if (n < 1) { + return func(); + } + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; + } + + /** + * Creates a function that, when called, invokes `func` with the `this` + * binding of `thisArg` and prepends any additional `bind` arguments to those + * passed to the bound function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to bind. + * @param {Mixed} [thisArg] The `this` binding of `func`. + * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var func = function(greeting) { + * return greeting + ' ' + this.name; + * }; + * + * func = _.bind(func, { 'name': 'moe' }, 'hi'); + * func(); + * // => 'hi moe' + */ + function bind(func, thisArg) { + // use `Function#bind` if it exists and is fast + // (in V8 `Function#bind` is slower except when partially applied) + return isBindFast || (nativeBind && arguments.length > 2) + ? nativeBind.call.apply(nativeBind, arguments) + : createBound(func, thisArg, slice(arguments, 2)); + } + + /** + * Binds methods on `object` to `object`, overwriting the existing method. + * Method names may be specified as individual arguments or as arrays of method + * names. If no method names are provided, all the function properties of `object` + * will be bound. + * + * @static + * @memberOf _ + * @category Functions + * @param {Object} object The object to bind and assign the bound methods to. + * @param {String} [methodName1, methodName2, ...] Method names on the object to bind. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'onClick': function() { alert('clicked ' + this.label); } + * }; + * + * _.bindAll(view); + * jQuery('#docs').on('click', view.onClick); + * // => alerts 'clicked docs', when the button is clicked + */ + function bindAll(object) { + var funcs = concat.apply(arrayRef, arguments), + index = funcs.length > 1 ? 0 : (funcs = functions(object), -1), + length = funcs.length; + + while (++index < length) { + var key = funcs[index]; + object[key] = bind(object[key], object); + } + return object; + } + + /** + * Creates a function that, when called, invokes the method at `object[key]` + * and prepends any additional `bindKey` arguments to those passed to the bound + * function. This method differs from `_.bind` by allowing bound functions to + * reference methods that will be redefined or don't yet exist. + * See http://michaux.ca/articles/lazy-function-definition-pattern. + * + * @static + * @memberOf _ + * @category Functions + * @param {Object} object The object the method belongs to. + * @param {String} key The key of the method. + * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'name': 'moe', + * 'greet': function(greeting) { + * return greeting + ' ' + this.name; + * } + * }; + * + * var func = _.bindKey(object, 'greet', 'hi'); + * func(); + * // => 'hi moe' + * + * object.greet = function(greeting) { + * return greeting + ', ' + this.name + '!'; + * }; + * + * func(); + * // => 'hi, moe!' + */ + function bindKey(object, key) { + return createBound(object, key, slice(arguments, 2)); + } + + /** + * Creates a function that is the composition of the passed functions, + * where each function consumes the return value of the function that follows. + * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. + * Each function is executed with the `this` binding of the composed function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} [func1, func2, ...] Functions to compose. + * @returns {Function} Returns the new composed function. + * @example + * + * var greet = function(name) { return 'hi ' + name; }; + * var exclaim = function(statement) { return statement + '!'; }; + * var welcome = _.compose(exclaim, greet); + * welcome('moe'); + * // => 'hi moe!' + */ + function compose() { + var funcs = arguments; + return function() { + var args = arguments, + length = funcs.length; + + while (length--) { + args = [funcs[length].apply(this, args)]; + } + return args[0]; + }; + } + + /** + * Creates a function that will delay the execution of `func` until after + * `wait` milliseconds have elapsed since the last time it was invoked. Pass + * `true` for `immediate` to cause debounce to invoke `func` on the leading, + * instead of the trailing, edge of the `wait` timeout. Subsequent calls to + * the debounced function will return the result of the last `func` call. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to debounce. + * @param {Number} wait The number of milliseconds to delay. + * @param {Boolean} immediate A flag to indicate execution is on the leading + * edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * var lazyLayout = _.debounce(calculateLayout, 300); + * jQuery(window).on('resize', lazyLayout); + */ + function debounce(func, wait, immediate) { + var args, + result, + thisArg, + timeoutId; + + function delayed() { + timeoutId = null; + if (!immediate) { + result = func.apply(thisArg, args); + } + } + return function() { + var isImmediate = immediate && !timeoutId; + args = arguments; + thisArg = this; + + clearTimeout(timeoutId); + timeoutId = setTimeout(delayed, wait); + + if (isImmediate) { + result = func.apply(thisArg, args); + } + return result; + }; + } + + /** + * Executes the `func` function after `wait` milliseconds. Additional arguments + * will be passed to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to delay. + * @param {Number} wait The number of milliseconds to delay execution. + * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with. + * @returns {Number} Returns the `setTimeout` timeout id. + * @example + * + * var log = _.bind(console.log, console); + * _.delay(log, 1000, 'logged later'); + * // => 'logged later' (Appears after one second.) + */ + function delay(func, wait) { + var args = slice(arguments, 2); + return setTimeout(function() { func.apply(undefined, args); }, wait); + } + + /** + * Defers executing the `func` function until the current call stack has cleared. + * Additional arguments will be passed to `func` when it is invoked. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to defer. + * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the function with. + * @returns {Number} Returns the `setTimeout` timeout id. + * @example + * + * _.defer(function() { alert('deferred'); }); + * // returns from the function before `alert` is called + */ + function defer(func) { + var args = slice(arguments, 1); + return setTimeout(function() { func.apply(undefined, args); }, 1); + } + // use `setImmediate` if it's available in Node.js + if (isV8 && freeModule && typeof setImmediate == 'function') { + defer = bind(setImmediate, window); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * passed, it will be used to determine the cache key for storing the result + * based on the arguments passed to the memoized function. By default, the first + * argument passed to the memoized function is used as the cache key. The `func` + * is executed with the `this` binding of the memoized function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] A function used to resolve the cache key. + * @returns {Function} Returns the new memoizing function. + * @example + * + * var fibonacci = _.memoize(function(n) { + * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); + * }); + */ + function memoize(func, resolver) { + var cache = {}; + return function() { + var key = (resolver ? resolver.apply(this, arguments) : arguments[0]) + ''; + return hasOwnProperty.call(cache, key) + ? cache[key] + : (cache[key] = func.apply(this, arguments)); + }; + } + + /** + * Creates a function that is restricted to execute `func` once. Repeat calls to + * the function will return the value of the first call. The `func` is executed + * with the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // `initialize` executes `createApplication` once + */ + function once(func) { + var ran, + result; + + return function() { + if (ran) { + return result; + } + ran = true; + result = func.apply(this, arguments); + + // clear the `func` variable so the function may be garbage collected + func = null; + return result; + }; + } + + /** + * Creates a function that, when called, invokes `func` with any additional + * `partial` arguments prepended to those passed to the new function. This + * method is similar to `_.bind`, except it does **not** alter the `this` binding. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to partially apply arguments to. + * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var greet = function(greeting, name) { return greeting + ' ' + name; }; + * var hi = _.partial(greet, 'hi'); + * hi('moe'); + * // => 'hi moe' + */ + function partial(func) { + return createBound(func, slice(arguments, 1)); + } + + /** + * This method is similar to `_.partial`, except that `partial` arguments are + * appended to those passed to the new function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to partially apply arguments to. + * @param {Mixed} [arg1, arg2, ...] Arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * var defaultsDeep = _.partialRight(_.merge, _.defaults); + * + * var options = { + * 'variable': 'data', + * 'imports': { 'jq': $ } + * }; + * + * defaultsDeep(options, _.templateSettings); + * + * options.variable + * // => 'data' + * + * options.imports + * // => { '_': _, 'jq': $ } + */ + function partialRight(func) { + return createBound(func, slice(arguments, 1), null, indicatorObject); + } + + /** + * Creates a function that, when executed, will only call the `func` + * function at most once per every `wait` milliseconds. If the throttled + * function is invoked more than once during the `wait` timeout, `func` will + * also be called on the trailing edge of the timeout. Subsequent calls to the + * throttled function will return the result of the last `func` call. + * + * @static + * @memberOf _ + * @category Functions + * @param {Function} func The function to throttle. + * @param {Number} wait The number of milliseconds to throttle executions to. + * @returns {Function} Returns the new throttled function. + * @example + * + * var throttled = _.throttle(updatePosition, 100); + * jQuery(window).on('scroll', throttled); + */ + function throttle(func, wait) { + var args, + result, + thisArg, + timeoutId, + lastCalled = 0; + + function trailingCall() { + lastCalled = new Date; + timeoutId = null; + result = func.apply(thisArg, args); + } + return function() { + var now = new Date, + remaining = wait - (now - lastCalled); + + args = arguments; + thisArg = this; + + if (remaining <= 0) { + clearTimeout(timeoutId); + timeoutId = null; + lastCalled = now; + result = func.apply(thisArg, args); + } + else if (!timeoutId) { + timeoutId = setTimeout(trailingCall, remaining); + } + return result; + }; + } + + /** + * Creates a function that passes `value` to the `wrapper` function as its + * first argument. Additional arguments passed to the function are appended + * to those passed to the `wrapper` function. The `wrapper` is executed with + * the `this` binding of the created function. + * + * @static + * @memberOf _ + * @category Functions + * @param {Mixed} value The value to wrap. + * @param {Function} wrapper The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var hello = function(name) { return 'hello ' + name; }; + * hello = _.wrap(hello, function(func) { + * return 'before, ' + func('moe') + ', after'; + * }); + * hello(); + * // => 'before, hello moe, after' + */ + function wrap(value, wrapper) { + return function() { + var args = [value]; + push.apply(args, arguments); + return wrapper.apply(this, args); + }; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their + * corresponding HTML entities. + * + * @static + * @memberOf _ + * @category Utilities + * @param {String} string The string to escape. + * @returns {String} Returns the escaped string. + * @example + * + * _.escape('Moe, Larry & Curly'); + * // => 'Moe, Larry & Curly' + */ + function escape(string) { + return string == null ? '' : (string + '').replace(reUnescapedHtml, escapeHtmlChar); + } + + /** + * This function returns the first argument passed to it. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Mixed} value Any value. + * @returns {Mixed} Returns `value`. + * @example + * + * var moe = { 'name': 'moe' }; + * moe === _.identity(moe); + * // => true + */ + function identity(value) { + return value; + } + + /** + * Adds functions properties of `object` to the `lodash` function and chainable + * wrapper. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Object} object The object of function properties to add to `lodash`. + * @example + * + * _.mixin({ + * 'capitalize': function(string) { + * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); + * } + * }); + * + * _.capitalize('moe'); + * // => 'Moe' + * + * _('moe').capitalize(); + * // => 'Moe' + */ + function mixin(object) { + forEach(functions(object), function(methodName) { + var func = lodash[methodName] = object[methodName]; + + lodash.prototype[methodName] = function() { + var args = [this.__wrapped__]; + push.apply(args, arguments); + return new lodash(func.apply(lodash, args)); + }; + }); + } + + /** + * Reverts the '_' variable to its previous value and returns a reference to + * the `lodash` function. + * + * @static + * @memberOf _ + * @category Utilities + * @returns {Function} Returns the `lodash` function. + * @example + * + * var lodash = _.noConflict(); + */ + function noConflict() { + window._ = oldDash; + return this; + } + + /** + * Produces a random number between `min` and `max` (inclusive). If only one + * argument is passed, a number between `0` and the given number will be returned. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Number} [min=0] The minimum possible value. + * @param {Number} [max=1] The maximum possible value. + * @returns {Number} Returns a random number. + * @example + * + * _.random(0, 5); + * // => a number between 0 and 5 + * + * _.random(5); + * // => also a number between 0 and 5 + */ + function random(min, max) { + if (min == null && max == null) { + max = 1; + } + min = +min || 0; + if (max == null) { + max = min; + min = 0; + } + return min + floor(nativeRandom() * ((+max || 0) - min + 1)); + } + + /** + * Resolves the value of `property` on `object`. If `property` is a function, + * it will be invoked and its result returned, else the property value is + * returned. If `object` is falsey, then `null` is returned. + * + * @static + * @memberOf _ + * @category Utilities + * @param {Object} object The object to inspect. + * @param {String} property The property to get the value of. + * @returns {Mixed} Returns the resolved value. + * @example + * + * var object = { + * 'cheese': 'crumpets', + * 'stuff': function() { + * return 'nonsense'; + * } + * }; + * + * _.result(object, 'cheese'); + * // => 'crumpets' + * + * _.result(object, 'stuff'); + * // => 'nonsense' + */ + function result(object, property) { + var value = object ? object[property] : undefined; + return isFunction(value) ? object[property]() : value; + } + + /** + * A micro-templating method that handles arbitrary delimiters, preserves + * whitespace, and correctly escapes quotes within interpolated code. + * + * Note: In the development build, `_.template` utilizes sourceURLs for easier + * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl + * + * Note: Lo-Dash may be used in Chrome extensions by either creating a `lodash csp` + * build and using precompiled templates, or loading Lo-Dash in a sandbox. + * + * For more information on precompiling templates see: + * http://lodash.com/#custom-builds + * + * For more information on Chrome extension sandboxes see: + * http://developer.chrome.com/stable/extensions/sandboxingEval.html + * + * @static + * @memberOf _ + * @category Utilities + * @param {String} text The template text. + * @param {Obect} data The data object used to populate the text. + * @param {Object} options The options object. + * escape - The "escape" delimiter regexp. + * evaluate - The "evaluate" delimiter regexp. + * interpolate - The "interpolate" delimiter regexp. + * sourceURL - The sourceURL of the template's compiled source. + * variable - The data object variable name. + * + * @returns {Function|String} Returns a compiled function when no `data` object + * is given, else it returns the interpolated text. + * @example + * + * // using a compiled template + * var compiled = _.template('hello <%= name %>'); + * compiled({ 'name': 'moe' }); + * // => 'hello moe' + * + * var list = '<% _.forEach(people, function(name) { %>
  1. <%= name %>
  2. <% }); %>'; + * _.template(list, { 'people': ['moe', 'larry'] }); + * // => '
  3. moe
  4. larry
  5. ' + * + * // using the "escape" delimiter to escape HTML in data property values + * _.template('<%- value %>', { 'value': '\n```\n\nUsing [`npm`](http://npmjs.org/):\n\n```bash\nnpm install lodash\n\nnpm install -g lodash\nnpm link lodash\n```\n\nTo avoid potential issues, update `npm` before installing Lo-Dash:\n\n```bash\nnpm install npm -g\n```\n\nIn [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/):\n\n```js\nvar _ = require('lodash');\n\n// or as a drop-in replacement for Underscore\nvar _ = require('lodash/lodash.underscore');\n```\n\n**Note:** If Lo-Dash is installed globally, run [`npm link lodash`](http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/) in your project’s root directory before requiring it.\n\nIn [RingoJS v0.7.0-](http://ringojs.org/):\n\n```js\nvar _ = require('lodash')._;\n```\n\nIn [Rhino](http://www.mozilla.org/rhino/):\n\n```js\nload('lodash.js');\n```\n\nIn an AMD loader like [RequireJS](http://requirejs.org/):\n\n```js\nrequire({\n 'paths': {\n 'underscore': 'path/to/lodash'\n }\n},\n['underscore'], function(_) {\n console.log(_.VERSION);\n});\n```\n\n## Release Notes\n\n### v1.0.1\n\n * Add support for specifying source map URLs in `-p`/`--source-map` build options\n * Ensured the second argument passed to `_.assign` is not treated as a `callback`\n * Ensured `-p`/`--source-map` build options correctly set the `sourceMappingURL`\n * Made `-p`/`--source-map` build options set source map *“sources”* keys based on the builds performed\n * Made `_.defer` use `setImmediate`, in Node.js, when available\n * Made `_.where` search arrays for values regardless of their index position\n * Removed dead code from `_.template`\n\nThe full changelog is available [here](https://github.com/bestiejs/lodash/wiki/Changelog).\n\n## BestieJS\n\nLo-Dash is part of the BestieJS *“Best in Class”* module collection. This means we promote solid browser/environment support, ES5 precedents, unit testing, and plenty of documentation.\n\n## Author\n\n* [John-David Dalton](http://allyoucanleet.com/)\n [![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton \"Follow @jdalton on Twitter\")\n\n## Contributors\n\n* [Kit Cambridge](http://kitcambridge.github.com/)\n [![twitter/kitcambridge](http://gravatar.com/avatar/6662a1d02f351b5ef2f8b4d815804661?s=70)](https://twitter.com/kitcambridge \"Follow @kitcambridge on Twitter\")\n* [Mathias Bynens](http://mathiasbynens.be/)\n [![twitter/mathias](http://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias \"Follow @mathias on Twitter\")\n", + "readmeFilename": "README.md", + "_id": "lodash@1.0.1", + "_from": "lodash@~1.0.1" +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/perf/perf.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/perf/perf.js new file mode 100644 index 000000000..4ff9cf5bc --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/perf/perf.js @@ -0,0 +1,1724 @@ +(function(window) { + + /** Use a single "load" function */ + var load = typeof require == 'function' ? require : window.load; + + /** The file path of the Lo-Dash file to test */ + var filePath = (function() { + var min = 0; + var result = window.phantom + ? phantom.args + : (window.system + ? (min = 1, system.args) + : (window.process ? (min = 2, process.argv) : (window.arguments || [])) + ); + + var last = result[result.length - 1]; + result = (result.length > min && last != 'test.js') ? last : '../lodash.js'; + + try { + result = require('fs').realpathSync(result); + } catch(e) { } + + return result; + }()); + + /** Load Benchmark.js */ + var Benchmark = + window.Benchmark || ( + Benchmark = load('../vendor/benchmark.js/benchmark.js') || window.Benchmark, + Benchmark.Benchmark || Benchmark + ); + + /** Load Lo-Dash */ + var lodash = + window.lodash || ( + lodash = load(filePath) || window._, + lodash = lodash._ || lodash, + lodash.noConflict() + ); + + /** Load Underscore */ + var _ = + window._ || ( + _ = load('../vendor/underscore/underscore.js') || window._, + _._ || _ + ); + + /** Used to access the Firebug Lite panel (set by `run`) */ + var fbPanel; + + /** Used to score performance */ + var score = { 'a': 0, 'b': 0 }; + + /** Used to queue benchmark suites */ + var suites = []; + + /** The `ui` object */ + var ui = window.ui || { + 'buildPath': basename(filePath, '.js'), + 'otherPath': 'underscore' + }; + + /** The Lo-Dash build basename */ + var buildName = basename(ui.buildPath, '.js'); + + /** The other library basename */ + var otherName = basename(ui.otherPath, '.js'); + + /** Expose functions to the global object */ + window._ = _; + window.Benchmark = Benchmark; + window.lodash = lodash; + + /** Add `console.log()` support for Narwhal and RingoJS */ + if (!window.console && window.print) { + window.console = { 'log': window.print }; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Gets the basename of the given `filePath`. If the file `extension` is passed, + * it will be removed from the basename. + * + * @private + * @param {String} path The file path to inspect. + * @param {String} extension The extension to remove. + * @returns {String} Returns the basename. + */ + function basename(filePath, extension) { + var result = (filePath || '').split(/[\\/]/).pop(); + return arguments.length < 2 + ? result + : result.replace(RegExp(extension.replace(/[.*+?^=!:${}()|[\]\/\\]/g, '\\$&') + '$'), ''); + } + + /** + * Gets the Hz, i.e. operations per second, of `bench` adjusted for the + * margin of error. + * + * @private + * @param {Object} bench The benchmark object. + * @returns {Number} Returns the adjusted Hz. + */ + function getHz(bench) { + var result = 1 / (bench.stats.mean + bench.stats.moe); + return isFinite(result) ? result : 0; + } + + /** + * Logs text to the console. + * + * @private + * @param {String} text The text to log. + */ + function log(text) { + console.log(text + ''); + if (fbPanel) { + // scroll the Firebug Lite panel down + fbPanel.scrollTop = fbPanel.scrollHeight; + } + } + + /** + * Runs all benchmark suites. + * + * @private (@public in the browser) + */ + function run() { + fbPanel = (fbPanel = window.document && document.getElementById('FirebugUI')) && + (fbPanel = (fbPanel = fbPanel.contentWindow || fbPanel.contentDocument).document || fbPanel) && + fbPanel.getElementById('fbPanel1'); + + log('\nSit back and relax, this may take a while.'); + suites[0].run(); + } + + /*--------------------------------------------------------------------------*/ + + lodash.extend(Benchmark.Suite.options, { + 'onStart': function() { + log('\n' + this.name + ':'); + }, + 'onCycle': function(event) { + log(event.target); + }, + 'onComplete': function() { + var formatNumber = Benchmark.formatNumber, + fastest = this.filter('fastest'), + fastestHz = getHz(fastest[0]), + slowest = this.filter('slowest'), + slowestHz = getHz(slowest[0]), + aHz = getHz(this[0]), + bHz = getHz(this[1]); + + if (fastest.length > 1) { + log('It\'s too close to call.'); + aHz = bHz = slowestHz; + } + else { + var percent = ((fastestHz / slowestHz) - 1) * 100; + + log( + fastest[0].name + ' is ' + + formatNumber(percent < 1 ? percent.toFixed(2) : Math.round(percent)) + + '% faster.' + ); + } + // add score adjusted for margin of error + score.a += aHz; + score.b += bHz; + + // remove current suite from queue + suites.shift(); + + if (suites.length) { + // run next suite + suites[0].run(); + } + else { + var fastestTotalHz = Math.max(score.a, score.b), + slowestTotalHz = Math.min(score.a, score.b), + totalPercent = formatNumber(Math.round(((fastestTotalHz / slowestTotalHz) - 1) * 100)), + totalX = fastestTotalHz / slowestTotalHz, + message = 'is ' + totalPercent + '% ' + (totalX == 1 ? '' : '(' + formatNumber(totalX.toFixed(2)) + 'x) ') + 'faster than'; + + // report results + if (score.a >= score.b) { + log('\n' + buildName + ' ' + message + ' ' + otherName + '.'); + } else { + log('\n' + otherName + ' ' + message + ' ' + buildName + '.'); + } + } + } + }); + + /*--------------------------------------------------------------------------*/ + + lodash.extend(Benchmark.options, { + 'async': true, + 'setup': '\ + var window = Function("return this || global")(),\ + _ = window._,\ + lodash = window.lodash,\ + belt = this.name == "Lo-Dash" ? lodash : _;\ + \ + var index,\ + date = new Date,\ + limit = 20,\ + regexp = /x/,\ + object = {},\ + objects = Array(limit),\ + numbers = Array(limit),\ + fourNumbers = [5, 25, 10, 30],\ + nestedNumbers = [1, [2], [3, [[4]]]],\ + twoNumbers = [12, 23];\ + \ + for (index = 0; index < limit; index++) {\ + numbers[index] = index;\ + object["key" + index] = index;\ + objects[index] = { "num": index };\ + }\ + \ + if (typeof bind != "undefined") {\ + var contextObject = { "name": "moe" },\ + ctor = function() {};\ + \ + var func = function(greeting, punctuation) {\ + return greeting + ", " + this.name + (punctuation || ".");\ + };\ + \ + var lodashBoundNormal = lodash.bind(func, contextObject),\ + lodashBoundPartial = lodash.bind(func, contextObject, "hi");\ + \ + var _boundNormal = _.bind(func, contextObject),\ + _boundPartial = _.bind(func, contextObject, "hi");\ + }\ + \ + if (typeof bindAll != "undefined") {\ + var bindAllObjects = Array(this.count),\ + funcNames = belt.functions(lodash);\ + \ + // potentially expensive\n\ + for (index = 0; index < this.count; index++) {\ + bindAllObjects[index] = belt.reduce(funcNames, function(object, funcName) {\ + object[funcName] = lodash[funcName];\ + return object;\ + }, {});\ + }\ + }\ + if (typeof compact != "undefined") {\ + var uncompacted = numbers.slice();\ + uncompacted[2] = false;\ + uncompacted[6] = null;\ + uncompacted[18] = "";\ + }\ + \ + if (typeof countBy != "undefined" || typeof omit != "undefined") {\ + var wordToNumber = {\ + "one": 1,\ + "two": 2,\ + "three": 3,\ + "four": 4,\ + "five": 5,\ + "six": 6,\ + "seven": 7,\ + "eight": 8,\ + "nine": 9,\ + "ten": 10,\ + "eleven": 11,\ + "twelve": 12,\ + "thirteen": 13,\ + "fourteen": 14,\ + "fifteen": 15,\ + "sixteen": 16,\ + "seventeen": 17,\ + "eighteen": 18,\ + "nineteen": 19,\ + "twenty": 20,\ + "twenty-one": 21,\ + "twenty-two": 22,\ + "twenty-three": 23,\ + "twenty-four": 24,\ + "twenty-five": 25,\ + "twenty-six": 26,\ + "twenty-seven": 27,\ + "twenty-eight": 28,\ + "twenty-nine": 29,\ + "thirty": 30,\ + "thirty-one": 31,\ + "thirty-two": 32,\ + "thirty-three": 33,\ + "thirty-four": 34,\ + "thirty-five": 35,\ + "thirty-six": 36,\ + "thirty-seven": 37,\ + "thirty-eight": 38,\ + "thirty-nine": 39,\ + "forty": 40\ + };\ + \ + var words = belt.keys(wordToNumber).slice(0, limit);\ + }\ + \ + if (typeof isEqual != "undefined") {\ + var objectOfPrimitives = {\ + "boolean": true,\ + "number": 1,\ + "string": "a"\ + };\ + \ + var objectOfObjects = {\ + "boolean": new Boolean(true),\ + "number": new Number(1),\ + "string": new String("a")\ + };\ + \ + var object2 = {},\ + objects2 = Array(limit),\ + numbers2 = Array(limit),\ + nestedNumbers2 = [1, [2], [3, [[4]]]],\ + nestedNumbers3 = [1, [2], [5, [[6]]]],\ + simpleObject = { "a": 1 },\ + simpleObject2 = { "a": 2 },\ + simpleObjects = [simpleObject],\ + simpleObjects2 = [simpleObject2],\ + twoNumbers2 = [18, 27];\ + \ + for (index = 0; index < limit; index++) {\ + object2["key" + index] = index;\ + objects2[index] = { "num": index };\ + numbers2[index] = index;\ + }\ + }\ + \ + if (typeof multiArrays != "undefined") {\ + var twentyValues = Array(20),\ + twentyValues2 = Array(20),\ + twentyFiveValues = Array(25),\ + twentyFiveValues2 = Array(25),\ + thirtyValues = Array(30),\ + thirtyValues2 = Array(30),\ + fortyValues = Array(40),\ + fortyValues2 = Array(40),\ + fiftyValues = Array(50),\ + fiftyValues2 = Array(50),\ + seventyFiveValues = Array(75),\ + seventyFiveValues2 = Array(75),\ + hundredValues = Array(100),\ + hundredValues2 = Array(100),\ + lowerChars = "abcdefghijklmnopqrstuvwxyz".split(""),\ + upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");\ + \ + for (index = 0; index < 100; index++) {\ + if (index < 15) {\ + twentyValues[index] = lowerChars[index];\ + twentyValues2[index] = upperChars[index];\ + }\ + if (index < 20) {\ + twentyValues[index] =\ + twentyValues2[index] = index;\ + \ + twentyFiveValues[index] = lowerChars[index];\ + twentyFiveValues2[index] = upperChars[index];\ + }\ + if (index < 25) {\ + twentyFiveValues[index] =\ + twentyFiveValues2[index] = index;\ + \ + thirtyValues[index] =\ + fortyValues[index] =\ + fiftyValues[index] =\ + seventyFiveValues[index] =\ + hundredValues[index] = lowerChars[index];\ + \ + thirtyValues2[index] =\ + fortyValues2[index] =\ + fiftyValues2[index] =\ + seventyFiveValues2[index] =\ + hundredValues2[index] = upperChars[index];\ + }\ + else {\ + if (index < 30) {\ + thirtyValues[index] =\ + thirtyValues2[index] = index;\ + }\ + if (index < 40) {\ + fortyValues[index] =\ + fortyValues2[index] = index;\ + }\ + if (index < 50) {\ + fiftyValues[index] =\ + fiftyValues2[index] = index;\ + }\ + if (index < 75) {\ + seventyFiveValues[index] =\ + seventyFiveValues2[index] = index;\ + }\ + hundredValues[index] =\ + hundredValues2[index] = index;\ + }\ + }\ + }\ + \ + if (typeof template != "undefined") {\ + var tplData = {\ + "header1": "Header1",\ + "header2": "Header2",\ + "header3": "Header3",\ + "header4": "Header4",\ + "header5": "Header5",\ + "header6": "Header6",\ + "list": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]\ + };\ + \ + var tpl =\ + "
    " +\ + "

    <%= header1 %>

    " +\ + "

    <%= header2 %>

    " +\ + "

    <%= header3 %>

    " +\ + "

    <%= header4 %>

    " +\ + "
    <%= header5 %>
    " +\ + "
    <%= header6 %>
    " +\ + "
      " +\ + "<% for (var index = 0, length = list.length; index < length; index++) { %>" +\ + "
    • <%= list[index] %>
    • " +\ + "<% } %>" +\ + "
    " +\ + "
    ";\ + \ + var tplVerbose =\ + "
    " +\ + "

    <%= data.header1 %>

    " +\ + "

    <%= data.header2 %>

    " +\ + "

    <%= data.header3 %>

    " +\ + "

    <%= data.header4 %>

    " +\ + "
    <%= data.header5 %>
    " +\ + "
    <%= data.header6 %>
    " +\ + "
      " +\ + "<% for (var index = 0, length = data.list.length; index < length; index++) { %>" +\ + "
    • <%= data.list[index] %>
    • " +\ + "<% } %>" +\ + "
    " +\ + "
    ";\ + \ + var settingsObject = { "variable": "data" };\ + \ + var lodashTpl = lodash.template(tpl),\ + lodashTplVerbose = lodash.template(tplVerbose, null, settingsObject);\ + \ + var _tpl = _.template(tpl),\ + _tplVerbose = _.template(tplVerbose, null, settingsObject);\ + }' + }); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.bind` (uses native `Function#bind` if available and inferred fast)') + .add(buildName, { + 'fn': 'lodash.bind(func, { "name": "moe" }, "hi")', + 'teardown': 'function bind(){}' + }) + .add(otherName, { + 'fn': '_.bind(func, { "name": "moe" }, "hi")', + 'teardown': 'function bind(){}' + }) + ); + + suites.push( + Benchmark.Suite('bound call') + .add(buildName, { + 'fn': 'lodashBoundNormal()', + 'teardown': 'function bind(){}' + }) + .add(otherName, { + 'fn': '_boundNormal()', + 'teardown': 'function bind(){}' + }) + ); + + suites.push( + Benchmark.Suite('bound call with arguments') + .add(buildName, { + 'fn': 'lodashBoundNormal("hi", "!")', + 'teardown': 'function bind(){}' + }) + .add(otherName, { + 'fn': '_boundNormal("hi", "!")', + 'teardown': 'function bind(){}' + }) + ); + + suites.push( + Benchmark.Suite('bound and partially applied call (uses native `Function#bind` if available)') + .add(buildName, { + 'fn': 'lodashBoundPartial()', + 'teardown': 'function bind(){}' + }) + .add(otherName, { + 'fn': '_boundPartial()', + 'teardown': 'function bind(){}' + }) + ); + + suites.push( + Benchmark.Suite('bound and partially applied call with arguments (uses native `Function#bind` if available)') + .add(buildName, { + 'fn': 'lodashBoundPartial("!")', + 'teardown': 'function bind(){}' + }) + .add(otherName, { + 'fn': '_boundPartial("!")', + 'teardown': 'function bind(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.bindAll` iterating arguments') + .add(buildName, { + 'fn': 'lodash.bindAll.apply(lodash, [bindAllObjects.pop()].concat(funcNames))', + 'teardown': 'function bindAll(){}' + }) + .add(otherName, { + 'fn': '_.bindAll.apply(_, [bindAllObjects.pop()].concat(funcNames))', + 'teardown': 'function bindAll(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.bindAll` iterating the `object`') + .add(buildName, { + 'fn': 'lodash.bindAll(bindAllObjects.pop())', + 'teardown': 'function bindAll(){}' + }) + .add(otherName, { + 'fn': '_.bindAll(bindAllObjects.pop())', + 'teardown': 'function bindAll(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.clone` with an object') + .add(buildName, '\ + lodash.clone(object)' + ) + .add(otherName, '\ + _.clone(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.compact`') + .add(buildName, { + 'fn': 'lodash.compact(uncompacted)', + 'teardown': 'function compact(){}' + }) + .add(otherName, { + 'fn': '_.compact(uncompacted)', + 'teardown': 'function compact(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.contains` iterating an array') + .add(buildName, '\ + lodash.contains(numbers, 19)' + ) + .add(otherName, '\ + _.contains(numbers, 19)' + ) + ); + + suites.push( + Benchmark.Suite('`_.contains` iterating an object') + .add(buildName, '\ + lodash.contains(object, 19)' + ) + .add(otherName, '\ + _.contains(object, 19)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.countBy` with `callback` iterating an array') + .add(buildName, '\ + lodash.countBy(numbers, function(num) { return num >> 1; })' + ) + .add(otherName, '\ + _.countBy(numbers, function(num) { return num >> 1; })' + ) + ); + + suites.push( + Benchmark.Suite('`_.countBy` with `property` name iterating an array') + .add(buildName, { + 'fn': 'lodash.countBy(words, "length")', + 'teardown': 'function countBy(){}' + }) + .add(otherName, { + 'fn': '_.countBy(words, "length")', + 'teardown': 'function countBy(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.countBy` with `callback` iterating an object') + .add(buildName, { + 'fn': 'lodash.countBy(wordToNumber, function(num) { return num >> 1; })', + 'teardown': 'function countBy(){}' + }) + .add(otherName, { + 'fn': '_.countBy(wordToNumber, function(num) { return num >> 1; })', + 'teardown': 'function countBy(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.defaults`') + .add(buildName, '\ + lodash.defaults({ "key2": 2, "key6": 6, "key18": 18 }, object)' + ) + .add(otherName, '\ + _.defaults({ "key2": 2, "key6": 6, "key18": 18 }, object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.difference`') + .add(buildName, '\ + lodash.difference(numbers, twoNumbers, fourNumbers)' + ) + .add(otherName, '\ + _.difference(numbers, twoNumbers, fourNumbers)' + ) + ); + + suites.push( + Benchmark.Suite('`_.difference` iterating 30 elements') + .add(buildName, { + 'fn': 'lodash.difference(thirtyValues, thirtyValues2)', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.difference(thirtyValues, thirtyValues2)', + 'teardown': 'function multiArrays(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.difference` iterating 20 and 40 elements') + .add(buildName, { + 'fn': 'lodash.difference(twentyValues, fortyValues2)', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.difference(twentyValues, fortyValues2)', + 'teardown': 'function multiArrays(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.each` iterating an array') + .add(buildName, '\ + var result = [];\ + lodash.each(numbers, function(num) {\ + result.push(num * 2);\ + })' + ) + .add(otherName, '\ + var result = [];\ + _.each(numbers, function(num) {\ + result.push(num * 2);\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.each` iterating an array with `thisArg` (slow path)') + .add(buildName, '\ + var result = [];\ + lodash.each(numbers, function(num, index) {\ + result.push(num + this["key" + index]);\ + }, object)' + ) + .add(otherName, '\ + var result = [];\ + _.each(numbers, function(num, index) {\ + result.push(num + this["key" + index]);\ + }, object)' + ) + ); + + suites.push( + Benchmark.Suite('`_.each` iterating an object') + .add(buildName, '\ + var result = [];\ + lodash.each(object, function(num) {\ + result.push(num * 2);\ + })' + ) + .add(otherName, '\ + var result = [];\ + _.each(object, function(num) {\ + result.push(num * 2);\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.every` iterating an array') + .add(buildName, '\ + lodash.every(numbers, function(num) {\ + return num + "";\ + })' + ) + .add(otherName, '\ + _.every(numbers, function(num) {\ + return num + "";\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.every` iterating an object') + .add(buildName, '\ + lodash.every(object, function(num) {\ + return num + "";\ + })' + ) + .add(otherName, '\ + _.every(object, function(num) {\ + return num + "";\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.extend`') + .add(buildName, '\ + lodash.extend({}, object)' + ) + .add(otherName, '\ + _.extend({}, object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.filter` iterating an array') + .add(buildName, '\ + lodash.filter(numbers, function(num) {\ + return num % 2;\ + })' + ) + .add(otherName, '\ + _.filter(numbers, function(num) {\ + return num % 2;\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.filter` iterating an array with `thisArg` (slow path)') + .add(buildName, '\ + lodash.filter(numbers, function(num, index) {\ + return this["key" + index] % 2;\ + }, object)' + ) + .add(otherName, '\ + _.filter(numbers, function(num, index) {\ + return this["key" + index] % 2;\ + }, object)' + ) + ); + + suites.push( + Benchmark.Suite('`_.filter` iterating an object') + .add(buildName, '\ + lodash.filter(object, function(num) {\ + return num % 2\ + })' + ) + .add(otherName, '\ + _.filter(object, function(num) {\ + return num % 2\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.find` iterating an array') + .add(buildName, '\ + lodash.find(numbers, function(num) {\ + return num === 19;\ + })' + ) + .add(otherName, '\ + _.find(numbers, function(num) {\ + return num === 19;\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.find` iterating an object') + .add(buildName, '\ + lodash.find(object, function(value, key) {\ + return /\D9$/.test(key);\ + })' + ) + .add(otherName, '\ + _.find(object, function(value, key) {\ + return /\D9$/.test(key);\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.find` with `properties`') + .add(buildName, '\ + lodash.find(objects, { "num": 9 });' + ) + .add(otherName, '\ + _.findWhere(objects, { "num": 9 });' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.flatten`') + .add(buildName, '\ + lodash.flatten(nestedNumbers)' + ) + .add(otherName, '\ + _.flatten(nestedNumbers)' + ) + ); + + suites.push( + Benchmark.Suite('`_.flatten` with `shallow`') + .add(buildName, '\ + lodash.flatten(nestedNumbers, true)' + ) + .add(otherName, '\ + _.flatten(nestedNumbers, true)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.functions`') + .add(buildName, '\ + lodash.functions(lodash)' + ) + .add(otherName, '\ + _.functions(lodash)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.groupBy` with `callback` iterating an array') + .add(buildName, '\ + lodash.groupBy(numbers, function(num) { return num >> 1; })' + ) + .add(otherName, '\ + _.groupBy(numbers, function(num) { return num >> 1; })' + ) + ); + + suites.push( + Benchmark.Suite('`_.groupBy` with `property` name iterating an array') + .add(buildName, { + 'fn': 'lodash.groupBy(words, "length")', + 'teardown': 'function countBy(){}' + }) + .add(otherName, { + 'fn': '_.groupBy(words, "length")', + 'teardown': 'function countBy(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.groupBy` with `callback` iterating an object') + .add(buildName, { + 'fn': 'lodash.groupBy(wordToNumber, function(num) { return num >> 1; })', + 'teardown': 'function countBy(){}' + }) + .add(otherName, { + 'fn': '_.groupBy(wordToNumber, function(num) { return num >> 1; })', + 'teardown': 'function countBy(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.indexOf`') + .add(buildName, '\ + lodash.indexOf(numbers, 9)' + ) + .add(otherName, '\ + _.indexOf(numbers, 9)' + ) + ); + + suites.push( + Benchmark.Suite('`_.indexOf` with `isSorted`') + .add(buildName, '\ + lodash.indexOf(numbers, 19, true)' + ) + .add(otherName, '\ + _.indexOf(numbers, 19, true)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.intersection`') + .add(buildName, '\ + lodash.intersection(numbers, twoNumbers, fourNumbers)' + ) + .add(otherName, '\ + _.intersection(numbers, twoNumbers, fourNumbers)' + ) + ); + + suites.push( + Benchmark.Suite('`_.intersection` iterating 100 elements') + .add(buildName, { + 'fn': 'lodash.intersection(hundredValues, hundredValues2)', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.intersection(hundredValues, hundredValues2)', + 'teardown': 'function multiArrays(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.invert`') + .add(buildName, '\ + lodash.invert(object)' + ) + .add(otherName, '\ + _.invert(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.invoke` iterating an array') + .add(buildName, '\ + lodash.invoke(numbers, "toFixed", "2")' + ) + .add(otherName, '\ + _.invoke(numbers, "toFixed", "2")' + ) + ); + + suites.push( + Benchmark.Suite('`_.invoke` with a function for `methodName` iterating an array') + .add(buildName, '\ + lodash.invoke(numbers, String.prototype.split, "")' + ) + .add(otherName, '\ + _.invoke(numbers, String.prototype.split, "")' + ) + ); + + suites.push( + Benchmark.Suite('`_.invoke` iterating an object') + .add(buildName, '\ + lodash.invoke(object, "toFixed", "2")' + ) + .add(otherName, '\ + _.invoke(object, "toFixed", "2")' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.isEqual` comparing primitives and objects (edge case)') + .add(buildName, { + 'fn': 'lodash.isEqual(objectOfPrimitives, objectOfObjects)', + 'teardown': 'function isEqual(){}' + }) + .add(otherName, { + 'fn': '_.isEqual(objectOfPrimitives, objectOfObjects)', + 'teardown': 'function isEqual(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.isEqual` comparing arrays') + .add(buildName, { + 'fn': '\ + lodash.isEqual(numbers, numbers2);\ + lodash.isEqual(twoNumbers, twoNumbers2);', + 'teardown': 'function isEqual(){}' + }) + .add(otherName, { + 'fn': '\ + _.isEqual(numbers, numbers2);\ + _.isEqual(twoNumbers, twoNumbers2);', + 'teardown': 'function isEqual(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.isEqual` comparing nested arrays') + .add(buildName, { + 'fn': '\ + lodash.isEqual(nestedNumbers, nestedNumbers2);\ + lodash.isEqual(nestedNumbers2, nestedNumbers3);', + 'teardown': 'function isEqual(){}' + }) + .add(otherName, { + 'fn': '\ + _.isEqual(nestedNumbers, nestedNumbers2);\ + _.isEqual(nestedNumbers2, nestedNumbers3);', + 'teardown': 'function isEqual(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.isEqual` comparing arrays of objects') + .add(buildName, { + 'fn': '\ + lodash.isEqual(objects, objects2);\ + lodash.isEqual(simpleObjects, simpleObjects2);', + 'teardown': 'function isEqual(){}' + }) + .add(otherName, { + 'fn': '\ + _.isEqual(objects, objects2);\ + _.isEqual(simpleObjects, simpleObjects2);', + 'teardown': 'function isEqual(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.isEqual` comparing objects') + .add(buildName, { + 'fn': '\ + lodash.isEqual(object, object2);\ + lodash.isEqual(simpleObject, simpleObject2);', + 'teardown': 'function isEqual(){}' + }) + .add(otherName, { + 'fn': '\ + _.isEqual(object, object2);\ + _.isEqual(simpleObject, simpleObject2);', + 'teardown': 'function isEqual(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.isArguments`, `_.isDate`, `_.isFunction`, `_.isNumber`, `_.isRegExp`') + .add(buildName, '\ + lodash.isArguments(arguments);\ + lodash.isArguments(object);\ + lodash.isDate(date);\ + lodash.isDate(object);\ + lodash.isFunction(lodash);\ + lodash.isFunction(object);\ + lodash.isNumber(1);\ + lodash.isNumber(object);\ + lodash.isRegExp(regexp);\ + lodash.isRegExp(object);' + ) + .add(otherName, '\ + _.isArguments(arguments);\ + _.isArguments(object);\ + _.isDate(date);\ + _.isDate(object);\ + _.isFunction(_);\ + _.isFunction(object);\ + _.isNumber(1);\ + _.isNumber(object);\ + _.isRegExp(regexp);\ + _.isRegExp(object);' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.keys` (uses native `Object.keys` if available)') + .add(buildName, '\ + lodash.keys(object)' + ) + .add(otherName, '\ + _.keys(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.lastIndexOf`') + .add(buildName, '\ + lodash.lastIndexOf(numbers, 9)' + ) + .add(otherName, '\ + _.lastIndexOf(numbers, 9)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.map` iterating an array') + .add(buildName, '\ + lodash.map(objects, function(value) {\ + return value.num;\ + })' + ) + .add(otherName, '\ + _.map(objects, function(value) {\ + return value.num;\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.map` with `thisArg` iterating an array (slow path)') + .add(buildName, '\ + lodash.map(objects, function(value, index) {\ + return this["key" + index] + value.num;\ + }, object)' + ) + .add(otherName, '\ + _.map(objects, function(value, index) {\ + return this["key" + index] + value.num;\ + }, object)' + ) + ); + + suites.push( + Benchmark.Suite('`_.map` iterating an object') + .add(buildName, '\ + lodash.map(object, function(value) {\ + return value;\ + })' + ) + .add(otherName, '\ + _.map(object, function(value) {\ + return value;\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.max`') + .add(buildName, '\ + lodash.max(numbers)' + ) + .add(otherName, '\ + _.max(numbers)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.min`') + .add(buildName, '\ + lodash.min(numbers)' + ) + .add(otherName, '\ + _.min(numbers)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.omit` iterating 20 properties, omitting 2 keys') + .add(buildName, '\ + lodash.omit(object, "key6", "key13")' + ) + .add(otherName, '\ + _.omit(object, "key6", "key13")' + ) + ); + + suites.push( + Benchmark.Suite('`_.omit` iterating 40 properties, omitting 20 keys') + .add(buildName, { + 'fn': 'lodash.omit(wordToNumber, words)', + 'teardown': 'function omit(){}' + }) + .add(otherName, { + 'fn': 'result = _.omit(wordToNumber, words)', + 'teardown': 'function omit(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.pairs`') + .add(buildName, '\ + lodash.pairs(object)' + ) + .add(otherName, '\ + _.pairs(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.pick`') + .add(buildName, '\ + lodash.pick(object, "key6", "key13")' + ) + .add(otherName, '\ + _.pick(object, "key6", "key13")' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.pluck`') + .add(buildName, '\ + lodash.pluck(objects, "num")' + ) + .add(otherName, '\ + _.pluck(objects, "num")' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.reduce` iterating an array') + .add(buildName, '\ + lodash.reduce(numbers, function(result, value, index) {\ + result[index] = value;\ + return result;\ + }, {});' + ) + .add(otherName, '\ + _.reduce(numbers, function(result, value, index) {\ + result[index] = value;\ + return result;\ + }, {});' + ) + ); + + suites.push( + Benchmark.Suite('`_.reduce` iterating an object') + .add(buildName, '\ + lodash.reduce(object, function(result, value, key) {\ + result.push([key, value]);\ + return result;\ + }, []);' + ) + .add(otherName, '\ + _.reduce(object, function(result, value, key) {\ + result.push([key, value]);\ + return result;\ + }, []);' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.reduceRight` iterating an array') + .add(buildName, '\ + lodash.reduceRight(numbers, function(result, value, index) {\ + result[index] = value;\ + return result;\ + }, {});' + ) + .add(otherName, '\ + _.reduceRight(numbers, function(result, value, index) {\ + result[index] = value;\ + return result;\ + }, {});' + ) + ); + + suites.push( + Benchmark.Suite('`_.reduceRight` iterating an object') + .add(buildName, '\ + lodash.reduceRight(object, function(result, value, key) {\ + result.push([key, value]);\ + return result;\ + }, []);' + ) + .add(otherName, '\ + _.reduceRight(object, function(result, value, key) {\ + result.push([key, value]);\ + return result;\ + }, []);' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.reject` iterating an array') + .add(buildName, '\ + lodash.reject(numbers, function(num) {\ + return num % 2;\ + })' + ) + .add(otherName, '\ + _.reject(numbers, function(num) {\ + return num % 2;\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.reject` iterating an array with `thisArg` (slow path)') + .add(buildName, '\ + lodash.reject(numbers, function(num, index) {\ + return this["key" + index] % 2;\ + }, object)' + ) + .add(otherName, '\ + _.reject(numbers, function(num, index) {\ + return this["key" + index] % 2;\ + }, object)' + ) + ); + + suites.push( + Benchmark.Suite('`_.reject` iterating an object') + .add(buildName, '\ + lodash.reject(object, function(num) {\ + return num % 2\ + })' + ) + .add(otherName, '\ + _.reject(object, function(num) {\ + return num % 2\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.shuffle`') + .add(buildName, '\ + lodash.shuffle(numbers)' + ) + .add(otherName, '\ + _.shuffle(numbers)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.size` with an object') + .add(buildName, '\ + lodash.size(object)' + ) + .add(otherName, '\ + _.size(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.some` iterating an array') + .add(buildName, '\ + lodash.some(numbers, function(num) {\ + return num == 19;\ + })' + ) + .add(otherName, '\ + _.some(numbers, function(num) {\ + return num == 19;\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.some` with `thisArg` iterating an array (slow path)') + .add(buildName, '\ + lodash.some(objects, function(value, index) {\ + return this["key" + index] == 19;\ + }, object)' + ) + .add(otherName, '\ + _.some(objects, function(value, index) {\ + return this["key" + index] == 19;\ + }, object)' + ) + ); + + suites.push( + Benchmark.Suite('`_.some` iterating an object') + .add(buildName, '\ + lodash.some(object, function(num) {\ + return num == 19;\ + })' + ) + .add(otherName, '\ + _.some(object, function(num) {\ + return num == 19;\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.sortBy` with `callback`') + .add(buildName, '\ + lodash.sortBy(numbers, function(num) { return Math.sin(num); })' + ) + .add(otherName, '\ + _.sortBy(numbers, function(num) { return Math.sin(num); })' + ) + ); + + suites.push( + Benchmark.Suite('`_.sortBy` with `callback` and `thisArg` (slow path)') + .add(buildName, '\ + lodash.sortBy(numbers, function(num) { return this.sin(num); }, Math)' + ) + .add(otherName, '\ + _.sortBy(numbers, function(num) { return this.sin(num); }, Math)' + ) + ); + + suites.push( + Benchmark.Suite('`_.sortBy` with `property` name') + .add(buildName, { + 'fn': 'lodash.sortBy(words, "length")', + 'teardown': 'function countBy(){}' + }) + .add(otherName, { + 'fn': '_.sortBy(words, "length")', + 'teardown': 'function countBy(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.sortedIndex`') + .add(buildName, '\ + lodash.sortedIndex(numbers, 25)' + ) + .add(otherName, '\ + _.sortedIndex(numbers, 25)' + ) + ); + + suites.push( + Benchmark.Suite('`_.sortedIndex` with `callback`') + .add(buildName, { + 'fn': '\ + lodash.sortedIndex(words, "twenty-five", function(value) {\ + return wordToNumber[value];\ + })', + 'teardown': 'function countBy(){}' + }) + .add(otherName, { + 'fn': '\ + _.sortedIndex(words, "twenty-five", function(value) {\ + return wordToNumber[value];\ + })', + 'teardown': 'function countBy(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.template` (slow path)') + .add(buildName, { + 'fn': 'lodash.template(tpl, tplData)', + 'teardown': 'function template(){}' + }) + .add(otherName, { + 'fn': '_.template(tpl, tplData)', + 'teardown': 'function template(){}' + }) + ); + + suites.push( + Benchmark.Suite('compiled template') + .add(buildName, { + 'fn': 'lodashTpl(tplData)', + 'teardown': 'function template(){}' + }) + .add(otherName, { + 'fn': '_tpl(tplData)', + 'teardown': 'function template(){}' + }) + ); + + suites.push( + Benchmark.Suite('compiled template without a with-statement') + .add(buildName, { + 'fn': 'lodashTplVerbose(tplData)', + 'teardown': 'function template(){}' + }) + .add(otherName, { + 'fn': '_tplVerbose(tplData)', + 'teardown': 'function template(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.times`') + .add(buildName, '\ + var result = [];\ + lodash.times(limit, function(n) { result.push(n); })' + ) + .add(otherName, '\ + var result = [];\ + _.times(limit, function(n) { result.push(n); })' + ) + ); + + suites.push( + Benchmark.Suite('`_.times` with `thisArg`') + .add(buildName, '\ + var result = [];\ + lodash.times(limit, function(n) { result.push(this.sin(n)); }, Math)' + ) + .add(otherName, '\ + var result = [];\ + _.times(limit, function(n) { result.push(this.sin(n)); }, Math)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.toArray` with an array (edge case)') + .add(buildName, '\ + lodash.toArray(numbers)' + ) + .add(otherName, '\ + _.toArray(numbers)' + ) + ); + + suites.push( + Benchmark.Suite('`_.toArray` with an object') + .add(buildName, '\ + lodash.toArray(object)' + ) + .add(otherName, '\ + _.toArray(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.union`') + .add(buildName, '\ + lodash.union(numbers, twoNumbers, fourNumbers)' + ) + .add(otherName, '\ + _.union(numbers, twoNumbers, fourNumbers)' + ) + ); + + suites.push( + Benchmark.Suite('`_.union` iterating an array of 75 elements') + .add(buildName, { + 'fn': 'lodash.union(fiftyValues, twentyFiveValues2);', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.union(fiftyValues, twentyFiveValues2);', + 'teardown': 'function multiArrays(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.uniq`') + .add(buildName, '\ + lodash.uniq(numbers.concat(twoNumbers, fourNumbers))' + ) + .add(otherName, '\ + _.uniq(numbers.concat(twoNumbers, fourNumbers))' + ) + ); + + suites.push( + Benchmark.Suite('`_.uniq` with `callback`') + .add(buildName, '\ + lodash.uniq(numbers.concat(twoNumbers, fourNumbers), function(num) {\ + return num % 2;\ + });' + ) + .add(otherName, '\ + _.uniq(numbers.concat(twoNumbers, fourNumbers), function(num) {\ + return num % 2;\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.uniq` iterating an array of 75 elements') + .add(buildName, { + 'fn': 'lodash.uniq(fiftyValues.concat(twentyFiveValues2));', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.uniq(fiftyValues.concat(twentyFiveValues2));', + 'teardown': 'function multiArrays(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.values`') + .add(buildName, '\ + lodash.values(object)' + ) + .add(otherName, '\ + _.values(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.where`') + .add(buildName, '\ + lodash.where(objects, { "num": 9 });' + ) + .add(otherName, '\ + _.where(objects, { "num": 9 });' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.without`') + .add(buildName, '\ + lodash.without(numbers, 9, 12, 14, 15)' + ) + .add(otherName, '\ + _.without(numbers, 9, 12, 14, 15)' + ) + ); + + suites.push( + Benchmark.Suite('`_.without` iterating an array of 30 elements') + .add(buildName, { + 'fn': 'lodash.without.apply(lodash, [thirtyValues].concat(thirtyValues2));', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.without.apply(_, [thirtyValues].concat(thirtyValues2));', + 'teardown': 'function multiArrays(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + if (Benchmark.platform + '') { + log(Benchmark.platform); + } + + // in the browser, expose `run` to be called later + if (window.document && !window.phantom) { + window.run = run; + } else { + run(); + } +}(typeof global == 'object' && global || this)); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/template/a.jst b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/template/a.jst new file mode 100644 index 000000000..cca541d8f --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/template/a.jst @@ -0,0 +1,3 @@ +
      +<% _.forEach(people, function(name) { %>
    • <%- name %>
    • <% }); %> +
    \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/template/b.jst b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/template/b.jst new file mode 100644 index 000000000..cad081d19 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/template/b.jst @@ -0,0 +1 @@ +<% print("Hello " + epithet); %>. \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/template/c.jst b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/template/c.jst new file mode 100644 index 000000000..f92679903 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/template/c.jst @@ -0,0 +1 @@ +Hello ${ name }! \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/template/d.tpl b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/template/d.tpl new file mode 100644 index 000000000..c7a43bc1f --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/template/d.tpl @@ -0,0 +1 @@ +Hello {{ name }}! \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/test-build.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/test-build.js new file mode 100644 index 000000000..759d98ebc --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/test-build.js @@ -0,0 +1,1324 @@ +#!/usr/bin/env node +;(function(undefined) { + 'use strict'; + + /** Load modules */ + var fs = require('fs'), + path = require('path'), + vm = require('vm'), + build = require('../build.js'), + minify = require('../build/minify'), + _ = require('../lodash.js'); + + /** The unit testing framework */ + var QUnit = ( + global.addEventListener || (global.addEventListener = Function.prototype), + global.QUnit = require('../vendor/qunit/qunit/qunit.js'), + require('../vendor/qunit-clib/qunit-clib.js'), + global.addEventListener === Function.prototype && delete global.addEventListener, + global.QUnit + ); + + /** The time limit for the tests to run (milliseconds) */ + var timeLimit = process.argv.reduce(function(result, value, index) { + if (/--time-limit/.test(value)) { + return parseInt(process.argv[index + 1].replace(/(\d+h)?(\d+m)?(\d+s)?/, function(match, h, m, s) { + return ((parseInt(h) || 0) * 3600000) + + ((parseInt(m) || 0) * 60000) + + ((parseInt(s) || 0) * 1000); + })) || result; + } + return result; + }, 0); + + /** Used to associate aliases with their real names */ + var aliasToRealMap = { + 'all': 'every', + 'any': 'some', + 'collect': 'map', + 'detect': 'find', + 'drop': 'rest', + 'each': 'forEach', + 'extend': 'assign', + 'foldl': 'reduce', + 'foldr': 'reduceRight', + 'head': 'first', + 'include': 'contains', + 'inject': 'reduce', + 'methods': 'functions', + 'select': 'filter', + 'tail': 'rest', + 'take': 'first', + 'unique': 'uniq' + }; + + /** Used to associate real names with their aliases */ + var realToAliasMap = { + 'assign': ['extend'], + 'contains': ['include'], + 'every': ['all'], + 'filter': ['select'], + 'find': ['detect'], + 'first': ['head', 'take'], + 'forEach': ['each'], + 'functions': ['methods'], + 'map': ['collect'], + 'reduce': ['foldl', 'inject'], + 'reduceRight': ['foldr'], + 'rest': ['drop', 'tail'], + 'some': ['any'], + 'uniq': ['unique'] + }; + + /** List of all Lo-Dash methods */ + var allMethods = _.functions(_) + .filter(function(methodName) { return !/^_/.test(methodName); }) + .concat('chain') + .sort(); + + /** List of "Arrays" category methods */ + var arraysMethods = [ + 'compact', + 'difference', + 'drop', + 'first', + 'flatten', + 'head', + 'indexOf', + 'initial', + 'intersection', + 'last', + 'lastIndexOf', + 'object', + 'range', + 'rest', + 'sortedIndex', + 'tail', + 'take', + 'union', + 'uniq', + 'unique', + 'without', + 'zip' + ]; + + /** List of "Chaining" category methods */ + var chainingMethods = [ + 'mixin', + 'tap', + 'value' + ]; + + /** List of "Collections" category methods */ + var collectionsMethods = [ + 'all', + 'any', + 'at', + 'collect', + 'contains', + 'countBy', + 'detect', + 'each', + 'every', + 'filter', + 'find', + 'foldl', + 'foldr', + 'forEach', + 'groupBy', + 'include', + 'inject', + 'invoke', + 'map', + 'max', + 'min', + 'pluck', + 'reduce', + 'reduceRight', + 'reject', + 'select', + 'shuffle', + 'size', + 'some', + 'sortBy', + 'toArray', + 'where' + ]; + + /** List of "Functions" category methods */ + var functionsMethods = [ + 'after', + 'bind', + 'bindAll', + 'bindKey', + 'compose', + 'debounce', + 'defer', + 'delay', + 'memoize', + 'once', + 'partial', + 'partialRight', + 'throttle', + 'wrap' + ]; + + /** List of "Objects" category methods */ + var objectsMethods = [ + 'assign', + 'clone', + 'cloneDeep', + 'defaults', + 'extend', + 'forIn', + 'forOwn', + 'functions', + 'has', + 'invert', + 'isArguments', + 'isArray', + 'isBoolean', + 'isDate', + 'isElement', + 'isEmpty', + 'isEqual', + 'isFinite', + 'isFunction', + 'isNaN', + 'isNull', + 'isNumber', + 'isObject', + 'isPlainObject', + 'isRegExp', + 'isString', + 'isUndefined', + 'keys', + 'methods', + 'merge', + 'omit', + 'pairs', + 'pick', + 'values' + ]; + + /** List of "Utilities" category methods */ + var utilityMethods = [ + 'escape', + 'identity', + 'noConflict', + 'random', + 'result', + 'template', + 'times', + 'unescape', + 'uniqueId' + ]; + + /** List of Backbone's Lo-Dash dependencies */ + var backboneDependencies = [ + 'bind', + 'bindAll', + 'chain', + 'clone', + 'contains', + 'countBy', + 'defaults', + 'escape', + 'every', + 'extend', + 'filter', + 'find', + 'first', + 'forEach', + 'groupBy', + 'has', + 'indexOf', + 'initial', + 'invoke', + 'isArray', + 'isEmpty', + 'isEqual', + 'isFunction', + 'isObject', + 'isRegExp', + 'isString', + 'keys', + 'last', + 'lastIndexOf', + 'map', + 'max', + 'min', + 'mixin', + 'once', + 'pick', + 'reduce', + 'reduceRight', + 'reject', + 'rest', + 'result', + 'shuffle', + 'size', + 'some', + 'sortBy', + 'sortedIndex', + 'toArray', + 'uniqueId', + 'value', + 'without' + ]; + + /** List of methods used by Underscore */ + var underscoreMethods = _.without.apply(_, [allMethods].concat([ + 'at', + 'bindKey', + 'cloneDeep', + 'forIn', + 'forOwn', + 'isPlainObject', + 'merge', + 'partialRight' + ])); + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a context object to use with `vm.runInContext`. + * + * @private + * @returns {Object} Returns a new context object. + */ + function createContext() { + return vm.createContext({ + 'clearTimeout': clearTimeout, + 'setTimeout': setTimeout + }); + } + + /** + * Expands a list of method names to include real and alias names. + * + * @private + * @param {Array} methodNames The array of method names to expand. + * @returns {Array} Returns a new array of expanded method names. + */ + function expandMethodNames(methodNames) { + return methodNames.reduce(function(result, methodName) { + var realName = getRealName(methodName); + result.push.apply(result, [realName].concat(getAliases(realName))); + return result; + }, []); + } + + /** + * Gets the aliases associated with a given function name. + * + * @private + * @param {String} funcName The name of the function to get aliases for. + * @returns {Array} Returns an array of aliases. + */ + function getAliases(funcName) { + return realToAliasMap[funcName] || []; + } + + /** + * Gets the names of methods belonging to the given `category`. + * + * @private + * @param {String} category The category to filter by. + * @returns {Array} Returns a new array of method names belonging to the given category. + */ + function getMethodsByCategory(category) { + switch (category) { + case 'Arrays': + return arraysMethods.slice(); + case 'Chaining': + return chainingMethods.slice(); + case 'Collections': + return collectionsMethods.slice(); + case 'Functions': + return functionsMethods.slice(); + case 'Objects': + return objectsMethods.slice(); + case 'Utilities': + return utilityMethods.slice(); + } + return []; + } + + /** + * Gets the real name, not alias, of a given function name. + * + * @private + * @param {String} funcName The name of the function to resolve. + * @returns {String} Returns the real name. + */ + function getRealName(funcName) { + return aliasToRealMap[funcName] || funcName; + } + + /** + * Tests if a given method on the `lodash` object can be called successfully. + * + * @private + * @param {Object} lodash The built Lo-Dash object. + * @param {String} methodName The name of the Lo-Dash method to test. + * @param {String} message The unit test message. + */ + function testMethod(lodash, methodName, message) { + var pass = true, + array = [['a', 1], ['b', 2], ['c', 3]], + object = { 'a': 1, 'b': 2, 'c': 3 }, + noop = function() {}, + string = 'abc', + template = '<%= a %>', + func = lodash[methodName]; + + try { + if (arraysMethods.indexOf(methodName) > -1) { + if (/(?:indexOf|sortedIndex|without)$/i.test(methodName)) { + func(array, string); + } else if (/^(?:difference|intersection|union|uniq|zip)/.test(methodName)) { + func(array, array); + } else if (methodName == 'range') { + func(2, 4); + } else { + func(array); + } + } + else if (chainingMethods.indexOf(methodName) > -1) { + if (methodName == 'chain') { + lodash.chain(array); + lodash(array).chain(); + } + else if (methodName == 'mixin') { + lodash.mixin({}); + } + else { + lodash(array)[methodName](noop); + } + } + else if (collectionsMethods.indexOf(methodName) > -1) { + if (/^(?:count|group|sort)By$/.test(methodName)) { + func(array, noop); + func(array, string); + func(object, noop); + func(object, string); + } + else if (/^(?:size|toArray)$/.test(methodName)) { + func(array); + func(object); + } + else if (methodName == 'at') { + func(array, 0, 2); + func(object, 'a', 'c'); + } + else if (methodName == 'invoke') { + func(array, 'slice'); + func(object, 'toFixed'); + } + else if (methodName == 'where') { + func(array, object); + func(object, object); + } + else { + func(array, noop, object); + func(object, noop, object); + } + } + else if (functionsMethods.indexOf(methodName) > -1) { + if (methodName == 'after') { + func(1, noop); + } else if (methodName == 'bindAll') { + func({ 'noop': noop }); + } else if (methodName == 'bindKey') { + func(lodash, 'identity', array, string); + } else if (/^(?:bind|partial(?:Right)?)$/.test(methodName)) { + func(noop, object, array, string); + } else if (/^(?:compose|memoize|wrap)$/.test(methodName)) { + func(noop, noop); + } else if (/^(?:debounce|throttle)$/.test(methodName)) { + func(noop, 100); + } else { + func(noop); + } + } + else if (objectsMethods.indexOf(methodName) > -1) { + if (methodName == 'clone') { + func(object); + func(object, true); + } + else if (/^(?:defaults|extend|merge)$/.test(methodName)) { + func({}, object); + } else if (/^(?:forIn|forOwn)$/.test(methodName)) { + func(object, noop); + } else if (/^(?:omit|pick)$/.test(methodName)) { + func(object, 'b'); + } else if (methodName == 'has') { + func(object, string); + } else { + func(object); + } + } + else if (utilityMethods.indexOf(methodName) > -1) { + if (methodName == 'result') { + func(object, 'b'); + } else if (methodName == 'template') { + func(template, object); + func(template, null, { 'imports': object })(object); + } else if (methodName == 'times') { + func(2, noop, object); + } else { + func(string, object); + } + } + } + catch(e) { + console.log(e); + pass = false; + } + ok(pass, '_.' + methodName + ': ' + message); + } + + /*--------------------------------------------------------------------------*/ + + QUnit.module('minified AMD snippet'); + + (function() { + var start = _.once(QUnit.start); + + asyncTest('`lodash`', function() { + build(['-s'], function(data) { + // used by r.js build optimizer + var defineHasRegExp = /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g, + basename = path.basename(data.outputPath, '.js'); + + ok(!!defineHasRegExp.exec(data.source), basename); + start(); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('template builds'); + + (function() { + var templatePath = __dirname + '/template'; + + asyncTest('`lodash template=*.jst`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'template=' + templatePath + '/*.jst'], function(data) { + var basename = path.basename(data.outputPath, '.js'), + context = createContext(); + + var object = { + 'a': { 'people': ['moe', 'larry', 'curly'] }, + 'b': { 'epithet': 'stooge' }, + 'c': { 'name': 'ES6' } + }; + + context._ = _; + vm.runInContext(data.source, context); + + equal(_.templates.a(object.a).replace(/[\r\n]+/g, ''), '
    • moe
    • larry
    • curly
    ', basename); + equal(_.templates.b(object.b), 'Hello stooge.', basename); + equal(_.templates.c(object.c), 'Hello ES6!', basename); + delete _.templates; + start(); + }); + }); + + var commands = [ + '', + 'moduleId=underscore' + ]; + + commands.forEach(function(command) { + var expectedId = /underscore/.test(command) ? 'underscore' : 'lodash'; + + asyncTest('`lodash template=*.jst exports=amd' + (command ? ' ' + command : '') + '`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'template=' + templatePath + '/*.jst', 'exports=amd'].concat(command || []), function(data) { + var moduleId, + basename = path.basename(data.outputPath, '.js'), + context = createContext(); + + context.define = function(requires, factory) { + factory(_); + moduleId = requires[0]; + }; + + context.define.amd = {}; + vm.runInContext(data.source, context); + + equal(moduleId, expectedId, basename); + ok('a' in _.templates && 'b' in _.templates, basename); + equal(_.templates.a({ 'people': ['moe', 'larry'] }), '
      \n
    • moe
    • larry
    • \n
    ', basename); + + delete _.templates; + start(); + }); + }); + + asyncTest('`lodash settings=...' + (command ? ' ' + command : '') + '`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'template=' + templatePath + '/*.tpl', 'settings={interpolate:/{{([\\s\\S]+?)}}/}'].concat(command || []), function(data) { + var moduleId, + basename = path.basename(data.outputPath, '.js'), + context = createContext(); + + var object = { + 'd': { 'name': 'Mustache' } + }; + + context.define = function(requires, factory) { + factory(_); + moduleId = requires[0]; + }; + + context.define.amd = {}; + vm.runInContext(data.source, context); + + equal(moduleId, expectedId, basename); + equal(_.templates.d(object.d), 'Hello Mustache!', basename); + delete _.templates; + start(); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('independent builds'); + + (function() { + var reCustom = /Custom Build/, + reLicense = /^\/\**\s+\* @license[\s\S]+?\*\/\n/; + + asyncTest('debug only', function() { + var start = _.once(QUnit.start); + build(['-d', '-s'], function(data) { + equal(path.basename(data.outputPath, '.js'), 'lodash'); + start(); + }); + }); + + asyncTest('debug custom', function() { + var start = _.once(QUnit.start); + build(['-d', '-s', 'backbone'], function(data) { + equal(path.basename(data.outputPath, '.js'), 'lodash.custom'); + + var comment = data.source.match(reLicense); + ok(reCustom.test(comment)); + start(); + }); + }); + + asyncTest('minified only', function() { + var start = _.once(QUnit.start); + build(['-m', '-s'], function(data) { + equal(path.basename(data.outputPath, '.js'), 'lodash.min'); + start(); + }); + }); + + asyncTest('minified custom', function() { + var start = _.once(QUnit.start); + build(['-m', '-s', 'backbone'], function(data) { + equal(path.basename(data.outputPath, '.js'), 'lodash.custom.min'); + + var comment = data.source.match(reLicense); + ok(reCustom.test(comment)); + start(); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('source maps'); + + (function() { + var mapCommands = [ + '-p', + '-p custom.map', + '--source-map', + '--source-map custom.map' + ]; + + var outputCommands = [ + '', + '-o foo.js', + '-m -o bar.js' + ]; + + mapCommands.forEach(function(mapCommand) { + outputCommands.forEach(function(outputCommand) { + asyncTest('`lodash ' + mapCommand + (outputCommand ? ' ' + outputCommand : '') + '`', function() { + var callback = _.once(function(data) { + var basename = path.basename(data.outputPath, '.js'), + comment = (/(\s*\/\/.*\s*|\s*\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/\s*)$/.exec(data.source) || [])[0], + sources = /foo.js/.test(outputCommand) ? ['foo.js'] : ['lodash' + (outputCommand.length ? '' : '.custom') + '.js'], + sourceMap = JSON.parse(data.sourceMap), + sourceMapURL = (/\w+(?=\.map$)/.exec(mapCommand) || [basename])[0]; + + ok(RegExp('/\\*\\n//@ sourceMappingURL=' + sourceMapURL + '.map\\n\\*/').test(comment), basename); + equal(sourceMap.file, basename + '.js', basename); + deepEqual(sourceMap.sources, sources, basename); + + QUnit.start(); + }); + + outputCommand = outputCommand ? outputCommand.split(' ') : []; + if (outputCommand.indexOf('-m') < 0) { + callback = _.after(2, callback); + } + build(['-s'].concat(mapCommand.split(' '), outputCommand), callback); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('strict modifier'); + + (function() { + var object = Object.freeze({ + 'a': _.identity, + 'b': undefined + }); + + var modes = [ + 'non-strict', + 'strict' + ]; + + modes.forEach(function(strictMode, index) { + asyncTest(strictMode + ' should ' + (index ? 'error': 'silently fail') + ' attempting to overwrite read-only properties', function() { + var commands = ['-s', 'include=bindAll,defaults,extend'], + start = _.after(2, _.once(QUnit.start)); + + if (index) { + commands.push('strict'); + } + build(commands, function(data) { + var basename = path.basename(data.outputPath, '.js'), + context = createContext(); + + vm.runInContext(data.source, context); + var lodash = context._; + + var actual = _.every([ + function() { lodash.bindAll(object); }, + function() { lodash.extend(object, { 'a': 1 }); }, + function() { lodash.defaults(object, { 'b': 2 }); } + ], function(fn) { + var pass = !index; + try { + fn(); + } catch(e) { + pass = !!index; + } + return pass; + }); + + ok(actual, basename); + start(); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('underscore chaining methods'); + + (function() { + var commands = [ + 'backbone', + 'underscore' + ]; + + commands.forEach(function(command) { + asyncTest('`lodash ' + command +'`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', command], function(data) { + var basename = path.basename(data.outputPath, '.js'), + context = createContext(); + + vm.runInContext(data.source, context); + var lodash = context._; + + ok(lodash.chain(1) instanceof lodash, '_.chain: ' + basename); + ok(lodash(1).chain() instanceof lodash, '_#chain: ' + basename); + + var wrapped = lodash(1); + strictEqual(wrapped.identity(), 1, '_(...) wrapped values are not chainable by default: ' + basename); + equal(String(wrapped) === '1', false, '_#toString should not be implemented: ' + basename); + equal(Number(wrapped) === 1 , false, '_#valueOf should not be implemented: ' + basename); + + wrapped.chain(); + ok(wrapped.has('x') instanceof lodash, '_#has returns wrapped values when chaining: ' + basename); + ok(wrapped.join() instanceof lodash, '_#join returns wrapped values when chaining: ' + basename); + + wrapped = lodash([1, 2, 3]); + ok(wrapped.pop() instanceof lodash, '_#pop returns wrapped values: ' + basename); + ok(wrapped.shift() instanceof lodash, '_#shift returns wrapped values: ' + basename); + deepEqual(wrapped.splice(0, 0).value(), [2], '_#splice returns wrapper: ' + basename); + + start(); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('underscore modifier'); + + (function() { + asyncTest('modified methods should work correctly', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'underscore'], function(data) { + var last, + array = [{ 'a': 1, 'b': 2 }, { 'a': 2, 'b': 2 }], + basename = path.basename(data.outputPath, '.js'), + context = createContext(); + + vm.runInContext(data.source, context); + var lodash = context._; + + var object = { + 'fn': lodash.bind(function(foo) { + return foo + this.bar; + }, { 'bar': 1 }, 1) + }; + + equal(object.fn(), 2, '_.bind: ' + basename); + + var actual = lodash.clone('a', function() { + return this.a; + }, { 'a': 'A' }); + + equal(actual, 'a', '_.clone should ignore `callback` and `thisArg`: ' + basename); + strictEqual(lodash.clone(array, true)[0], array[0], '_.clone should ignore `deep`: ' + basename); + + strictEqual(lodash.contains({ 'a': 1, 'b': 2 }, 1), true, '_.contains should work with objects: ' + basename); + strictEqual(lodash.contains([1, 2, 3], 1, 2), true, '_.contains should ignore `fromIndex`: ' + basename); + strictEqual(lodash.every([true, false, true]), false, '_.every: ' + basename); + + function Foo() {} + Foo.prototype = { 'a': 1 }; + + actual = lodash.defaults({ 'a': null }, { 'a': 1 }); + strictEqual(actual.a, 1, '_.defaults should overwrite `null` values: ' + basename); + + deepEqual(lodash.defaults({}, new Foo), Foo.prototype, '_.defaults should assign inherited `source` properties: ' + basename); + deepEqual(lodash.extend({}, new Foo), Foo.prototype, '_.extend should assign inherited `source` properties: ' + basename); + + actual = lodash.extend({}, { 'a': 0 }, function(a, b) { + return this[b]; + }, [2]); + + strictEqual(actual.a, 0, '_.extend should ignore `callback` and `thisArg`: ' + basename); + + actual = lodash.find(array, function(value) { + return 'a' in value; + }); + + equal(actual, _.first(array), '_.find: ' + basename); + + actual = lodash.forEach(array, function(value) { + last = value; + return false; + }); + + equal(last, _.last(array), '_.forEach should not exit early: ' + basename); + equal(actual, undefined, '_.forEach should return `undefined`: ' + basename); + + object = { 'length': 0, 'splice': Array.prototype.splice }; + equal(lodash.isEmpty(object), false, '_.isEmpty should return `false` for jQuery/MooTools DOM query collections: ' + basename); + + object = { 'a': 1, 'b': 2, 'c': 3 }; + equal(lodash.isEqual(object, { 'a': 1, 'b': 0, 'c': 3 }), false, '_.isEqual: ' + basename); + + actual = lodash.isEqual('a', 'b', function(a, b) { + return this[a] == this[b]; + }, { 'a': 1, 'b': 1 }); + + strictEqual(actual, false, '_.isEqual should ignore `callback` and `thisArg`: ' + basename); + + equal(lodash.max('abc'), -Infinity, '_.max should return `-Infinity` for strings: ' + basename); + equal(lodash.min('abc'), Infinity, '_.min should return `Infinity` for strings: ' + basename); + + // avoid issues comparing objects with `deepEqual` + object = { 'a': 1, 'b': 2, 'c': 3 }; + actual = lodash.omit(object, function(value) { return value == 3; }); + deepEqual(_.keys(actual).sort(), ['a', 'b', 'c'], '_.omit should not accept a `callback`: ' + basename); + + actual = lodash.pick(object, function(value) { return value != 3; }); + deepEqual(_.keys(actual), [], '_.pick should not accept a `callback`: ' + basename); + + strictEqual(lodash.result(), null, '_.result should return `null` for falsey `object` arguments: ' + basename); + strictEqual(lodash.some([false, true, false]), true, '_.some: ' + basename); + equal(lodash.template('${a}', object), '${a}', '_.template should ignore ES6 delimiters: ' + basename); + equal('imports' in lodash.templateSettings, false, '_.templateSettings should not have an "imports" property: ' + basename); + strictEqual(lodash.uniqueId(0), '1', '_.uniqueId should ignore a prefix of `0`: ' + basename); + + var collection = [{ 'a': { 'b': 1, 'c': 2 } }]; + deepEqual(lodash.where(collection, { 'a': { 'b': 1 } }), [], '_.where performs shallow comparisons: ' + basename); + + collection = [{ 'a': 1 }, { 'a': 1 }]; + deepEqual(lodash.where(collection, { 'a': 1 }, true), collection[0], '_.where supports a `first` argument: ' + basename); + deepEqual(lodash.where(collection, {}, true), null, '_.where should return `null` when passed `first` and falsey `properties`: ' + basename); + + deepEqual(lodash.findWhere(collection, { 'a': 1 }), collection[0], '_.findWhere: ' + basename); + strictEqual(lodash.findWhere(collection, {}), null, '_.findWhere should return `null` for falsey `properties`: ' + basename); + + start(); + }); + }); + + asyncTest('should not have any Lo-Dash-only methods', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'underscore'], function(data) { + var basename = path.basename(data.outputPath, '.js'), + context = createContext(); + + vm.runInContext(data.source, context); + var lodash = context._; + + _.each([ + 'assign', + 'at', + 'bindKey', + 'forIn', + 'forOwn', + 'isPlainObject', + 'merge', + 'partialRight' + ], function(methodName) { + equal(lodash[methodName], undefined, '_.' + methodName + ' should not exist: ' + basename); + }); + + start(); + }); + }); + + asyncTest('`lodash underscore include=findWhere`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'underscore', 'include=findWhere'], function(data) { + var basename = path.basename(data.outputPath, '.js'), + context = createContext(); + + vm.runInContext(data.source, context); + var lodash = context._; + + var collection = [{ 'a': 1 }, { 'a': 1 }]; + deepEqual(lodash.findWhere(collection, { 'a': 1 }), collection[0], '_.findWhere: ' + basename); + + start(); + }); + }); + + asyncTest('`lodash underscore include=partial`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'underscore', 'include=partial'], function(data) { + var basename = path.basename(data.outputPath, '.js'), + context = createContext(); + + vm.runInContext(data.source, context); + var lodash = context._; + + equal(lodash.partial(_.identity, 2)(), 2, '_.partial: ' + basename); + start(); + }); + }); + + asyncTest('`lodash underscore plus=clone`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'underscore', 'plus=clone'], function(data) { + var array = [{ 'value': 1 }], + basename = path.basename(data.outputPath, '.js'), + context = createContext(); + + vm.runInContext(data.source, context); + var lodash = context._, + clone = lodash.clone(array, true); + + ok(_.isEqual(array, clone), basename); + notEqual(array[0], clone[0], basename); + start(); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('exports command'); + + (function() { + var commands = [ + 'exports=amd', + 'exports=commonjs', + 'exports=global', + 'exports=node', + 'exports=none' + ]; + + commands.forEach(function(command, index) { + asyncTest('`lodash ' + command +'`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', command], function(data) { + var basename = path.basename(data.outputPath, '.js'), + context = createContext(), + pass = false, + source = data.source; + + switch(index) { + case 0: + context.define = function(fn) { + pass = true; + context._ = fn(); + }; + context.define.amd = {}; + vm.runInContext(source, context); + ok(pass, basename); + break; + + case 1: + context.exports = {}; + vm.runInContext(source, context); + ok(_.isFunction(context.exports._), basename); + strictEqual(context._, undefined, basename); + break; + + case 2: + vm.runInContext(source, context); + ok(_.isFunction(context._), basename); + break; + + case 3: + context.exports = {}; + context.module = { 'exports': context.exports }; + vm.runInContext(source, context); + ok(_.isFunction(context.module.exports), basename); + strictEqual(context._, undefined, basename); + break; + + case 4: + vm.runInContext(source, context); + strictEqual(context._, undefined, basename); + } + start(); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('iife command'); + + (function() { + var commands = [ + 'iife=this["lodash"]=(function(window,undefined){%output%;return lodash}(this))', + 'iife=define(function(window,undefined){return function(){%output%;return lodash}}(this));' + ]; + + commands.forEach(function(command) { + asyncTest('`lodash ' + command +'`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'exports=none', command], function(data) { + var basename = path.basename(data.outputPath, '.js'), + context = createContext(); + + context.define = function(func) { + context.lodash = func(); + }; + + try { + vm.runInContext(data.source, context); + } catch(e) { + console.log(e); + } + + var lodash = context.lodash || {}; + ok(_.isString(lodash.VERSION), basename); + start(); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('output options'); + + (function() { + var commands = [ + '-o a.js', + '--output a.js' + ]; + + commands.forEach(function(command, index) { + asyncTest('`lodash ' + command +'`', function() { + var counter = -1, + start = _.after(2, _.once(QUnit.start)); + + build(['-s'].concat(command.split(' ')), function(data) { + equal(path.basename(data.outputPath, '.js'), (++counter ? 'a.min' : 'a'), command); + start(); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('stdout options'); + + (function() { + var commands = [ + '-c', + '-c -d', + '--stdout', + ]; + + commands.forEach(function(command, index) { + asyncTest('`lodash ' + command +'`', function() { + var written, + start = _.once(QUnit.start), + write = process.stdout.write; + + process.stdout.write = function(string) { + written = string; + }; + + build(['exports=', 'include='].concat(command.split(' ')), function(data) { + process.stdout.write = write; + equal(written, data.source); + equal(arguments.length, 1); + start(); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('mobile build'); + + (function() { + asyncTest('`lodash mobile`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'mobile'], function(data) { + var basename = path.basename(data.outputPath, '.js'), + context = createContext(); + + try { + vm.runInContext(data.source, context); + } catch(e) { + console.log(e); + } + + var array = [1, 2, 3], + object1 = [{ 'a': 1 }], + object2 = [{ 'b': 2 }], + object3 = [{ 'a': 1, 'b': 2 }], + circular1 = { 'a': 1 }, + circular2 = { 'a': 1 }, + lodash = context._; + + circular1.b = circular1; + circular2.b = circular2; + + deepEqual(lodash.merge(object1, object2), object3, basename); + deepEqual(lodash.sortBy([3, 2, 1], _.identity), array, basename); + strictEqual(lodash.isEqual(circular1, circular2), true, basename); + + var actual = lodash.cloneDeep(circular1); + ok(actual != circular1 && actual.b == actual, basename); + start(); + }); + }); + + asyncTest('`lodash csp`', function() { + var sources = []; + + var check = _.after(2, _.once(function() { + equal(sources[0], sources[1]); + QUnit.start(); + })); + + var callback = function(data) { + // remove copyright header and append source + sources.push(data.source.replace(/^\/\**[\s\S]+?\*\/\n/, '')); + check(); + }; + + build(['-s', '-d', 'csp'], callback); + build(['-s', '-d', 'mobile'], callback); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('lodash build'); + + (function() { + var commands = [ + 'backbone', + 'csp', + 'legacy', + 'mobile', + 'modern', + 'strict', + 'underscore', + 'category=arrays', + 'category=chaining', + 'category=collections', + 'category=functions', + 'category=objects', + 'category=utilities', + 'exclude=union,uniq,zip', + 'include=each,filter,map', + 'include=once plus=bind,Chaining', + 'category=collections,functions', + 'backbone legacy category=utilities minus=first,last', + 'legacy include=defer', + 'legacy underscore', + 'underscore include=debounce,throttle plus=after minus=throttle', + 'underscore mobile strict category=functions exports=amd,global plus=pick,uniq', + ] + .concat( + allMethods.map(function(methodName) { + return 'include=' + methodName; + }) + ); + + commands.forEach(function(origCommand) { + _.times(4, function(index) { + var command = origCommand; + + if (index == 1) { + if (/legacy|mobile/.test(command)) { + return; + } + command = 'mobile ' + command; + } + if (index == 2) { + if (/legacy|modern/.test(command)) { + return; + } + command = 'modern ' + command; + } + if (index == 3) { + if (/category|legacy|underscore/.test(command)) { + return; + } + command = 'underscore ' + command; + } + asyncTest('`lodash ' + command +'`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['--silent'].concat(command.split(' ')), function(data) { + var methodNames, + basename = path.basename(data.outputPath, '.js'), + context = createContext(), + isUnderscore = /backbone|underscore/.test(command), + exposeAssign = !isUnderscore; + + try { + vm.runInContext(data.source, context); + } catch(e) { + console.log(e); + } + // add method names explicitly + if (/include/.test(command)) { + methodNames = command.match(/include=(\S*)/)[1].split(/, */); + } + // add method names required by Backbone and Underscore builds + if (/backbone/.test(command) && !methodNames) { + methodNames = backboneDependencies.slice(); + } + if (isUnderscore) { + if (methodNames) { + exposeAssign = methodNames.indexOf('assign') > -1; + } else { + methodNames = underscoreMethods.slice(); + } + } + // add method names explicitly by category + if (/category/.test(command)) { + // resolve method names belonging to each category (case-insensitive) + methodNames = command.match(/category=(\S*)/)[1].split(/, */).reduce(function(result, category) { + var capitalized = category[0].toUpperCase() + category.toLowerCase().slice(1); + return result.concat(getMethodsByCategory(capitalized)); + }, methodNames || []); + } + // init `methodNames` if it hasn't been inited + if (!methodNames) { + methodNames = allMethods.slice(); + } + if (/plus/.test(command)) { + methodNames = methodNames.concat(command.match(/plus=(\S*)/)[1].split(/, */)); + } + if (/minus/.test(command)) { + methodNames = _.without.apply(_, [methodNames] + .concat(expandMethodNames(command.match(/minus=(\S*)/)[1].split(/, */)))); + } + if (/exclude/.test(command)) { + methodNames = _.without.apply(_, [methodNames] + .concat(expandMethodNames(command.match(/exclude=(\S*)/)[1].split(/, */)))); + } + + // expand aliases and categories to real method names + methodNames = expandMethodNames(methodNames).reduce(function(result, methodName) { + return result.concat(methodName, getMethodsByCategory(methodName)); + }, []); + + // remove nonexistent and duplicate method names + methodNames = _.uniq(_.intersection(allMethods, expandMethodNames(methodNames))); + + if (!exposeAssign) { + methodNames = _.without(methodNames, 'assign'); + } + var lodash = context._ || {}; + methodNames.forEach(function(methodName) { + testMethod(lodash, methodName, basename); + }); + + start(); + }); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + if (timeLimit > 0) { + setTimeout(function() { + process.exit(QUnit.config.stats.bad ? 1 : 0); + }, timeLimit); + } + // explicitly call `QUnit.start()` for Narwhal, Node.js, Rhino, and RingoJS + if (!global.document) { + QUnit.start(); + } +}()); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/test.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/test.js new file mode 100644 index 000000000..632af43ab --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/test/test.js @@ -0,0 +1,2920 @@ +;(function(window, undefined) { + 'use strict'; + + /** Use a single "load" function */ + var load = typeof require == 'function' ? require : window.load; + + /** The file path of the Lo-Dash file to test */ + var filePath = (function() { + var min = 0; + var result = window.phantom + ? phantom.args + : (window.system + ? (min = 1, system.args) + : (window.process ? (min = 2, process.argv) : (window.arguments || [])) + ); + + var last = result[result.length - 1]; + result = (result.length > min && last != 'test.js') ? last : '../lodash.js'; + + try { + result = require('fs').realpathSync(result); + } catch(e) { } + + return result; + }()); + + /** The basename of the Lo-Dash file to test */ + var basename = /[\w.-]+$/.exec(filePath)[0]; + + /** The `platform` object to check */ + var platform = + window.platform || + load('../vendor/platform.js/platform.js') || + window.platform; + + /** The unit testing framework */ + var QUnit = + window.QUnit || ( + window.addEventListener || (window.addEventListener = Function.prototype), + window.setTimeout || (window.setTimeout = Function.prototype), + window.QUnit = load('../vendor/qunit/qunit/qunit.js') || window.QUnit, + load('../vendor/qunit-clib/qunit-clib.js'), + window.addEventListener === Function.prototype && delete window.addEventListener, + window.QUnit + ); + + /** The `lodash` function to test */ + var _ = window._ || ( + _ = load(filePath) || window._, + _._ || _ + ); + + /** Used to pass falsey values to methods */ + var falsey = [ + , + '', + 0, + false, + NaN, + null, + undefined + ]; + + /** Shortcut used to make object properties immutable */ + var freeze = Object.freeze; + + /** Used to set property descriptors */ + var setDescriptor = (function(fn) { + try { + var o = {}; + return fn(o, o, o) && fn; + } catch(e) { } + }(Object.defineProperty)); + + /** Shortcut used to convert array-like objects to arrays */ + var slice = [].slice; + + /** Used to check problem JScript properties (a.k.a. the [[DontEnum]] bug) */ + var shadowed = { + 'constructor': 1, + 'hasOwnProperty': 2, + 'isPrototypeOf': 3, + 'propertyIsEnumerable': 4, + 'toLocaleString': 5, + 'toString': 6, + 'valueOf': 7 + }; + + /** Used to check problem JScript properties too */ + var shadowedKeys = [ + 'constructor', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'toLocaleString', + 'toString', + 'valueOf' + ]; + + /*--------------------------------------------------------------------------*/ + + /** + * Skips a given number of tests with a passing result. + * + * @private + * @param {Number} [count=1] The number of tests to skip. + */ + function skipTest(count) { + count || (count = 1); + while (count--) { + ok(true, 'test skipped'); + } + } + + /*--------------------------------------------------------------------------*/ + + // add object from iframe + (function() { + if (!window.document || window.phantom) { + return; + } + var body = document.body, + iframe = document.createElement('iframe'); + + iframe.frameBorder = iframe.height = iframe.width = 0; + body.appendChild(iframe); + var idoc = (idoc = iframe.contentDocument || iframe.contentWindow).document || idoc; + idoc.write(" +``` + +Optionally, expose Java’s nanosecond timer by adding the `nano` applet to the ``: + +```html + +``` + +Or enable Chrome’s microsecond timer by using the [command line switch](http://peter.sh/experiments/chromium-command-line-switches/#enable-benchmarking): + + --enable-benchmarking + +Via [npm](http://npmjs.org/): + +```bash +npm install benchmark +``` + +In [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/): + +```js +var Benchmark = require('benchmark'); +``` + +Optionally, use the [microtime module](https://github.com/wadey/node-microtime) by Wade Simmons: + +```bash +npm install microtime +``` + +In [RingoJS v0.7.0-](http://ringojs.org/): + +```js +var Benchmark = require('benchmark').Benchmark; +``` + +In [Rhino](http://www.mozilla.org/rhino/): + +```js +load('benchmark.js'); +``` + +In an AMD loader like [RequireJS](http://requirejs.org/): + +```js +require({ + 'paths': { + 'benchmark': 'path/to/benchmark' + } +}, +['benchmark'], function(Benchmark) { + console.log(Benchmark.version); +}); + +// or with platform.js +// https://github.com/bestiejs/platform.js +require({ + 'paths': { + 'benchmark': 'path/to/benchmark', + 'platform': 'path/to/platform' + } +}, +['benchmark', 'platform'], function(Benchmark, platform) { + Benchmark.platform = platform; + console.log(Benchmark.platform.name); +}); +``` + +Usage example: + +```js +var suite = new Benchmark.Suite; + +// add tests +suite.add('RegExp#test', function() { + /o/.test('Hello World!'); +}) +.add('String#indexOf', function() { + 'Hello World!'.indexOf('o') > -1; +}) +// add listeners +.on('cycle', function(event) { + console.log(String(event.target)); +}) +.on('complete', function() { + console.log('Fastest is ' + this.filter('fastest').pluck('name')); +}) +// run async +.run({ 'async': true }); + +// logs: +// > RegExp#test x 4,161,532 +-0.99% (59 cycles) +// > String#indexOf x 6,139,623 +-1.00% (131 cycles) +// > Fastest is String#indexOf +``` + +## BestieJS + +Benchmark.js is part of the BestieJS *"Best in Class"* module collection. This means we promote solid browser/environment support, ES5 precedents, unit testing, and plenty of documentation. + +## Authors + +* [Mathias Bynens](http://mathiasbynens.be/) + [![twitter/mathias](http://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") +* [John-David Dalton](http://allyoucanleet.com/) + [![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") + +## Contributors + +* [Kit Cambridge](http://kitcambridge.github.com/) + [![twitter/kitcambridge](http://gravatar.com/avatar/6662a1d02f351b5ef2f8b4d815804661?s=70)](https://twitter.com/kitcambridge "Follow @kitcambridge on Twitter") diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/benchmark.js/benchmark.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/benchmark.js/benchmark.js new file mode 100644 index 000000000..6adf726ce --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/benchmark.js/benchmark.js @@ -0,0 +1,3960 @@ +/*! + * Benchmark.js v1.0.0 + * Copyright 2010-2013 Mathias Bynens + * Based on JSLitmus.js, copyright Robert Kieffer + * Modified by John-David Dalton + * Available under MIT license + */ +;(function(window, undefined) { + 'use strict'; + + /** Used to assign each benchmark an incrimented id */ + var counter = 0; + + /** Detect DOM document object */ + var doc = isHostType(window, 'document') && document; + + /** Detect free variable `define` */ + var freeDefine = typeof define == 'function' && + typeof define.amd == 'object' && define.amd && define; + + /** Detect free variable `exports` */ + var freeExports = typeof exports == 'object' && exports && + (typeof global == 'object' && global && global == global.global && (window = global), exports); + + /** Detect free variable `require` */ + var freeRequire = typeof require == 'function' && require; + + /** Used to store the `Object` built-in in case it's overwritten later */ + var Object = window.Object; + + /** Used to crawl all properties regardless of enumerability */ + var getAllKeys = Object.getOwnPropertyNames; + + /** Used to get property descriptors */ + var getDescriptor = Object.getOwnPropertyDescriptor; + + /** Used in case an object doesn't have its own method */ + var hasOwnProperty = {}.hasOwnProperty; + + /** Used to check if an object is extensible */ + var isExtensible = Object.isExtensible || function() { return true; }; + + /** Used to access Wade Simmons' Node microtime module */ + var microtimeObject = req('microtime'); + + /** Used to access the browser's high resolution timer */ + var perfObject = isHostType(window, 'performance') && performance; + + /** Used to call the browser's high resolution timer */ + var perfName = perfObject && ( + perfObject.now && 'now' || + perfObject.webkitNow && 'webkitNow' + ); + + /** Used to access Node's high resolution timer */ + var processObject = isHostType(window, 'process') && process; + + /** Used to check if an own property is enumerable */ + var propertyIsEnumerable = {}.propertyIsEnumerable; + + /** Used to set property descriptors */ + var setDescriptor = Object.defineProperty; + + /** Used to resolve a value's internal [[Class]] */ + var toString = {}.toString; + + /** Used to prevent a `removeChild` memory leak in IE < 9 */ + var trash = doc && doc.createElement('div'); + + /** Used to integrity check compiled tests */ + var uid = 'uid' + (+new Date); + + /** Used to avoid infinite recursion when methods call each other */ + var calledBy = {}; + + /** Used to avoid hz of Infinity */ + var divisors = { + '1': 4096, + '2': 512, + '3': 64, + '4': 8, + '5': 0 + }; + + /** + * T-Distribution two-tailed critical values for 95% confidence + * http://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm + */ + var tTable = { + '1': 12.706,'2': 4.303, '3': 3.182, '4': 2.776, '5': 2.571, '6': 2.447, + '7': 2.365, '8': 2.306, '9': 2.262, '10': 2.228, '11': 2.201, '12': 2.179, + '13': 2.16, '14': 2.145, '15': 2.131, '16': 2.12, '17': 2.11, '18': 2.101, + '19': 2.093, '20': 2.086, '21': 2.08, '22': 2.074, '23': 2.069, '24': 2.064, + '25': 2.06, '26': 2.056, '27': 2.052, '28': 2.048, '29': 2.045, '30': 2.042, + 'infinity': 1.96 + }; + + /** + * Critical Mann-Whitney U-values for 95% confidence + * http://www.saburchill.com/IBbiology/stats/003.html + */ + var uTable = { + '5': [0, 1, 2], + '6': [1, 2, 3, 5], + '7': [1, 3, 5, 6, 8], + '8': [2, 4, 6, 8, 10, 13], + '9': [2, 4, 7, 10, 12, 15, 17], + '10': [3, 5, 8, 11, 14, 17, 20, 23], + '11': [3, 6, 9, 13, 16, 19, 23, 26, 30], + '12': [4, 7, 11, 14, 18, 22, 26, 29, 33, 37], + '13': [4, 8, 12, 16, 20, 24, 28, 33, 37, 41, 45], + '14': [5, 9, 13, 17, 22, 26, 31, 36, 40, 45, 50, 55], + '15': [5, 10, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59, 64], + '16': [6, 11, 15, 21, 26, 31, 37, 42, 47, 53, 59, 64, 70, 75], + '17': [6, 11, 17, 22, 28, 34, 39, 45, 51, 57, 63, 67, 75, 81, 87], + '18': [7, 12, 18, 24, 30, 36, 42, 48, 55, 61, 67, 74, 80, 86, 93, 99], + '19': [7, 13, 19, 25, 32, 38, 45, 52, 58, 65, 72, 78, 85, 92, 99, 106, 113], + '20': [8, 14, 20, 27, 34, 41, 48, 55, 62, 69, 76, 83, 90, 98, 105, 112, 119, 127], + '21': [8, 15, 22, 29, 36, 43, 50, 58, 65, 73, 80, 88, 96, 103, 111, 119, 126, 134, 142], + '22': [9, 16, 23, 30, 38, 45, 53, 61, 69, 77, 85, 93, 101, 109, 117, 125, 133, 141, 150, 158], + '23': [9, 17, 24, 32, 40, 48, 56, 64, 73, 81, 89, 98, 106, 115, 123, 132, 140, 149, 157, 166, 175], + '24': [10, 17, 25, 33, 42, 50, 59, 67, 76, 85, 94, 102, 111, 120, 129, 138, 147, 156, 165, 174, 183, 192], + '25': [10, 18, 27, 35, 44, 53, 62, 71, 80, 89, 98, 107, 117, 126, 135, 145, 154, 163, 173, 182, 192, 201, 211], + '26': [11, 19, 28, 37, 46, 55, 64, 74, 83, 93, 102, 112, 122, 132, 141, 151, 161, 171, 181, 191, 200, 210, 220, 230], + '27': [11, 20, 29, 38, 48, 57, 67, 77, 87, 97, 107, 118, 125, 138, 147, 158, 168, 178, 188, 199, 209, 219, 230, 240, 250], + '28': [12, 21, 30, 40, 50, 60, 70, 80, 90, 101, 111, 122, 132, 143, 154, 164, 175, 186, 196, 207, 218, 228, 239, 250, 261, 272], + '29': [13, 22, 32, 42, 52, 62, 73, 83, 94, 105, 116, 127, 138, 149, 160, 171, 182, 193, 204, 215, 226, 238, 249, 260, 271, 282, 294], + '30': [13, 23, 33, 43, 54, 65, 76, 87, 98, 109, 120, 131, 143, 154, 166, 177, 189, 200, 212, 223, 235, 247, 258, 270, 282, 293, 305, 317] + }; + + /** + * An object used to flag environments/features. + * + * @static + * @memberOf Benchmark + * @type Object + */ + var support = {}; + + (function() { + + /** + * Detect Adobe AIR. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.air = isClassOf(window.runtime, 'ScriptBridgingProxyObject'); + + /** + * Detect if `arguments` objects have the correct internal [[Class]] value. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.argumentsClass = isClassOf(arguments, 'Arguments'); + + /** + * Detect if in a browser environment. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.browser = doc && isHostType(window, 'navigator'); + + /** + * Detect if strings support accessing characters by index. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.charByIndex = + // IE 8 supports indexes on string literals but not string objects + ('x'[0] + Object('x')[0]) == 'xx'; + + /** + * Detect if strings have indexes as own properties. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.charByOwnIndex = + // Narwhal, Rhino, RingoJS, IE 8, and Opera < 10.52 support indexes on + // strings but don't detect them as own properties + support.charByIndex && hasKey('x', '0'); + + /** + * Detect if Java is enabled/exposed. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.java = isClassOf(window.java, 'JavaPackage'); + + /** + * Detect if the Timers API exists. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.timeout = isHostType(window, 'setTimeout') && isHostType(window, 'clearTimeout'); + + /** + * Detect if functions support decompilation. + * + * @name decompilation + * @memberOf Benchmark.support + * @type Boolean + */ + try { + // Safari 2.x removes commas in object literals + // from Function#toString results + // http://webk.it/11609 + // Firefox 3.6 and Opera 9.25 strip grouping + // parentheses from Function#toString results + // http://bugzil.la/559438 + support.decompilation = Function( + 'return (' + (function(x) { return { 'x': '' + (1 + x) + '', 'y': 0 }; }) + ')' + )()(0).x === '1'; + } catch(e) { + support.decompilation = false; + } + + /** + * Detect ES5+ property descriptor API. + * + * @name descriptors + * @memberOf Benchmark.support + * @type Boolean + */ + try { + var o = {}; + support.descriptors = (setDescriptor(o, o, o), 'value' in getDescriptor(o, o)); + } catch(e) { + support.descriptors = false; + } + + /** + * Detect ES5+ Object.getOwnPropertyNames(). + * + * @name getAllKeys + * @memberOf Benchmark.support + * @type Boolean + */ + try { + support.getAllKeys = /\bvalueOf\b/.test(getAllKeys(Object.prototype)); + } catch(e) { + support.getAllKeys = false; + } + + /** + * Detect if own properties are iterated before inherited properties (all but IE < 9). + * + * @name iteratesOwnLast + * @memberOf Benchmark.support + * @type Boolean + */ + support.iteratesOwnFirst = (function() { + var props = []; + function ctor() { this.x = 1; } + ctor.prototype = { 'y': 1 }; + for (var prop in new ctor) { props.push(prop); } + return props[0] == 'x'; + }()); + + /** + * Detect if a node's [[Class]] is resolvable (all but IE < 9) + * and that the JS engine errors when attempting to coerce an object to a + * string without a `toString` property value of `typeof` "function". + * + * @name nodeClass + * @memberOf Benchmark.support + * @type Boolean + */ + try { + support.nodeClass = ({ 'toString': 0 } + '', toString.call(doc || 0) != '[object Object]'); + } catch(e) { + support.nodeClass = true; + } + }()); + + /** + * Timer object used by `clock()` and `Deferred#resolve`. + * + * @private + * @type Object + */ + var timer = { + + /** + * The timer namespace object or constructor. + * + * @private + * @memberOf timer + * @type Function|Object + */ + 'ns': Date, + + /** + * Starts the deferred timer. + * + * @private + * @memberOf timer + * @param {Object} deferred The deferred instance. + */ + 'start': null, // lazy defined in `clock()` + + /** + * Stops the deferred timer. + * + * @private + * @memberOf timer + * @param {Object} deferred The deferred instance. + */ + 'stop': null // lazy defined in `clock()` + }; + + /** Shortcut for inverse results */ + var noArgumentsClass = !support.argumentsClass, + noCharByIndex = !support.charByIndex, + noCharByOwnIndex = !support.charByOwnIndex; + + /** Math shortcuts */ + var abs = Math.abs, + floor = Math.floor, + log = Math.log, + max = Math.max, + min = Math.min, + pow = Math.pow, + sqrt = Math.sqrt; + + /*--------------------------------------------------------------------------*/ + + /** + * The Benchmark constructor. + * + * @constructor + * @param {String} name A name to identify the benchmark. + * @param {Function|String} fn The test to benchmark. + * @param {Object} [options={}] Options object. + * @example + * + * // basic usage (the `new` operator is optional) + * var bench = new Benchmark(fn); + * + * // or using a name first + * var bench = new Benchmark('foo', fn); + * + * // or with options + * var bench = new Benchmark('foo', fn, { + * + * // displayed by Benchmark#toString if `name` is not available + * 'id': 'xyz', + * + * // called when the benchmark starts running + * 'onStart': onStart, + * + * // called after each run cycle + * 'onCycle': onCycle, + * + * // called when aborted + * 'onAbort': onAbort, + * + * // called when a test errors + * 'onError': onError, + * + * // called when reset + * 'onReset': onReset, + * + * // called when the benchmark completes running + * 'onComplete': onComplete, + * + * // compiled/called before the test loop + * 'setup': setup, + * + * // compiled/called after the test loop + * 'teardown': teardown + * }); + * + * // or name and options + * var bench = new Benchmark('foo', { + * + * // a flag to indicate the benchmark is deferred + * 'defer': true, + * + * // benchmark test function + * 'fn': function(deferred) { + * // call resolve() when the deferred test is finished + * deferred.resolve(); + * } + * }); + * + * // or options only + * var bench = new Benchmark({ + * + * // benchmark name + * 'name': 'foo', + * + * // benchmark test as a string + * 'fn': '[1,2,3,4].sort()' + * }); + * + * // a test's `this` binding is set to the benchmark instance + * var bench = new Benchmark('foo', function() { + * 'My name is '.concat(this.name); // My name is foo + * }); + */ + function Benchmark(name, fn, options) { + var me = this; + + // allow instance creation without the `new` operator + if (me == null || me.constructor != Benchmark) { + return new Benchmark(name, fn, options); + } + // juggle arguments + if (isClassOf(name, 'Object')) { + // 1 argument (options) + options = name; + } + else if (isClassOf(name, 'Function')) { + // 2 arguments (fn, options) + options = fn; + fn = name; + } + else if (isClassOf(fn, 'Object')) { + // 2 arguments (name, options) + options = fn; + fn = null; + me.name = name; + } + else { + // 3 arguments (name, fn [, options]) + me.name = name; + } + setOptions(me, options); + me.id || (me.id = ++counter); + me.fn == null && (me.fn = fn); + me.stats = deepClone(me.stats); + me.times = deepClone(me.times); + } + + /** + * The Deferred constructor. + * + * @constructor + * @memberOf Benchmark + * @param {Object} clone The cloned benchmark instance. + */ + function Deferred(clone) { + var me = this; + if (me == null || me.constructor != Deferred) { + return new Deferred(clone); + } + me.benchmark = clone; + clock(me); + } + + /** + * The Event constructor. + * + * @constructor + * @memberOf Benchmark + * @param {String|Object} type The event type. + */ + function Event(type) { + var me = this; + return (me == null || me.constructor != Event) + ? new Event(type) + : (type instanceof Event) + ? type + : extend(me, { 'timeStamp': +new Date }, typeof type == 'string' ? { 'type': type } : type); + } + + /** + * The Suite constructor. + * + * @constructor + * @memberOf Benchmark + * @param {String} name A name to identify the suite. + * @param {Object} [options={}] Options object. + * @example + * + * // basic usage (the `new` operator is optional) + * var suite = new Benchmark.Suite; + * + * // or using a name first + * var suite = new Benchmark.Suite('foo'); + * + * // or with options + * var suite = new Benchmark.Suite('foo', { + * + * // called when the suite starts running + * 'onStart': onStart, + * + * // called between running benchmarks + * 'onCycle': onCycle, + * + * // called when aborted + * 'onAbort': onAbort, + * + * // called when a test errors + * 'onError': onError, + * + * // called when reset + * 'onReset': onReset, + * + * // called when the suite completes running + * 'onComplete': onComplete + * }); + */ + function Suite(name, options) { + var me = this; + + // allow instance creation without the `new` operator + if (me == null || me.constructor != Suite) { + return new Suite(name, options); + } + // juggle arguments + if (isClassOf(name, 'Object')) { + // 1 argument (options) + options = name; + } else { + // 2 arguments (name [, options]) + me.name = name; + } + setOptions(me, options); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Note: Some array methods have been implemented in plain JavaScript to avoid + * bugs in IE, Opera, Rhino, and Mobile Safari. + * + * IE compatibility mode and IE < 9 have buggy Array `shift()` and `splice()` + * functions that fail to remove the last element, `object[0]`, of + * array-like-objects even though the `length` property is set to `0`. + * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()` + * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9. + * + * In Opera < 9.50 and some older/beta Mobile Safari versions using `unshift()` + * generically to augment the `arguments` object will pave the value at index 0 + * without incrimenting the other values's indexes. + * https://github.com/documentcloud/underscore/issues/9 + * + * Rhino and environments it powers, like Narwhal and RingoJS, may have + * buggy Array `concat()`, `reverse()`, `shift()`, `slice()`, `splice()` and + * `unshift()` functions that make sparse arrays non-sparse by assigning the + * undefined indexes a value of undefined. + * https://github.com/mozilla/rhino/commit/702abfed3f8ca043b2636efd31c14ba7552603dd + */ + + /** + * Creates an array containing the elements of the host array followed by the + * elements of each argument in order. + * + * @memberOf Benchmark.Suite + * @returns {Array} The new array. + */ + function concat() { + var value, + j = -1, + length = arguments.length, + result = slice.call(this), + index = result.length; + + while (++j < length) { + value = arguments[j]; + if (isClassOf(value, 'Array')) { + for (var k = 0, l = value.length; k < l; k++, index++) { + if (k in value) { + result[index] = value[k]; + } + } + } else { + result[index++] = value; + } + } + return result; + } + + /** + * Utility function used by `shift()`, `splice()`, and `unshift()`. + * + * @private + * @param {Number} start The index to start inserting elements. + * @param {Number} deleteCount The number of elements to delete from the insert point. + * @param {Array} elements The elements to insert. + * @returns {Array} An array of deleted elements. + */ + function insert(start, deleteCount, elements) { + // `result` should have its length set to the `deleteCount` + // see https://bugs.ecmascript.org/show_bug.cgi?id=332 + var deleteEnd = start + deleteCount, + elementCount = elements ? elements.length : 0, + index = start - 1, + length = start + elementCount, + object = this, + result = Array(deleteCount), + tail = slice.call(object, deleteEnd); + + // delete elements from the array + while (++index < deleteEnd) { + if (index in object) { + result[index - start] = object[index]; + delete object[index]; + } + } + // insert elements + index = start - 1; + while (++index < length) { + object[index] = elements[index - start]; + } + // append tail elements + start = index--; + length = max(0, (object.length >>> 0) - deleteCount + elementCount); + while (++index < length) { + if ((index - start) in tail) { + object[index] = tail[index - start]; + } else if (index in object) { + delete object[index]; + } + } + // delete excess elements + deleteCount = deleteCount > elementCount ? deleteCount - elementCount : 0; + while (deleteCount--) { + index = length + deleteCount; + if (index in object) { + delete object[index]; + } + } + object.length = length; + return result; + } + + /** + * Rearrange the host array's elements in reverse order. + * + * @memberOf Benchmark.Suite + * @returns {Array} The reversed array. + */ + function reverse() { + var upperIndex, + value, + index = -1, + object = Object(this), + length = object.length >>> 0, + middle = floor(length / 2); + + if (length > 1) { + while (++index < middle) { + upperIndex = length - index - 1; + value = upperIndex in object ? object[upperIndex] : uid; + if (index in object) { + object[upperIndex] = object[index]; + } else { + delete object[upperIndex]; + } + if (value != uid) { + object[index] = value; + } else { + delete object[index]; + } + } + } + return object; + } + + /** + * Removes the first element of the host array and returns it. + * + * @memberOf Benchmark.Suite + * @returns {Mixed} The first element of the array. + */ + function shift() { + return insert.call(this, 0, 1)[0]; + } + + /** + * Creates an array of the host array's elements from the start index up to, + * but not including, the end index. + * + * @memberOf Benchmark.Suite + * @param {Number} start The starting index. + * @param {Number} end The end index. + * @returns {Array} The new array. + */ + function slice(start, end) { + var index = -1, + object = Object(this), + length = object.length >>> 0, + result = []; + + start = toInteger(start); + start = start < 0 ? max(length + start, 0) : min(start, length); + start--; + end = end == null ? length : toInteger(end); + end = end < 0 ? max(length + end, 0) : min(end, length); + + while ((++index, ++start) < end) { + if (start in object) { + result[index] = object[start]; + } + } + return result; + } + + /** + * Allows removing a range of elements and/or inserting elements into the + * host array. + * + * @memberOf Benchmark.Suite + * @param {Number} start The start index. + * @param {Number} deleteCount The number of elements to delete. + * @param {Mixed} [val1, val2, ...] values to insert at the `start` index. + * @returns {Array} An array of removed elements. + */ + function splice(start, deleteCount) { + var object = Object(this), + length = object.length >>> 0; + + start = toInteger(start); + start = start < 0 ? max(length + start, 0) : min(start, length); + + // support the de-facto SpiderMonkey extension + // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice#Parameters + // https://bugs.ecmascript.org/show_bug.cgi?id=429 + deleteCount = arguments.length == 1 + ? length - start + : min(max(toInteger(deleteCount), 0), length - start); + + return insert.call(object, start, deleteCount, slice.call(arguments, 2)); + } + + /** + * Converts the specified `value` to an integer. + * + * @private + * @param {Mixed} value The value to convert. + * @returns {Number} The resulting integer. + */ + function toInteger(value) { + value = +value; + return value === 0 || !isFinite(value) ? value || 0 : value - (value % 1); + } + + /** + * Appends arguments to the host array. + * + * @memberOf Benchmark.Suite + * @returns {Number} The new length. + */ + function unshift() { + var object = Object(this); + insert.call(object, 0, 0, arguments); + return object.length; + } + + /*--------------------------------------------------------------------------*/ + + /** + * A generic `Function#bind` like method. + * + * @private + * @param {Function} fn The function to be bound to `thisArg`. + * @param {Mixed} thisArg The `this` binding for the given function. + * @returns {Function} The bound function. + */ + function bind(fn, thisArg) { + return function() { fn.apply(thisArg, arguments); }; + } + + /** + * Creates a function from the given arguments string and body. + * + * @private + * @param {String} args The comma separated function arguments. + * @param {String} body The function body. + * @returns {Function} The new function. + */ + function createFunction() { + // lazy define + createFunction = function(args, body) { + var result, + anchor = freeDefine ? define.amd : Benchmark, + prop = uid + 'createFunction'; + + runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}'); + result = anchor[prop]; + delete anchor[prop]; + return result; + }; + // fix JaegerMonkey bug + // http://bugzil.la/639720 + createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || noop)() == uid ? createFunction : Function; + return createFunction.apply(null, arguments); + } + + /** + * Delay the execution of a function based on the benchmark's `delay` property. + * + * @private + * @param {Object} bench The benchmark instance. + * @param {Object} fn The function to execute. + */ + function delay(bench, fn) { + bench._timerId = setTimeout(fn, bench.delay * 1e3); + } + + /** + * Destroys the given element. + * + * @private + * @param {Element} element The element to destroy. + */ + function destroyElement(element) { + trash.appendChild(element); + trash.innerHTML = ''; + } + + /** + * Iterates over an object's properties, executing the `callback` for each. + * Callbacks may terminate the loop by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} callback The function executed per own property. + * @param {Object} options The options object. + * @returns {Object} Returns the object iterated over. + */ + function forProps() { + var forShadowed, + skipSeen, + forArgs = true, + shadowed = ['constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf']; + + (function(enumFlag, key) { + // must use a non-native constructor to catch the Safari 2 issue + function Klass() { this.valueOf = 0; }; + Klass.prototype.valueOf = 0; + // check various for-in bugs + for (key in new Klass) { + enumFlag += key == 'valueOf' ? 1 : 0; + } + // check if `arguments` objects have non-enumerable indexes + for (key in arguments) { + key == '0' && (forArgs = false); + } + // Safari 2 iterates over shadowed properties twice + // http://replay.waybackmachine.org/20090428222941/http://tobielangel.com/2007/1/29/for-in-loop-broken-in-safari/ + skipSeen = enumFlag == 2; + // IE < 9 incorrectly makes an object's properties non-enumerable if they have + // the same name as other non-enumerable properties in its prototype chain. + forShadowed = !enumFlag; + }(0)); + + // lazy define + forProps = function(object, callback, options) { + options || (options = {}); + + var result = object; + object = Object(object); + + var ctor, + key, + keys, + skipCtor, + done = !result, + which = options.which, + allFlag = which == 'all', + index = -1, + iteratee = object, + length = object.length, + ownFlag = allFlag || which == 'own', + seen = {}, + skipProto = isClassOf(object, 'Function'), + thisArg = options.bind; + + if (thisArg !== undefined) { + callback = bind(callback, thisArg); + } + // iterate all properties + if (allFlag && support.getAllKeys) { + for (index = 0, keys = getAllKeys(object), length = keys.length; index < length; index++) { + key = keys[index]; + if (callback(object[key], key, object) === false) { + break; + } + } + } + // else iterate only enumerable properties + else { + for (key in object) { + // Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 + // (if the prototype or a property on the prototype has been set) + // incorrectly set a function's `prototype` property [[Enumerable]] value + // to `true`. Because of this we standardize on skipping the `prototype` + // property of functions regardless of their [[Enumerable]] value. + if ((done = + !(skipProto && key == 'prototype') && + !(skipSeen && (hasKey(seen, key) || !(seen[key] = true))) && + (!ownFlag || ownFlag && hasKey(object, key)) && + callback(object[key], key, object) === false)) { + break; + } + } + // in IE < 9 strings don't support accessing characters by index + if (!done && (forArgs && isArguments(object) || + ((noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String') && + (iteratee = noCharByIndex ? object.split('') : object)))) { + while (++index < length) { + if ((done = + callback(iteratee[index], String(index), object) === false)) { + break; + } + } + } + if (!done && forShadowed) { + // Because IE < 9 can't set the `[[Enumerable]]` attribute of an existing + // property and the `constructor` property of a prototype defaults to + // non-enumerable, we manually skip the `constructor` property when we + // think we are iterating over a `prototype` object. + ctor = object.constructor; + skipCtor = ctor && ctor.prototype && ctor.prototype.constructor === ctor; + for (index = 0; index < 7; index++) { + key = shadowed[index]; + if (!(skipCtor && key == 'constructor') && + hasKey(object, key) && + callback(object[key], key, object) === false) { + break; + } + } + } + } + return result; + }; + return forProps.apply(null, arguments); + } + + /** + * Gets the name of the first argument from a function's source. + * + * @private + * @param {Function} fn The function. + * @returns {String} The argument name. + */ + function getFirstArgument(fn) { + return (!hasKey(fn, 'toString') && + (/^[\s(]*function[^(]*\(([^\s,)]+)/.exec(fn) || 0)[1]) || ''; + } + + /** + * Computes the geometric mean (log-average) of a sample. + * See http://en.wikipedia.org/wiki/Geometric_mean#Relationship_with_arithmetic_mean_of_logarithms. + * + * @private + * @param {Array} sample The sample. + * @returns {Number} The geometric mean. + */ + function getGeometricMean(sample) { + return pow(Math.E, reduce(sample, function(sum, x) { + return sum + log(x); + }) / sample.length) || 0; + } + + /** + * Computes the arithmetic mean of a sample. + * + * @private + * @param {Array} sample The sample. + * @returns {Number} The mean. + */ + function getMean(sample) { + return (reduce(sample, function(sum, x) { + return sum + x; + }) / sample.length) || 0; + } + + /** + * Gets the source code of a function. + * + * @private + * @param {Function} fn The function. + * @param {String} altSource A string used when a function's source code is unretrievable. + * @returns {String} The function's source code. + */ + function getSource(fn, altSource) { + var result = altSource; + if (isStringable(fn)) { + result = String(fn); + } else if (support.decompilation) { + // escape the `{` for Firefox 1 + result = (/^[^{]+\{([\s\S]*)\}\s*$/.exec(fn) || 0)[1]; + } + // trim string + result = (result || '').replace(/^\s+|\s+$/g, ''); + + // detect strings containing only the "use strict" directive + return /^(?:\/\*+[\w|\W]*?\*\/|\/\/.*?[\n\r\u2028\u2029]|\s)*(["'])use strict\1;?$/.test(result) + ? '' + : result; + } + + /** + * Checks if a value is an `arguments` object. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the value is an `arguments` object, else `false`. + */ + function isArguments() { + // lazy define + isArguments = function(value) { + return toString.call(value) == '[object Arguments]'; + }; + if (noArgumentsClass) { + isArguments = function(value) { + return hasKey(value, 'callee') && + !(propertyIsEnumerable && propertyIsEnumerable.call(value, 'callee')); + }; + } + return isArguments(arguments[0]); + } + + /** + * Checks if an object is of the specified class. + * + * @private + * @param {Mixed} value The value to check. + * @param {String} name The name of the class. + * @returns {Boolean} Returns `true` if the value is of the specified class, else `false`. + */ + function isClassOf(value, name) { + return value != null && toString.call(value) == '[object ' + name + ']'; + } + + /** + * Host objects can return type values that are different from their actual + * data type. The objects we are concerned with usually return non-primitive + * types of object, function, or unknown. + * + * @private + * @param {Mixed} object The owner of the property. + * @param {String} property The property to check. + * @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`. + */ + function isHostType(object, property) { + var type = object != null ? typeof object[property] : 'number'; + return !/^(?:boolean|number|string|undefined)$/.test(type) && + (type == 'object' ? !!object[property] : true); + } + + /** + * Checks if a given `value` is an object created by the `Object` constructor + * assuming objects created by the `Object` constructor have no inherited + * enumerable properties and that there are no `Object.prototype` extensions. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a plain `Object` object, else `false`. + */ + function isPlainObject(value) { + // avoid non-objects and false positives for `arguments` objects in IE < 9 + var result = false; + if (!(value && typeof value == 'object') || isArguments(value)) { + return result; + } + // IE < 9 presents DOM nodes as `Object` objects except they have `toString` + // methods that are `typeof` "string" and still can coerce nodes to strings. + // Also check that the constructor is `Object` (i.e. `Object instanceof Object`) + var ctor = value.constructor; + if ((support.nodeClass || !(typeof value.toString != 'function' && typeof (value + '') == 'string')) && + (!isClassOf(ctor, 'Function') || ctor instanceof ctor)) { + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + if (support.iteratesOwnFirst) { + forProps(value, function(subValue, subKey) { + result = subKey; + }); + return result === false || hasKey(value, result); + } + // IE < 9 iterates inherited properties before own properties. If the first + // iterated property is an object's own property then there are no inherited + // enumerable properties. + forProps(value, function(subValue, subKey) { + result = !hasKey(value, subKey); + return false; + }); + return result === false; + } + return result; + } + + /** + * Checks if a value can be safely coerced to a string. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the value can be coerced, else `false`. + */ + function isStringable(value) { + return hasKey(value, 'toString') || isClassOf(value, 'String'); + } + + /** + * Wraps a function and passes `this` to the original function as the + * first argument. + * + * @private + * @param {Function} fn The function to be wrapped. + * @returns {Function} The new function. + */ + function methodize(fn) { + return function() { + var args = [this]; + args.push.apply(args, arguments); + return fn.apply(null, args); + }; + } + + /** + * A no-operation function. + * + * @private + */ + function noop() { + // no operation performed + } + + /** + * A wrapper around require() to suppress `module missing` errors. + * + * @private + * @param {String} id The module id. + * @returns {Mixed} The exported module or `null`. + */ + function req(id) { + try { + var result = freeExports && freeRequire(id); + } catch(e) { } + return result || null; + } + + /** + * Runs a snippet of JavaScript via script injection. + * + * @private + * @param {String} code The code to run. + */ + function runScript(code) { + var anchor = freeDefine ? define.amd : Benchmark, + script = doc.createElement('script'), + sibling = doc.getElementsByTagName('script')[0], + parent = sibling.parentNode, + prop = uid + 'runScript', + prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();'; + + // Firefox 2.0.0.2 cannot use script injection as intended because it executes + // asynchronously, but that's OK because script injection is only used to avoid + // the previously commented JaegerMonkey bug. + try { + // remove the inserted script *before* running the code to avoid differences + // in the expected script element count/order of the document. + script.appendChild(doc.createTextNode(prefix + code)); + anchor[prop] = function() { destroyElement(script); }; + } catch(e) { + parent = parent.cloneNode(false); + sibling = null; + script.text = code; + } + parent.insertBefore(script, sibling); + delete anchor[prop]; + } + + /** + * A helper function for setting options/event handlers. + * + * @private + * @param {Object} bench The benchmark instance. + * @param {Object} [options={}] Options object. + */ + function setOptions(bench, options) { + options = extend({}, bench.constructor.options, options); + bench.options = forOwn(options, function(value, key) { + if (value != null) { + // add event listeners + if (/^on[A-Z]/.test(key)) { + forEach(key.split(' '), function(key) { + bench.on(key.slice(2).toLowerCase(), value); + }); + } else if (!hasKey(bench, key)) { + bench[key] = deepClone(value); + } + } + }); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Handles cycling/completing the deferred benchmark. + * + * @memberOf Benchmark.Deferred + */ + function resolve() { + var me = this, + clone = me.benchmark, + bench = clone._original; + + if (bench.aborted) { + // cycle() -> clone cycle/complete event -> compute()'s invoked bench.run() cycle/complete + me.teardown(); + clone.running = false; + cycle(me); + } + else if (++me.cycles < clone.count) { + // continue the test loop + if (support.timeout) { + // use setTimeout to avoid a call stack overflow if called recursively + setTimeout(function() { clone.compiled.call(me, timer); }, 0); + } else { + clone.compiled.call(me, timer); + } + } + else { + timer.stop(me); + me.teardown(); + delay(clone, function() { cycle(me); }); + } + } + + /*--------------------------------------------------------------------------*/ + + /** + * A deep clone utility. + * + * @static + * @memberOf Benchmark + * @param {Mixed} value The value to clone. + * @returns {Mixed} The cloned value. + */ + function deepClone(value) { + var accessor, + circular, + clone, + ctor, + descriptor, + extensible, + key, + length, + markerKey, + parent, + result, + source, + subIndex, + data = { 'value': value }, + index = 0, + marked = [], + queue = { 'length': 0 }, + unmarked = []; + + /** + * An easily detectable decorator for cloned values. + */ + function Marker(object) { + this.raw = object; + } + + /** + * The callback used by `forProps()`. + */ + function forPropsCallback(subValue, subKey) { + // exit early to avoid cloning the marker + if (subValue && subValue.constructor == Marker) { + return; + } + // add objects to the queue + if (subValue === Object(subValue)) { + queue[queue.length++] = { 'key': subKey, 'parent': clone, 'source': value }; + } + // assign non-objects + else { + try { + // will throw an error in strict mode if the property is read-only + clone[subKey] = subValue; + } catch(e) { } + } + } + + /** + * Gets an available marker key for the given object. + */ + function getMarkerKey(object) { + // avoid collisions with existing keys + var result = uid; + while (object[result] && object[result].constructor != Marker) { + result += 1; + } + return result; + } + + do { + key = data.key; + parent = data.parent; + source = data.source; + clone = value = source ? source[key] : data.value; + accessor = circular = descriptor = false; + + // create a basic clone to filter out functions, DOM elements, and + // other non `Object` objects + if (value === Object(value)) { + // use custom deep clone function if available + if (isClassOf(value.deepClone, 'Function')) { + clone = value.deepClone(); + } else { + ctor = value.constructor; + switch (toString.call(value)) { + case '[object Array]': + clone = new ctor(value.length); + break; + + case '[object Boolean]': + clone = new ctor(value == true); + break; + + case '[object Date]': + clone = new ctor(+value); + break; + + case '[object Object]': + isPlainObject(value) && (clone = {}); + break; + + case '[object Number]': + case '[object String]': + clone = new ctor(value); + break; + + case '[object RegExp]': + clone = ctor(value.source, + (value.global ? 'g' : '') + + (value.ignoreCase ? 'i' : '') + + (value.multiline ? 'm' : '')); + } + } + // continue clone if `value` doesn't have an accessor descriptor + // http://es5.github.com/#x8.10.1 + if (clone && clone != value && + !(descriptor = source && support.descriptors && getDescriptor(source, key), + accessor = descriptor && (descriptor.get || descriptor.set))) { + // use an existing clone (circular reference) + if ((extensible = isExtensible(value))) { + markerKey = getMarkerKey(value); + if (value[markerKey]) { + circular = clone = value[markerKey].raw; + } + } else { + // for frozen/sealed objects + for (subIndex = 0, length = unmarked.length; subIndex < length; subIndex++) { + data = unmarked[subIndex]; + if (data.object === value) { + circular = clone = data.clone; + break; + } + } + } + if (!circular) { + // mark object to allow quickly detecting circular references and tie it to its clone + if (extensible) { + value[markerKey] = new Marker(clone); + marked.push({ 'key': markerKey, 'object': value }); + } else { + // for frozen/sealed objects + unmarked.push({ 'clone': clone, 'object': value }); + } + // iterate over object properties + forProps(value, forPropsCallback, { 'which': 'all' }); + } + } + } + if (parent) { + // for custom property descriptors + if (accessor || (descriptor && !(descriptor.configurable && descriptor.enumerable && descriptor.writable))) { + if ('value' in descriptor) { + descriptor.value = clone; + } + setDescriptor(parent, key, descriptor); + } + // for default property descriptors + else { + parent[key] = clone; + } + } else { + result = clone; + } + } while ((data = queue[index++])); + + // remove markers + for (index = 0, length = marked.length; index < length; index++) { + data = marked[index]; + delete data.object[data.key]; + } + return result; + } + + /** + * An iteration utility for arrays and objects. + * Callbacks may terminate the loop by explicitly returning `false`. + * + * @static + * @memberOf Benchmark + * @param {Array|Object} object The object to iterate over. + * @param {Function} callback The function called per iteration. + * @param {Mixed} thisArg The `this` binding for the callback. + * @returns {Array|Object} Returns the object iterated over. + */ + function each(object, callback, thisArg) { + var result = object; + object = Object(object); + + var fn = callback, + index = -1, + length = object.length, + isSnapshot = !!(object.snapshotItem && (length = object.snapshotLength)), + isSplittable = (noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String'), + isConvertable = isSnapshot || isSplittable || 'item' in object, + origObject = object; + + // in Opera < 10.5 `hasKey(object, 'length')` returns `false` for NodeLists + if (length === length >>> 0) { + if (isConvertable) { + // the third argument of the callback is the original non-array object + callback = function(value, index) { + return fn.call(this, value, index, origObject); + }; + // in IE < 9 strings don't support accessing characters by index + if (isSplittable) { + object = object.split(''); + } else { + object = []; + while (++index < length) { + // in Safari 2 `index in object` is always `false` for NodeLists + object[index] = isSnapshot ? result.snapshotItem(index) : result[index]; + } + } + } + forEach(object, callback, thisArg); + } else { + forOwn(object, callback, thisArg); + } + return result; + } + + /** + * Copies enumerable properties from the source(s) object to the destination object. + * + * @static + * @memberOf Benchmark + * @param {Object} destination The destination object. + * @param {Object} [source={}] The source object. + * @returns {Object} The destination object. + */ + function extend(destination, source) { + // Chrome < 14 incorrectly sets `destination` to `undefined` when we `delete arguments[0]` + // http://code.google.com/p/v8/issues/detail?id=839 + var result = destination; + delete arguments[0]; + + forEach(arguments, function(source) { + forProps(source, function(value, key) { + result[key] = value; + }); + }); + return result; + } + + /** + * A generic `Array#filter` like method. + * + * @static + * @memberOf Benchmark + * @param {Array} array The array to iterate over. + * @param {Function|String} callback The function/alias called per iteration. + * @param {Mixed} thisArg The `this` binding for the callback. + * @returns {Array} A new array of values that passed callback filter. + * @example + * + * // get odd numbers + * Benchmark.filter([1, 2, 3, 4, 5], function(n) { + * return n % 2; + * }); // -> [1, 3, 5]; + * + * // get fastest benchmarks + * Benchmark.filter(benches, 'fastest'); + * + * // get slowest benchmarks + * Benchmark.filter(benches, 'slowest'); + * + * // get benchmarks that completed without erroring + * Benchmark.filter(benches, 'successful'); + */ + function filter(array, callback, thisArg) { + var result; + + if (callback == 'successful') { + // callback to exclude those that are errored, unrun, or have hz of Infinity + callback = function(bench) { return bench.cycles && isFinite(bench.hz); }; + } + else if (callback == 'fastest' || callback == 'slowest') { + // get successful, sort by period + margin of error, and filter fastest/slowest + result = filter(array, 'successful').sort(function(a, b) { + a = a.stats; b = b.stats; + return (a.mean + a.moe > b.mean + b.moe ? 1 : -1) * (callback == 'fastest' ? 1 : -1); + }); + result = filter(result, function(bench) { + return result[0].compare(bench) == 0; + }); + } + return result || reduce(array, function(result, value, index) { + return callback.call(thisArg, value, index, array) ? (result.push(value), result) : result; + }, []); + } + + /** + * A generic `Array#forEach` like method. + * Callbacks may terminate the loop by explicitly returning `false`. + * + * @static + * @memberOf Benchmark + * @param {Array} array The array to iterate over. + * @param {Function} callback The function called per iteration. + * @param {Mixed} thisArg The `this` binding for the callback. + * @returns {Array} Returns the array iterated over. + */ + function forEach(array, callback, thisArg) { + var index = -1, + length = (array = Object(array)).length >>> 0; + + if (thisArg !== undefined) { + callback = bind(callback, thisArg); + } + while (++index < length) { + if (index in array && + callback(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * Iterates over an object's own properties, executing the `callback` for each. + * Callbacks may terminate the loop by explicitly returning `false`. + * + * @static + * @memberOf Benchmark + * @param {Object} object The object to iterate over. + * @param {Function} callback The function executed per own property. + * @param {Mixed} thisArg The `this` binding for the callback. + * @returns {Object} Returns the object iterated over. + */ + function forOwn(object, callback, thisArg) { + return forProps(object, callback, { 'bind': thisArg, 'which': 'own' }); + } + + /** + * Converts a number to a more readable comma-separated string representation. + * + * @static + * @memberOf Benchmark + * @param {Number} number The number to convert. + * @returns {String} The more readable string representation. + */ + function formatNumber(number) { + number = String(number).split('.'); + return number[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ',') + + (number[1] ? '.' + number[1] : ''); + } + + /** + * Checks if an object has the specified key as a direct property. + * + * @static + * @memberOf Benchmark + * @param {Object} object The object to check. + * @param {String} key The key to check for. + * @returns {Boolean} Returns `true` if key is a direct property, else `false`. + */ + function hasKey() { + // lazy define for worst case fallback (not as accurate) + hasKey = function(object, key) { + var parent = object != null && (object.constructor || Object).prototype; + return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]); + }; + // for modern browsers + if (isClassOf(hasOwnProperty, 'Function')) { + hasKey = function(object, key) { + return object != null && hasOwnProperty.call(object, key); + }; + } + // for Safari 2 + else if ({}.__proto__ == Object.prototype) { + hasKey = function(object, key) { + var result = false; + if (object != null) { + object = Object(object); + object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0]; + } + return result; + }; + } + return hasKey.apply(this, arguments); + } + + /** + * A generic `Array#indexOf` like method. + * + * @static + * @memberOf Benchmark + * @param {Array} array The array to iterate over. + * @param {Mixed} value The value to search for. + * @param {Number} [fromIndex=0] The index to start searching from. + * @returns {Number} The index of the matched value or `-1`. + */ + function indexOf(array, value, fromIndex) { + var index = toInteger(fromIndex), + length = (array = Object(array)).length >>> 0; + + index = (index < 0 ? max(0, length + index) : index) - 1; + while (++index < length) { + if (index in array && value === array[index]) { + return index; + } + } + return -1; + } + + /** + * Modify a string by replacing named tokens with matching object property values. + * + * @static + * @memberOf Benchmark + * @param {String} string The string to modify. + * @param {Object} object The template object. + * @returns {String} The modified string. + */ + function interpolate(string, object) { + forOwn(object, function(value, key) { + // escape regexp special characters in `key` + string = string.replace( + RegExp('#\\{' + key.replace(/([.*+?^${}()|[\]\\])/g, '\\$1') + '\\}', 'g'), + value.replace(/\$/g, '$$$$') + ); + }); + return string; + } + + /** + * Invokes a method on all items in an array. + * + * @static + * @memberOf Benchmark + * @param {Array} benches Array of benchmarks to iterate over. + * @param {String|Object} name The name of the method to invoke OR options object. + * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with. + * @returns {Array} A new array of values returned from each method invoked. + * @example + * + * // invoke `reset` on all benchmarks + * Benchmark.invoke(benches, 'reset'); + * + * // invoke `emit` with arguments + * Benchmark.invoke(benches, 'emit', 'complete', listener); + * + * // invoke `run(true)`, treat benchmarks as a queue, and register invoke callbacks + * Benchmark.invoke(benches, { + * + * // invoke the `run` method + * 'name': 'run', + * + * // pass a single argument + * 'args': true, + * + * // treat as queue, removing benchmarks from front of `benches` until empty + * 'queued': true, + * + * // called before any benchmarks have been invoked. + * 'onStart': onStart, + * + * // called between invoking benchmarks + * 'onCycle': onCycle, + * + * // called after all benchmarks have been invoked. + * 'onComplete': onComplete + * }); + */ + function invoke(benches, name) { + var args, + bench, + queued, + index = -1, + eventProps = { 'currentTarget': benches }, + options = { 'onStart': noop, 'onCycle': noop, 'onComplete': noop }, + result = map(benches, function(bench) { return bench; }); + + /** + * Invokes the method of the current object and if synchronous, fetches the next. + */ + function execute() { + var listeners, + async = isAsync(bench); + + if (async) { + // use `getNext` as the first listener + bench.on('complete', getNext); + listeners = bench.events.complete; + listeners.splice(0, 0, listeners.pop()); + } + // execute method + result[index] = isClassOf(bench && bench[name], 'Function') ? bench[name].apply(bench, args) : undefined; + // if synchronous return true until finished + return !async && getNext(); + } + + /** + * Fetches the next bench or executes `onComplete` callback. + */ + function getNext(event) { + var cycleEvent, + last = bench, + async = isAsync(last); + + if (async) { + last.off('complete', getNext); + last.emit('complete'); + } + // emit "cycle" event + eventProps.type = 'cycle'; + eventProps.target = last; + cycleEvent = Event(eventProps); + options.onCycle.call(benches, cycleEvent); + + // choose next benchmark if not exiting early + if (!cycleEvent.aborted && raiseIndex() !== false) { + bench = queued ? benches[0] : result[index]; + if (isAsync(bench)) { + delay(bench, execute); + } + else if (async) { + // resume execution if previously asynchronous but now synchronous + while (execute()) { } + } + else { + // continue synchronous execution + return true; + } + } else { + // emit "complete" event + eventProps.type = 'complete'; + options.onComplete.call(benches, Event(eventProps)); + } + // When used as a listener `event.aborted = true` will cancel the rest of + // the "complete" listeners because they were already called above and when + // used as part of `getNext` the `return false` will exit the execution while-loop. + if (event) { + event.aborted = true; + } else { + return false; + } + } + + /** + * Checks if invoking `Benchmark#run` with asynchronous cycles. + */ + function isAsync(object) { + // avoid using `instanceof` here because of IE memory leak issues with host objects + var async = args[0] && args[0].async; + return Object(object).constructor == Benchmark && name == 'run' && + ((async == null ? object.options.async : async) && support.timeout || object.defer); + } + + /** + * Raises `index` to the next defined index or returns `false`. + */ + function raiseIndex() { + var length = result.length; + if (queued) { + // if queued remove the previous bench and subsequent skipped non-entries + do { + ++index > 0 && shift.call(benches); + } while ((length = benches.length) && !('0' in benches)); + } + else { + while (++index < length && !(index in result)) { } + } + // if we reached the last index then return `false` + return (queued ? length : index < length) ? index : (index = false); + } + + // juggle arguments + if (isClassOf(name, 'String')) { + // 2 arguments (array, name) + args = slice.call(arguments, 2); + } else { + // 2 arguments (array, options) + options = extend(options, name); + name = options.name; + args = isClassOf(args = 'args' in options ? options.args : [], 'Array') ? args : [args]; + queued = options.queued; + } + + // start iterating over the array + if (raiseIndex() !== false) { + // emit "start" event + bench = result[index]; + eventProps.type = 'start'; + eventProps.target = bench; + options.onStart.call(benches, Event(eventProps)); + + // end early if the suite was aborted in an "onStart" listener + if (benches.aborted && benches.constructor == Suite && name == 'run') { + // emit "cycle" event + eventProps.type = 'cycle'; + options.onCycle.call(benches, Event(eventProps)); + // emit "complete" event + eventProps.type = 'complete'; + options.onComplete.call(benches, Event(eventProps)); + } + // else start + else { + if (isAsync(bench)) { + delay(bench, execute); + } else { + while (execute()) { } + } + } + } + return result; + } + + /** + * Creates a string of joined array values or object key-value pairs. + * + * @static + * @memberOf Benchmark + * @param {Array|Object} object The object to operate on. + * @param {String} [separator1=','] The separator used between key-value pairs. + * @param {String} [separator2=': '] The separator used between keys and values. + * @returns {String} The joined result. + */ + function join(object, separator1, separator2) { + var result = [], + length = (object = Object(object)).length, + arrayLike = length === length >>> 0; + + separator2 || (separator2 = ': '); + each(object, function(value, key) { + result.push(arrayLike ? value : key + separator2 + value); + }); + return result.join(separator1 || ','); + } + + /** + * A generic `Array#map` like method. + * + * @static + * @memberOf Benchmark + * @param {Array} array The array to iterate over. + * @param {Function} callback The function called per iteration. + * @param {Mixed} thisArg The `this` binding for the callback. + * @returns {Array} A new array of values returned by the callback. + */ + function map(array, callback, thisArg) { + return reduce(array, function(result, value, index) { + result[index] = callback.call(thisArg, value, index, array); + return result; + }, Array(Object(array).length >>> 0)); + } + + /** + * Retrieves the value of a specified property from all items in an array. + * + * @static + * @memberOf Benchmark + * @param {Array} array The array to iterate over. + * @param {String} property The property to pluck. + * @returns {Array} A new array of property values. + */ + function pluck(array, property) { + return map(array, function(object) { + return object == null ? undefined : object[property]; + }); + } + + /** + * A generic `Array#reduce` like method. + * + * @static + * @memberOf Benchmark + * @param {Array} array The array to iterate over. + * @param {Function} callback The function called per iteration. + * @param {Mixed} accumulator Initial value of the accumulator. + * @returns {Mixed} The accumulator. + */ + function reduce(array, callback, accumulator) { + var noaccum = arguments.length < 3; + forEach(array, function(value, index) { + accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, array); + }); + return accumulator; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Aborts all benchmarks in the suite. + * + * @name abort + * @memberOf Benchmark.Suite + * @returns {Object} The suite instance. + */ + function abortSuite() { + var event, + me = this, + resetting = calledBy.resetSuite; + + if (me.running) { + event = Event('abort'); + me.emit(event); + if (!event.cancelled || resetting) { + // avoid infinite recursion + calledBy.abortSuite = true; + me.reset(); + delete calledBy.abortSuite; + + if (!resetting) { + me.aborted = true; + invoke(me, 'abort'); + } + } + } + return me; + } + + /** + * Adds a test to the benchmark suite. + * + * @memberOf Benchmark.Suite + * @param {String} name A name to identify the benchmark. + * @param {Function|String} fn The test to benchmark. + * @param {Object} [options={}] Options object. + * @returns {Object} The benchmark instance. + * @example + * + * // basic usage + * suite.add(fn); + * + * // or using a name first + * suite.add('foo', fn); + * + * // or with options + * suite.add('foo', fn, { + * 'onCycle': onCycle, + * 'onComplete': onComplete + * }); + * + * // or name and options + * suite.add('foo', { + * 'fn': fn, + * 'onCycle': onCycle, + * 'onComplete': onComplete + * }); + * + * // or options only + * suite.add({ + * 'name': 'foo', + * 'fn': fn, + * 'onCycle': onCycle, + * 'onComplete': onComplete + * }); + */ + function add(name, fn, options) { + var me = this, + bench = Benchmark(name, fn, options), + event = Event({ 'type': 'add', 'target': bench }); + + if (me.emit(event), !event.cancelled) { + me.push(bench); + } + return me; + } + + /** + * Creates a new suite with cloned benchmarks. + * + * @name clone + * @memberOf Benchmark.Suite + * @param {Object} options Options object to overwrite cloned options. + * @returns {Object} The new suite instance. + */ + function cloneSuite(options) { + var me = this, + result = new me.constructor(extend({}, me.options, options)); + + // copy own properties + forOwn(me, function(value, key) { + if (!hasKey(result, key)) { + result[key] = value && isClassOf(value.clone, 'Function') + ? value.clone() + : deepClone(value); + } + }); + return result; + } + + /** + * An `Array#filter` like method. + * + * @name filter + * @memberOf Benchmark.Suite + * @param {Function|String} callback The function/alias called per iteration. + * @returns {Object} A new suite of benchmarks that passed callback filter. + */ + function filterSuite(callback) { + var me = this, + result = new me.constructor; + + result.push.apply(result, filter(me, callback)); + return result; + } + + /** + * Resets all benchmarks in the suite. + * + * @name reset + * @memberOf Benchmark.Suite + * @returns {Object} The suite instance. + */ + function resetSuite() { + var event, + me = this, + aborting = calledBy.abortSuite; + + if (me.running && !aborting) { + // no worries, `resetSuite()` is called within `abortSuite()` + calledBy.resetSuite = true; + me.abort(); + delete calledBy.resetSuite; + } + // reset if the state has changed + else if ((me.aborted || me.running) && + (me.emit(event = Event('reset')), !event.cancelled)) { + me.running = false; + if (!aborting) { + invoke(me, 'reset'); + } + } + return me; + } + + /** + * Runs the suite. + * + * @name run + * @memberOf Benchmark.Suite + * @param {Object} [options={}] Options object. + * @returns {Object} The suite instance. + * @example + * + * // basic usage + * suite.run(); + * + * // or with options + * suite.run({ 'async': true, 'queued': true }); + */ + function runSuite(options) { + var me = this; + + me.reset(); + me.running = true; + options || (options = {}); + + invoke(me, { + 'name': 'run', + 'args': options, + 'queued': options.queued, + 'onStart': function(event) { + me.emit(event); + }, + 'onCycle': function(event) { + var bench = event.target; + if (bench.error) { + me.emit({ 'type': 'error', 'target': bench }); + } + me.emit(event); + event.aborted = me.aborted; + }, + 'onComplete': function(event) { + me.score = getGeometricMean(map(me, function(bench) { + return bench.reference / (bench.times.period * 1e6); + })) || 0; + + me.running = false; + me.emit(event); + } + }); + return me; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Executes all registered listeners of the specified event type. + * + * @memberOf Benchmark, Benchmark.Suite + * @param {String|Object} type The event type or object. + * @returns {Mixed} Returns the return value of the last listener executed. + */ + function emit(type) { + var listeners, + me = this, + event = Event(type), + events = me.events, + args = (arguments[0] = event, arguments); + + event.currentTarget || (event.currentTarget = me); + event.target || (event.target = me); + delete event.result; + + if (events && (listeners = hasKey(events, event.type) && events[event.type])) { + forEach(listeners.slice(), function(listener) { + if ((event.result = listener.apply(me, args)) === false) { + event.cancelled = true; + } + return !event.aborted; + }); + } + return event.result; + } + + /** + * Returns an array of event listeners for a given type that can be manipulated + * to add or remove listeners. + * + * @memberOf Benchmark, Benchmark.Suite + * @param {String} type The event type. + * @returns {Array} The listeners array. + */ + function listeners(type) { + var me = this, + events = me.events || (me.events = {}); + + return hasKey(events, type) ? events[type] : (events[type] = []); + } + + /** + * Unregisters a listener for the specified event type(s), + * or unregisters all listeners for the specified event type(s), + * or unregisters all listeners for all event types. + * + * @memberOf Benchmark, Benchmark.Suite + * @param {String} [type] The event type. + * @param {Function} [listener] The function to unregister. + * @returns {Object} The benchmark instance. + * @example + * + * // unregister a listener for an event type + * bench.off('cycle', listener); + * + * // unregister a listener for multiple event types + * bench.off('start cycle', listener); + * + * // unregister all listeners for an event type + * bench.off('cycle'); + * + * // unregister all listeners for multiple event types + * bench.off('start cycle complete'); + * + * // unregister all listeners for all event types + * bench.off(); + */ + function off(type, listener) { + var me = this, + events = me.events; + + events && each(type ? type.split(' ') : events, function(listeners, type) { + var index; + if (typeof listeners == 'string') { + type = listeners; + listeners = hasKey(events, type) && events[type]; + } + if (listeners) { + if (listener) { + index = indexOf(listeners, listener); + if (index > -1) { + listeners.splice(index, 1); + } + } else { + listeners.length = 0; + } + } + }); + return me; + } + + /** + * Registers a listener for the specified event type(s). + * + * @memberOf Benchmark, Benchmark.Suite + * @param {String} type The event type. + * @param {Function} listener The function to register. + * @returns {Object} The benchmark instance. + * @example + * + * // register a listener for an event type + * bench.on('cycle', listener); + * + * // register a listener for multiple event types + * bench.on('start cycle', listener); + */ + function on(type, listener) { + var me = this, + events = me.events || (me.events = {}); + + forEach(type.split(' '), function(type) { + (hasKey(events, type) + ? events[type] + : (events[type] = []) + ).push(listener); + }); + return me; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Aborts the benchmark without recording times. + * + * @memberOf Benchmark + * @returns {Object} The benchmark instance. + */ + function abort() { + var event, + me = this, + resetting = calledBy.reset; + + if (me.running) { + event = Event('abort'); + me.emit(event); + if (!event.cancelled || resetting) { + // avoid infinite recursion + calledBy.abort = true; + me.reset(); + delete calledBy.abort; + + if (support.timeout) { + clearTimeout(me._timerId); + delete me._timerId; + } + if (!resetting) { + me.aborted = true; + me.running = false; + } + } + } + return me; + } + + /** + * Creates a new benchmark using the same test and options. + * + * @memberOf Benchmark + * @param {Object} options Options object to overwrite cloned options. + * @returns {Object} The new benchmark instance. + * @example + * + * var bizarro = bench.clone({ + * 'name': 'doppelganger' + * }); + */ + function clone(options) { + var me = this, + result = new me.constructor(extend({}, me, options)); + + // correct the `options` object + result.options = extend({}, me.options, options); + + // copy own custom properties + forOwn(me, function(value, key) { + if (!hasKey(result, key)) { + result[key] = deepClone(value); + } + }); + return result; + } + + /** + * Determines if a benchmark is faster than another. + * + * @memberOf Benchmark + * @param {Object} other The benchmark to compare. + * @returns {Number} Returns `-1` if slower, `1` if faster, and `0` if indeterminate. + */ + function compare(other) { + var critical, + zStat, + me = this, + sample1 = me.stats.sample, + sample2 = other.stats.sample, + size1 = sample1.length, + size2 = sample2.length, + maxSize = max(size1, size2), + minSize = min(size1, size2), + u1 = getU(sample1, sample2), + u2 = getU(sample2, sample1), + u = min(u1, u2); + + function getScore(xA, sampleB) { + return reduce(sampleB, function(total, xB) { + return total + (xB > xA ? 0 : xB < xA ? 1 : 0.5); + }, 0); + } + + function getU(sampleA, sampleB) { + return reduce(sampleA, function(total, xA) { + return total + getScore(xA, sampleB); + }, 0); + } + + function getZ(u) { + return (u - ((size1 * size2) / 2)) / sqrt((size1 * size2 * (size1 + size2 + 1)) / 12); + } + + // exit early if comparing the same benchmark + if (me == other) { + return 0; + } + // reject the null hyphothesis the two samples come from the + // same population (i.e. have the same median) if... + if (size1 + size2 > 30) { + // ...the z-stat is greater than 1.96 or less than -1.96 + // http://www.statisticslectures.com/topics/mannwhitneyu/ + zStat = getZ(u); + return abs(zStat) > 1.96 ? (zStat > 0 ? -1 : 1) : 0; + } + // ...the U value is less than or equal the critical U value + // http://www.geoib.com/mann-whitney-u-test.html + critical = maxSize < 5 || minSize < 3 ? 0 : uTable[maxSize][minSize - 3]; + return u <= critical ? (u == u1 ? 1 : -1) : 0; + } + + /** + * Reset properties and abort if running. + * + * @memberOf Benchmark + * @returns {Object} The benchmark instance. + */ + function reset() { + var data, + event, + me = this, + index = 0, + changes = { 'length': 0 }, + queue = { 'length': 0 }; + + if (me.running && !calledBy.abort) { + // no worries, `reset()` is called within `abort()` + calledBy.reset = true; + me.abort(); + delete calledBy.reset; + } + else { + // a non-recursive solution to check if properties have changed + // http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4 + data = { 'destination': me, 'source': extend({}, me.constructor.prototype, me.options) }; + do { + forOwn(data.source, function(value, key) { + var changed, + destination = data.destination, + currValue = destination[key]; + + if (value && typeof value == 'object') { + if (isClassOf(value, 'Array')) { + // check if an array value has changed to a non-array value + if (!isClassOf(currValue, 'Array')) { + changed = currValue = []; + } + // or has changed its length + if (currValue.length != value.length) { + changed = currValue = currValue.slice(0, value.length); + currValue.length = value.length; + } + } + // check if an object has changed to a non-object value + else if (!currValue || typeof currValue != 'object') { + changed = currValue = {}; + } + // register a changed object + if (changed) { + changes[changes.length++] = { 'destination': destination, 'key': key, 'value': currValue }; + } + queue[queue.length++] = { 'destination': currValue, 'source': value }; + } + // register a changed primitive + else if (value !== currValue && !(value == null || isClassOf(value, 'Function'))) { + changes[changes.length++] = { 'destination': destination, 'key': key, 'value': value }; + } + }); + } + while ((data = queue[index++])); + + // if changed emit the `reset` event and if it isn't cancelled reset the benchmark + if (changes.length && (me.emit(event = Event('reset')), !event.cancelled)) { + forEach(changes, function(data) { + data.destination[data.key] = data.value; + }); + } + } + return me; + } + + /** + * Displays relevant benchmark information when coerced to a string. + * + * @name toString + * @memberOf Benchmark + * @returns {String} A string representation of the benchmark instance. + */ + function toStringBench() { + var me = this, + error = me.error, + hz = me.hz, + id = me.id, + stats = me.stats, + size = stats.sample.length, + pm = support.java ? '+/-' : '\xb1', + result = me.name || (isNaN(id) ? id : ''); + + if (error) { + result += ': ' + join(error); + } else { + result += ' x ' + formatNumber(hz.toFixed(hz < 100 ? 2 : 0)) + ' ops/sec ' + pm + + stats.rme.toFixed(2) + '% (' + size + ' run' + (size == 1 ? '' : 's') + ' sampled)'; + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Clocks the time taken to execute a test per cycle (secs). + * + * @private + * @param {Object} bench The benchmark instance. + * @returns {Number} The time taken. + */ + function clock() { + var applet, + options = Benchmark.options, + template = { 'begin': 's$=new n$', 'end': 'r$=(new n$-s$)/1e3', 'uid': uid }, + timers = [{ 'ns': timer.ns, 'res': max(0.0015, getRes('ms')), 'unit': 'ms' }]; + + // lazy define for hi-res timers + clock = function(clone) { + var deferred; + if (clone instanceof Deferred) { + deferred = clone; + clone = deferred.benchmark; + } + + var bench = clone._original, + fn = bench.fn, + fnArg = deferred ? getFirstArgument(fn) || 'deferred' : '', + stringable = isStringable(fn); + + var source = { + 'setup': getSource(bench.setup, preprocess('m$.setup()')), + 'fn': getSource(fn, preprocess('m$.fn(' + fnArg + ')')), + 'fnArg': fnArg, + 'teardown': getSource(bench.teardown, preprocess('m$.teardown()')) + }; + + var count = bench.count = clone.count, + decompilable = support.decompilation || stringable, + id = bench.id, + isEmpty = !(source.fn || stringable), + name = bench.name || (typeof id == 'number' ? '' : id), + ns = timer.ns, + result = 0; + + // init `minTime` if needed + clone.minTime = bench.minTime || (bench.minTime = bench.options.minTime = options.minTime); + + // repair nanosecond timer + // (some Chrome builds erase the `ns` variable after millions of executions) + if (applet) { + try { + ns.nanoTime(); + } catch(e) { + // use non-element to avoid issues with libs that augment them + ns = timer.ns = new applet.Packages.nano; + } + } + + // Compile in setup/teardown functions and the test loop. + // Create a new compiled test, instead of using the cached `bench.compiled`, + // to avoid potential engine optimizations enabled over the life of the test. + var compiled = bench.compiled = createFunction(preprocess('t$'), interpolate( + preprocess(deferred + ? 'var d$=this,#{fnArg}=d$,m$=d$.benchmark._original,f$=m$.fn,su$=m$.setup,td$=m$.teardown;' + + // when `deferred.cycles` is `0` then... + 'if(!d$.cycles){' + + // set `deferred.fn` + 'd$.fn=function(){var #{fnArg}=d$;if(typeof f$=="function"){try{#{fn}\n}catch(e$){f$(d$)}}else{#{fn}\n}};' + + // set `deferred.teardown` + 'd$.teardown=function(){d$.cycles=0;if(typeof td$=="function"){try{#{teardown}\n}catch(e$){td$()}}else{#{teardown}\n}};' + + // execute the benchmark's `setup` + 'if(typeof su$=="function"){try{#{setup}\n}catch(e$){su$()}}else{#{setup}\n};' + + // start timer + 't$.start(d$);' + + // execute `deferred.fn` and return a dummy object + '}d$.fn();return{}' + + : 'var r$,s$,m$=this,f$=m$.fn,i$=m$.count,n$=t$.ns;#{setup}\n#{begin};' + + 'while(i$--){#{fn}\n}#{end};#{teardown}\nreturn{elapsed:r$,uid:"#{uid}"}'), + source + )); + + try { + if (isEmpty) { + // Firefox may remove dead code from Function#toString results + // http://bugzil.la/536085 + throw new Error('The test "' + name + '" is empty. This may be the result of dead code removal.'); + } + else if (!deferred) { + // pretest to determine if compiled code is exits early, usually by a + // rogue `return` statement, by checking for a return object with the uid + bench.count = 1; + compiled = (compiled.call(bench, timer) || {}).uid == uid && compiled; + bench.count = count; + } + } catch(e) { + compiled = null; + clone.error = e || new Error(String(e)); + bench.count = count; + } + // fallback when a test exits early or errors during pretest + if (decompilable && !compiled && !deferred && !isEmpty) { + compiled = createFunction(preprocess('t$'), interpolate( + preprocess( + (clone.error && !stringable + ? 'var r$,s$,m$=this,f$=m$.fn,i$=m$.count' + : 'function f$(){#{fn}\n}var r$,s$,m$=this,i$=m$.count' + ) + + ',n$=t$.ns;#{setup}\n#{begin};m$.f$=f$;while(i$--){m$.f$()}#{end};' + + 'delete m$.f$;#{teardown}\nreturn{elapsed:r$}' + ), + source + )); + + try { + // pretest one more time to check for errors + bench.count = 1; + compiled.call(bench, timer); + bench.compiled = compiled; + bench.count = count; + delete clone.error; + } + catch(e) { + bench.count = count; + if (clone.error) { + compiled = null; + } else { + bench.compiled = compiled; + clone.error = e || new Error(String(e)); + } + } + } + // assign `compiled` to `clone` before calling in case a deferred benchmark + // immediately calls `deferred.resolve()` + clone.compiled = compiled; + // if no errors run the full test loop + if (!clone.error) { + result = compiled.call(deferred || bench, timer).elapsed; + } + return result; + }; + + /*------------------------------------------------------------------------*/ + + /** + * Gets the current timer's minimum resolution (secs). + */ + function getRes(unit) { + var measured, + begin, + count = 30, + divisor = 1e3, + ns = timer.ns, + sample = []; + + // get average smallest measurable time + while (count--) { + if (unit == 'us') { + divisor = 1e6; + if (ns.stop) { + ns.start(); + while (!(measured = ns.microseconds())) { } + } else if (ns[perfName]) { + divisor = 1e3; + measured = Function('n', 'var r,s=n.' + perfName + '();while(!(r=n.' + perfName + '()-s)){};return r')(ns); + } else { + begin = ns(); + while (!(measured = ns() - begin)) { } + } + } + else if (unit == 'ns') { + divisor = 1e9; + if (ns.nanoTime) { + begin = ns.nanoTime(); + while (!(measured = ns.nanoTime() - begin)) { } + } else { + begin = (begin = ns())[0] + (begin[1] / divisor); + while (!(measured = ((measured = ns())[0] + (measured[1] / divisor)) - begin)) { } + divisor = 1; + } + } + else { + begin = new ns; + while (!(measured = new ns - begin)) { } + } + // check for broken timers (nanoTime may have issues) + // http://alivebutsleepy.srnet.cz/unreliable-system-nanotime/ + if (measured > 0) { + sample.push(measured); + } else { + sample.push(Infinity); + break; + } + } + // convert to seconds + return getMean(sample) / divisor; + } + + /** + * Replaces all occurrences of `$` with a unique number and + * template tokens with content. + */ + function preprocess(code) { + return interpolate(code, template).replace(/\$/g, /\d+/.exec(uid)); + } + + /*------------------------------------------------------------------------*/ + + // detect nanosecond support from a Java applet + each(doc && doc.applets || [], function(element) { + return !(timer.ns = applet = 'nanoTime' in element && element); + }); + + // check type in case Safari returns an object instead of a number + try { + if (typeof timer.ns.nanoTime() == 'number') { + timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' }); + } + } catch(e) { } + + // detect Chrome's microsecond timer: + // enable benchmarking via the --enable-benchmarking command + // line switch in at least Chrome 7 to use chrome.Interval + try { + if ((timer.ns = new (window.chrome || window.chromium).Interval)) { + timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' }); + } + } catch(e) { } + + // detect `performance.now` microsecond resolution timer + if ((timer.ns = perfName && perfObject)) { + timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' }); + } + + // detect Node's nanosecond resolution timer available in Node >= 0.8 + if (processObject && typeof (timer.ns = processObject.hrtime) == 'function') { + timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' }); + } + + // detect Wade Simmons' Node microtime module + if (microtimeObject && typeof (timer.ns = microtimeObject.now) == 'function') { + timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' }); + } + + // pick timer with highest resolution + timer = reduce(timers, function(timer, other) { + return other.res < timer.res ? other : timer; + }); + + // remove unused applet + if (timer.unit != 'ns' && applet) { + applet = destroyElement(applet); + } + // error if there are no working timers + if (timer.res == Infinity) { + throw new Error('Benchmark.js was unable to find a working timer.'); + } + // use API of chosen timer + if (timer.unit == 'ns') { + if (timer.ns.nanoTime) { + extend(template, { + 'begin': 's$=n$.nanoTime()', + 'end': 'r$=(n$.nanoTime()-s$)/1e9' + }); + } else { + extend(template, { + 'begin': 's$=n$()', + 'end': 'r$=n$(s$);r$=r$[0]+(r$[1]/1e9)' + }); + } + } + else if (timer.unit == 'us') { + if (timer.ns.stop) { + extend(template, { + 'begin': 's$=n$.start()', + 'end': 'r$=n$.microseconds()/1e6' + }); + } else if (perfName) { + extend(template, { + 'begin': 's$=n$.' + perfName + '()', + 'end': 'r$=(n$.' + perfName + '()-s$)/1e3' + }); + } else { + extend(template, { + 'begin': 's$=n$()', + 'end': 'r$=(n$()-s$)/1e6' + }); + } + } + + // define `timer` methods + timer.start = createFunction(preprocess('o$'), + preprocess('var n$=this.ns,#{begin};o$.elapsed=0;o$.timeStamp=s$')); + + timer.stop = createFunction(preprocess('o$'), + preprocess('var n$=this.ns,s$=o$.timeStamp,#{end};o$.elapsed=r$')); + + // resolve time span required to achieve a percent uncertainty of at most 1% + // http://spiff.rit.edu/classes/phys273/uncert/uncert.html + options.minTime || (options.minTime = max(timer.res / 2 / 0.01, 0.05)); + return clock.apply(null, arguments); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Computes stats on benchmark results. + * + * @private + * @param {Object} bench The benchmark instance. + * @param {Object} options The options object. + */ + function compute(bench, options) { + options || (options = {}); + + var async = options.async, + elapsed = 0, + initCount = bench.initCount, + minSamples = bench.minSamples, + queue = [], + sample = bench.stats.sample; + + /** + * Adds a clone to the queue. + */ + function enqueue() { + queue.push(bench.clone({ + '_original': bench, + 'events': { + 'abort': [update], + 'cycle': [update], + 'error': [update], + 'start': [update] + } + })); + } + + /** + * Updates the clone/original benchmarks to keep their data in sync. + */ + function update(event) { + var clone = this, + type = event.type; + + if (bench.running) { + if (type == 'start') { + // Note: `clone.minTime` prop is inited in `clock()` + clone.count = bench.initCount; + } + else { + if (type == 'error') { + bench.error = clone.error; + } + if (type == 'abort') { + bench.abort(); + bench.emit('cycle'); + } else { + event.currentTarget = event.target = bench; + bench.emit(event); + } + } + } else if (bench.aborted) { + // clear abort listeners to avoid triggering bench's abort/cycle again + clone.events.abort.length = 0; + clone.abort(); + } + } + + /** + * Determines if more clones should be queued or if cycling should stop. + */ + function evaluate(event) { + var critical, + df, + mean, + moe, + rme, + sd, + sem, + variance, + clone = event.target, + done = bench.aborted, + now = +new Date, + size = sample.push(clone.times.period), + maxedOut = size >= minSamples && (elapsed += now - clone.times.timeStamp) / 1e3 > bench.maxTime, + times = bench.times, + varOf = function(sum, x) { return sum + pow(x - mean, 2); }; + + // exit early for aborted or unclockable tests + if (done || clone.hz == Infinity) { + maxedOut = !(size = sample.length = queue.length = 0); + } + + if (!done) { + // sample mean (estimate of the population mean) + mean = getMean(sample); + // sample variance (estimate of the population variance) + variance = reduce(sample, varOf, 0) / (size - 1) || 0; + // sample standard deviation (estimate of the population standard deviation) + sd = sqrt(variance); + // standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean) + sem = sd / sqrt(size); + // degrees of freedom + df = size - 1; + // critical value + critical = tTable[Math.round(df) || 1] || tTable.infinity; + // margin of error + moe = sem * critical; + // relative margin of error + rme = (moe / mean) * 100 || 0; + + extend(bench.stats, { + 'deviation': sd, + 'mean': mean, + 'moe': moe, + 'rme': rme, + 'sem': sem, + 'variance': variance + }); + + // Abort the cycle loop when the minimum sample size has been collected + // and the elapsed time exceeds the maximum time allowed per benchmark. + // We don't count cycle delays toward the max time because delays may be + // increased by browsers that clamp timeouts for inactive tabs. + // https://developer.mozilla.org/en/window.setTimeout#Inactive_tabs + if (maxedOut) { + // reset the `initCount` in case the benchmark is rerun + bench.initCount = initCount; + bench.running = false; + done = true; + times.elapsed = (now - times.timeStamp) / 1e3; + } + if (bench.hz != Infinity) { + bench.hz = 1 / mean; + times.cycle = mean * bench.count; + times.period = mean; + } + } + // if time permits, increase sample size to reduce the margin of error + if (queue.length < 2 && !maxedOut) { + enqueue(); + } + // abort the invoke cycle when done + event.aborted = done; + } + + // init queue and begin + enqueue(); + invoke(queue, { + 'name': 'run', + 'args': { 'async': async }, + 'queued': true, + 'onCycle': evaluate, + 'onComplete': function() { bench.emit('complete'); } + }); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Cycles a benchmark until a run `count` can be established. + * + * @private + * @param {Object} clone The cloned benchmark instance. + * @param {Object} options The options object. + */ + function cycle(clone, options) { + options || (options = {}); + + var deferred; + if (clone instanceof Deferred) { + deferred = clone; + clone = clone.benchmark; + } + + var clocked, + cycles, + divisor, + event, + minTime, + period, + async = options.async, + bench = clone._original, + count = clone.count, + times = clone.times; + + // continue, if not aborted between cycles + if (clone.running) { + // `minTime` is set to `Benchmark.options.minTime` in `clock()` + cycles = ++clone.cycles; + clocked = deferred ? deferred.elapsed : clock(clone); + minTime = clone.minTime; + + if (cycles > bench.cycles) { + bench.cycles = cycles; + } + if (clone.error) { + event = Event('error'); + event.message = clone.error; + clone.emit(event); + if (!event.cancelled) { + clone.abort(); + } + } + } + + // continue, if not errored + if (clone.running) { + // time taken to complete last test cycle + bench.times.cycle = times.cycle = clocked; + // seconds per operation + period = bench.times.period = times.period = clocked / count; + // ops per second + bench.hz = clone.hz = 1 / period; + // avoid working our way up to this next time + bench.initCount = clone.initCount = count; + // do we need to do another cycle? + clone.running = clocked < minTime; + + if (clone.running) { + // tests may clock at `0` when `initCount` is a small number, + // to avoid that we set its count to something a bit higher + if (!clocked && (divisor = divisors[clone.cycles]) != null) { + count = floor(4e6 / divisor); + } + // calculate how many more iterations it will take to achive the `minTime` + if (count <= clone.count) { + count += Math.ceil((minTime - clocked) / period); + } + clone.running = count != Infinity; + } + } + // should we exit early? + event = Event('cycle'); + clone.emit(event); + if (event.aborted) { + clone.abort(); + } + // figure out what to do next + if (clone.running) { + // start a new cycle + clone.count = count; + if (deferred) { + clone.compiled.call(deferred, timer); + } else if (async) { + delay(clone, function() { cycle(clone, options); }); + } else { + cycle(clone); + } + } + else { + // fix TraceMonkey bug associated with clock fallbacks + // http://bugzil.la/509069 + if (support.browser) { + runScript(uid + '=1;delete ' + uid); + } + // done + clone.emit('complete'); + } + } + + /*--------------------------------------------------------------------------*/ + + /** + * Runs the benchmark. + * + * @memberOf Benchmark + * @param {Object} [options={}] Options object. + * @returns {Object} The benchmark instance. + * @example + * + * // basic usage + * bench.run(); + * + * // or with options + * bench.run({ 'async': true }); + */ + function run(options) { + var me = this, + event = Event('start'); + + // set `running` to `false` so `reset()` won't call `abort()` + me.running = false; + me.reset(); + me.running = true; + + me.count = me.initCount; + me.times.timeStamp = +new Date; + me.emit(event); + + if (!event.cancelled) { + options = { 'async': ((options = options && options.async) == null ? me.async : options) && support.timeout }; + + // for clones created within `compute()` + if (me._original) { + if (me.defer) { + Deferred(me); + } else { + cycle(me, options); + } + } + // for original benchmarks + else { + compute(me, options); + } + } + return me; + } + + /*--------------------------------------------------------------------------*/ + + // Firefox 1 erroneously defines variable and argument names of functions on + // the function itself as non-configurable properties with `undefined` values. + // The bugginess continues as the `Benchmark` constructor has an argument + // named `options` and Firefox 1 will not assign a value to `Benchmark.options`, + // making it non-writable in the process, unless it is the first property + // assigned by for-in loop of `extend()`. + extend(Benchmark, { + + /** + * The default options copied by benchmark instances. + * + * @static + * @memberOf Benchmark + * @type Object + */ + 'options': { + + /** + * A flag to indicate that benchmark cycles will execute asynchronously + * by default. + * + * @memberOf Benchmark.options + * @type Boolean + */ + 'async': false, + + /** + * A flag to indicate that the benchmark clock is deferred. + * + * @memberOf Benchmark.options + * @type Boolean + */ + 'defer': false, + + /** + * The delay between test cycles (secs). + * @memberOf Benchmark.options + * @type Number + */ + 'delay': 0.005, + + /** + * Displayed by Benchmark#toString when a `name` is not available + * (auto-generated if absent). + * + * @memberOf Benchmark.options + * @type String + */ + 'id': undefined, + + /** + * The default number of times to execute a test on a benchmark's first cycle. + * + * @memberOf Benchmark.options + * @type Number + */ + 'initCount': 1, + + /** + * The maximum time a benchmark is allowed to run before finishing (secs). + * + * Note: Cycle delays aren't counted toward the maximum time. + * + * @memberOf Benchmark.options + * @type Number + */ + 'maxTime': 5, + + /** + * The minimum sample size required to perform statistical analysis. + * + * @memberOf Benchmark.options + * @type Number + */ + 'minSamples': 5, + + /** + * The time needed to reduce the percent uncertainty of measurement to 1% (secs). + * + * @memberOf Benchmark.options + * @type Number + */ + 'minTime': 0, + + /** + * The name of the benchmark. + * + * @memberOf Benchmark.options + * @type String + */ + 'name': undefined, + + /** + * An event listener called when the benchmark is aborted. + * + * @memberOf Benchmark.options + * @type Function + */ + 'onAbort': undefined, + + /** + * An event listener called when the benchmark completes running. + * + * @memberOf Benchmark.options + * @type Function + */ + 'onComplete': undefined, + + /** + * An event listener called after each run cycle. + * + * @memberOf Benchmark.options + * @type Function + */ + 'onCycle': undefined, + + /** + * An event listener called when a test errors. + * + * @memberOf Benchmark.options + * @type Function + */ + 'onError': undefined, + + /** + * An event listener called when the benchmark is reset. + * + * @memberOf Benchmark.options + * @type Function + */ + 'onReset': undefined, + + /** + * An event listener called when the benchmark starts running. + * + * @memberOf Benchmark.options + * @type Function + */ + 'onStart': undefined, + + /** + * The reference time taken to execute the test once (usecs). + * + * @memberOf Benchmark.options + * @type Number + */ + 'reference': 0 + }, + + /** + * Platform object with properties describing things like browser name, + * version, and operating system. + * + * @static + * @memberOf Benchmark + * @type Object + */ + 'platform': req('platform') || window.platform || { + + /** + * The platform description. + * + * @memberOf Benchmark.platform + * @type String + */ + 'description': window.navigator && navigator.userAgent || null, + + /** + * The name of the browser layout engine. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'layout': null, + + /** + * The name of the product hosting the browser. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'product': null, + + /** + * The name of the browser/environment. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'name': null, + + /** + * The name of the product's manufacturer. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'manufacturer': null, + + /** + * The name of the operating system. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'os': null, + + /** + * The alpha/beta release indicator. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'prerelease': null, + + /** + * The browser/environment version. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'version': null, + + /** + * Return platform description when the platform object is coerced to a string. + * + * @memberOf Benchmark.platform + * @type Function + * @returns {String} The platform description. + */ + 'toString': function() { + return this.description || ''; + } + }, + + /** + * The semantic version number. + * + * @static + * @memberOf Benchmark + * @type String + */ + 'version': '1.0.0', + + // an object of environment/feature detection flags + 'support': support, + + // clone objects + 'deepClone': deepClone, + + // iteration utility + 'each': each, + + // augment objects + 'extend': extend, + + // generic Array#filter + 'filter': filter, + + // generic Array#forEach + 'forEach': forEach, + + // generic own property iteration utility + 'forOwn': forOwn, + + // converts a number to a comma-separated string + 'formatNumber': formatNumber, + + // generic Object#hasOwnProperty + // (trigger hasKey's lazy define before assigning it to Benchmark) + 'hasKey': (hasKey(Benchmark, ''), hasKey), + + // generic Array#indexOf + 'indexOf': indexOf, + + // template utility + 'interpolate': interpolate, + + // invokes a method on each item in an array + 'invoke': invoke, + + // generic Array#join for arrays and objects + 'join': join, + + // generic Array#map + 'map': map, + + // retrieves a property value from each item in an array + 'pluck': pluck, + + // generic Array#reduce + 'reduce': reduce + }); + + /*--------------------------------------------------------------------------*/ + + extend(Benchmark.prototype, { + + /** + * The number of times a test was executed. + * + * @memberOf Benchmark + * @type Number + */ + 'count': 0, + + /** + * The number of cycles performed while benchmarking. + * + * @memberOf Benchmark + * @type Number + */ + 'cycles': 0, + + /** + * The number of executions per second. + * + * @memberOf Benchmark + * @type Number + */ + 'hz': 0, + + /** + * The compiled test function. + * + * @memberOf Benchmark + * @type Function|String + */ + 'compiled': undefined, + + /** + * The error object if the test failed. + * + * @memberOf Benchmark + * @type Object + */ + 'error': undefined, + + /** + * The test to benchmark. + * + * @memberOf Benchmark + * @type Function|String + */ + 'fn': undefined, + + /** + * A flag to indicate if the benchmark is aborted. + * + * @memberOf Benchmark + * @type Boolean + */ + 'aborted': false, + + /** + * A flag to indicate if the benchmark is running. + * + * @memberOf Benchmark + * @type Boolean + */ + 'running': false, + + /** + * Compiled into the test and executed immediately **before** the test loop. + * + * @memberOf Benchmark + * @type Function|String + * @example + * + * // basic usage + * var bench = Benchmark({ + * 'setup': function() { + * var c = this.count, + * element = document.getElementById('container'); + * while (c--) { + * element.appendChild(document.createElement('div')); + * } + * }, + * 'fn': function() { + * element.removeChild(element.lastChild); + * } + * }); + * + * // compiles to something like: + * var c = this.count, + * element = document.getElementById('container'); + * while (c--) { + * element.appendChild(document.createElement('div')); + * } + * var start = new Date; + * while (count--) { + * element.removeChild(element.lastChild); + * } + * var end = new Date - start; + * + * // or using strings + * var bench = Benchmark({ + * 'setup': '\ + * var a = 0;\n\ + * (function() {\n\ + * (function() {\n\ + * (function() {', + * 'fn': 'a += 1;', + * 'teardown': '\ + * }())\n\ + * }())\n\ + * }())' + * }); + * + * // compiles to something like: + * var a = 0; + * (function() { + * (function() { + * (function() { + * var start = new Date; + * while (count--) { + * a += 1; + * } + * var end = new Date - start; + * }()) + * }()) + * }()) + */ + 'setup': noop, + + /** + * Compiled into the test and executed immediately **after** the test loop. + * + * @memberOf Benchmark + * @type Function|String + */ + 'teardown': noop, + + /** + * An object of stats including mean, margin or error, and standard deviation. + * + * @memberOf Benchmark + * @type Object + */ + 'stats': { + + /** + * The margin of error. + * + * @memberOf Benchmark#stats + * @type Number + */ + 'moe': 0, + + /** + * The relative margin of error (expressed as a percentage of the mean). + * + * @memberOf Benchmark#stats + * @type Number + */ + 'rme': 0, + + /** + * The standard error of the mean. + * + * @memberOf Benchmark#stats + * @type Number + */ + 'sem': 0, + + /** + * The sample standard deviation. + * + * @memberOf Benchmark#stats + * @type Number + */ + 'deviation': 0, + + /** + * The sample arithmetic mean. + * + * @memberOf Benchmark#stats + * @type Number + */ + 'mean': 0, + + /** + * The array of sampled periods. + * + * @memberOf Benchmark#stats + * @type Array + */ + 'sample': [], + + /** + * The sample variance. + * + * @memberOf Benchmark#stats + * @type Number + */ + 'variance': 0 + }, + + /** + * An object of timing data including cycle, elapsed, period, start, and stop. + * + * @memberOf Benchmark + * @type Object + */ + 'times': { + + /** + * The time taken to complete the last cycle (secs). + * + * @memberOf Benchmark#times + * @type Number + */ + 'cycle': 0, + + /** + * The time taken to complete the benchmark (secs). + * + * @memberOf Benchmark#times + * @type Number + */ + 'elapsed': 0, + + /** + * The time taken to execute the test once (secs). + * + * @memberOf Benchmark#times + * @type Number + */ + 'period': 0, + + /** + * A timestamp of when the benchmark started (ms). + * + * @memberOf Benchmark#times + * @type Number + */ + 'timeStamp': 0 + }, + + // aborts benchmark (does not record times) + 'abort': abort, + + // creates a new benchmark using the same test and options + 'clone': clone, + + // compares benchmark's hertz with another + 'compare': compare, + + // executes listeners + 'emit': emit, + + // get listeners + 'listeners': listeners, + + // unregister listeners + 'off': off, + + // register listeners + 'on': on, + + // reset benchmark properties + 'reset': reset, + + // runs the benchmark + 'run': run, + + // pretty print benchmark info + 'toString': toStringBench + }); + + /*--------------------------------------------------------------------------*/ + + extend(Deferred.prototype, { + + /** + * The deferred benchmark instance. + * + * @memberOf Benchmark.Deferred + * @type Object + */ + 'benchmark': null, + + /** + * The number of deferred cycles performed while benchmarking. + * + * @memberOf Benchmark.Deferred + * @type Number + */ + 'cycles': 0, + + /** + * The time taken to complete the deferred benchmark (secs). + * + * @memberOf Benchmark.Deferred + * @type Number + */ + 'elapsed': 0, + + /** + * A timestamp of when the deferred benchmark started (ms). + * + * @memberOf Benchmark.Deferred + * @type Number + */ + 'timeStamp': 0, + + // cycles/completes the deferred benchmark + 'resolve': resolve + }); + + /*--------------------------------------------------------------------------*/ + + extend(Event.prototype, { + + /** + * A flag to indicate if the emitters listener iteration is aborted. + * + * @memberOf Benchmark.Event + * @type Boolean + */ + 'aborted': false, + + /** + * A flag to indicate if the default action is cancelled. + * + * @memberOf Benchmark.Event + * @type Boolean + */ + 'cancelled': false, + + /** + * The object whose listeners are currently being processed. + * + * @memberOf Benchmark.Event + * @type Object + */ + 'currentTarget': undefined, + + /** + * The return value of the last executed listener. + * + * @memberOf Benchmark.Event + * @type Mixed + */ + 'result': undefined, + + /** + * The object to which the event was originally emitted. + * + * @memberOf Benchmark.Event + * @type Object + */ + 'target': undefined, + + /** + * A timestamp of when the event was created (ms). + * + * @memberOf Benchmark.Event + * @type Number + */ + 'timeStamp': 0, + + /** + * The event type. + * + * @memberOf Benchmark.Event + * @type String + */ + 'type': '' + }); + + /*--------------------------------------------------------------------------*/ + + /** + * The default options copied by suite instances. + * + * @static + * @memberOf Benchmark.Suite + * @type Object + */ + Suite.options = { + + /** + * The name of the suite. + * + * @memberOf Benchmark.Suite.options + * @type String + */ + 'name': undefined + }; + + /*--------------------------------------------------------------------------*/ + + extend(Suite.prototype, { + + /** + * The number of benchmarks in the suite. + * + * @memberOf Benchmark.Suite + * @type Number + */ + 'length': 0, + + /** + * A score computed using the normalized result of each benchmark in the suite. + * + * @memberOf Benchmark.Suite + * @type Number + */ + 'score': 0, + + /** + * A flag to indicate if the suite is aborted. + * + * @memberOf Benchmark.Suite + * @type Boolean + */ + 'aborted': false, + + /** + * A flag to indicate if the suite is running. + * + * @memberOf Benchmark.Suite + * @type Boolean + */ + 'running': false, + + /** + * An `Array#forEach` like method. + * Callbacks may terminate the loop by explicitly returning `false`. + * + * @memberOf Benchmark.Suite + * @param {Function} callback The function called per iteration. + * @returns {Object} The suite iterated over. + */ + 'forEach': methodize(forEach), + + /** + * An `Array#indexOf` like method. + * + * @memberOf Benchmark.Suite + * @param {Mixed} value The value to search for. + * @returns {Number} The index of the matched value or `-1`. + */ + 'indexOf': methodize(indexOf), + + /** + * Invokes a method on all benchmarks in the suite. + * + * @memberOf Benchmark.Suite + * @param {String|Object} name The name of the method to invoke OR options object. + * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with. + * @returns {Array} A new array of values returned from each method invoked. + */ + 'invoke': methodize(invoke), + + /** + * Converts the suite of benchmarks to a string. + * + * @memberOf Benchmark.Suite + * @param {String} [separator=','] A string to separate each element of the array. + * @returns {String} The string. + */ + 'join': [].join, + + /** + * An `Array#map` like method. + * + * @memberOf Benchmark.Suite + * @param {Function} callback The function called per iteration. + * @returns {Array} A new array of values returned by the callback. + */ + 'map': methodize(map), + + /** + * Retrieves the value of a specified property from all benchmarks in the suite. + * + * @memberOf Benchmark.Suite + * @param {String} property The property to pluck. + * @returns {Array} A new array of property values. + */ + 'pluck': methodize(pluck), + + /** + * Removes the last benchmark from the suite and returns it. + * + * @memberOf Benchmark.Suite + * @returns {Mixed} The removed benchmark. + */ + 'pop': [].pop, + + /** + * Appends benchmarks to the suite. + * + * @memberOf Benchmark.Suite + * @returns {Number} The suite's new length. + */ + 'push': [].push, + + /** + * Sorts the benchmarks of the suite. + * + * @memberOf Benchmark.Suite + * @param {Function} [compareFn=null] A function that defines the sort order. + * @returns {Object} The sorted suite. + */ + 'sort': [].sort, + + /** + * An `Array#reduce` like method. + * + * @memberOf Benchmark.Suite + * @param {Function} callback The function called per iteration. + * @param {Mixed} accumulator Initial value of the accumulator. + * @returns {Mixed} The accumulator. + */ + 'reduce': methodize(reduce), + + // aborts all benchmarks in the suite + 'abort': abortSuite, + + // adds a benchmark to the suite + 'add': add, + + // creates a new suite with cloned benchmarks + 'clone': cloneSuite, + + // executes listeners of a specified type + 'emit': emit, + + // creates a new suite of filtered benchmarks + 'filter': filterSuite, + + // get listeners + 'listeners': listeners, + + // unregister listeners + 'off': off, + + // register listeners + 'on': on, + + // resets all benchmarks in the suite + 'reset': resetSuite, + + // runs all benchmarks in the suite + 'run': runSuite, + + // array methods + 'concat': concat, + + 'reverse': reverse, + + 'shift': shift, + + 'slice': slice, + + 'splice': splice, + + 'unshift': unshift + }); + + /*--------------------------------------------------------------------------*/ + + // expose Deferred, Event and Suite + extend(Benchmark, { + 'Deferred': Deferred, + 'Event': Event, + 'Suite': Suite + }); + + // expose Benchmark + // some AMD build optimizers, like r.js, check for specific condition patterns like the following: + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + // define as an anonymous module so, through path mapping, it can be aliased + define(function() { + return Benchmark; + }); + } + // check for `exports` after `define` in case a build optimizer adds an `exports` object + else if (freeExports) { + // in Node.js or RingoJS v0.8.0+ + if (typeof module == 'object' && module && module.exports == freeExports) { + (module.exports = Benchmark).Benchmark = Benchmark; + } + // in Narwhal or RingoJS v0.7.0- + else { + freeExports.Benchmark = Benchmark; + } + } + // in a browser or Rhino + else { + // use square bracket notation so Closure Compiler won't munge `Benchmark` + // http://code.google.com/closure/compiler/docs/api-tutorial3.html#export + window['Benchmark'] = Benchmark; + } + + // trigger clock's lazy define early to avoid a security error + if (support.air) { + clock({ '_original': { 'fn': noop, 'count': 1, 'options': {} } }); + } +}(this)); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/platform.js/LICENSE.txt b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/platform.js/LICENSE.txt new file mode 100644 index 000000000..a7501f98d --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/platform.js/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright 2011-2013 John-David Dalton + +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/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/platform.js/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/platform.js/README.md new file mode 100644 index 000000000..c2f1cb632 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/platform.js/README.md @@ -0,0 +1,98 @@ +# Platform.js v1.0.0 + +A platform detection library that works on nearly all JavaScript platforms1. + +## Disclaimer + +Platform.js is for informational purposes only and **not** intended as a substitution for [feature detection/inference](http://allyoucanleet.com/post/18087210413/feature-testing-costs#screencast2) checks. + +## BestieJS + +Platform.js is part of the BestieJS *"Best in Class"* module collection. This means we promote solid browser/environment support, ES5 precedents, unit testing, and plenty of documentation. + +## Documentation + +The documentation for Platform.js can be viewed here: [/doc/README.md](https://github.com/bestiejs/platform.js/blob/master/doc/README.md#readme) + +For a list of upcoming features, check out our [roadmap](https://github.com/bestiejs/platform.js/wiki/Roadmap). + +## Support + +Platform.js has been tested in at least Adobe AIR 3.1, Chrome 5-21, Firefox 1-14, IE 6-9, Opera 9.25-12, Safari 3-6, Node.js 0.8.6, Narwhal 0.3.2, RingoJS 0.8, and Rhino 1.7RC5. + +## Installation and usage + +In a browser or Adobe AIR: + +```html + +``` + +Via [npm](http://npmjs.org/): + +```bash +npm install platform +``` + +In [Node.js](http://nodejs.org/) and [RingoJS](http://ringojs.org/): + +```js +var platform = require('platform'); +``` + +In [Rhino](http://www.mozilla.org/rhino/): + +```js +load('platform.js'); +``` + +In an AMD loader like [RequireJS](http://requirejs.org/): + +```js +require({ + 'paths': { + 'platform': 'path/to/platform' + } +}, +['platform'], function(platform) { + console.log(platform.name); +}); +``` + +Usage example: + +```js +// on IE10 x86 platform preview running in IE7 compatibility mode on Windows 7 64 bit edition +platform.name; // 'IE' +platform.version; // '10.0' +platform.layout; // 'Trident' +platform.os; // 'Windows Server 2008 R2 / 7 x64' +platform.description; // 'IE 10.0 x86 (platform preview; running in IE 7 mode) on Windows Server 2008 R2 / 7 x64' + +// or on an iPad +platform.name; // 'Safari' +platform.version; // '5.1' +platform.product; // 'iPad' +platform.manufacturer; // 'Apple' +platform.layout; // 'WebKit' +platform.os; // 'iOS 5.0' +platform.description; // 'Safari 5.1 on Apple iPad (iOS 5.0)' + +// or parsing a given UA string +var info = platform.parse('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7.2; en; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 11.52'); +info.name; // 'Opera' +info.version; // '11.52' +info.layout; // 'Presto' +info.os; // 'Mac OS X 10.7.2' +info.description; // 'Opera 11.52 (identifying as Firefox 4.0) on Mac OS X 10.7.2' +``` + +## Author + +* [John-David Dalton](http://allyoucanleet.com/) + [![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") + +## Contributors + +* [Mathias Bynens](http://mathiasbynens.be/) + [![twitter/mathias](http://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/platform.js/platform.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/platform.js/platform.js new file mode 100644 index 000000000..d643c1883 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/platform.js/platform.js @@ -0,0 +1,996 @@ +/*! + * Platform.js v1.0.0 + * Copyright 2010-2013 John-David Dalton + * Available under MIT license + */ +;(function(window) { + 'use strict'; + + /** Backup possible window/global object */ + var oldWin = window; + + /** Detect free variable `exports` */ + var freeExports = typeof exports == 'object' && exports; + + /** Detect free variable `global` */ + var freeGlobal = typeof global == 'object' && global && + (global == global.global ? (window = global) : global); + + /** Opera regexp */ + var reOpera = /Opera/; + + /** Used to resolve a value's internal [[Class]] */ + var toString = {}.toString; + + /** Detect Java environment */ + var java = /Java/.test(getClassOf(window.java)) && window.java; + + /** A character to represent alpha */ + var alpha = java ? 'a' : '\u03b1'; + + /** A character to represent beta */ + var beta = java ? 'b' : '\u03b2'; + + /** Browser document object */ + var doc = window.document || {}; + + /** Used to check for own properties of an object */ + var hasOwnProperty = {}.hasOwnProperty; + + /** Browser navigator object */ + var nav = window.navigator || {}; + + /** + * Detect Opera browser + * http://www.howtocreate.co.uk/operaStuff/operaObject.html + * http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#operamini + */ + var opera = window.operamini || window.opera; + + /** Opera [[Class]] */ + var operaClass = reOpera.test(operaClass = getClassOf(opera)) ? operaClass : (opera = null); + + /** Possible global object */ + var thisBinding = this; + + /** Browser user agent string */ + var userAgent = nav.userAgent || ''; + + /*--------------------------------------------------------------------------*/ + + /** + * Capitalizes a string value. + * + * @private + * @param {String} string The string to capitalize. + * @returns {String} The capitalized string. + */ + function capitalize(string) { + string = String(string); + return string.charAt(0).toUpperCase() + string.slice(1); + } + + /** + * An iteration utility for arrays and objects. + * + * @private + * @param {Array|Object} object The object to iterate over. + * @param {Function} callback The function called per iteration. + */ + function each(object, callback) { + var index = -1, + length = object.length; + + if (length == length >>> 0) { + while (++index < length) { + callback(object[index], index, object); + } + } else { + forOwn(object, callback); + } + } + + /** + * Trim and conditionally capitalize string values. + * + * @private + * @param {String} string The string to format. + * @returns {String} The formatted string. + */ + function format(string) { + string = trim(string); + return /^(?:webOS|i(?:OS|P))/.test(string) + ? string + : capitalize(string); + } + + /** + * Iterates over an object's own properties, executing the `callback` for each. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} callback The function executed per own property. + */ + function forOwn(object, callback) { + for (var key in object) { + hasKey(object, key) && callback(object[key], key, object); + } + } + + /** + * Gets the internal [[Class]] of a value. + * + * @private + * @param {Mixed} value The value. + * @returns {String} The [[Class]]. + */ + function getClassOf(value) { + return value == null + ? capitalize(value) + : toString.call(value).slice(8, -1); + } + + /** + * Checks if an object has the specified key as a direct property. + * + * @private + * @param {Object} object The object to check. + * @param {String} key The key to check for. + * @returns {Boolean} Returns `true` if key is a direct property, else `false`. + */ + function hasKey() { + // lazy define for others (not as accurate) + hasKey = function(object, key) { + var parent = object != null && (object.constructor || Object).prototype; + return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]); + }; + // for modern browsers + if (getClassOf(hasOwnProperty) == 'Function') { + hasKey = function(object, key) { + return object != null && hasOwnProperty.call(object, key); + }; + } + // for Safari 2 + else if ({}.__proto__ == Object.prototype) { + hasKey = function(object, key) { + var result = false; + if (object != null) { + object = Object(object); + object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0]; + } + return result; + }; + } + return hasKey.apply(this, arguments); + } + + /** + * Host objects can return type values that are different from their actual + * data type. The objects we are concerned with usually return non-primitive + * types of object, function, or unknown. + * + * @private + * @param {Mixed} object The owner of the property. + * @param {String} property The property to check. + * @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`. + */ + function isHostType(object, property) { + var type = object != null ? typeof object[property] : 'number'; + return !/^(?:boolean|number|string|undefined)$/.test(type) && + (type == 'object' ? !!object[property] : true); + } + + /** + * Prepares a string for use in a RegExp constructor by making hyphens and + * spaces optional. + * + * @private + * @param {String} string The string to qualify. + * @returns {String} The qualified string. + */ + function qualify(string) { + return String(string).replace(/([ -])(?!$)/g, '$1?'); + } + + /** + * A bare-bones` Array#reduce` like utility function. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function called per iteration. + * @param {Mixed} accumulator Initial value of the accumulator. + * @returns {Mixed} The accumulator. + */ + function reduce(array, callback) { + var accumulator = null; + each(array, function(value, index) { + accumulator = callback(accumulator, value, index, array); + }); + return accumulator; + } + + /** + * Removes leading and trailing whitespace from a string. + * + * @private + * @param {String} string The string to trim. + * @returns {String} The trimmed string. + */ + function trim(string) { + return String(string).replace(/^ +| +$/g, ''); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a new platform object. + * + * @memberOf platform + * @param {String} [ua = navigator.userAgent] The user agent string. + * @returns {Object} A platform object. + */ + function parse(ua) { + + ua || (ua = userAgent); + + /** Temporary variable used over the script's lifetime */ + var data; + + /** The CPU architecture */ + var arch = ua; + + /** Platform description array */ + var description = []; + + /** Platform alpha/beta indicator */ + var prerelease = null; + + /** A flag to indicate that environment features should be used to resolve the platform */ + var useFeatures = ua == userAgent; + + /** The browser/environment version */ + var version = useFeatures && opera && typeof opera.version == 'function' && opera.version(); + + /* Detectable layout engines (order is important) */ + var layout = getLayout([ + { 'label': 'WebKit', 'pattern': 'AppleWebKit' }, + 'iCab', + 'Presto', + 'NetFront', + 'Tasman', + 'Trident', + 'KHTML', + 'Gecko' + ]); + + /* Detectable browser names (order is important) */ + var name = getName([ + 'Adobe AIR', + 'Arora', + 'Avant Browser', + 'Camino', + 'Epiphany', + 'Fennec', + 'Flock', + 'Galeon', + 'GreenBrowser', + 'iCab', + 'Iceweasel', + 'Iron', + 'K-Meleon', + 'Konqueror', + 'Lunascape', + 'Maxthon', + 'Midori', + 'Nook Browser', + 'PhantomJS', + 'Raven', + 'Rekonq', + 'RockMelt', + 'SeaMonkey', + { 'label': 'Silk', 'pattern': '(?:Cloud9|Silk-Accelerated)' }, + 'Sleipnir', + 'SlimBrowser', + 'Sunrise', + 'Swiftfox', + 'WebPositive', + 'Opera Mini', + 'Opera', + 'Chrome', + { 'label': 'Chrome Mobile', 'pattern': '(?:CriOS|CrMo)' }, + { 'label': 'Firefox', 'pattern': '(?:Firefox|Minefield)' }, + { 'label': 'IE', 'pattern': 'MSIE' }, + 'Safari' + ]); + + /* Detectable products (order is important) */ + var product = getProduct([ + 'BlackBerry', + { 'label': 'Galaxy S', 'pattern': 'GT-I9000' }, + { 'label': 'Galaxy S2', 'pattern': 'GT-I9100' }, + 'Google TV', + 'iPad', + 'iPod', + 'iPhone', + 'Kindle', + { 'label': 'Kindle Fire', 'pattern': '(?:Cloud9|Silk-Accelerated)' }, + 'Nook', + 'PlayBook', + 'PlayStation Vita', + 'TouchPad', + 'Transformer', + 'Xoom' + ]); + + /* Detectable manufacturers */ + var manufacturer = getManufacturer({ + 'Apple': { 'iPad': 1, 'iPhone': 1, 'iPod': 1 }, + 'Amazon': { 'Kindle': 1, 'Kindle Fire': 1 }, + 'Asus': { 'Transformer': 1 }, + 'Barnes & Noble': { 'Nook': 1 }, + 'BlackBerry': { 'PlayBook': 1 }, + 'Google': { 'Google TV': 1 }, + 'HP': { 'TouchPad': 1 }, + 'LG': { }, + 'Motorola': { 'Xoom': 1 }, + 'Nokia': { }, + 'Samsung': { 'Galaxy S': 1, 'Galaxy S2': 1 }, + 'Sony': { 'PlayStation Vita': 1 } + }); + + /* Detectable OSes (order is important) */ + var os = getOS([ + 'Android', + 'CentOS', + 'Debian', + 'Fedora', + 'FreeBSD', + 'Gentoo', + 'Haiku', + 'Kubuntu', + 'Linux Mint', + 'Red Hat', + 'SuSE', + 'Ubuntu', + 'Xubuntu', + 'Cygwin', + 'Symbian OS', + 'hpwOS', + 'webOS ', + 'webOS', + 'Tablet OS', + 'Linux', + 'Mac OS X', + 'Macintosh', + 'Mac', + 'Windows 98;', + 'Windows ' + ]); + + /*------------------------------------------------------------------------*/ + + /** + * Picks the layout engine from an array of guesses. + * + * @private + * @param {Array} guesses An array of guesses. + * @returns {String|Null} The detected layout engine. + */ + function getLayout(guesses) { + return reduce(guesses, function(result, guess) { + return result || RegExp('\\b' + ( + guess.pattern || qualify(guess) + ) + '\\b', 'i').exec(ua) && (guess.label || guess); + }); + } + + /** + * Picks the manufacturer from an array of guesses. + * + * @private + * @param {Array} guesses An array of guesses. + * @returns {String|Null} The detected manufacturer. + */ + function getManufacturer(guesses) { + return reduce(guesses, function(result, value, key) { + // lookup the manufacturer by product or scan the UA for the manufacturer + return result || ( + value[product] || + value[0/*Opera 9.25 fix*/, /^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] || + RegExp('\\b' + (key.pattern || qualify(key)) + '(?:\\b|\\w*\\d)', 'i').exec(ua) + ) && (key.label || key); + }); + } + + /** + * Picks the browser name from an array of guesses. + * + * @private + * @param {Array} guesses An array of guesses. + * @returns {String|Null} The detected browser name. + */ + function getName(guesses) { + return reduce(guesses, function(result, guess) { + return result || RegExp('\\b' + ( + guess.pattern || qualify(guess) + ) + '\\b', 'i').exec(ua) && (guess.label || guess); + }); + } + + /** + * Picks the OS name from an array of guesses. + * + * @private + * @param {Array} guesses An array of guesses. + * @returns {String|Null} The detected OS name. + */ + function getOS(guesses) { + return reduce(guesses, function(result, guess) { + var pattern = guess.pattern || qualify(guess); + if (!result && (result = + RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua))) { + // platform tokens defined at + // http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx + // http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx + data = { + '6.2': '8', + '6.1': 'Server 2008 R2 / 7', + '6.0': 'Server 2008 / Vista', + '5.2': 'Server 2003 / XP 64-bit', + '5.1': 'XP', + '5.01': '2000 SP1', + '5.0': '2000', + '4.0': 'NT', + '4.90': 'ME' + }; + // detect Windows version from platform tokens + if (/^Win/i.test(result) && + (data = data[0/*Opera 9.25 fix*/, /[\d.]+$/.exec(result)])) { + result = 'Windows ' + data; + } + // correct character case and cleanup + result = format(String(result) + .replace(RegExp(pattern, 'i'), guess.label || guess) + .replace(/ ce$/i, ' CE') + .replace(/hpw/i, 'web') + .replace(/Macintosh/, 'Mac OS') + .replace(/_PowerPC/i, ' OS') + .replace(/(OS X) [^ \d]+/i, '$1') + .replace(/\/(\d)/, ' $1') + .replace(/_/g, '.') + .replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '') + .replace(/x86\.64/gi, 'x86_64') + .split(' on ')[0]); + } + return result; + }); + } + + /** + * Picks the product name from an array of guesses. + * + * @private + * @param {Array} guesses An array of guesses. + * @returns {String|Null} The detected product name. + */ + function getProduct(guesses) { + return reduce(guesses, function(result, guess) { + var pattern = guess.pattern || qualify(guess); + if (!result && (result = + RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) || + RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua) + )) { + // split by forward slash and append product version if needed + if ((result = String(guess.label || result).split('/'))[1] && !/[\d.]+/.test(result[0])) { + result[0] += ' ' + result[1]; + } + // correct character case and cleanup + guess = guess.label || guess; + result = format(result[0] + .replace(RegExp(pattern, 'i'), guess) + .replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ') + .replace(RegExp('(' + guess + ')(\\w)', 'i'), '$1 $2')); + } + return result; + }); + } + + /** + * Resolves the version using an array of UA patterns. + * + * @private + * @param {Array} patterns An array of UA patterns. + * @returns {String|Null} The detected version. + */ + function getVersion(patterns) { + return reduce(patterns, function(result, pattern) { + return result || (RegExp(pattern + + '(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null; + }); + } + + /*------------------------------------------------------------------------*/ + + /** + * Returns `platform.description` when the platform object is coerced to a string. + * + * @name toString + * @memberOf platform + * @returns {String} Returns `platform.description` if available, else an empty string. + */ + function toStringPlatform() { + return this.description || ''; + } + + /*------------------------------------------------------------------------*/ + + // convert layout to an array so we can add extra details + layout && (layout = [layout]); + + // detect product names that contain their manufacturer's name + if (manufacturer && !product) { + product = getProduct([manufacturer]); + } + // clean up Google TV + if ((data = /Google TV/.exec(product))) { + product = data[0]; + } + // detect simulators + if (/\bSimulator\b/i.test(ua)) { + product = (product ? product + ' ' : '') + 'Simulator'; + } + // detect iOS + if (/^iP/.test(product)) { + name || (name = 'Safari'); + os = 'iOS' + ((data = / OS ([\d_]+)/i.exec(ua)) + ? ' ' + data[1].replace(/_/g, '.') + : ''); + } + // detect Kubuntu + else if (name == 'Konqueror' && !/buntu/i.test(os)) { + os = 'Kubuntu'; + } + // detect Android browsers + else if (manufacturer && manufacturer != 'Google' && + /Chrome|Vita/.test(name + ';' + product)) { + name = 'Android Browser'; + os = /Android/.test(os) ? os : 'Android'; + } + // detect false positives for Firefox/Safari + else if (!name || (data = !/\bMinefield\b/i.test(ua) && /Firefox|Safari/.exec(name))) { + // escape the `/` for Firefox 1 + if (name && !product && /[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) { + // clear name of false positives + name = null; + } + // reassign a generic name + if ((data = product || manufacturer || os) && + (product || manufacturer || /Android|Symbian OS|Tablet OS|webOS/.test(os))) { + name = /[a-z]+(?: Hat)?/i.exec(/Android/.test(os) ? os : data) + ' Browser'; + } + } + // detect non-Opera versions (order is important) + if (!version) { + version = getVersion([ + '(?:Cloud9|CriOS|CrMo|Opera ?Mini|Raven|Silk(?!/[\\d.]+$))', + 'Version', + qualify(name), + '(?:Firefox|Minefield|NetFront)' + ]); + } + // detect stubborn layout engines + if (layout == 'iCab' && parseFloat(version) > 3) { + layout = ['WebKit']; + } else if (data = + /Opera/.test(name) && 'Presto' || + /\b(?:Midori|Nook|Safari)\b/i.test(ua) && 'WebKit' || + !layout && /\bMSIE\b/i.test(ua) && (/^Mac/.test(os) ? 'Tasman' : 'Trident')) { + layout = [data]; + } + // leverage environment features + if (useFeatures) { + // detect server-side environments + // Rhino has a global function while others have a global object + if (isHostType(window, 'global')) { + if (java) { + data = java.lang.System; + arch = data.getProperty('os.arch'); + os = os || data.getProperty('os.name') + ' ' + data.getProperty('os.version'); + } + if (typeof exports == 'object' && exports) { + // if `thisBinding` is the [ModuleScope] + if (thisBinding == oldWin && typeof system == 'object' && (data = [system])[0]) { + os || (os = data[0].os || null); + try { + data[1] = require('ringo/engine').version; + version = data[1].join('.'); + name = 'RingoJS'; + } catch(e) { + if (data[0].global == freeGlobal) { + name = 'Narwhal'; + } + } + } else if (typeof process == 'object' && (data = process)) { + name = 'Node.js'; + arch = data.arch; + os = data.platform; + version = /[\d.]+/.exec(data.version)[0]; + } + } else if (getClassOf(window.environment) == 'Environment') { + name = 'Rhino'; + } + } + // detect Adobe AIR + else if (getClassOf(data = window.runtime) == 'ScriptBridgingProxyObject') { + name = 'Adobe AIR'; + os = data.flash.system.Capabilities.os; + } + // detect PhantomJS + else if (getClassOf(data = window.phantom) == 'RuntimeObject') { + name = 'PhantomJS'; + version = (data = data.version || null) && (data.major + '.' + data.minor + '.' + data.patch); + } + // detect IE compatibility modes + else if (typeof doc.documentMode == 'number' && (data = /\bTrident\/(\d+)/i.exec(ua))) { + // we're in compatibility mode when the Trident version + 4 doesn't + // equal the document mode + version = [version, doc.documentMode]; + if ((data = +data[1] + 4) != version[1]) { + description.push('IE ' + version[1] + ' mode'); + layout[1] = ''; + version[1] = data; + } + version = name == 'IE' ? String(version[1].toFixed(1)) : version[0]; + } + os = os && format(os); + } + // detect prerelease phases + if (version && (data = + /(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version) || + /(?:alpha|beta)(?: ?\d)?/i.exec(ua + ';' + (useFeatures && nav.appMinorVersion)) || + /\bMinefield\b/i.test(ua) && 'a')) { + prerelease = /b/i.test(data) ? 'beta' : 'alpha'; + version = version.replace(RegExp(data + '\\+?$'), '') + + (prerelease == 'beta' ? beta : alpha) + (/\d+\+?/.exec(data) || ''); + } + // rename code name "Fennec" + if (name == 'Fennec') { + name = 'Firefox Mobile'; + } + // obscure Maxthon's unreliable version + else if (name == 'Maxthon' && version) { + version = version.replace(/\.[\d.]+/, '.x'); + } + // detect Silk desktop/accelerated modes + else if (name == 'Silk') { + if (!/Mobi/i.test(ua)) { + os = 'Android'; + description.unshift('desktop mode'); + } + if (/Accelerated *= *true/i.test(ua)) { + description.unshift('accelerated'); + } + } + // detect Windows Phone desktop mode + else if (name == 'IE' && (data = (/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua) || 0)[1])) { + name += ' Mobile'; + os = 'Windows Phone OS ' + data + '.x'; + description.unshift('desktop mode'); + } + // add mobile postfix + else if ((name == 'IE' || name && !product && !/Browser|Mobi/.test(name)) && + (os == 'Windows CE' || /Mobi/i.test(ua))) { + name += ' Mobile'; + } + // detect IE platform preview + else if (name == 'IE' && useFeatures && typeof external == 'object' && !external) { + description.unshift('platform preview'); + } + // detect BlackBerry OS version + // http://docs.blackberry.com/en/developers/deliverables/18169/HTTP_headers_sent_by_BB_Browser_1234911_11.jsp + else if (/BlackBerry/.test(product) && (data = + (RegExp(product.replace(/ +/g, ' *') + '/([.\\d]+)', 'i').exec(ua) || 0)[1] || + version)) { + os = 'Device Software ' + data; + version = null; + } + // detect Opera identifying/masking itself as another browser + // http://www.opera.com/support/kb/view/843/ + else if (this != forOwn && ( + (useFeatures && opera) || + (/Opera/.test(name) && /\b(?:MSIE|Firefox)\b/i.test(ua)) || + (name == 'Firefox' && /OS X (?:\d+\.){2,}/.test(os)) || + (name == 'IE' && ( + (os && !/^Win/.test(os) && version > 5.5) || + /Windows XP/.test(os) && version > 8 || + version == 8 && !/Trident/.test(ua) + )) + ) && !reOpera.test(data = parse.call(forOwn, ua.replace(reOpera, '') + ';')) && data.name) { + + // when "indentifying", the UA contains both Opera and the other browser's name + data = 'ing as ' + data.name + ((data = data.version) ? ' ' + data : ''); + if (reOpera.test(name)) { + if (/IE/.test(data) && os == 'Mac OS') { + os = null; + } + data = 'identify' + data; + } + // when "masking", the UA contains only the other browser's name + else { + data = 'mask' + data; + if (operaClass) { + name = format(operaClass.replace(/([a-z])([A-Z])/g, '$1 $2')); + } else { + name = 'Opera'; + } + if (/IE/.test(data)) { + os = null; + } + if (!useFeatures) { + version = null; + } + } + layout = ['Presto']; + description.push(data); + } + // detect WebKit Nightly and approximate Chrome/Safari versions + if ((data = (/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua) || 0)[1])) { + // correct build for numeric comparison + // (e.g. "532.5" becomes "532.05") + data = [parseFloat(data.replace(/\.(\d)$/, '.0$1')), data]; + // nightly builds are postfixed with a `+` + if (name == 'Safari' && data[1].slice(-1) == '+') { + name = 'WebKit Nightly'; + prerelease = 'alpha'; + version = data[1].slice(0, -1); + } + // clear incorrect browser versions + else if (version == data[1] || + version == (/\bSafari\/([\d.]+\+?)/i.exec(ua) || 0)[1]) { + version = null; + } + // use the full Chrome version when available + data = [data[0], (/\bChrome\/([\d.]+)/i.exec(ua) || 0)[1]]; + + // detect JavaScriptCore + // http://stackoverflow.com/questions/6768474/how-can-i-detect-which-javascript-engine-v8-or-jsc-is-used-at-runtime-in-androi + if (!useFeatures || (/internal|\n/i.test(toString.toString()) && !data[1])) { + layout[1] = 'like Safari'; + data = (data = data[0], data < 400 ? 1 : data < 500 ? 2 : data < 526 ? 3 : data < 533 ? 4 : data < 534 ? '4+' : data < 535 ? 5 : '5'); + } else { + layout[1] = 'like Chrome'; + data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.05 ? 3 : data < 533 ? 4 : data < 534.03 ? 5 : data < 534.07 ? 6 : data < 534.10 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.30 ? 11 : data < 535.01 ? 12 : data < 535.02 ? '13+' : data < 535.07 ? 15 : data < 535.11 ? 16 : data < 535.19 ? 17 : data < 536.05 ? 18 : data < 536.10 ? 19 : data < 537.01 ? 20 : '21'); + } + // add the postfix of ".x" or "+" for approximate versions + layout[1] += ' ' + (data += typeof data == 'number' ? '.x' : /[.+]/.test(data) ? '' : '+'); + // obscure version for some Safari 1-2 releases + if (name == 'Safari' && (!version || parseInt(version) > 45)) { + version = data; + } + } + // detect Opera desktop modes + if (name == 'Opera' && (data = /(?:zbov|zvav)$/.exec(os))) { + name += ' '; + description.unshift('desktop mode'); + if (data == 'zvav') { + name += 'Mini'; + version = null; + } else { + name += 'Mobile'; + } + } + // detect Chrome desktop mode + else if (name == 'Safari' && /Chrome/.exec(layout[1])) { + description.unshift('desktop mode'); + name = 'Chrome Mobile'; + version = null; + + if (/Mac OS X/.test(os)) { + manufacturer = 'Apple'; + os = 'iOS 4.3+'; + } else { + os = null; + } + } + // strip incorrect OS versions + if (version && version.indexOf(data = /[\d.]+$/.exec(os)) == 0 && + ua.indexOf('/' + data + '-') > -1) { + os = trim(os.replace(data, '')); + } + // add layout engine + if (layout && !/Avant|Nook/.test(name) && ( + /Browser|Lunascape|Maxthon/.test(name) || + /^(?:Adobe|Arora|Midori|Phantom|Rekonq|Rock|Sleipnir|Web)/.test(name) && layout[1])) { + // don't add layout details to description if they are falsey + (data = layout[layout.length - 1]) && description.push(data); + } + // combine contextual information + if (description.length) { + description = ['(' + description.join('; ') + ')']; + } + // append manufacturer + if (manufacturer && product && product.indexOf(manufacturer) < 0) { + description.push('on ' + manufacturer); + } + // append product + if (product) { + description.push((/^on /.test(description[description.length -1]) ? '' : 'on ') + product); + } + // parse OS into an object + if (os) { + data = / ([\d.+]+)$/.exec(os); + os = { + 'architecture': 32, + 'family': data ? os.replace(data[0], '') : os, + 'version': data ? data[1] : null, + 'toString': function() { + var version = this.version; + return this.family + (version ? ' ' + version : '') + (this.architecture == 64 ? ' 64-bit' : ''); + } + }; + } + // add browser/OS architecture + if ((data = /\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch)) && !/\bi686\b/i.test(arch)) { + if (os) { + os.architecture = 64; + os.family = os.family.replace(RegExp(' *' + data), ''); + } + if (name && (/WOW64/i.test(ua) || + (useFeatures && /\w(?:86|32)$/.test(nav.cpuClass || nav.platform)))) { + description.unshift('32-bit'); + } + } + + ua || (ua = null); + + /*------------------------------------------------------------------------*/ + + /** + * The platform object. + * + * @name platform + * @type Object + */ + return { + + /** + * The browser/environment version. + * + * @memberOf platform + * @type String|Null + */ + 'version': name && version && (description.unshift(version), version), + + /** + * The name of the browser/environment. + * + * @memberOf platform + * @type String|Null + */ + 'name': name && (description.unshift(name), name), + + /** + * The name of the operating system. + * + * @memberOf platform + * @type Object + */ + 'os': os + ? (name && + !(os == String(os).split(' ')[0] && (os == name.split(' ')[0] || product)) && + description.push(product ? '(' + os + ')' : 'on ' + os), os) + : { + + /** + * The CPU architecture the OS is built for. + * + * @memberOf platform.os + * @type Number|Null + */ + 'architecture': null, + + /** + * The family of the OS. + * + * @memberOf platform.os + * @type String|Null + */ + 'family': null, + + /** + * The version of the OS. + * + * @memberOf platform.os + * @type String|Null + */ + 'version': null, + + /** + * Returns the OS string. + * + * @memberOf platform.os + * @returns {String} The OS string. + */ + 'toString': function() { return 'null'; } + }, + + /** + * The platform description. + * + * @memberOf platform + * @type String|Null + */ + 'description': description.length ? description.join(' ') : ua, + + /** + * The name of the browser layout engine. + * + * @memberOf platform + * @type String|Null + */ + 'layout': layout && layout[0], + + /** + * The name of the product's manufacturer. + * + * @memberOf platform + * @type String|Null + */ + 'manufacturer': manufacturer, + + /** + * The alpha/beta release indicator. + * + * @memberOf platform + * @type String|Null + */ + 'prerelease': prerelease, + + /** + * The name of the product hosting the browser. + * + * @memberOf platform + * @type String|Null + */ + 'product': product, + + /** + * The browser's user agent string. + * + * @memberOf platform + * @type String|Null + */ + 'ua': ua, + + // parses a user agent string into a platform object + 'parse': parse, + + // returns the platform description + 'toString': toStringPlatform + }; + } + + /*--------------------------------------------------------------------------*/ + + // expose platform + // some AMD build optimizers, like r.js, check for specific condition patterns like the following: + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + // define as an anonymous module so, through path mapping, it can be aliased + define(function() { + return parse(); + }); + } + // check for `exports` after `define` in case a build optimizer adds an `exports` object + else if (freeExports) { + // in Narwhal, Node.js, or RingoJS + forOwn(parse(), function(value, key) { + freeExports[key] = value; + }); + } + // in a browser or Rhino + else { + // use square bracket notation so Closure Compiler won't munge `platform` + // http://code.google.com/closure/compiler/docs/api-tutorial3.html#export + window['platform'] = parse(); + } +}(this)); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit-clib/LICENSE.txt b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit-clib/LICENSE.txt new file mode 100644 index 000000000..a7501f98d --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit-clib/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright 2011-2013 John-David Dalton + +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/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit-clib/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit-clib/README.md new file mode 100644 index 000000000..7c2edfa8f --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit-clib/README.md @@ -0,0 +1,58 @@ +# QUnit CLIB v1.2.0 +## command-line interface boilerplate + +QUnit CLIB helps extend QUnit's CLI support to many common CLI environments. + +## Screenshot + +![QUnit CLIB brings QUnit to your favorite shell.](http://i.imgur.com/jpu9l.png) + +## Support + +QUnit CLIB has been tested in at least Node.js 0.4.8-0.8.19, Narwhal v0.3.2, PhantomJS 1.8.1, RingoJS v0.9, and Rhino v1.7RC5. + +## Usage + +```js +(function(window) { + + // use a single "load" function + var load = typeof require == 'function' ? require : window.load; + + // load QUnit and CLIB if needed + var QUnit = + window.QUnit || ( + window.addEventListener || (window.addEventListener = Function.prototype), + window.setTimeout || (window.setTimeout = Function.prototype), + window.QUnit = load('path/to/qunit.js') || window.QUnit, + load('path/to/qunit-clib.js'), + window.addEventListener === Function.prototype && delete window.addEventListener, + window.QUnit + ); + + // explicitly call `QUnit.module()` instead of `module()` + // in case we are in a CLI environment + QUnit.module('A Test Module'); + + test('A Test', function() { + // ... + }); + + // must call `QUnit.start()` if using QUnit < 1.3.0 with Node.js or any + // version of QUnit with Narwhal, PhantomJS, Rhino, or RingoJS + if (!window.document) { + QUnit.start(); + } +}(typeof global == 'object' && global || this)); +``` + +## Footnotes + + 1. QUnit v1.3.0 does not work with Narwhal or Ringo < v0.8.0 + + 2. Rhino v1.7RC4 does not support timeout fallbacks `clearTimeout` and `setTimeout` + +## Author + +* [John-David Dalton](http://allyoucanleet.com/) + [![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit-clib/qunit-clib.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit-clib/qunit-clib.js new file mode 100644 index 000000000..7174febe1 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit-clib/qunit-clib.js @@ -0,0 +1,269 @@ +/*! + * QUnit CLI Boilerplate v1.2.0 + * Copyright 2011-2012 John-David Dalton + * Based on a gist by Jörn Zaefferer + * Available under MIT license + */ +;(function(window) { + 'use strict'; + + /** + * Timeout fallbacks based on the work of Andrea Giammarchi and Weston C. + * https://github.com/WebReflection/wru/blob/master/src/rhinoTimers.js + * http://stackoverflow.com/questions/2261705/how-to-run-a-javascript-function-asynchronously-without-using-settimeout + */ + (function() { + + /** + * Schedules timer-based callbacks. + * + * @private + * @param {Function|String} fn The function to call. + * @oaram {Number} delay The number of milliseconds to delay the `fn` call. + * @param [arg1, arg2, ...] Arguments to invoke `fn` with. + * @param {Boolean} repeated A flag to specify whether `fn` is called repeatedly. + * @returns {Number} The the ID of the timeout. + */ + function schedule(fn, delay, args, repeated) { + // Rhino 1.7RC4 will error assigning `task` below + // https://bugzilla.mozilla.org/show_bug.cgi?id=775566 + var task = ids[++counter] = new JavaAdapter(java.util.TimerTask, { + 'run': function() { + fn.apply(window, args); + } + }); + // support non-functions + if (typeof fn != 'function') { + fn = (function(code) { + code = String(code); + return function() { eval(code); }; + }(fn)); + } + // used by setInterval + if (repeated) { + timer.schedule(task, delay, delay); + } + // used by setTimeout + else { + timer.schedule(task, delay); + } + return counter; + } + + /** + * Clears the delay set by `setInterval` or `setTimeout`. + * + * @memberOf window + * @param {Number} id The ID of the timeout to be cleared. + */ + function clearTimer(id) { + if (ids[id]) { + ids[id].cancel(); + timer.purge(); + delete ids[id]; + } + } + + /** + * Executes a code snippet or function repeatedly, with a delay between each call. + * + * @memberOf window + * @param {Function|String} fn The function to call or string to evaluate. + * @oaram {Number} delay The number of milliseconds to delay each `fn` call. + * @param [arg1, arg2, ...] Arguments to invoke `fn` with. + * @returns {Number} The the ID of the timeout. + */ + function setInterval(fn, delay) { + return schedule(fn, delay, slice.call(arguments, 2), true); + } + + /** + * Executes a code snippet or a function after specified delay. + * + * @memberOf window + * @param {Function|String} fn The function to call or string to evaluate. + * @oaram {Number} delay The number of milliseconds to delay the `fn` call. + * @param [arg1, arg2, ...] Arguments to invoke `fn` with. + * @returns {Number} The the ID of the timeout. + */ + function setTimeout(fn, delay) { + return schedule(fn, delay, slice.call(arguments, 2)); + } + + try { + var counter = 0, + ids = {}, + slice = Array.prototype.slice, + timer = new java.util.Timer; + + window.clearInterval = + window.clearTimeout = clearTimer; + window.setInterval = setInterval; + window.setTimeout = setTimeout; + } catch(e) { } + }()); + + /*--------------------------------------------------------------------------*/ + + (function() { + + /** Used as a horizontal rule in console output */ + var hr = '----------------------------------------'; + + /** Shorten `window.QUnit.QUnit` to `window.QUnit` */ + window.QUnit && (QUnit = QUnit.QUnit || QUnit); + + /** + * A logging callback triggered when all testing is completed. + * + * @memberOf QUnit + * @param {Object} details An object with properties `failed`, `passed`, `runtime`, and `total`. + */ + QUnit.done(function() { + var ran; + return function(details) { + // stop `asyncTest()` from erroneously calling `done()` twice in + // environments w/o timeouts + if (ran) { + return; + } + ran = true; + + console.log(hr); + console.log(' PASS: ' + details.passed + ' FAIL: ' + details.failed + ' TOTAL: ' + details.total); + console.log(' Finished in ' + details.runtime + ' milliseconds.'); + console.log(hr); + + // exit out of Rhino + try { + quit(); + } catch(e) { } + + // exit out of Node.js or PhantomJS + try { + var process = window.process || window.phantom; + if (details.failed) { + console.error('Error: ' + details.failed + ' of ' + details.total + ' tests failed.'); + process.exit(1); + } else { + process.exit(0); + } + } catch(e) { } + }; + }()); + + /** + * A logging callback triggered after every assertion. + * + * @memberOf QUnit + * @param {Object} details An object with properties `actual`, `expected`, `message`, and `result`. + */ + QUnit.log(function(details) { + var expected = details.expected, + result = details.result, + type = typeof expected != 'undefined' ? 'EQ' : 'OK'; + + var assertion = [ + result ? 'PASS' : 'FAIL', + type, + details.message || 'ok' + ]; + + if (!result && type == 'EQ') { + assertion.push('Expected: ' + expected + ', Actual: ' + details.actual); + } + QUnit.config.testStats.assertions.push(assertion.join(' | ')); + }); + + /** + * A logging callback triggered at the start of every test module. + * + * @memberOf QUnit + * @param {Object} details An object with property `name`. + */ + QUnit.moduleStart(function(details) { + console.log(hr); + console.log(details.name); + console.log(hr); + }); + + /** + * Converts an object into a string representation. + * + * @memberOf QUnit + * @type Function + * @param {Object} object The object to stringify. + * @returns {String} The result string. + */ + QUnit.jsDump.parsers.object = (function() { + var func = QUnit.jsDump.parsers.object; + return function(object) { + // fork to support Rhino's error objects + if (typeof object.rhinoException == 'object') { + return object.name + + ' { message: "' + object.message + + '", fileName: "' + object.fileName + + '", lineNumber: ' + object.lineNumber + ' }'; + } + return func(object); + }; + }()); + + /** + * A logging callback triggered after a test is completed. + * + * @memberOf QUnit + * @param {Object} details An object with properties `failed`, `name`, `passed`, and `total`. + */ + QUnit.testDone(function(details) { + var assertions = QUnit.config.testStats.assertions, + testName = details.name; + + if (details.failed > 0) { + console.log(' FAIL - '+ testName); + assertions.forEach(function(value) { + console.log(' ' + value); + }); + } + else { + console.log(' PASS - ' + testName); + } + assertions.length = 0; + }); + + /** + * An object used to hold information about the current running test. + * + * @memberOf QUnit.config + * @type Object + */ + QUnit.config.testStats = { + + /** + * An array of test summaries (pipe separated). + * + * @memberOf QUnit.config.testStats + * @type Array + */ + 'assertions': [] + }; + }()); + + /*--------------------------------------------------------------------------*/ + + // expose shortcuts + // exclude `module` because some environments have it as a built-in object + ('asyncTest deepEqual equal equals expect notDeepEqual notEqual notStrictEqual ' + + 'ok raises same start stop strictEqual test throws').replace(/\S+/g, function(methodName) { + window[methodName] = QUnit[methodName]; + }); + + // add `console.log()` support for Narwhal, Rhino, and RingoJS + if (!window.console && window.print) { + window.console = { 'log': window.print }; + } + // must call `QUnit.start()` in the test file if using QUnit < 1.3.0 with + // Node.js or any version of QUnit with Narwhal, PhantomJS, Rhino, or RingoJS + QUnit.init(); + +}(typeof global == 'object' && global || this)); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit/README.md new file mode 100644 index 000000000..6ab73f57a --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit/README.md @@ -0,0 +1,62 @@ +[QUnit](http://qunitjs.com) - A JavaScript Unit Testing framework. +================================ + +QUnit is a powerful, easy-to-use, JavaScript test suite. It's used by the jQuery +project to test its code and plugins but is capable of testing any generic +JavaScript code (and even capable of testing JavaScript code on the server-side). + +QUnit is especially useful for regression testing: Whenever a bug is reported, +write a test that asserts the existence of that particular bug. Then fix it and +commit both. Every time you work on the code again, run the tests. If the bug +comes up again - a regression - you'll spot it immediately and know how to fix +it, because you know what code you just changed. + +Having good unit test coverage makes safe refactoring easy and cheap. You can +run the tests after each small refactoring step and always know what change +broke something. + +QUnit is similar to other unit testing frameworks like JUnit, but makes use of +the features JavaScript provides and helps with testing code in the browser, e.g. +with its stop/start facilities for testing asynchronous code. + +If you are interested in helping developing QUnit, you are in the right place. +For related discussions, visit the +[QUnit and Testing forum](http://forum.jquery.com/qunit-and-testing). + +Development +----------- + +To submit patches, fork the repository, create a branch for the change. Then implement +the change, run `grunt` to lint and test it, then commit, push and create a pull request. + +Include some background for the change in the commit message and `Fixes #nnn`, referring +to the issue number you're addressing. + +To run `grunt`, you need `node` and `npm`, then `npm install grunt -g`. That gives you a global +grunt binary. For additional grunt tasks, also run `npm install`. + +Releases +-------- + +Install git-extras and run `git changelog` to update History.md. +Update qunit/qunit.js|css and package.json to the release version, commit and +tag, update them again to the next version, commit and push commits and tags +(`git push --tags origin master`). + +Put the 'v' in front of the tag, e.g. `v1.8.0`. Clean up the changelog, removing merge commits +or whitespace cleanups. + +To upload to code.jquery.com (replace $version accordingly), ssh to code.origin.jquery.com: + + cp qunit/qunit.js /var/www/html/code.jquery.com/qunit/qunit-$version.js + cp qunit/qunit.css /var/www/html/code.jquery.com/qunit/qunit-$version.css + +Then update /var/www/html/code.jquery.com/index.html and purge it with: + + curl -s http://code.origin.jquery.com/?reload + +Update web-base-template to link to those files for qunitjs.com. + +Publish to npm via + + npm publish diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit/qunit/qunit.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit/qunit/qunit.js new file mode 100644 index 000000000..302545f40 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/qunit/qunit/qunit.js @@ -0,0 +1,2152 @@ +/** + * QUnit v1.11.0 - A JavaScript Unit Testing Framework + * + * http://qunitjs.com + * + * Copyright 2012 jQuery Foundation and other contributors + * Released under the MIT license. + * http://jquery.org/license + */ + +(function( window ) { + +var QUnit, + assert, + config, + onErrorFnPrev, + testId = 0, + fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""), + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + // Keep a local reference to Date (GH-283) + Date = window.Date, + defined = { + setTimeout: typeof window.setTimeout !== "undefined", + sessionStorage: (function() { + var x = "qunit-test-string"; + try { + sessionStorage.setItem( x, x ); + sessionStorage.removeItem( x ); + return true; + } catch( e ) { + return false; + } + }()) + }, + /** + * Provides a normalized error string, correcting an issue + * with IE 7 (and prior) where Error.prototype.toString is + * not properly implemented + * + * Based on http://es5.github.com/#x15.11.4.4 + * + * @param {String|Error} error + * @return {String} error message + */ + errorString = function( error ) { + var name, message, + errorString = error.toString(); + if ( errorString.substring( 0, 7 ) === "[object" ) { + name = error.name ? error.name.toString() : "Error"; + message = error.message ? error.message.toString() : ""; + if ( name && message ) { + return name + ": " + message; + } else if ( name ) { + return name; + } else if ( message ) { + return message; + } else { + return "Error"; + } + } else { + return errorString; + } + }, + /** + * Makes a clone of an object using only Array or Object as base, + * and copies over the own enumerable properties. + * + * @param {Object} obj + * @return {Object} New object with only the own properties (recursively). + */ + objectValues = function( obj ) { + // Grunt 0.3.x uses an older version of jshint that still has jshint/jshint#392. + /*jshint newcap: false */ + var key, val, + vals = QUnit.is( "array", obj ) ? [] : {}; + for ( key in obj ) { + if ( hasOwn.call( obj, key ) ) { + val = obj[key]; + vals[key] = val === Object(val) ? objectValues(val) : val; + } + } + return vals; + }; + +function Test( settings ) { + extend( this, settings ); + this.assertions = []; + this.testNumber = ++Test.count; +} + +Test.count = 0; + +Test.prototype = { + init: function() { + var a, b, li, + tests = id( "qunit-tests" ); + + if ( tests ) { + b = document.createElement( "strong" ); + b.innerHTML = this.nameHtml; + + // `a` initialized at top of scope + a = document.createElement( "a" ); + a.innerHTML = "Rerun"; + a.href = QUnit.url({ testNumber: this.testNumber }); + + li = document.createElement( "li" ); + li.appendChild( b ); + li.appendChild( a ); + li.className = "running"; + li.id = this.id = "qunit-test-output" + testId++; + + tests.appendChild( li ); + } + }, + setup: function() { + if ( this.module !== config.previousModule ) { + if ( config.previousModule ) { + runLoggingCallbacks( "moduleDone", QUnit, { + name: config.previousModule, + failed: config.moduleStats.bad, + passed: config.moduleStats.all - config.moduleStats.bad, + total: config.moduleStats.all + }); + } + config.previousModule = this.module; + config.moduleStats = { all: 0, bad: 0 }; + runLoggingCallbacks( "moduleStart", QUnit, { + name: this.module + }); + } else if ( config.autorun ) { + runLoggingCallbacks( "moduleStart", QUnit, { + name: this.module + }); + } + + config.current = this; + + this.testEnvironment = extend({ + setup: function() {}, + teardown: function() {} + }, this.moduleTestEnvironment ); + + this.started = +new Date(); + runLoggingCallbacks( "testStart", QUnit, { + name: this.testName, + module: this.module + }); + + // allow utility functions to access the current test environment + // TODO why?? + QUnit.current_testEnvironment = this.testEnvironment; + + if ( !config.pollution ) { + saveGlobal(); + } + if ( config.notrycatch ) { + this.testEnvironment.setup.call( this.testEnvironment ); + return; + } + try { + this.testEnvironment.setup.call( this.testEnvironment ); + } catch( e ) { + QUnit.pushFailure( "Setup failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) ); + } + }, + run: function() { + config.current = this; + + var running = id( "qunit-testresult" ); + + if ( running ) { + running.innerHTML = "Running:
    " + this.nameHtml; + } + + if ( this.async ) { + QUnit.stop(); + } + + this.callbackStarted = +new Date(); + + if ( config.notrycatch ) { + this.callback.call( this.testEnvironment, QUnit.assert ); + this.callbackRuntime = +new Date() - this.callbackStarted; + return; + } + + try { + this.callback.call( this.testEnvironment, QUnit.assert ); + this.callbackRuntime = +new Date() - this.callbackStarted; + } catch( e ) { + this.callbackRuntime = +new Date() - this.callbackStarted; + + QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + ( e.message || e ), extractStacktrace( e, 0 ) ); + // else next test will carry the responsibility + saveGlobal(); + + // Restart the tests if they're blocking + if ( config.blocking ) { + QUnit.start(); + } + } + }, + teardown: function() { + config.current = this; + if ( config.notrycatch ) { + if ( typeof this.callbackRuntime === "undefined" ) { + this.callbackRuntime = +new Date() - this.callbackStarted; + } + this.testEnvironment.teardown.call( this.testEnvironment ); + return; + } else { + try { + this.testEnvironment.teardown.call( this.testEnvironment ); + } catch( e ) { + QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + ( e.message || e ), extractStacktrace( e, 1 ) ); + } + } + checkPollution(); + }, + finish: function() { + config.current = this; + if ( config.requireExpects && this.expected === null ) { + QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack ); + } else if ( this.expected !== null && this.expected !== this.assertions.length ) { + QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack ); + } else if ( this.expected === null && !this.assertions.length ) { + QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack ); + } + + var i, assertion, a, b, time, li, ol, + test = this, + good = 0, + bad = 0, + tests = id( "qunit-tests" ); + + this.runtime = +new Date() - this.started; + config.stats.all += this.assertions.length; + config.moduleStats.all += this.assertions.length; + + if ( tests ) { + ol = document.createElement( "ol" ); + ol.className = "qunit-assert-list"; + + for ( i = 0; i < this.assertions.length; i++ ) { + assertion = this.assertions[i]; + + li = document.createElement( "li" ); + li.className = assertion.result ? "pass" : "fail"; + li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" ); + ol.appendChild( li ); + + if ( assertion.result ) { + good++; + } else { + bad++; + config.stats.bad++; + config.moduleStats.bad++; + } + } + + // store result when possible + if ( QUnit.config.reorder && defined.sessionStorage ) { + if ( bad ) { + sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad ); + } else { + sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName ); + } + } + + if ( bad === 0 ) { + addClass( ol, "qunit-collapsed" ); + } + + // `b` initialized at top of scope + b = document.createElement( "strong" ); + b.innerHTML = this.nameHtml + " (" + bad + ", " + good + ", " + this.assertions.length + ")"; + + addEvent(b, "click", function() { + var next = b.parentNode.lastChild, + collapsed = hasClass( next, "qunit-collapsed" ); + ( collapsed ? removeClass : addClass )( next, "qunit-collapsed" ); + }); + + addEvent(b, "dblclick", function( e ) { + var target = e && e.target ? e.target : window.event.srcElement; + if ( target.nodeName.toLowerCase() === "span" || target.nodeName.toLowerCase() === "b" ) { + target = target.parentNode; + } + if ( window.location && target.nodeName.toLowerCase() === "strong" ) { + window.location = QUnit.url({ testNumber: test.testNumber }); + } + }); + + // `time` initialized at top of scope + time = document.createElement( "span" ); + time.className = "runtime"; + time.innerHTML = this.runtime + " ms"; + + // `li` initialized at top of scope + li = id( this.id ); + li.className = bad ? "fail" : "pass"; + li.removeChild( li.firstChild ); + a = li.firstChild; + li.appendChild( b ); + li.appendChild( a ); + li.appendChild( time ); + li.appendChild( ol ); + + } else { + for ( i = 0; i < this.assertions.length; i++ ) { + if ( !this.assertions[i].result ) { + bad++; + config.stats.bad++; + config.moduleStats.bad++; + } + } + } + + runLoggingCallbacks( "testDone", QUnit, { + name: this.testName, + module: this.module, + failed: bad, + passed: this.assertions.length - bad, + total: this.assertions.length, + duration: this.runtime + }); + + QUnit.reset(); + + config.current = undefined; + }, + + queue: function() { + var bad, + test = this; + + synchronize(function() { + test.init(); + }); + function run() { + // each of these can by async + synchronize(function() { + test.setup(); + }); + synchronize(function() { + test.run(); + }); + synchronize(function() { + test.teardown(); + }); + synchronize(function() { + test.finish(); + }); + } + + // `bad` initialized at top of scope + // defer when previous test run passed, if storage is available + bad = QUnit.config.reorder && defined.sessionStorage && + +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName ); + + if ( bad ) { + run(); + } else { + synchronize( run, true ); + } + } +}; + +// Root QUnit object. +// `QUnit` initialized at top of scope +QUnit = { + + // call on start of module test to prepend name to all tests + module: function( name, testEnvironment ) { + config.currentModule = name; + config.currentModuleTestEnvironment = testEnvironment; + config.modules[name] = true; + }, + + asyncTest: function( testName, expected, callback ) { + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + + QUnit.test( testName, expected, callback, true ); + }, + + test: function( testName, expected, callback, async ) { + var test, + nameHtml = "" + escapeText( testName ) + ""; + + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + + if ( config.currentModule ) { + nameHtml = "" + escapeText( config.currentModule ) + ": " + nameHtml; + } + + test = new Test({ + nameHtml: nameHtml, + testName: testName, + expected: expected, + async: async, + callback: callback, + module: config.currentModule, + moduleTestEnvironment: config.currentModuleTestEnvironment, + stack: sourceFromStacktrace( 2 ) + }); + + if ( !validTest( test ) ) { + return; + } + + test.queue(); + }, + + // Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. + expect: function( asserts ) { + if (arguments.length === 1) { + config.current.expected = asserts; + } else { + return config.current.expected; + } + }, + + start: function( count ) { + // QUnit hasn't been initialized yet. + // Note: RequireJS (et al) may delay onLoad + if ( config.semaphore === undefined ) { + QUnit.begin(function() { + // This is triggered at the top of QUnit.load, push start() to the event loop, to allow QUnit.load to finish first + setTimeout(function() { + QUnit.start( count ); + }); + }); + return; + } + + config.semaphore -= count || 1; + // don't start until equal number of stop-calls + if ( config.semaphore > 0 ) { + return; + } + // ignore if start is called more often then stop + if ( config.semaphore < 0 ) { + config.semaphore = 0; + QUnit.pushFailure( "Called start() while already started (QUnit.config.semaphore was 0 already)", null, sourceFromStacktrace(2) ); + return; + } + // A slight delay, to avoid any current callbacks + if ( defined.setTimeout ) { + window.setTimeout(function() { + if ( config.semaphore > 0 ) { + return; + } + if ( config.timeout ) { + clearTimeout( config.timeout ); + } + + config.blocking = false; + process( true ); + }, 13); + } else { + config.blocking = false; + process( true ); + } + }, + + stop: function( count ) { + config.semaphore += count || 1; + config.blocking = true; + + if ( config.testTimeout && defined.setTimeout ) { + clearTimeout( config.timeout ); + config.timeout = window.setTimeout(function() { + QUnit.ok( false, "Test timed out" ); + config.semaphore = 1; + QUnit.start(); + }, config.testTimeout ); + } + } +}; + +// `assert` initialized at top of scope +// Asssert helpers +// All of these must either call QUnit.push() or manually do: +// - runLoggingCallbacks( "log", .. ); +// - config.current.assertions.push({ .. }); +// We attach it to the QUnit object *after* we expose the public API, +// otherwise `assert` will become a global variable in browsers (#341). +assert = { + /** + * Asserts rough true-ish result. + * @name ok + * @function + * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); + */ + ok: function( result, msg ) { + if ( !config.current ) { + throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) ); + } + result = !!result; + + var source, + details = { + module: config.current.module, + name: config.current.testName, + result: result, + message: msg + }; + + msg = escapeText( msg || (result ? "okay" : "failed" ) ); + msg = "" + msg + ""; + + if ( !result ) { + source = sourceFromStacktrace( 2 ); + if ( source ) { + details.source = source; + msg += "
    Source:
    " + escapeText( source ) + "
    "; + } + } + runLoggingCallbacks( "log", QUnit, details ); + config.current.assertions.push({ + result: result, + message: msg + }); + }, + + /** + * Assert that the first two arguments are equal, with an optional message. + * Prints out both actual and expected values. + * @name equal + * @function + * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" ); + */ + equal: function( actual, expected, message ) { + /*jshint eqeqeq:false */ + QUnit.push( expected == actual, actual, expected, message ); + }, + + /** + * @name notEqual + * @function + */ + notEqual: function( actual, expected, message ) { + /*jshint eqeqeq:false */ + QUnit.push( expected != actual, actual, expected, message ); + }, + + /** + * @name propEqual + * @function + */ + propEqual: function( actual, expected, message ) { + actual = objectValues(actual); + expected = objectValues(expected); + QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name notPropEqual + * @function + */ + notPropEqual: function( actual, expected, message ) { + actual = objectValues(actual); + expected = objectValues(expected); + QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name deepEqual + * @function + */ + deepEqual: function( actual, expected, message ) { + QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name notDeepEqual + * @function + */ + notDeepEqual: function( actual, expected, message ) { + QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name strictEqual + * @function + */ + strictEqual: function( actual, expected, message ) { + QUnit.push( expected === actual, actual, expected, message ); + }, + + /** + * @name notStrictEqual + * @function + */ + notStrictEqual: function( actual, expected, message ) { + QUnit.push( expected !== actual, actual, expected, message ); + }, + + "throws": function( block, expected, message ) { + var actual, + expectedOutput = expected, + ok = false; + + // 'expected' is optional + if ( typeof expected === "string" ) { + message = expected; + expected = null; + } + + config.current.ignoreGlobalErrors = true; + try { + block.call( config.current.testEnvironment ); + } catch (e) { + actual = e; + } + config.current.ignoreGlobalErrors = false; + + if ( actual ) { + // we don't want to validate thrown error + if ( !expected ) { + ok = true; + expectedOutput = null; + // expected is a regexp + } else if ( QUnit.objectType( expected ) === "regexp" ) { + ok = expected.test( errorString( actual ) ); + // expected is a constructor + } else if ( actual instanceof expected ) { + ok = true; + // expected is a validation function which returns true is validation passed + } else if ( expected.call( {}, actual ) === true ) { + expectedOutput = null; + ok = true; + } + + QUnit.push( ok, actual, expectedOutput, message ); + } else { + QUnit.pushFailure( message, null, 'No exception was thrown.' ); + } + } +}; + +/** + * @deprecate since 1.8.0 + * Kept assertion helpers in root for backwards compatibility. + */ +extend( QUnit, assert ); + +/** + * @deprecated since 1.9.0 + * Kept root "raises()" for backwards compatibility. + * (Note that we don't introduce assert.raises). + */ +QUnit.raises = assert[ "throws" ]; + +/** + * @deprecated since 1.0.0, replaced with error pushes since 1.3.0 + * Kept to avoid TypeErrors for undefined methods. + */ +QUnit.equals = function() { + QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" ); +}; +QUnit.same = function() { + QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" ); +}; + +// We want access to the constructor's prototype +(function() { + function F() {} + F.prototype = QUnit; + QUnit = new F(); + // Make F QUnit's constructor so that we can add to the prototype later + QUnit.constructor = F; +}()); + +/** + * Config object: Maintain internal state + * Later exposed as QUnit.config + * `config` initialized at top of scope + */ +config = { + // The queue of tests to run + queue: [], + + // block until document ready + blocking: true, + + // when enabled, show only failing tests + // gets persisted through sessionStorage and can be changed in UI via checkbox + hidepassed: false, + + // by default, run previously failed tests first + // very useful in combination with "Hide passed tests" checked + reorder: true, + + // by default, modify document.title when suite is done + altertitle: true, + + // when enabled, all tests must call expect() + requireExpects: false, + + // add checkboxes that are persisted in the query-string + // when enabled, the id is set to `true` as a `QUnit.config` property + urlConfig: [ + { + id: "noglobals", + label: "Check for Globals", + tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings." + }, + { + id: "notrycatch", + label: "No try-catch", + tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings." + } + ], + + // Set of all modules. + modules: {}, + + // logging callback queues + begin: [], + done: [], + log: [], + testStart: [], + testDone: [], + moduleStart: [], + moduleDone: [] +}; + +// Export global variables, unless an 'exports' object exists, +// in that case we assume we're in CommonJS (dealt with on the bottom of the script) +if ( typeof exports === "undefined" ) { + extend( window, QUnit ); + + // Expose QUnit object + window.QUnit = QUnit; +} + +// Initialize more QUnit.config and QUnit.urlParams +(function() { + var i, + location = window.location || { search: "", protocol: "file:" }, + params = location.search.slice( 1 ).split( "&" ), + length = params.length, + urlParams = {}, + current; + + if ( params[ 0 ] ) { + for ( i = 0; i < length; i++ ) { + current = params[ i ].split( "=" ); + current[ 0 ] = decodeURIComponent( current[ 0 ] ); + // allow just a key to turn on a flag, e.g., test.html?noglobals + current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; + urlParams[ current[ 0 ] ] = current[ 1 ]; + } + } + + QUnit.urlParams = urlParams; + + // String search anywhere in moduleName+testName + config.filter = urlParams.filter; + + // Exact match of the module name + config.module = urlParams.module; + + config.testNumber = parseInt( urlParams.testNumber, 10 ) || null; + + // Figure out if we're running the tests from a server or not + QUnit.isLocal = location.protocol === "file:"; +}()); + +// Extend QUnit object, +// these after set here because they should not be exposed as global functions +extend( QUnit, { + assert: assert, + + config: config, + + // Initialize the configuration options + init: function() { + extend( config, { + stats: { all: 0, bad: 0 }, + moduleStats: { all: 0, bad: 0 }, + started: +new Date(), + updateRate: 1000, + blocking: false, + autostart: true, + autorun: false, + filter: "", + queue: [], + semaphore: 1 + }); + + var tests, banner, result, + qunit = id( "qunit" ); + + if ( qunit ) { + qunit.innerHTML = + "

    " + escapeText( document.title ) + "

    " + + "

    " + + "
    " + + "

    " + + "
      "; + } + + tests = id( "qunit-tests" ); + banner = id( "qunit-banner" ); + result = id( "qunit-testresult" ); + + if ( tests ) { + tests.innerHTML = ""; + } + + if ( banner ) { + banner.className = ""; + } + + if ( result ) { + result.parentNode.removeChild( result ); + } + + if ( tests ) { + result = document.createElement( "p" ); + result.id = "qunit-testresult"; + result.className = "result"; + tests.parentNode.insertBefore( result, tests ); + result.innerHTML = "Running...
       "; + } + }, + + // Resets the test setup. Useful for tests that modify the DOM. + reset: function() { + var fixture = id( "qunit-fixture" ); + if ( fixture ) { + fixture.innerHTML = config.fixture; + } + }, + + // Trigger an event on an element. + // @example triggerEvent( document.body, "click" ); + triggerEvent: function( elem, type, event ) { + if ( document.createEvent ) { + event = document.createEvent( "MouseEvents" ); + event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, + 0, 0, 0, 0, 0, false, false, false, false, 0, null); + + elem.dispatchEvent( event ); + } else if ( elem.fireEvent ) { + elem.fireEvent( "on" + type ); + } + }, + + // Safe object type checking + is: function( type, obj ) { + return QUnit.objectType( obj ) === type; + }, + + objectType: function( obj ) { + if ( typeof obj === "undefined" ) { + return "undefined"; + // consider: typeof null === object + } + if ( obj === null ) { + return "null"; + } + + var match = toString.call( obj ).match(/^\[object\s(.*)\]$/), + type = match && match[1] || ""; + + switch ( type ) { + case "Number": + if ( isNaN(obj) ) { + return "nan"; + } + return "number"; + case "String": + case "Boolean": + case "Array": + case "Date": + case "RegExp": + case "Function": + return type.toLowerCase(); + } + if ( typeof obj === "object" ) { + return "object"; + } + return undefined; + }, + + push: function( result, actual, expected, message ) { + if ( !config.current ) { + throw new Error( "assertion outside test context, was " + sourceFromStacktrace() ); + } + + var output, source, + details = { + module: config.current.module, + name: config.current.testName, + result: result, + message: message, + actual: actual, + expected: expected + }; + + message = escapeText( message ) || ( result ? "okay" : "failed" ); + message = "" + message + ""; + output = message; + + if ( !result ) { + expected = escapeText( QUnit.jsDump.parse(expected) ); + actual = escapeText( QUnit.jsDump.parse(actual) ); + output += ""; + + if ( actual !== expected ) { + output += ""; + output += ""; + } + + source = sourceFromStacktrace(); + + if ( source ) { + details.source = source; + output += ""; + } + + output += "
      Expected:
      " + expected + "
      Result:
      " + actual + "
      Diff:
      " + QUnit.diff( expected, actual ) + "
      Source:
      " + escapeText( source ) + "
      "; + } + + runLoggingCallbacks( "log", QUnit, details ); + + config.current.assertions.push({ + result: !!result, + message: output + }); + }, + + pushFailure: function( message, source, actual ) { + if ( !config.current ) { + throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) ); + } + + var output, + details = { + module: config.current.module, + name: config.current.testName, + result: false, + message: message + }; + + message = escapeText( message ) || "error"; + message = "" + message + ""; + output = message; + + output += ""; + + if ( actual ) { + output += ""; + } + + if ( source ) { + details.source = source; + output += ""; + } + + output += "
      Result:
      " + escapeText( actual ) + "
      Source:
      " + escapeText( source ) + "
      "; + + runLoggingCallbacks( "log", QUnit, details ); + + config.current.assertions.push({ + result: false, + message: output + }); + }, + + url: function( params ) { + params = extend( extend( {}, QUnit.urlParams ), params ); + var key, + querystring = "?"; + + for ( key in params ) { + if ( !hasOwn.call( params, key ) ) { + continue; + } + querystring += encodeURIComponent( key ) + "=" + + encodeURIComponent( params[ key ] ) + "&"; + } + return window.location.protocol + "//" + window.location.host + + window.location.pathname + querystring.slice( 0, -1 ); + }, + + extend: extend, + id: id, + addEvent: addEvent + // load, equiv, jsDump, diff: Attached later +}); + +/** + * @deprecated: Created for backwards compatibility with test runner that set the hook function + * into QUnit.{hook}, instead of invoking it and passing the hook function. + * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here. + * Doing this allows us to tell if the following methods have been overwritten on the actual + * QUnit object. + */ +extend( QUnit.constructor.prototype, { + + // Logging callbacks; all receive a single argument with the listed properties + // run test/logs.html for any related changes + begin: registerLoggingCallback( "begin" ), + + // done: { failed, passed, total, runtime } + done: registerLoggingCallback( "done" ), + + // log: { result, actual, expected, message } + log: registerLoggingCallback( "log" ), + + // testStart: { name } + testStart: registerLoggingCallback( "testStart" ), + + // testDone: { name, failed, passed, total, duration } + testDone: registerLoggingCallback( "testDone" ), + + // moduleStart: { name } + moduleStart: registerLoggingCallback( "moduleStart" ), + + // moduleDone: { name, failed, passed, total } + moduleDone: registerLoggingCallback( "moduleDone" ) +}); + +if ( typeof document === "undefined" || document.readyState === "complete" ) { + config.autorun = true; +} + +QUnit.load = function() { + runLoggingCallbacks( "begin", QUnit, {} ); + + // Initialize the config, saving the execution queue + var banner, filter, i, label, len, main, ol, toolbar, userAgent, val, + urlConfigCheckboxesContainer, urlConfigCheckboxes, moduleFilter, + numModules = 0, + moduleFilterHtml = "", + urlConfigHtml = "", + oldconfig = extend( {}, config ); + + QUnit.init(); + extend(config, oldconfig); + + config.blocking = false; + + len = config.urlConfig.length; + + for ( i = 0; i < len; i++ ) { + val = config.urlConfig[i]; + if ( typeof val === "string" ) { + val = { + id: val, + label: val, + tooltip: "[no tooltip available]" + }; + } + config[ val.id ] = QUnit.urlParams[ val.id ]; + urlConfigHtml += ""; + } + + moduleFilterHtml += ""; + + // `userAgent` initialized at top of scope + userAgent = id( "qunit-userAgent" ); + if ( userAgent ) { + userAgent.innerHTML = navigator.userAgent; + } + + // `banner` initialized at top of scope + banner = id( "qunit-header" ); + if ( banner ) { + banner.innerHTML = "" + banner.innerHTML + " "; + } + + // `toolbar` initialized at top of scope + toolbar = id( "qunit-testrunner-toolbar" ); + if ( toolbar ) { + // `filter` initialized at top of scope + filter = document.createElement( "input" ); + filter.type = "checkbox"; + filter.id = "qunit-filter-pass"; + + addEvent( filter, "click", function() { + var tmp, + ol = document.getElementById( "qunit-tests" ); + + if ( filter.checked ) { + ol.className = ol.className + " hidepass"; + } else { + tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; + ol.className = tmp.replace( / hidepass /, " " ); + } + if ( defined.sessionStorage ) { + if (filter.checked) { + sessionStorage.setItem( "qunit-filter-passed-tests", "true" ); + } else { + sessionStorage.removeItem( "qunit-filter-passed-tests" ); + } + } + }); + + if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) { + filter.checked = true; + // `ol` initialized at top of scope + ol = document.getElementById( "qunit-tests" ); + ol.className = ol.className + " hidepass"; + } + toolbar.appendChild( filter ); + + // `label` initialized at top of scope + label = document.createElement( "label" ); + label.setAttribute( "for", "qunit-filter-pass" ); + label.setAttribute( "title", "Only show tests and assertons that fail. Stored in sessionStorage." ); + label.innerHTML = "Hide passed tests"; + toolbar.appendChild( label ); + + urlConfigCheckboxesContainer = document.createElement("span"); + urlConfigCheckboxesContainer.innerHTML = urlConfigHtml; + urlConfigCheckboxes = urlConfigCheckboxesContainer.getElementsByTagName("input"); + // For oldIE support: + // * Add handlers to the individual elements instead of the container + // * Use "click" instead of "change" + // * Fallback from event.target to event.srcElement + addEvents( urlConfigCheckboxes, "click", function( event ) { + var params = {}, + target = event.target || event.srcElement; + params[ target.name ] = target.checked ? true : undefined; + window.location = QUnit.url( params ); + }); + toolbar.appendChild( urlConfigCheckboxesContainer ); + + if (numModules > 1) { + moduleFilter = document.createElement( 'span' ); + moduleFilter.setAttribute( 'id', 'qunit-modulefilter-container' ); + moduleFilter.innerHTML = moduleFilterHtml; + addEvent( moduleFilter.lastChild, "change", function() { + var selectBox = moduleFilter.getElementsByTagName("select")[0], + selectedModule = decodeURIComponent(selectBox.options[selectBox.selectedIndex].value); + + window.location = QUnit.url( { module: ( selectedModule === "" ) ? undefined : selectedModule } ); + }); + toolbar.appendChild(moduleFilter); + } + } + + // `main` initialized at top of scope + main = id( "qunit-fixture" ); + if ( main ) { + config.fixture = main.innerHTML; + } + + if ( config.autostart ) { + QUnit.start(); + } +}; + +addEvent( window, "load", QUnit.load ); + +// `onErrorFnPrev` initialized at top of scope +// Preserve other handlers +onErrorFnPrev = window.onerror; + +// Cover uncaught exceptions +// Returning true will surpress the default browser handler, +// returning false will let it run. +window.onerror = function ( error, filePath, linerNr ) { + var ret = false; + if ( onErrorFnPrev ) { + ret = onErrorFnPrev( error, filePath, linerNr ); + } + + // Treat return value as window.onerror itself does, + // Only do our handling if not surpressed. + if ( ret !== true ) { + if ( QUnit.config.current ) { + if ( QUnit.config.current.ignoreGlobalErrors ) { + return true; + } + QUnit.pushFailure( error, filePath + ":" + linerNr ); + } else { + QUnit.test( "global failure", extend( function() { + QUnit.pushFailure( error, filePath + ":" + linerNr ); + }, { validTest: validTest } ) ); + } + return false; + } + + return ret; +}; + +function done() { + config.autorun = true; + + // Log the last module results + if ( config.currentModule ) { + runLoggingCallbacks( "moduleDone", QUnit, { + name: config.currentModule, + failed: config.moduleStats.bad, + passed: config.moduleStats.all - config.moduleStats.bad, + total: config.moduleStats.all + }); + } + + var i, key, + banner = id( "qunit-banner" ), + tests = id( "qunit-tests" ), + runtime = +new Date() - config.started, + passed = config.stats.all - config.stats.bad, + html = [ + "Tests completed in ", + runtime, + " milliseconds.
      ", + "", + passed, + " assertions of ", + config.stats.all, + " passed, ", + config.stats.bad, + " failed." + ].join( "" ); + + if ( banner ) { + banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" ); + } + + if ( tests ) { + id( "qunit-testresult" ).innerHTML = html; + } + + if ( config.altertitle && typeof document !== "undefined" && document.title ) { + // show ✖ for good, ✔ for bad suite result in title + // use escape sequences in case file gets loaded with non-utf-8-charset + document.title = [ + ( config.stats.bad ? "\u2716" : "\u2714" ), + document.title.replace( /^[\u2714\u2716] /i, "" ) + ].join( " " ); + } + + // clear own sessionStorage items if all tests passed + if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) { + // `key` & `i` initialized at top of scope + for ( i = 0; i < sessionStorage.length; i++ ) { + key = sessionStorage.key( i++ ); + if ( key.indexOf( "qunit-test-" ) === 0 ) { + sessionStorage.removeItem( key ); + } + } + } + + // scroll back to top to show results + if ( window.scrollTo ) { + window.scrollTo(0, 0); + } + + runLoggingCallbacks( "done", QUnit, { + failed: config.stats.bad, + passed: passed, + total: config.stats.all, + runtime: runtime + }); +} + +/** @return Boolean: true if this test should be ran */ +function validTest( test ) { + var include, + filter = config.filter && config.filter.toLowerCase(), + module = config.module && config.module.toLowerCase(), + fullName = (test.module + ": " + test.testName).toLowerCase(); + + // Internally-generated tests are always valid + if ( test.callback && test.callback.validTest === validTest ) { + delete test.callback.validTest; + return true; + } + + if ( config.testNumber ) { + return test.testNumber === config.testNumber; + } + + if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) { + return false; + } + + if ( !filter ) { + return true; + } + + include = filter.charAt( 0 ) !== "!"; + if ( !include ) { + filter = filter.slice( 1 ); + } + + // If the filter matches, we need to honour include + if ( fullName.indexOf( filter ) !== -1 ) { + return include; + } + + // Otherwise, do the opposite + return !include; +} + +// so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions) +// Later Safari and IE10 are supposed to support error.stack as well +// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack +function extractStacktrace( e, offset ) { + offset = offset === undefined ? 3 : offset; + + var stack, include, i; + + if ( e.stacktrace ) { + // Opera + return e.stacktrace.split( "\n" )[ offset + 3 ]; + } else if ( e.stack ) { + // Firefox, Chrome + stack = e.stack.split( "\n" ); + if (/^error$/i.test( stack[0] ) ) { + stack.shift(); + } + if ( fileName ) { + include = []; + for ( i = offset; i < stack.length; i++ ) { + if ( stack[ i ].indexOf( fileName ) !== -1 ) { + break; + } + include.push( stack[ i ] ); + } + if ( include.length ) { + return include.join( "\n" ); + } + } + return stack[ offset ]; + } else if ( e.sourceURL ) { + // Safari, PhantomJS + // hopefully one day Safari provides actual stacktraces + // exclude useless self-reference for generated Error objects + if ( /qunit.js$/.test( e.sourceURL ) ) { + return; + } + // for actual exceptions, this is useful + return e.sourceURL + ":" + e.line; + } +} +function sourceFromStacktrace( offset ) { + try { + throw new Error(); + } catch ( e ) { + return extractStacktrace( e, offset ); + } +} + +/** + * Escape text for attribute or text content. + */ +function escapeText( s ) { + if ( !s ) { + return ""; + } + s = s + ""; + // Both single quotes and double quotes (for attributes) + return s.replace( /['"<>&]/g, function( s ) { + switch( s ) { + case '\'': + return '''; + case '"': + return '"'; + case '<': + return '<'; + case '>': + return '>'; + case '&': + return '&'; + } + }); +} + +function synchronize( callback, last ) { + config.queue.push( callback ); + + if ( config.autorun && !config.blocking ) { + process( last ); + } +} + +function process( last ) { + function next() { + process( last ); + } + var start = new Date().getTime(); + config.depth = config.depth ? config.depth + 1 : 1; + + while ( config.queue.length && !config.blocking ) { + if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { + config.queue.shift()(); + } else { + window.setTimeout( next, 13 ); + break; + } + } + config.depth--; + if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { + done(); + } +} + +function saveGlobal() { + config.pollution = []; + + if ( config.noglobals ) { + for ( var key in window ) { + // in Opera sometimes DOM element ids show up here, ignore them + if ( !hasOwn.call( window, key ) || /^qunit-test-output/.test( key ) ) { + continue; + } + config.pollution.push( key ); + } + } +} + +function checkPollution() { + var newGlobals, + deletedGlobals, + old = config.pollution; + + saveGlobal(); + + newGlobals = diff( config.pollution, old ); + if ( newGlobals.length > 0 ) { + QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") ); + } + + deletedGlobals = diff( old, config.pollution ); + if ( deletedGlobals.length > 0 ) { + QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") ); + } +} + +// returns a new Array with the elements that are in a but not in b +function diff( a, b ) { + var i, j, + result = a.slice(); + + for ( i = 0; i < result.length; i++ ) { + for ( j = 0; j < b.length; j++ ) { + if ( result[i] === b[j] ) { + result.splice( i, 1 ); + i--; + break; + } + } + } + return result; +} + +function extend( a, b ) { + for ( var prop in b ) { + if ( b[ prop ] === undefined ) { + delete a[ prop ]; + + // Avoid "Member not found" error in IE8 caused by setting window.constructor + } else if ( prop !== "constructor" || a !== window ) { + a[ prop ] = b[ prop ]; + } + } + + return a; +} + +/** + * @param {HTMLElement} elem + * @param {string} type + * @param {Function} fn + */ +function addEvent( elem, type, fn ) { + // Standards-based browsers + if ( elem.addEventListener ) { + elem.addEventListener( type, fn, false ); + // IE + } else { + elem.attachEvent( "on" + type, fn ); + } +} + +/** + * @param {Array|NodeList} elems + * @param {string} type + * @param {Function} fn + */ +function addEvents( elems, type, fn ) { + var i = elems.length; + while ( i-- ) { + addEvent( elems[i], type, fn ); + } +} + +function hasClass( elem, name ) { + return (" " + elem.className + " ").indexOf(" " + name + " ") > -1; +} + +function addClass( elem, name ) { + if ( !hasClass( elem, name ) ) { + elem.className += (elem.className ? " " : "") + name; + } +} + +function removeClass( elem, name ) { + var set = " " + elem.className + " "; + // Class name may appear multiple times + while ( set.indexOf(" " + name + " ") > -1 ) { + set = set.replace(" " + name + " " , " "); + } + // If possible, trim it for prettiness, but not neccecarily + elem.className = window.jQuery ? jQuery.trim( set ) : ( set.trim ? set.trim() : set ); +} + +function id( name ) { + return !!( typeof document !== "undefined" && document && document.getElementById ) && + document.getElementById( name ); +} + +function registerLoggingCallback( key ) { + return function( callback ) { + config[key].push( callback ); + }; +} + +// Supports deprecated method of completely overwriting logging callbacks +function runLoggingCallbacks( key, scope, args ) { + var i, callbacks; + if ( QUnit.hasOwnProperty( key ) ) { + QUnit[ key ].call(scope, args ); + } else { + callbacks = config[ key ]; + for ( i = 0; i < callbacks.length; i++ ) { + callbacks[ i ].call( scope, args ); + } + } +} + +// Test for equality any JavaScript type. +// Author: Philippe Rathé +QUnit.equiv = (function() { + + // Call the o related callback with the given arguments. + function bindCallbacks( o, callbacks, args ) { + var prop = QUnit.objectType( o ); + if ( prop ) { + if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) { + return callbacks[ prop ].apply( callbacks, args ); + } else { + return callbacks[ prop ]; // or undefined + } + } + } + + // the real equiv function + var innerEquiv, + // stack to decide between skip/abort functions + callers = [], + // stack to avoiding loops from circular referencing + parents = [], + + getProto = Object.getPrototypeOf || function ( obj ) { + return obj.__proto__; + }, + callbacks = (function () { + + // for string, boolean, number and null + function useStrictEquality( b, a ) { + /*jshint eqeqeq:false */ + if ( b instanceof a.constructor || a instanceof b.constructor ) { + // to catch short annotaion VS 'new' annotation of a + // declaration + // e.g. var i = 1; + // var j = new Number(1); + return a == b; + } else { + return a === b; + } + } + + return { + "string": useStrictEquality, + "boolean": useStrictEquality, + "number": useStrictEquality, + "null": useStrictEquality, + "undefined": useStrictEquality, + + "nan": function( b ) { + return isNaN( b ); + }, + + "date": function( b, a ) { + return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf(); + }, + + "regexp": function( b, a ) { + return QUnit.objectType( b ) === "regexp" && + // the regex itself + a.source === b.source && + // and its modifers + a.global === b.global && + // (gmi) ... + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline && + a.sticky === b.sticky; + }, + + // - skip when the property is a method of an instance (OOP) + // - abort otherwise, + // initial === would have catch identical references anyway + "function": function() { + var caller = callers[callers.length - 1]; + return caller !== Object && typeof caller !== "undefined"; + }, + + "array": function( b, a ) { + var i, j, len, loop; + + // b could be an object literal here + if ( QUnit.objectType( b ) !== "array" ) { + return false; + } + + len = a.length; + if ( len !== b.length ) { + // safe and faster + return false; + } + + // track reference to avoid circular references + parents.push( a ); + for ( i = 0; i < len; i++ ) { + loop = false; + for ( j = 0; j < parents.length; j++ ) { + if ( parents[j] === a[i] ) { + loop = true;// dont rewalk array + } + } + if ( !loop && !innerEquiv(a[i], b[i]) ) { + parents.pop(); + return false; + } + } + parents.pop(); + return true; + }, + + "object": function( b, a ) { + var i, j, loop, + // Default to true + eq = true, + aProperties = [], + bProperties = []; + + // comparing constructors is more strict than using + // instanceof + if ( a.constructor !== b.constructor ) { + // Allow objects with no prototype to be equivalent to + // objects with Object as their constructor. + if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) || + ( getProto(b) === null && getProto(a) === Object.prototype ) ) ) { + return false; + } + } + + // stack constructor before traversing properties + callers.push( a.constructor ); + // track reference to avoid circular references + parents.push( a ); + + for ( i in a ) { // be strict: don't ensures hasOwnProperty + // and go deep + loop = false; + for ( j = 0; j < parents.length; j++ ) { + if ( parents[j] === a[i] ) { + // don't go down the same path twice + loop = true; + } + } + aProperties.push(i); // collect a's properties + + if (!loop && !innerEquiv( a[i], b[i] ) ) { + eq = false; + break; + } + } + + callers.pop(); // unstack, we are done + parents.pop(); + + for ( i in b ) { + bProperties.push( i ); // collect b's properties + } + + // Ensures identical properties name + return eq && innerEquiv( aProperties.sort(), bProperties.sort() ); + } + }; + }()); + + innerEquiv = function() { // can take multiple arguments + var args = [].slice.apply( arguments ); + if ( args.length < 2 ) { + return true; // end transition + } + + return (function( a, b ) { + if ( a === b ) { + return true; // catch the most you can + } else if ( a === null || b === null || typeof a === "undefined" || + typeof b === "undefined" || + QUnit.objectType(a) !== QUnit.objectType(b) ) { + return false; // don't lose time with error prone cases + } else { + return bindCallbacks(a, callbacks, [ b, a ]); + } + + // apply transition with (1..n) arguments + }( args[0], args[1] ) && arguments.callee.apply( this, args.splice(1, args.length - 1 )) ); + }; + + return innerEquiv; +}()); + +/** + * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | + * http://flesler.blogspot.com Licensed under BSD + * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 + * + * @projectDescription Advanced and extensible data dumping for Javascript. + * @version 1.0.0 + * @author Ariel Flesler + * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} + */ +QUnit.jsDump = (function() { + function quote( str ) { + return '"' + str.toString().replace( /"/g, '\\"' ) + '"'; + } + function literal( o ) { + return o + ""; + } + function join( pre, arr, post ) { + var s = jsDump.separator(), + base = jsDump.indent(), + inner = jsDump.indent(1); + if ( arr.join ) { + arr = arr.join( "," + s + inner ); + } + if ( !arr ) { + return pre + post; + } + return [ pre, inner + arr, base + post ].join(s); + } + function array( arr, stack ) { + var i = arr.length, ret = new Array(i); + this.up(); + while ( i-- ) { + ret[i] = this.parse( arr[i] , undefined , stack); + } + this.down(); + return join( "[", ret, "]" ); + } + + var reName = /^function (\w+)/, + jsDump = { + // type is used mostly internally, you can fix a (custom)type in advance + parse: function( obj, type, stack ) { + stack = stack || [ ]; + var inStack, res, + parser = this.parsers[ type || this.typeOf(obj) ]; + + type = typeof parser; + inStack = inArray( obj, stack ); + + if ( inStack !== -1 ) { + return "recursion(" + (inStack - stack.length) + ")"; + } + if ( type === "function" ) { + stack.push( obj ); + res = parser.call( this, obj, stack ); + stack.pop(); + return res; + } + return ( type === "string" ) ? parser : this.parsers.error; + }, + typeOf: function( obj ) { + var type; + if ( obj === null ) { + type = "null"; + } else if ( typeof obj === "undefined" ) { + type = "undefined"; + } else if ( QUnit.is( "regexp", obj) ) { + type = "regexp"; + } else if ( QUnit.is( "date", obj) ) { + type = "date"; + } else if ( QUnit.is( "function", obj) ) { + type = "function"; + } else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) { + type = "window"; + } else if ( obj.nodeType === 9 ) { + type = "document"; + } else if ( obj.nodeType ) { + type = "node"; + } else if ( + // native arrays + toString.call( obj ) === "[object Array]" || + // NodeList objects + ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) + ) { + type = "array"; + } else if ( obj.constructor === Error.prototype.constructor ) { + type = "error"; + } else { + type = typeof obj; + } + return type; + }, + separator: function() { + return this.multiline ? this.HTML ? "
      " : "\n" : this.HTML ? " " : " "; + }, + // extra can be a number, shortcut for increasing-calling-decreasing + indent: function( extra ) { + if ( !this.multiline ) { + return ""; + } + var chr = this.indentChar; + if ( this.HTML ) { + chr = chr.replace( /\t/g, " " ).replace( / /g, " " ); + } + return new Array( this._depth_ + (extra||0) ).join(chr); + }, + up: function( a ) { + this._depth_ += a || 1; + }, + down: function( a ) { + this._depth_ -= a || 1; + }, + setParser: function( name, parser ) { + this.parsers[name] = parser; + }, + // The next 3 are exposed so you can use them + quote: quote, + literal: literal, + join: join, + // + _depth_: 1, + // This is the list of parsers, to modify them, use jsDump.setParser + parsers: { + window: "[Window]", + document: "[Document]", + error: function(error) { + return "Error(\"" + error.message + "\")"; + }, + unknown: "[Unknown]", + "null": "null", + "undefined": "undefined", + "function": function( fn ) { + var ret = "function", + // functions never have name in IE + name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1]; + + if ( name ) { + ret += " " + name; + } + ret += "( "; + + ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" ); + return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" ); + }, + array: array, + nodelist: array, + "arguments": array, + object: function( map, stack ) { + var ret = [ ], keys, key, val, i; + QUnit.jsDump.up(); + keys = []; + for ( key in map ) { + keys.push( key ); + } + keys.sort(); + for ( i = 0; i < keys.length; i++ ) { + key = keys[ i ]; + val = map[ key ]; + ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) ); + } + QUnit.jsDump.down(); + return join( "{", ret, "}" ); + }, + node: function( node ) { + var len, i, val, + open = QUnit.jsDump.HTML ? "<" : "<", + close = QUnit.jsDump.HTML ? ">" : ">", + tag = node.nodeName.toLowerCase(), + ret = open + tag, + attrs = node.attributes; + + if ( attrs ) { + for ( i = 0, len = attrs.length; i < len; i++ ) { + val = attrs[i].nodeValue; + // IE6 includes all attributes in .attributes, even ones not explicitly set. + // Those have values like undefined, null, 0, false, "" or "inherit". + if ( val && val !== "inherit" ) { + ret += " " + attrs[i].nodeName + "=" + QUnit.jsDump.parse( val, "attribute" ); + } + } + } + ret += close; + + // Show content of TextNode or CDATASection + if ( node.nodeType === 3 || node.nodeType === 4 ) { + ret += node.nodeValue; + } + + return ret + open + "/" + tag + close; + }, + // function calls it internally, it's the arguments part of the function + functionArgs: function( fn ) { + var args, + l = fn.length; + + if ( !l ) { + return ""; + } + + args = new Array(l); + while ( l-- ) { + // 97 is 'a' + args[l] = String.fromCharCode(97+l); + } + return " " + args.join( ", " ) + " "; + }, + // object calls it internally, the key part of an item in a map + key: quote, + // function calls it internally, it's the content of the function + functionCode: "[code]", + // node calls it internally, it's an html attribute value + attribute: quote, + string: quote, + date: quote, + regexp: literal, + number: literal, + "boolean": literal + }, + // if true, entities are escaped ( <, >, \t, space and \n ) + HTML: false, + // indentation unit + indentChar: " ", + // if true, items in a collection, are separated by a \n, else just a space. + multiline: true + }; + + return jsDump; +}()); + +// from jquery.js +function inArray( elem, array ) { + if ( array.indexOf ) { + return array.indexOf( elem ); + } + + for ( var i = 0, length = array.length; i < length; i++ ) { + if ( array[ i ] === elem ) { + return i; + } + } + + return -1; +} + +/* + * Javascript Diff Algorithm + * By John Resig (http://ejohn.org/) + * Modified by Chu Alan "sprite" + * + * Released under the MIT license. + * + * More Info: + * http://ejohn.org/projects/javascript-diff-algorithm/ + * + * Usage: QUnit.diff(expected, actual) + * + * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick brown fox jumped jumps over" + */ +QUnit.diff = (function() { + /*jshint eqeqeq:false, eqnull:true */ + function diff( o, n ) { + var i, + ns = {}, + os = {}; + + for ( i = 0; i < n.length; i++ ) { + if ( !hasOwn.call( ns, n[i] ) ) { + ns[ n[i] ] = { + rows: [], + o: null + }; + } + ns[ n[i] ].rows.push( i ); + } + + for ( i = 0; i < o.length; i++ ) { + if ( !hasOwn.call( os, o[i] ) ) { + os[ o[i] ] = { + rows: [], + n: null + }; + } + os[ o[i] ].rows.push( i ); + } + + for ( i in ns ) { + if ( !hasOwn.call( ns, i ) ) { + continue; + } + if ( ns[i].rows.length === 1 && hasOwn.call( os, i ) && os[i].rows.length === 1 ) { + n[ ns[i].rows[0] ] = { + text: n[ ns[i].rows[0] ], + row: os[i].rows[0] + }; + o[ os[i].rows[0] ] = { + text: o[ os[i].rows[0] ], + row: ns[i].rows[0] + }; + } + } + + for ( i = 0; i < n.length - 1; i++ ) { + if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null && + n[ i + 1 ] == o[ n[i].row + 1 ] ) { + + n[ i + 1 ] = { + text: n[ i + 1 ], + row: n[i].row + 1 + }; + o[ n[i].row + 1 ] = { + text: o[ n[i].row + 1 ], + row: i + 1 + }; + } + } + + for ( i = n.length - 1; i > 0; i-- ) { + if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null && + n[ i - 1 ] == o[ n[i].row - 1 ]) { + + n[ i - 1 ] = { + text: n[ i - 1 ], + row: n[i].row - 1 + }; + o[ n[i].row - 1 ] = { + text: o[ n[i].row - 1 ], + row: i - 1 + }; + } + } + + return { + o: o, + n: n + }; + } + + return function( o, n ) { + o = o.replace( /\s+$/, "" ); + n = n.replace( /\s+$/, "" ); + + var i, pre, + str = "", + out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ), + oSpace = o.match(/\s+/g), + nSpace = n.match(/\s+/g); + + if ( oSpace == null ) { + oSpace = [ " " ]; + } + else { + oSpace.push( " " ); + } + + if ( nSpace == null ) { + nSpace = [ " " ]; + } + else { + nSpace.push( " " ); + } + + if ( out.n.length === 0 ) { + for ( i = 0; i < out.o.length; i++ ) { + str += "" + out.o[i] + oSpace[i] + ""; + } + } + else { + if ( out.n[0].text == null ) { + for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) { + str += "" + out.o[n] + oSpace[n] + ""; + } + } + + for ( i = 0; i < out.n.length; i++ ) { + if (out.n[i].text == null) { + str += "" + out.n[i] + nSpace[i] + ""; + } + else { + // `pre` initialized at top of scope + pre = ""; + + for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) { + pre += "" + out.o[n] + oSpace[n] + ""; + } + str += " " + out.n[i].text + nSpace[i] + pre; + } + } + } + + return str; + }; +}()); + +// for CommonJS enviroments, export everything +if ( typeof exports !== "undefined" ) { + extend( exports, QUnit ); +} + +// get at whatever the global object is, like window in browsers +}( (function() {return this;}.call()) )); diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/README.md new file mode 100644 index 000000000..7cfe3bbca --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/README.md @@ -0,0 +1,50 @@ +# node-tar + +Tar for Node.js. + +## Goals of this project + +1. Be able to parse and reasonably extract the contents of any tar file + created by any program that creates tar files, period. + + At least, this includes every version of: + + * bsdtar + * gnutar + * solaris posix tar + * Joerg Schilling's star ("Schilly tar") + +2. Create tar files that can be extracted by any of the following tar + programs: + + * bsdtar/libarchive version 2.6.2 + * gnutar 1.15 and above + * SunOS Posix tar + * Joerg Schilling's star ("Schilly tar") + +3. 100% test coverage. Speed is important. Correctness is slightly + more important. + +4. Create the kind of tar interface that Node users would want to use. + +5. Satisfy npm's needs for a portable tar implementation with a + JavaScript interface. + +6. No excuses. No complaining. No tolerance for failure. + +## But isn't there already a tar.js? + +Yes, there are a few. This one is going to be better, and it will be +fanatically maintained, because npm will depend on it. + +That's why I need to write it from scratch. Creating and extracting +tarballs is such a large part of what npm does, I simply can't have it +be a black box any longer. + +## Didn't you have something already? Where'd it go? + +It's in the "old" folder. It's not functional. Don't use it. + +It was a useful exploration to learn the issues involved, but like most +software of any reasonable complexity, node-tar won't be useful until +it's been written at least 3 times. diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/buffer-entry.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/buffer-entry.js new file mode 100644 index 000000000..c7b5a6e04 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/buffer-entry.js @@ -0,0 +1,30 @@ +// just like the Entry class, but it buffers the contents +// +// XXX It would be good to set a maximum BufferEntry filesize, +// since it eats up memory. In normal operation, +// these are only for long filenames or link names, which are +// rarely very big. + +module.exports = BufferEntry + +var inherits = require("../vendor/inherits/inherits.js") + , Entry = require("./entry.js") + +function BufferEntry () { + Entry.apply(this, arguments) + this._buffer = new Buffer(this.props.size) + this._offset = 0 + this.body = "" + this.on("end", function () { + this.body = this._buffer.toString().slice(0, -1) + }) +} + +// collect the bytes as they come in. +BufferEntry.prototype.write = function (c) { + c.copy(this._buffer, this._offset) + this._offset += c.length + Entry.prototype.write.call(this, c) +} + +inherits(BufferEntry, Entry) diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/entry-writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/entry-writer.js new file mode 100644 index 000000000..9d6a9b78b --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/entry-writer.js @@ -0,0 +1,169 @@ +module.exports = EntryWriter + +var tar = require("../tar.js") + , TarHeader = require("./header.js") + , Entry = require("./entry.js") + , inherits = require("../vendor/inherits/inherits.js") + , BlockStream = require("../vendor/block-stream/block-stream.js") + , ExtendedHeaderWriter + , Stream = require("stream").Stream + , EOF = {} + +inherits(EntryWriter, Stream) + +function EntryWriter (props) { + var me = this + + if (!(me instanceof EntryWriter)) { + return new EntryWriter(props) + } + + Stream.apply(this) + + me.writable = true + me.readable = true + + me._stream = new BlockStream(512) + + me._stream.on("data", function (c) { + me.emit("data", c) + }) + + me._stream.on("drain", function () { + me.emit("drain") + }) + + me._stream.on("end", function () { + me.emit("end") + me.emit("close") + }) + + me.props = props + if (props.type === "Directory") { + props.size = 0 + } + props.ustar = "ustar\0" + props.ustarver = "00" + me.path = props.path + + me._buffer = [] + me._didHeader = false + me._meta = false + + me.on("pipe", function () { + me._process() + }) +} + +EntryWriter.prototype.write = function (c) { + // console.error(".. ew write") + if (this._ended) return this.emit("error", new Error("write after end")) + this._buffer.push(c) + this._process() + this._needDrain = this._buffer.length > 0 + return !this._needDrain +} + +EntryWriter.prototype.end = function (c) { + // console.error(".. ew end") + if (c) this._buffer.push(c) + this._buffer.push(EOF) + this._ended = true + this._process() + this._needDrain = this._buffer.length > 0 +} + +EntryWriter.prototype.pause = function () { + // console.error(".. ew pause") + this._paused = true + this.emit("pause") +} + +EntryWriter.prototype.resume = function () { + // console.error(".. ew resume") + this._paused = false + this.emit("resume") + this._process() +} + +EntryWriter.prototype.add = function (entry) { + // console.error(".. ew add") + if (!this.parent) return this.emit("error", new Error("no parent")) + + // make sure that the _header and such is emitted, and clear out + // the _currentEntry link on the parent. + if (!this._ended) this.end() + + return this.parent.add(entry) +} + +EntryWriter.prototype._header = function () { + // console.error(".. ew header") + if (this._didHeader) return + this._didHeader = true + + var headerBlock = TarHeader.encode(this.props) + + if (this.props.needExtended && !this._meta) { + var me = this + + ExtendedHeaderWriter = ExtendedHeaderWriter || + require("./extended-header-writer.js") + + ExtendedHeaderWriter(this.props) + .on("data", function (c) { + me.emit("data", c) + }) + .on("error", function (er) { + me.emit("error", er) + }) + .end() + } + + // console.error(".. .. ew headerBlock emitting") + this.emit("data", headerBlock) + this.emit("header") +} + +EntryWriter.prototype._process = function () { + // console.error(".. .. ew process") + if (!this._didHeader && !this._meta) { + this._header() + } + + if (this._paused || this._processing) { + // console.error(".. .. .. paused=%j, processing=%j", this._paused, this._processing) + return + } + + this._processing = true + + var buf = this._buffer + for (var i = 0; i < buf.length; i ++) { + // console.error(".. .. .. i=%d", i) + + var c = buf[i] + + if (c === EOF) this._stream.end() + else this._stream.write(c) + + if (this._paused) { + // console.error(".. .. .. paused mid-emission") + this._processing = false + if (i < buf.length) { + this._needDrain = true + this._buffer = buf.slice(i + 1) + } + return + } + } + + // console.error(".. .. .. emitted") + this._buffer.length = 0 + this._processing = false + + // console.error(".. .. .. emitting drain") + this.emit("drain") +} + +EntryWriter.prototype.destroy = function () {} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/entry.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/entry.js new file mode 100644 index 000000000..9d5b8bca6 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/entry.js @@ -0,0 +1,212 @@ +// A passthrough read/write stream that sets its properties +// based on a header, extendedHeader, and globalHeader +// +// Can be either a file system object of some sort, or +// a pax/ustar metadata entry. + +module.exports = Entry + +var TarHeader = require("./header.js") + , tar = require("../tar") + , assert = require("assert").ok + , Stream = require("stream").Stream + , inherits = require("../vendor/inherits/inherits.js") + , fstream = require("../vendor/fstream/fstream.js").Abstract + +function Entry (header, extended, global) { + Stream.call(this) + this.readable = true + this.writable = true + + this._needDrain = false + this._paused = false + this._reading = false + this._ending = false + this._ended = false + this._remaining = 0 + this._queue = [] + this._index = 0 + this._queueLen = 0 + + this._read = this._read.bind(this) + + this.props = {} + this._header = header + this._extended = extended || {} + + // globals can change throughout the course of + // a file parse operation. Freeze it at its current state. + this._global = {} + var me = this + Object.keys(global || {}).forEach(function (g) { + me._global[g] = global[g] + }) + + this._setProps() +} + +inherits(Entry, Stream, +{ write: function (c) { + if (this._ending) this.error("write() after end()", null, true) + if (this._remaining === 0) { + this.error("invalid bytes past eof") + } + + // often we'll get a bunch of \0 at the end of the last write, + // since chunks will always be 512 bytes when reading a tarball. + if (c.length > this._remaining) { + c = c.slice(0, this._remaining) + } + this._remaining -= c.length + + // put it on the stack. + var ql = this._queueLen + this._queue.push(c) + this._queueLen ++ + + this._read() + + // either paused, or buffered + if (this._paused || ql > 0) { + this._needDrain = true + return false + } + + return true + } + +, end: function (c) { + if (c) this.write(c) + this._ending = true + this._read() + } + +, pause: function () { + this._paused = true + this.emit("pause") + } + +, resume: function () { + // console.error(" Tar Entry resume", this.path) + this.emit("resume") + this._paused = false + this._read() + return this._queueLen - this._index > 1 + } + + // This is bound to the instance +, _read: function () { + // console.error(" Tar Entry _read", this.path) + + if (this._paused || this._reading || this._ended) return + + // set this flag so that event handlers don't inadvertently + // get multiple _read() calls running. + this._reading = true + + // have any data to emit? + if (this._index < this._queueLen) { + var chunk = this._queue[this._index ++] + this.emit("data", chunk) + } + + // check if we're drained + if (this._index >= this._queueLen) { + this._queue.length = this._queueLen = this._index = 0 + if (this._needDrain) { + this._needDrain = false + this.emit("drain") + } + if (this._ending) { + this._ended = true + this.emit("end") + } + } + + // if the queue gets too big, then pluck off whatever we can. + // this should be fairly rare. + var mql = this._maxQueueLen + if (this._queueLen > mql && this._index > 0) { + mql = Math.min(this._index, mql) + this._index -= mql + this._queueLen -= mql + this._queue = this._queue.slice(mql) + } + + this._reading = false + } + +, _setProps: function () { + // props = extended->global->header->{} + var header = this._header + , extended = this._extended + , global = this._global + , props = this.props + + // first get the values from the normal header. + var fields = tar.fields + for (var f = 0; fields[f] !== null; f ++) { + var field = fields[f] + , val = header[field] + if (typeof val !== "undefined") props[field] = val + } + + // next, the global header for this file. + // numeric values, etc, will have already been parsed. + ;[global, extended].forEach(function (p) { + Object.keys(p).forEach(function (f) { + if (typeof p[f] !== "undefined") props[f] = p[f] + }) + }) + + // no nulls allowed in path or linkpath + ;["path", "linkpath"].forEach(function (p) { + if (props.hasOwnProperty(p)) { + props[p] = props[p].split("\0")[0] + } + }) + + + // set date fields to be a proper date + ;["mtime", "ctime", "atime"].forEach(function (p) { + if (props.hasOwnProperty(p)) { + props[p] = new Date(props[p] * 1000) + } + }) + + // set the type so that we know what kind of file to create + var type + switch (tar.types[props.type]) { + case "OldFile": + case "ContiguousFile": + type = "File" + break + + case "GNUDumpDir": + type = "Directory" + break + + case undefined: + type = "Unknown" + break + + case "Link": + case "SymbolicLink": + case "CharacterDevice": + case "BlockDevice": + case "Directory": + case "FIFO": + default: + type = tar.types[props.type] + } + + this.type = type + this.path = props.path + this.size = props.size + + // size is special, since it signals when the file needs to end. + this._remaining = props.size + } +, warn: fstream.warn +, error: fstream.error +}) diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/extended-header-writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/extended-header-writer.js new file mode 100644 index 000000000..10a7d8fe2 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/extended-header-writer.js @@ -0,0 +1,192 @@ + +module.exports = ExtendedHeaderWriter + +var inherits = require("../vendor/inherits/inherits.js") + , EntryWriter = require("./entry-writer.js") + +inherits(ExtendedHeaderWriter, EntryWriter) + +var tar = require("../tar.js") + , path = require("path") + , inherits = require("../vendor/inherits/inherits.js") + , TarHeader = require("./header.js") + +// props is the props of the thing we need to write an +// extended header for. +// Don't be shy with it. Just encode everything. +function ExtendedHeaderWriter (props) { + // console.error(">> ehw ctor") + var me = this + + if (!(me instanceof ExtendedHeaderWriter)) { + return new ExtendedHeaderWriter(props) + } + + me.fields = props + + var p = + { path : ("PaxHeader" + path.join("/", props.path || "")) + .replace(/\\/g, "/").substr(0, 100) + , mode : props.mode || 0666 + , uid : props.uid || 0 + , gid : props.gid || 0 + , size : 0 // will be set later + , mtime : props.mtime || Date.now() / 1000 + , type : "x" + , linkpath : "" + , ustar : "ustar\0" + , ustarver : "00" + , uname : props.uname || "" + , gname : props.gname || "" + , devmaj : props.devmaj || 0 + , devmin : props.devmin || 0 + } + + + EntryWriter.call(me, p) + // console.error(">> ehw props", me.props) + me.props = p + + me._meta = true +} + +ExtendedHeaderWriter.prototype.end = function () { + // console.error(">> ehw end") + var me = this + + if (me._ended) return + me._ended = true + + me._encodeFields() + + if (me.props.size === 0) { + // nothing to write! + me._ready = true + me._stream.end() + return + } + + me._stream.write(TarHeader.encode(me.props)) + me.body.forEach(function (l) { + me._stream.write(l) + }) + me._ready = true + + // console.error(">> ehw _process calling end()", me.props) + this._stream.end() +} + +ExtendedHeaderWriter.prototype._encodeFields = function () { + // console.error(">> ehw _encodeFields") + this.body = [] + if (this.fields.prefix) { + this.fields.path = this.fields.prefix + "/" + this.fields.path + this.fields.prefix = "" + } + encodeFields(this.fields, "", this.body, this.fields.noProprietary) + var me = this + this.body.forEach(function (l) { + me.props.size += l.length + }) +} + +function encodeFields (fields, prefix, body, nop) { + // console.error(">> >> ehw encodeFields") + // "%d %s=%s\n", , , + // The length is a decimal number, and includes itself and the \n + // Numeric values are decimal strings. + + Object.keys(fields).forEach(function (k) { + var val = fields[k] + , numeric = tar.numeric[k] + + if (prefix) k = prefix + "." + k + + // already including NODETAR.type, don't need File=true also + if (k === fields.type && val === true) return + + switch (k) { + // don't include anything that's always handled just fine + // in the normal header, or only meaningful in the context + // of nodetar + case "mode": + case "cksum": + case "ustar": + case "ustarver": + case "prefix": + case "basename": + case "dirname": + case "needExtended": + case "block": + case "filter": + return + + case "rdev": + if (val === 0) return + break + + case "nlink": + case "dev": // Truly a hero among men, Creator of Star! + case "ino": // Speak his name with reverent awe! It is: + k = "SCHILY." + k + break + + default: break + } + + if (val && typeof val === "object" && + !Buffer.isBuffer(val)) encodeFields(val, k, body, nop) + else if (val === null || val === undefined) return + else body.push.apply(body, encodeField(k, val, nop)) + }) + + return body +} + +function encodeField (k, v, nop) { + // lowercase keys must be valid, otherwise prefix with + // "NODETAR." + if (k.charAt(0) === k.charAt(0).toLowerCase()) { + var m = k.split(".")[0] + if (!tar.knownExtended[m]) k = "NODETAR." + k + } + + // no proprietary + if (nop && k.charAt(0) !== k.charAt(0).toLowerCase()) { + return [] + } + + if (typeof val === "number") val = val.toString(10) + + var s = new Buffer(" " + k + "=" + v + "\n") + , digits = Math.floor(Math.log(s.length) / Math.log(10)) + 1 + + // console.error("1 s=%j digits=%j s.length=%d", s.toString(), digits, s.length) + + // if adding that many digits will make it go over that length, + // then add one to it. For example, if the string is: + // " foo=bar\n" + // then that's 9 characters. With the "9", that bumps the length + // up to 10. However, this is invalid: + // "10 foo=bar\n" + // but, since that's actually 11 characters, since 10 adds another + // character to the length, and the length includes the number + // itself. In that case, just bump it up again. + if (s.length + digits >= Math.pow(10, digits)) digits += 1 + // console.error("2 s=%j digits=%j s.length=%d", s.toString(), digits, s.length) + + var len = digits + s.length + // console.error("3 s=%j digits=%j s.length=%d len=%d", s.toString(), digits, s.length, len) + var lenBuf = new Buffer("" + len) + if (lenBuf.length + s.length !== len) { + throw new Error("Bad length calculation\n"+ + "len="+len+"\n"+ + "lenBuf="+JSON.stringify(lenBuf.toString())+"\n"+ + "lenBuf.length="+lenBuf.length+"\n"+ + "digits="+digits+"\n"+ + "s="+JSON.stringify(s.toString())+"\n"+ + "s.length="+s.length) + } + + return [lenBuf, s] +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/extended-header.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/extended-header.js new file mode 100644 index 000000000..63b79eca9 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/extended-header.js @@ -0,0 +1,139 @@ +// An Entry consisting of: +// +// "%d %s=%s\n", , , +// +// The length is a decimal number, and includes itself and the \n +// \0 does not terminate anything. Only the length terminates the string. +// Numeric values are decimal strings. + +module.exports = ExtendedHeader + +var Entry = require("./entry.js") + , inherits = require("../vendor/inherits/inherits.js") + , tar = require("../tar.js") + , numeric = tar.numeric + , keyTrans = { "SCHILY.dev": "dev" + , "SCHILY.ino": "ino" + , "SCHILY.nlink": "nlink" } + +function ExtendedHeader () { + Entry.apply(this, arguments) + this.on("data", this._parse) + this.fields = {} + this._position = 0 + this._fieldPos = 0 + this._state = SIZE + this._sizeBuf = [] + this._keyBuf = [] + this._valBuf = [] + this._size = -1 + this._key = "" +} + +inherits(ExtendedHeader, Entry, { _parse: parse }) + +var s = 0 + , states = ExtendedHeader.states = {} + , SIZE = states.SIZE = s++ + , KEY = states.KEY = s++ + , VAL = states.VAL = s++ + , ERR = states.ERR = s++ + +Object.keys(states).forEach(function (s) { + states[states[s]] = states[s] +}) + +states[s] = null + +// char code values for comparison +var _0 = "0".charCodeAt(0) + , _9 = "9".charCodeAt(0) + , point = ".".charCodeAt(0) + , a = "a".charCodeAt(0) + , Z = "Z".charCodeAt(0) + , a = "a".charCodeAt(0) + , z = "z".charCodeAt(0) + , space = " ".charCodeAt(0) + , eq = "=".charCodeAt(0) + , cr = "\n".charCodeAt(0) + +function parse (c) { + if (this._state === ERR) return + + for ( var i = 0, l = c.length + ; i < l + ; this._position++, this._fieldPos++, i++) { + // console.error("top of loop, size="+this._size) + + var b = c[i] + + if (this._size >= 0 && this._fieldPos > this._size) { + error(this, "field exceeds length="+this._size) + return + } + + switch (this._state) { + case ERR: return + + case SIZE: + // console.error("parsing size, b=%d, rest=%j", b, c.slice(i).toString()) + if (b === space) { + this._state = KEY + // this._fieldPos = this._sizeBuf.length + this._size = parseInt(new Buffer(this._sizeBuf).toString(), 10) + this._sizeBuf.length = 0 + continue + } + if (b < _0 || b > _9) { + error(this, "expected [" + _0 + ".." + _9 + "], got " + b) + return + } + this._sizeBuf.push(b) + continue + + case KEY: + // can be any char except =, not > size. + if (b === eq) { + this._state = VAL + this._key = new Buffer(this._keyBuf).toString() + if (keyTrans[this._key]) this._key = keyTrans[this._key] + this._keyBuf.length = 0 + continue + } + this._keyBuf.push(b) + continue + + case VAL: + // field must end with cr + if (this._fieldPos === this._size - 1) { + // console.error("finished with "+this._key) + if (b !== cr) { + error(this, "expected \\n at end of field") + return + } + var val = new Buffer(this._valBuf).toString() + if (numeric[this._key]) { + val = parseFloat(val) + } + this.fields[this._key] = val + + this._valBuf.length = 0 + this._state = SIZE + this._size = -1 + this._fieldPos = -1 + continue + } + this._valBuf.push(b) + continue + } + } +} + +function error (me, msg) { + msg = "invalid header: " + msg + + "\nposition=" + me._position + + "\nfield position=" + me._fieldPos + + me.error(msg) + me.state = ERR +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/extract.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/extract.js new file mode 100644 index 000000000..bffc03380 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/extract.js @@ -0,0 +1,78 @@ +// give it a tarball and a path, and it'll dump the contents + +module.exports = Extract + +var tar = require("../tar.js") + , fstream = require("../vendor/fstream/fstream.js") + , inherits = require("../vendor/inherits/inherits.js") + , path = require("path") + +function Extract (opts) { + if (!(this instanceof Extract)) return new Extract(opts) + tar.Parse.apply(this) + + // have to dump into a directory + opts.type = "Directory" + opts.Directory = true + + if (typeof opts !== "object") { + opts = { path: opts } + } + + // better to drop in cwd? seems more standard. + opts.path = opts.path || path.resolve("node-tar-extract") + opts.type = "Directory" + opts.Directory = true + + // similar to --strip or --strip-components + opts.strip = +opts.strip + if (!opts.strip || opts.strip <= 0) opts.strip = 0 + + this._fst = fstream.Writer(opts) + + this.pause() + var me = this + + // Hardlinks in tarballs are relative to the root + // of the tarball. So, they need to be resolved against + // the target directory in order to be created properly. + me.on("entry", function (entry) { + // if there's a "strip" argument, then strip off that many + // path components. + if (opts.strip) { + var p = entry.path.split("/").slice(opts.strip).join("/") + entry.path = entry.props.path = p + if (entry.linkpath) { + var lp = entry.linkpath.split("/").slice(opts.strip).join("/") + entry.linkpath = entry.props.linkpath = lp + } + } + if (entry.type !== "Link") return + entry.linkpath = entry.props.linkpath = + path.join(opts.path, path.join("/", entry.props.linkpath)) + }) + + this._fst.on("ready", function () { + me.pipe(me._fst, { end: false }) + me.resume() + }) + + // this._fst.on("end", function () { + // console.error("\nEEEE Extract End", me._fst.path) + // }) + + this._fst.on("close", function () { + // console.error("\nEEEE Extract End", me._fst.path) + me.emit("end") + me.emit("close") + }) +} + +inherits(Extract, tar.Parse) + +Extract.prototype._streamEnd = function () { + var me = this + if (!me._ended) me.error("unexpected eof") + me._fst.end() + // my .end() is coming later. +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/global-header-writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/global-header-writer.js new file mode 100644 index 000000000..99ff25779 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/global-header-writer.js @@ -0,0 +1,14 @@ +module.exports = GlobalHeaderWriter + +var ExtendedHeaderWriter = require("./extended-header-writer.js") + , inherits = require("../vendor/inherits/inherits.js") + +inherits(GlobalHeaderWriter, ExtendedHeaderWriter) + +function GlobalHeaderWriter (props) { + if (!(this instanceof GlobalHeaderWriter)) { + return new GlobalHeaderWriter(props) + } + ExtendedHeaderWriter.call(this, props) + this.props.type = "g" +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/header.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/header.js new file mode 100644 index 000000000..05b237c0c --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/header.js @@ -0,0 +1,385 @@ +// parse a 512-byte header block to a data object, or vice-versa +// If the data won't fit nicely in a simple header, then generate +// the appropriate extended header file, and return that. + +module.exports = TarHeader + +var tar = require("../tar.js") + , fields = tar.fields + , fieldOffs = tar.fieldOffs + , fieldEnds = tar.fieldEnds + , fieldSize = tar.fieldSize + , numeric = tar.numeric + , assert = require("assert").ok + , space = " ".charCodeAt(0) + , slash = "/".charCodeAt(0) + , bslash = process.platform === "win32" ? "\\".charCodeAt(0) : null + +function TarHeader (block) { + if (!(this instanceof TarHeader)) return new TarHeader(block) + if (block) this.decode(block) +} + +TarHeader.prototype = + { decode : decode + , encode: encode + , calcSum: calcSum + , checkSum: checkSum + } + +TarHeader.parseNumeric = parseNumeric +TarHeader.encode = encode +TarHeader.decode = decode + +// note that this will only do the normal ustar header, not any kind +// of extended posix header file. If something doesn't fit comfortably, +// then it will set obj.needExtended = true, and set the block to +// the closest approximation. +function encode (obj) { + if (!obj && !(this instanceof TarHeader)) throw new Error( + "encode must be called on a TarHeader, or supplied an object") + + obj = obj || this + var block = obj.block = new Buffer(512) + + // if the object has a "prefix", then that's actually an extension of + // the path field. + if (obj.prefix) { + // console.error("%% header encoding, got a prefix", obj.prefix) + obj.path = obj.prefix + "/" + obj.path + // console.error("%% header encoding, prefixed path", obj.path) + obj.prefix = "" + } + + obj.needExtended = false + + if (obj.mode) { + if (typeof obj.mode === "string") obj.mode = parseInt(obj.mode, 8) + obj.mode = obj.mode & 0777 + } + + for (var f = 0; fields[f] !== null; f ++) { + var field = fields[f] + , off = fieldOffs[f] + , end = fieldEnds[f] + , ret + + switch (field) { + case "cksum": + // special, done below, after all the others + break + + case "prefix": + // special, this is an extension of the "path" field. + // console.error("%% header encoding, skip prefix later") + break + + case "type": + // convert from long name to a single char. + var type = obj.type || "0" + if (type.length > 1) { + type = tar.types[obj.type] + if (!type) type = "0" + } + writeText(block, off, end, type) + break + + case "path": + // uses the "prefix" field if > 100 bytes, but <= 255 + var pathLen = Buffer.byteLength(obj.path) + , pathFSize = fieldSize[fields.path] + , prefFSize = fieldSize[fields.prefix] + + // paths between 100 and 255 should use the prefix field. + // longer than 255 + if (pathLen > pathFSize && + pathLen <= pathFSize + prefFSize) { + // need to find a slash somewhere in the middle so that + // path and prefix both fit in their respective fields + var searchStart = pathLen - 1 - pathFSize + , searchEnd = prefFSize + , found = false + , pathBuf = new Buffer(obj.path) + + for ( var s = searchStart + ; (s <= searchEnd) + ; s ++ ) { + if (pathBuf[s] === slash || pathBuf[s] === bslash) { + found = s + break + } + } + + if (found !== false) { + prefix = pathBuf.slice(0, found).toString("utf8") + path = pathBuf.slice(found + 1).toString("utf8") + + ret = writeText(block, off, end, path) + off = fieldOffs[fields.prefix] + end = fieldEnds[fields.prefix] + // console.error("%% header writing prefix", off, end, prefix) + ret = writeText(block, off, end, prefix) || ret + break + } + } + + // paths less than 100 chars don't need a prefix + // and paths longer than 255 need an extended header and will fail + // on old implementations no matter what we do here. + // Null out the prefix, and fallthrough to default. + // console.error("%% header writing no prefix") + var poff = fieldOffs[fields.prefix] + , pend = fieldEnds[fields.prefix] + writeText(block, poff, pend, "") + // fallthrough + + // all other fields are numeric or text + default: + ret = numeric[field] + ? writeNumeric(block, off, end, obj[field]) + : writeText(block, off, end, obj[field] || "") + break + } + obj.needExtended = obj.needExtended || ret + } + + var off = fieldOffs[fields.cksum] + , end = fieldEnds[fields.cksum] + + writeNumeric(block, off, end, calcSum.call(this, block)) + + return block +} + +// if it's a negative number, or greater than will fit, +// then use write256. +var MAXNUM = { 12: 077777777777 + , 11: 07777777777 + , 8 : 07777777 + , 7 : 0777777 } +function writeNumeric (block, off, end, num) { + var writeLen = end - off + , maxNum = MAXNUM[writeLen] || 0 + + num = num || 0 + // console.error(" numeric", num) + + if (num instanceof Date || + Object.prototype.toString.call(num) === "[object Date]") { + num = num.getTime() / 1000 + } + + if (num > maxNum || num < 0) { + write256(block, off, end, num) + // need an extended header if negative or too big. + return true + } + + // god, tar is so annoying + // if the string is small enough, you should put a space + // between the octal string and the \0, but if it doesn't + // fit, then don't. + var numStr = Math.floor(num).toString(8) + if (num < MAXNUM[writeLen - 1]) numStr += " " + + // pad with "0" chars + if (numStr.length < writeLen) { + numStr = (new Array(writeLen - numStr.length).join("0")) + numStr + } + + if (numStr.length !== writeLen - 1) { + throw new Error("invalid length: " + JSON.stringify(numStr) + "\n" + + "expected: "+writeLen) + } + block.write(numStr, off, writeLen, "utf8") + block[end - 1] = 0 +} + +function write256 (block, off, end, num) { + var buf = block.slice(off, end) + var positive = num >= 0 + buf[0] = positive ? 0x80 : 0xFF + + // get the number as a base-256 tuple + if (!positive) num *= -1 + var tuple = [] + do { + var n = num % 256 + tuple.push(n) + num = (num - n) / 256 + } while (num) + + var bytes = tuple.length + + var fill = buf.length - bytes + for (var i = 1; i < fill; i ++) { + buf[i] = positive ? 0 : 0xFF + } + + // tuple is a base256 number, with [0] as the *least* significant byte + // if it's negative, then we need to flip all the bits once we hit the + // first non-zero bit. The 2's-complement is (0x100 - n), and the 1's- + // complement is (0xFF - n). + var zero = true + for (i = bytes; i > 0; i --) { + var byte = tuple[bytes - i] + if (positive) buf[fill + i] = byte + else if (zero && byte === 0) buf[fill + i] = 0 + else if (zero) { + zero = false + buf[fill + i] = 0x100 - byte + } else buf[fill + i] = 0xFF - byte + } +} + +function writeText (block, off, end, str) { + // strings are written as utf8, then padded with \0 + var strLen = Buffer.byteLength(str) + , writeLen = Math.min(strLen, end - off) + // non-ascii fields need extended headers + // long fields get truncated + , needExtended = strLen !== str.length || strLen > writeLen + + // write the string, and null-pad + if (writeLen > 0) block.write(str, off, writeLen, "utf8") + for (var i = off + writeLen; i < end; i ++) block[i] = 0 + + return needExtended +} + +function calcSum (block) { + block = block || this.block + assert(Buffer.isBuffer(block) && block.length === 512) + + if (!block) throw new Error("Need block to checksum") + + // now figure out what it would be if the cksum was " " + var sum = 0 + , start = fieldOffs[fields.cksum] + , end = fieldEnds[fields.cksum] + + for (var i = 0; i < fieldOffs[fields.cksum]; i ++) { + sum += block[i] + } + + for (var i = start; i < end; i ++) { + sum += space + } + + for (var i = end; i < 512; i ++) { + sum += block[i] + } + + return sum +} + + +function checkSum (block) { + var sum = calcSum.call(this, block) + block = block || this.block + + var cksum = block.slice(fieldOffs[fields.cksum], fieldEnds[fields.cksum]) + cksum = parseNumeric(cksum) + + return cksum === sum +} + +function decode (block) { + block = block || this.block + assert(Buffer.isBuffer(block) && block.length === 512) + + this.block = block + this.cksumValid = this.checkSum() + + var prefix = null + + // slice off each field. + for (var f = 0; fields[f] !== null; f ++) { + var field = fields[f] + , val = block.slice(fieldOffs[f], fieldEnds[f]) + + switch (field) { + case "ustar": + // if not ustar, then everything after that is just padding. + if (val.toString() !== "ustar\0") { + this.ustar = false + return + } else { + // console.error("ustar:", val, val.toString()) + this.ustar = val.toString() + } + break + + // prefix is special, since it might signal the xstar header + case "prefix": + var atime = parseNumeric(val.slice(131, 131 + 12)) + , ctime = parseNumeric(val.slice(131 + 12, 131 + 12 + 12)) + if ((val[130] === 0 || val[130] === space) && + typeof atime === "number" && + typeof ctime === "number" && + val[131 + 12] === space && + val[131 + 12 + 12] === space) { + this.atime = atime + this.ctime = ctime + val = val.slice(0, 130) + } + prefix = val.toString("utf8").replace(/\0+$/, "") + // console.error("%% header reading prefix", prefix) + break + + // all other fields are null-padding text + // or a number. + default: + if (numeric[field]) { + this[field] = parseNumeric(val) + } else { + this[field] = val.toString("utf8").replace(/\0+$/, "") + } + break + } + } + + // if we got a prefix, then prepend it to the path. + if (prefix) { + this.path = prefix + "/" + this.path + // console.error("%% header got a prefix", this.path) + } +} + +function parse256 (buf) { + // first byte MUST be either 80 or FF + // 80 for positive, FF for 2's comp + var positive + if (buf[0] === 0x80) positive = true + else if (buf[0] === 0xFF) positive = false + else return null + + // build up a base-256 tuple from the least sig to the highest + var zero = false + , tuple = [] + for (var i = buf.length - 1; i > 0; i --) { + var byte = buf[i] + if (positive) tuple.push(byte) + else if (zero && byte === 0) tuple.push(0) + else if (zero) { + zero = false + tuple.push(0x100 - byte) + } else tuple.push(0xFF - byte) + } + + for (var sum = 0, i = 0, l = tuple.length; i < l; i ++) { + sum += tuple[i] * Math.pow(256, i) + } + + return positive ? sum : -1 * sum +} + +function parseNumeric (f) { + if (f[0] & 0x80) return parse256(f) + + var str = f.toString("utf8").split("\0")[0].trim() + , res = parseInt(str, 8) + + return isNaN(res) ? null : res +} + diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/pack.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/pack.js new file mode 100644 index 000000000..11b11fb38 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/pack.js @@ -0,0 +1,226 @@ +// pipe in an fstream, and it'll make a tarball. +// key-value pair argument is global extended header props. + +module.exports = Pack + +var EntryWriter = require("./entry-writer.js") + , Stream = require("stream").Stream + , path = require("path") + , inherits = require("../vendor/inherits/inherits.js") + , GlobalHeaderWriter = require("./global-header-writer.js") + , collect = require("../vendor/fstream/fstream.js").collect + , eof = new Buffer(512) + +for (var i = 0; i < 512; i ++) eof[i] = 0 + +inherits(Pack, Stream) + +function Pack (props) { + // console.error("-- p ctor") + var me = this + if (!(me instanceof Pack)) return new Pack(props) + + if (props) me._noProprietary = props.noProprietary + else me._noProprietary = false + + me._global = props + + me.readable = true + me.writable = true + me._buffer = [] + // console.error("-- -- set current to null in ctor") + me._currentEntry = null + me._processing = false + + me._pipeRoot = null + me.on("pipe", function (src) { + if (src.root === me._pipeRoot) return + me._pipeRoot = src + src.on("end", function () { + me._pipeRoot = null + }) + me.add(src) + }) +} + +Pack.prototype.addGlobal = function (props) { + // console.error("-- p addGlobal") + if (this._didGlobal) return + this._didGlobal = true + + var me = this + GlobalHeaderWriter(props) + .on("data", function (c) { + me.emit("data", c) + }) + .end() +} + +Pack.prototype.add = function (stream) { + if (this._global && !this._didGlobal) this.addGlobal(this._global) + + if (this._ended) return this.emit("error", new Error("add after end")) + + collect(stream) + this._buffer.push(stream) + this._process() + this._needDrain = this._buffer.length > 0 + return !this._needDrain +} + +Pack.prototype.pause = function () { + this._paused = true + if (this._currentEntry) this._currentEntry.pause() + this.emit("pause") +} + +Pack.prototype.resume = function () { + this._paused = false + if (this._currentEntry) this._currentEntry.resume() + this.emit("resume") + this._process() +} + +Pack.prototype.end = function () { + this._ended = true + this._buffer.push(eof) + this._process() +} + +Pack.prototype._process = function () { + var me = this + if (me._paused || me._processing) { + return + } + + var entry = me._buffer.shift() + + if (!entry) { + if (me._needDrain) { + me.emit("drain") + } + return + } + + if (entry.ready === false) { + // console.error("-- entry is not ready", entry) + me._buffer.unshift(entry) + entry.on("ready", function () { + // console.error("-- -- ready!", entry) + me._process() + }) + return + } + + me._processing = true + + if (entry === eof) { + // need 2 ending null blocks. + me.emit("data", eof) + me.emit("data", eof) + me.emit("end") + me.emit("close") + return + } + + // Change the path to be relative to the root dir that was + // added to the tarball. + // + // XXX This should be more like how -C works, so you can + // explicitly set a root dir, and also explicitly set a pathname + // in the tarball to use. That way we can skip a lot of extra + // work when resolving symlinks for bundled dependencies in npm. + + var root = path.dirname((entry.root || entry).path) + var wprops = {} + + Object.keys(entry.props).forEach(function (k) { + wprops[k] = entry.props[k] + }) + + if (me._noProprietary) wprops.noProprietary = true + + wprops.path = path.relative(root, entry.path) + + // actually not a matter of opinion or taste. + if (process.platform === "win32") { + wprops.path = wprops.path.replace(/\\/g, "/") + } + + switch (wprops.type) { + // sockets not supported + case "Socket": + return + + case "Directory": + wprops.path += "/" + wprops.size = 0 + break + case "Link": + var lp = path.resolve(path.dirname(entry.path), entry.linkpath) + wprops.linkpath = path.relative(root, lp) || "." + wprops.size = 0 + break + case "SymbolicLink": + var lp = path.resolve(path.dirname(entry.path), entry.linkpath) + wprops.linkpath = path.relative(path.dirname(entry.path), lp) || "." + wprops.size = 0 + break + } + + // console.error("-- new writer", wprops) + // if (!wprops.type) { + // // console.error("-- no type?", entry.constructor.name, entry) + // } + + // console.error("-- -- set current to new writer", wprops.path) + var writer = me._currentEntry = EntryWriter(wprops) + + writer.parent = me + + // writer.on("end", function () { + // // console.error("-- -- writer end", writer.path) + // }) + + writer.on("data", function (c) { + me.emit("data", c) + }) + + writer.on("header", function () { + Buffer.prototype.toJSON = function () { + return this.toString().split(/\0/).join(".") + } + // console.error("-- -- writer header %j", writer.props) + if (writer.props.size === 0) nextEntry() + }) + writer.on("close", nextEntry) + + var ended = false + function nextEntry () { + if (ended) return + ended = true + + // console.error("-- -- writer close", writer.path) + // console.error("-- -- set current to null", wprops.path) + me._currentEntry = null + me._processing = false + me._process() + } + + writer.on("error", function (er) { + // console.error("-- -- writer error", writer.path) + me.emit("error", er) + }) + + // if it's the root, then there's no need to add its entries, + // or data, since they'll be added directly. + if (entry === me._pipeRoot) { + // console.error("-- is the root, don't auto-add") + writer.add = null + } + + entry.pipe(writer) +} + +Pack.prototype.destroy = function () {} +Pack.prototype.write = function () {} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/parse.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/parse.js new file mode 100644 index 000000000..3f71a92d5 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/lib/parse.js @@ -0,0 +1,270 @@ + +// A writable stream. +// It emits "entry" events, which provide a readable stream that has +// header info attached. + +module.exports = Parse.create = Parse + +var stream = require("stream") + , Stream = stream.Stream + , BlockStream = require("../vendor/block-stream/block-stream.js") + , tar = require("../tar.js") + , TarHeader = require("./header.js") + , Entry = require("./entry.js") + , BufferEntry = require("./buffer-entry.js") + , ExtendedHeader = require("./extended-header.js") + , assert = require("assert").ok + , inherits = require("../vendor/inherits/inherits.js") + , fstream = require("../vendor/fstream/fstream.js") + +// reading a tar is a lot like reading a directory +// However, we're actually not going to run the ctor, +// since it does a stat and various other stuff. +// This inheritance gives us the pause/resume/pipe +// behavior that is desired. +inherits(Parse, fstream.Reader) + +function Parse () { + var me = this + if (!(me instanceof Parse)) return new Parse() + + // doesn't apply fstream.Reader ctor? + // no, becasue we don't want to stat/etc, we just + // want to get the entry/add logic from .pipe() + Stream.apply(me) + + me.writable = true + me.readable = true + me._stream = new BlockStream(512) + me.position = 0 + + me._stream.on("error", function (e) { + me.emit("error", e) + }) + + me._stream.on("data", function (c) { + me._process(c) + }) + + me._stream.on("end", function () { + me._streamEnd() + }) + + me._stream.on("drain", function () { + me.emit("drain") + }) +} + +// overridden in Extract class, since it needs to +// wait for its DirWriter part to finish before +// emitting "end" +Parse.prototype._streamEnd = function () { + var me = this + if (!me._ended) me.error("unexpected eof") + me.emit("end") +} + +// a tar reader is actually a filter, not just a readable stream. +// So, you should pipe a tarball stream into it, and it needs these +// write/end methods to do that. +Parse.prototype.write = function (c) { + if (this._ended) { + // gnutar puts a LOT of nulls at the end. + // you can keep writing these things forever. + // Just ignore them. + for (var i = 0, l = c.length; i > l; i ++) { + if (c[i] !== 0) return this.error("write() after end()") + } + return + } + return this._stream.write(c) +} + +Parse.prototype.end = function (c) { + this._ended = true + return this._stream.end(c) +} + +// don't need to do anything, since we're just +// proxying the data up from the _stream. +// Just need to override the parent's "Not Implemented" +// error-thrower. +Parse.prototype._read = function () {} + +Parse.prototype._process = function (c) { + assert(c && c.length === 512, "block size should be 512") + + // one of three cases. + // 1. A new header + // 2. A part of a file/extended header + // 3. One of two or more EOF null blocks + + if (this._entry) { + var entry = this._entry + entry.write(c) + if (entry._remaining === 0) { + entry.end() + this._entry = null + } + } else { + // either zeroes or a header + var zero = true + for (var i = 0; i < 512 && zero; i ++) { + zero = c[i] === 0 + } + + // eof is *at least* 2 blocks of nulls, and then the end of the + // file. you can put blocks of nulls between entries anywhere, + // so appending one tarball to another is technically valid. + // ending without the eof null blocks is not allowed, however. + if (zero) { + this._ended = this._eofStarted + this._eofStarted = true + } else { + this._ended = this._eofStarted = false + this._startEntry(c) + } + + } + + this.position += 512 +} + +// take a header chunk, start the right kind of entry. +Parse.prototype._startEntry = function (c) { + var header = new TarHeader(c) + , self = this + , entry + , ev + , EntryType + , onend + , meta = false + + if (null === header.size || !header.cksumValid) { + var e = new Error("invalid tar file") + e.header = header + e.tar_file_offset = this.position + e.tar_block = this.position / 512 + this.emit("error", e) + } + + switch (tar.types[header.type]) { + case "File": + case "OldFile": + case "Link": + case "SymbolicLink": + case "CharacterDevice": + case "BlockDevice": + case "Directory": + case "FIFO": + case "ContiguousFile": + case "GNUDumpDir": + // start a file. + // pass in any extended headers + // These ones consumers are typically most interested in. + EntryType = Entry + ev = "entry" + break + + case "GlobalExtendedHeader": + // extended headers that apply to the rest of the tarball + EntryType = ExtendedHeader + onend = function () { + self._global = self._global || {} + Object.keys(entry.fields).forEach(function (k) { + self._global[k] = entry.fields[k] + }) + } + ev = "globalExtendedHeader" + meta = true + break + + case "ExtendedHeader": + case "OldExtendedHeader": + // extended headers that apply to the next entry + EntryType = ExtendedHeader + onend = function () { + self._extended = entry.fields + } + ev = "extendedHeader" + meta = true + break + + case "NextFileHasLongLinkpath": + // set linkpath= in extended header + EntryType = BufferEntry + onend = function () { + self._extended = self._extended || {} + self._extended.linkpath = entry.body + } + ev = "longLinkpath" + meta = true + break + + case "NextFileHasLongPath": + case "OldGnuLongPath": + // set path= in file-extended header + EntryType = BufferEntry + onend = function () { + self._extended = self._extended || {} + self._extended.path = entry.body + } + ev = "longPath" + meta = true + break + + default: + // all the rest we skip, but still set the _entry + // member, so that we can skip over their data appropriately. + // emit an event to say that this is an ignored entry type? + EntryType = Entry + ev = "ignoredEntry" + break + } + + var global, extended + if (meta) { + global = extended = null + } else { + var global = this._global + var extended = this._extended + + // extendedHeader only applies to one entry, so once we start + // an entry, it's over. + this._extended = null + } + entry = new EntryType(header, extended, global) + entry.meta = meta + + // only proxy data events of normal files. + if (!meta) { + entry.on("data", function (c) { + me.emit("data", c) + }) + } + + if (onend) entry.on("end", onend) + + this._entry = entry + var me = this + + entry.on("pause", function () { + me.pause() + }) + + entry.on("resume", function () { + me.resume() + }) + + if (this.listeners("*").length) { + this.emit("*", ev, entry) + } + + this.emit(ev, entry) + + // Zero-byte entry. End immediately. + if (entry.props.size === 0) { + entry.end() + this._entry = null + } +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/tar.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/tar.js new file mode 100644 index 000000000..b9dbca489 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/tar.js @@ -0,0 +1,172 @@ +// field paths that every tar file must have. +// header is padded to 512 bytes. +var f = 0 + , fields = {} + , path = fields.path = f++ + , mode = fields.mode = f++ + , uid = fields.uid = f++ + , gid = fields.gid = f++ + , size = fields.size = f++ + , mtime = fields.mtime = f++ + , cksum = fields.cksum = f++ + , type = fields.type = f++ + , linkpath = fields.linkpath = f++ + , headerSize = 512 + , blockSize = 512 + , fieldSize = [] + +fieldSize[path] = 100 +fieldSize[mode] = 8 +fieldSize[uid] = 8 +fieldSize[gid] = 8 +fieldSize[size] = 12 +fieldSize[mtime] = 12 +fieldSize[cksum] = 8 +fieldSize[type] = 1 +fieldSize[linkpath] = 100 + +// "ustar\0" may introduce another bunch of headers. +// these are optional, and will be nulled out if not present. + +var ustar = fields.ustar = f++ + , ustarver = fields.ustarver = f++ + , uname = fields.uname = f++ + , gname = fields.gname = f++ + , devmaj = fields.devmaj = f++ + , devmin = fields.devmin = f++ + , prefix = fields.prefix = f++ + , fill = fields.fill = f++ + +// terminate fields. +fields[f] = null + +fieldSize[ustar] = 6 +fieldSize[ustarver] = 2 +fieldSize[uname] = 32 +fieldSize[gname] = 32 +fieldSize[devmaj] = 8 +fieldSize[devmin] = 8 +fieldSize[prefix] = 155 +fieldSize[fill] = 12 + +// nb: prefix field may in fact be 130 bytes of prefix, +// a null char, 12 bytes for atime, 12 bytes for ctime. +// +// To recognize this format: +// 1. prefix[130] === ' ' or '\0' +// 2. atime and ctime are octal numeric values +// 3. atime and ctime have ' ' in their last byte + +var fieldEnds = {} + , fieldOffs = {} + , fe = 0 +for (var i = 0; i < f; i ++) { + fieldOffs[i] = fe + fieldEnds[i] = (fe += fieldSize[i]) +} + +// build a translation table of field paths. +Object.keys(fields).forEach(function (f) { + if (fields[f] !== null) fields[fields[f]] = f +}) + +// different values of the 'type' field +// paths match the values of Stats.isX() functions, where appropriate +var types = + { 0: "File" + , "\0": "OldFile" // like 0 + , 1: "Link" + , 2: "SymbolicLink" + , 3: "CharacterDevice" + , 4: "BlockDevice" + , 5: "Directory" + , 6: "FIFO" + , 7: "ContiguousFile" // like 0 + // posix headers + , g: "GlobalExtendedHeader" // k=v for the rest of the archive + , x: "ExtendedHeader" // k=v for the next file + // vendor-specific stuff + , A: "SolarisACL" // skip + , D: "GNUDumpDir" // like 5, but with data, which should be skipped + , I: "Inode" // metadata only, skip + , K: "NextFileHasLongLinkpath" // data = link path of next file + , L: "NextFileHasLongPath" // data = path of next file + , M: "ContinuationFile" // skip + , N: "OldGnuLongPath" // like L + , S: "SparseFile" // skip + , V: "TapeVolumeHeader" // skip + , X: "OldExtendedHeader" // like x + } + +Object.keys(types).forEach(function (t) { + types[types[t]] = types[types[t]] || t +}) + +// values for the mode field +var modes = + { suid: 04000 // set uid on extraction + , sgid: 02000 // set gid on extraction + , svtx: 01000 // set restricted deletion flag on dirs on extraction + , uread: 0400 + , uwrite: 0200 + , uexec: 0100 + , gread: 040 + , gwrite: 020 + , gexec: 010 + , oread: 4 + , owrite: 2 + , oexec: 1 + , all: 07777 + } + +var numeric = + { mode: true + , uid: true + , gid: true + , size: true + , mtime: true + , devmaj: true + , devmin: true + , cksum: true + , atime: true + , ctime: true + , dev: true + , ino: true + , nlink: true + } + +Object.keys(modes).forEach(function (t) { + modes[modes[t]] = modes[modes[t]] || t +}) + +var knownExtended = + { atime: true + , charset: true + , comment: true + , ctime: true + , gid: true + , gname: true + , linkpath: true + , mtime: true + , path: true + , realtime: true + , security: true + , size: true + , uid: true + , uname: true } + + +exports.fields = fields +exports.fieldSize = fieldSize +exports.fieldOffs = fieldOffs +exports.fieldEnds = fieldEnds +exports.types = types +exports.modes = modes +exports.numeric = numeric +exports.headerSize = headerSize +exports.blockSize = blockSize +exports.knownExtended = knownExtended + +exports.Pack = require("./lib/pack.js") +exports.Parse = require("./lib/parse.js") +exports.Extract = require("./lib/extract.js") diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/block-stream/LICENCE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/block-stream/LICENCE new file mode 100644 index 000000000..74489e2e2 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/block-stream/LICENCE @@ -0,0 +1,25 @@ +Copyright (c) Isaac Z. Schlueter +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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/block-stream/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/block-stream/README.md new file mode 100644 index 000000000..c16e9c468 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/block-stream/README.md @@ -0,0 +1,14 @@ +# block-stream + +A stream of blocks. + +Write data into it, and it'll output data in buffer blocks the size you +specify, padding with zeroes if necessary. + +```javascript +var block = new BlockStream(512) +fs.createReadStream("some-file").pipe(block) +block.pipe(fs.createWriteStream("block-file")) +``` + +When `.end()` or `.flush()` is called, it'll pad the block with zeroes. diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/block-stream/block-stream.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/block-stream/block-stream.js new file mode 100644 index 000000000..af63e5f72 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/block-stream/block-stream.js @@ -0,0 +1,209 @@ +// write data to it, and it'll emit data in 512 byte blocks. +// if you .end() or .flush(), it'll emit whatever it's got, +// padded with nulls to 512 bytes. + +module.exports = BlockStream + +var Stream = require("stream").Stream + , inherits = require("../inherits/inherits.js") + , assert = require("assert").ok + , debug = process.env.DEBUG ? console.error : function () {} + +function BlockStream (size, opt) { + this.writable = this.readable = true + this._opt = opt || {} + this._chunkSize = size || 512 + this._offset = 0 + this._buffer = [] + this._bufferLength = 0 + if (this._opt.nopad) this._zeroes = false + else { + this._zeroes = new Buffer(this._chunkSize) + for (var i = 0; i < this._chunkSize; i ++) { + this._zeroes[i] = 0 + } + } +} + +inherits(BlockStream, Stream) + +BlockStream.prototype.write = function (c) { + // debug(" BS write", c) + if (this._ended) throw new Error("BlockStream: write after end") + if (c && !Buffer.isBuffer(c)) c = new Buffer(c + "") + if (c.length) { + this._buffer.push(c) + this._bufferLength += c.length + } + // debug("pushed onto buffer", this._bufferLength) + if (this._bufferLength >= this._chunkSize) { + if (this._paused) { + // debug(" BS paused, return false, need drain") + this._needDrain = true + return false + } + this._emitChunk() + } + return true +} + +BlockStream.prototype.pause = function () { + // debug(" BS pausing") + this._paused = true +} + +BlockStream.prototype.resume = function () { + // debug(" BS resume") + this._paused = false + return this._emitChunk() +} + +BlockStream.prototype.end = function (chunk) { + // debug("end", chunk) + if (typeof chunk === "function") cb = chunk, chunk = null + if (chunk) this.write(chunk) + this._ended = true + this.flush() +} + +BlockStream.prototype.flush = function () { + this._emitChunk(true) +} + +BlockStream.prototype._emitChunk = function (flush) { + // debug("emitChunk flush=%j emitting=%j paused=%j", flush, this._emitting, this._paused) + + // emit a chunk + if (flush && this._zeroes) { + // debug(" BS push zeroes", this._bufferLength) + // push a chunk of zeroes + var padBytes = (this._bufferLength % this._chunkSize) + if (padBytes !== 0) padBytes = this._chunkSize - padBytes + if (padBytes > 0) { + // debug("padBytes", padBytes, this._zeroes.slice(0, padBytes)) + this._buffer.push(this._zeroes.slice(0, padBytes)) + this._bufferLength += padBytes + // debug(this._buffer[this._buffer.length - 1].length, this._bufferLength) + } + } + + if (this._emitting || this._paused) return + this._emitting = true + + // debug(" BS entering loops") + var bufferIndex = 0 + while (this._bufferLength >= this._chunkSize && + (flush || !this._paused)) { + // debug(" BS data emission loop", this._bufferLength) + + var out + , outOffset = 0 + , outHas = this._chunkSize + + while (outHas > 0 && (flush || !this._paused) ) { + // debug(" BS data inner emit loop", this._bufferLength) + var cur = this._buffer[bufferIndex] + , curHas = cur.length - this._offset + // debug("cur=", cur) + // debug("curHas=%j", curHas) + // If it's not big enough to fill the whole thing, then we'll need + // to copy multiple buffers into one. However, if it is big enough, + // then just slice out the part we want, to save unnecessary copying. + // Also, need to copy if we've already done some copying, since buffers + // can't be joined like cons strings. + if (out || curHas < outHas) { + out = out || new Buffer(this._chunkSize) + cur.copy(out, outOffset, + this._offset, this._offset + Math.min(curHas, outHas)) + } else if (cur.length === outHas && this._offset === 0) { + // shortcut -- cur is exactly long enough, and no offset. + out = cur + } else { + // slice out the piece of cur that we need. + out = cur.slice(this._offset, this._offset + outHas) + } + + if (curHas > outHas) { + // means that the current buffer couldn't be completely output + // update this._offset to reflect how much WAS written + this._offset += outHas + outHas = 0 + } else { + // output the entire current chunk. + // toss it away + outHas -= curHas + outOffset += curHas + bufferIndex ++ + this._offset = 0 + } + } + + this._bufferLength -= this._chunkSize + assert(out.length === this._chunkSize) + // debug("emitting data", out) + // debug(" BS emitting, paused=%j", this._paused, this._bufferLength) + this.emit("data", out) + out = null + } + // debug(" BS out of loops", this._bufferLength) + + // whatever is left, it's not enough to fill up a block, or we're paused + this._buffer = this._buffer.slice(bufferIndex) + if (this._paused) { + // debug(" BS paused, leaving", this._bufferLength) + this._needsDrain = true + this._emitting = false + return + } + + // if flushing, and not using null-padding, then need to emit the last + // chunk(s) sitting in the queue. We know that it's not enough to + // fill up a whole block, because otherwise it would have been emitted + // above, but there may be some offset. + var l = this._buffer.length + if (flush && !this._zeroes && l) { + if (l === 1) { + if (this._offset) { + this.emit("data", this._buffer[0].slice(this._offset)) + } else { + this.emit("data", this._buffer[0]) + } + } else { + var outHas = this._bufferLength + , out = new Buffer(outHas) + , outOffset = 0 + for (var i = 0; i < l; i ++) { + var cur = this._buffer[i] + , curHas = cur.length - this._offset + cur.copy(out, outOffset, this._offset) + this._offset = 0 + outOffset += curHas + this._bufferLength -= curHas + } + this.emit("data", out) + } + // truncate + this._buffer.length = 0 + this._bufferLength = 0 + this._offset = 0 + } + + // now either drained or ended + // debug("either draining, or ended", this._bufferLength, this._ended) + // means that we've flushed out all that we can so far. + if (this._needDrain) { + // debug("emitting drain", this._bufferLength) + this._needDrain = false + this.emit("drain") + } + + if ((this._bufferLength === 0) && this._ended && !this._endEmitted) { + // debug("emitting end", this._bufferLength) + this._endEmitted = true + this.emit("end") + } + + this._emitting = false + + // debug(" BS no longer emitting", flush, this._paused, this._emitting, this._bufferLength, this._chunkSize) +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/LICENCE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/LICENCE new file mode 100644 index 000000000..74489e2e2 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/LICENCE @@ -0,0 +1,25 @@ +Copyright (c) Isaac Z. Schlueter +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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/README.md new file mode 100644 index 000000000..9d8cb77e5 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/README.md @@ -0,0 +1,76 @@ +Like FS streams, but with stat on them, and supporting directories and +symbolic links, as well as normal files. Also, you can use this to set +the stats on a file, even if you don't change its contents, or to create +a symlink, etc. + +So, for example, you can "write" a directory, and it'll call `mkdir`. You +can specify a uid and gid, and it'll call `chown`. You can specify a +`mtime` and `atime`, and it'll call `utimes`. You can call it a symlink +and provide a `linkpath` and it'll call `symlink`. + +Note that it won't automatically resolve symbolic links. So, if you +call `fstream.Reader('/some/symlink')` then you'll get an object +that stats and then ends immediately (since it has no data). To follow +symbolic links, do this: `fstream.Reader({path:'/some/symlink', follow: +true })`. + +There are various checks to make sure that the bytes emitted are the +same as the intended size, if the size is set. + +## Examples + +```javascript +fstream + .Writer({ path: "path/to/file" + , mode: 0755 + , size: 6 + }) + .write("hello\n") + .end() +``` + +This will create the directories if they're missing, and then write +`hello\n` into the file, chmod it to 0755, and assert that 6 bytes have +been written when it's done. + +```javascript +fstream + .Writer({ path: "path/to/file" + , mode: 0755 + , size: 6 + , flags: "a" + }) + .write("hello\n") + .end() +``` + +You can pass flags in, if you want to append to a file. + +```javascript +fstream + .Writer({ path: "path/to/symlink" + , linkpath: "./file" + , SymbolicLink: true + , mode: "0755" // octal strings supported + }) + .end() +``` + +If isSymbolicLink is a function, it'll be called, and if it returns +true, then it'll treat it as a symlink. If it's not a function, then +any truish value will make a symlink, or you can set `type: +'SymbolicLink'`, which does the same thing. + +Note that the linkpath is relative to the symbolic link location, not +the parent dir or cwd. + +```javascript +fstream + .Reader("path/to/dir") + .pipe(fstream.Writer("path/to/other/dir")) +``` + +This will do like `cp -Rp path/to/dir path/to/other/dir`. If the other +dir exists and isn't a directory, then it'll emit an error. It'll also +set the uid, gid, mode, etc. to be identical. In this way, it's more +like `rsync -a` than simply a copy. diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/fstream.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/fstream.js new file mode 100644 index 000000000..c66d26f51 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/fstream.js @@ -0,0 +1,31 @@ +exports.Abstract = require("./lib/abstract.js") +exports.Reader = require("./lib/reader.js") +exports.Writer = require("./lib/writer.js") + +exports.File = + { Reader: require("./lib/file-reader.js") + , Writer: require("./lib/file-writer.js") } + +exports.Dir = + { Reader : require("./lib/dir-reader.js") + , Writer : require("./lib/dir-writer.js") } + +exports.Link = + { Reader : require("./lib/link-reader.js") + , Writer : require("./lib/link-writer.js") } + +exports.Proxy = + { Reader : require("./lib/proxy-reader.js") + , Writer : require("./lib/proxy-writer.js") } + +exports.Reader.Dir = exports.DirReader = exports.Dir.Reader +exports.Reader.File = exports.FileReader = exports.File.Reader +exports.Reader.Link = exports.LinkReader = exports.Link.Reader +exports.Reader.Proxy = exports.ProxyReader = exports.Proxy.Reader + +exports.Writer.Dir = exports.DirWriter = exports.Dir.Writer +exports.Writer.File = exports.FileWriter = exports.File.Writer +exports.Writer.Link = exports.LinkWriter = exports.Link.Writer +exports.Writer.Proxy = exports.ProxyWriter = exports.Proxy.Writer + +exports.collect = require("./lib/collect.js") diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/abstract.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/abstract.js new file mode 100644 index 000000000..6161f3bef --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/abstract.js @@ -0,0 +1,85 @@ +// the parent class for all fstreams. + +module.exports = Abstract + +var Stream = require("stream").Stream + , inherits = require("../../inherits/inherits.js") + +function Abstract () { + Stream.call(this) +} + +inherits(Abstract, Stream) + +Abstract.prototype.on = function (ev, fn) { + if (ev === "ready" && this.ready) { + process.nextTick(fn.bind(this)) + } else { + Stream.prototype.on.call(this, ev, fn) + } + return this +} + +Abstract.prototype.abort = function () { + this._aborted = true + this.emit("abort") +} + +Abstract.prototype.destroy = function () {} + +Abstract.prototype.warn = function (msg, code) { + var me = this + , er = decorate(msg, code, me) + if (!me.listeners("warn")) { + console.error("%s %s\n" + + "path = %s\n" + + "syscall = %s\n" + + "fstream_type = %s\n" + + "fstream_path = %s\n" + + "fstream_unc_path = %s\n" + + "fstream_class = %s\n" + + "fstream_stack =\n%s\n", + code || "UNKNOWN", + er.stack, + er.path, + er.syscall, + er.fstream_type, + er.fstream_path, + er.fstream_unc_path, + er.fstream_class, + er.fstream_stack.join("\n")) + } else { + me.emit("warn", er) + } +} + +Abstract.prototype.info = function (msg, code) { + this.emit("info", msg, code) +} + +Abstract.prototype.error = function (msg, code, th) { + var er = decorate(msg, code, this) + if (th) throw er + else this.emit("error", er) +} + +function decorate (er, code, me) { + if (!(er instanceof Error)) er = new Error(er) + er.code = er.code || code + er.path = er.path || me.path + er.fstream_type = er.fstream_type || me.type + er.fstream_path = er.fstream_path || me.path + if (me._path !== me.path) { + er.fstream_unc_path = er.fstream_unc_path || me._path + } + if (me.linkpath) { + er.fstream_linkpath = er.fstream_linkpath || me.linkpath + } + er.fstream_class = er.fstream_class || me.constructor.name + er.fstream_stack = er.fstream_stack || + new Error().stack.split(/\n/).slice(3).map(function (s) { + return s.replace(/^ at /, "") + }) + + return er +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/collect.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/collect.js new file mode 100644 index 000000000..a36f780eb --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/collect.js @@ -0,0 +1,67 @@ +module.exports = collect + +function collect (stream) { + if (stream._collected) return + + stream._collected = true + stream.pause() + + stream.on("data", save) + stream.on("end", save) + var buf = [] + function save (b) { + if (typeof b === "string") b = new Buffer(b) + if (Buffer.isBuffer(b) && !b.length) return + buf.push(b) + } + + stream.on("entry", saveEntry) + var entryBuffer = [] + function saveEntry (e) { + collect(e) + entryBuffer.push(e) + } + + stream.on("proxy", proxyPause) + function proxyPause (p) { + p.pause() + } + + + // replace the pipe method with a new version that will + // unlock the buffered stuff. if you just call .pipe() + // without a destination, then it'll re-play the events. + stream.pipe = (function (orig) { return function (dest) { + // console.error(" === open the pipes", dest && dest.path) + + // let the entries flow through one at a time. + // Once they're all done, then we can resume completely. + var e = 0 + ;(function unblockEntry () { + var entry = entryBuffer[e++] + // console.error(" ==== unblock entry", entry && entry.path) + if (!entry) return resume() + entry.on("end", unblockEntry) + if (dest) dest.add(entry) + else stream.emit("entry", entry) + })() + + function resume () { + stream.removeListener("entry", saveEntry) + stream.removeListener("data", save) + stream.removeListener("end", save) + + stream.pipe = orig + if (dest) stream.pipe(dest) + + buf.forEach(function (b) { + if (b) stream.emit("data", b) + else stream.emit("end") + }) + + stream.resume() + } + + return dest + }})(stream.pipe) +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/dir-reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/dir-reader.js new file mode 100644 index 000000000..e655b0d98 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/dir-reader.js @@ -0,0 +1,250 @@ +// A thing that emits "entry" events with Reader objects +// Pausing it causes it to stop emitting entry events, and also +// pauses the current entry if there is one. + +module.exports = DirReader + +var fs = require("../../graceful-fs/graceful-fs.js") + , fstream = require("../fstream.js") + , Reader = fstream.Reader + , inherits = require("../../inherits/inherits.js") + , mkdir = require("../../mkdirp") + , path = require("path") + , Reader = require("./reader.js") + , assert = require("assert").ok + +inherits(DirReader, Reader) + +function DirReader (props) { + var me = this + if (!(me instanceof DirReader)) throw new Error( + "DirReader must be called as constructor.") + + // should already be established as a Directory type + if (props.type !== "Directory" || !props.Directory) { + throw new Error("Non-directory type "+ props.type) + } + + me.entries = null + me._index = -1 + me._paused = false + me._length = -1 + + if (props.sort) { + this.sort = props.sort + } + + Reader.call(this, props) +} + +DirReader.prototype._getEntries = function () { + var me = this + + // race condition. might pause() before calling _getEntries, + // and then resume, and try to get them a second time. + if (me._gotEntries) return + me._gotEntries = true + + fs.readdir(me._path, function (er, entries) { + if (er) return me.error(er) + + me.entries = entries + + me.emit("entries", entries) + if (me._paused) me.once("resume", processEntries) + else processEntries() + + function processEntries () { + me._length = me.entries.length + if (typeof me.sort === "function") { + me.entries = me.entries.sort(me.sort.bind(me)) + } + me._read() + } + }) +} + +// start walking the dir, and emit an "entry" event for each one. +DirReader.prototype._read = function () { + var me = this + + if (!me.entries) return me._getEntries() + + if (me._paused || me._currentEntry || me._aborted) { + // console.error("DR paused=%j, current=%j, aborted=%j", me._paused, !!me._currentEntry, me._aborted) + return + } + + me._index ++ + if (me._index >= me.entries.length) { + if (!me._ended) { + me._ended = true + me.emit("end") + me.emit("close") + } + return + } + + // ok, handle this one, then. + + // save creating a proxy, by stat'ing the thing now. + var p = path.resolve(me._path, me.entries[me._index]) + assert(p !== me._path) + assert(me.entries[me._index]) + + // set this to prevent trying to _read() again in the stat time. + me._currentEntry = p + fs[ me.props.follow ? "stat" : "lstat" ](p, function (er, stat) { + if (er) return me.error(er) + + var who = me._proxy || me + + stat.path = p + stat.basename = path.basename(p) + stat.dirname = path.dirname(p) + var childProps = me.getChildProps.call(who, stat) + childProps.path = p + childProps.basename = path.basename(p) + childProps.dirname = path.dirname(p) + + var entry = Reader(childProps, stat) + + // console.error("DR Entry", p, stat.size) + + me._currentEntry = entry + + // "entry" events are for direct entries in a specific dir. + // "child" events are for any and all children at all levels. + // This nomenclature is not completely final. + + entry.on("pause", function (who) { + if (!me._paused && !entry._disowned) { + me.pause(who) + } + }) + + entry.on("resume", function (who) { + if (me._paused && !entry._disowned) { + me.resume(who) + } + }) + + entry.on("stat", function (props) { + me.emit("_entryStat", entry, props) + if (entry._aborted) return + if (entry._paused) entry.once("resume", function () { + me.emit("entryStat", entry, props) + }) + else me.emit("entryStat", entry, props) + }) + + entry.on("ready", function EMITCHILD () { + // console.error("DR emit child", entry._path) + if (me._paused) { + // console.error(" DR emit child - try again later") + // pause the child, and emit the "entry" event once we drain. + // console.error("DR pausing child entry") + entry.pause(me) + return me.once("resume", EMITCHILD) + } + + // skip over sockets. they can't be piped around properly, + // so there's really no sense even acknowledging them. + // if someone really wants to see them, they can listen to + // the "socket" events. + if (entry.type === "Socket") { + me.emit("socket", entry) + } else { + me.emitEntry(entry) + } + }) + + var ended = false + entry.on("close", onend) + entry.on("disown", onend) + function onend () { + if (ended) return + ended = true + me.emit("childEnd", entry) + me.emit("entryEnd", entry) + me._currentEntry = null + if (!me._paused) { + me._read() + } + } + + // XXX Remove this. Works in node as of 0.6.2 or so. + // Long filenames should not break stuff. + entry.on("error", function (er) { + if (entry._swallowErrors) { + me.warn(er) + entry.emit("end") + entry.emit("close") + } else { + me.emit("error", er) + } + }) + + // proxy up some events. + ; [ "child" + , "childEnd" + , "warn" + ].forEach(function (ev) { + entry.on(ev, me.emit.bind(me, ev)) + }) + }) +} + +DirReader.prototype.disown = function (entry) { + entry.emit("beforeDisown") + entry._disowned = true + entry.parent = entry.root = null + if (entry === this._currentEntry) { + this._currentEntry = null + } + entry.emit("disown") +} + +DirReader.prototype.getChildProps = function (stat) { + return { depth: this.depth + 1 + , root: this.root || this + , parent: this + , follow: this.follow + , filter: this.filter + , sort: this.props.sort + } +} + +DirReader.prototype.pause = function (who) { + var me = this + if (me._paused) return + who = who || me + me._paused = true + if (me._currentEntry && me._currentEntry.pause) { + me._currentEntry.pause(who) + } + me.emit("pause", who) +} + +DirReader.prototype.resume = function (who) { + var me = this + if (!me._paused) return + who = who || me + + me._paused = false + // console.error("DR Emit Resume", me._path) + me.emit("resume", who) + if (me._paused) { + // console.error("DR Re-paused", me._path) + return + } + + if (me._currentEntry) { + if (me._currentEntry.resume) me._currentEntry.resume(who) + } else me._read() +} + +DirReader.prototype.emitEntry = function (entry) { + this.emit("entry", entry) + this.emit("child", entry) +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/dir-writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/dir-writer.js new file mode 100644 index 000000000..71eb3584e --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/dir-writer.js @@ -0,0 +1,171 @@ +// It is expected that, when .add() returns false, the consumer +// of the DirWriter will pause until a "drain" event occurs. Note +// that this is *almost always going to be the case*, unless the +// thing being written is some sort of unsupported type, and thus +// skipped over. + +module.exports = DirWriter + +var fs = require("../../graceful-fs/graceful-fs.js") + , fstream = require("../fstream.js") + , Writer = require("./writer.js") + , inherits = require("../../inherits/inherits.js") + , mkdir = require("../../mkdirp") + , path = require("path") + , collect = require("./collect.js") + +inherits(DirWriter, Writer) + +function DirWriter (props) { + var me = this + if (!(me instanceof DirWriter)) me.error( + "DirWriter must be called as constructor.", null, true) + + // should already be established as a Directory type + if (props.type !== "Directory" || !props.Directory) { + me.error("Non-directory type "+ props.type + " " + + JSON.stringify(props), null, true) + } + + Writer.call(this, props) +} + +DirWriter.prototype._create = function () { + var me = this + mkdir(me._path, Writer.dirmode, function (er) { + if (er) return me.error(er) + // ready to start getting entries! + me.ready = true + me.emit("ready") + me._process() + }) +} + +// a DirWriter has an add(entry) method, but its .write() doesn't +// do anything. Why a no-op rather than a throw? Because this +// leaves open the door for writing directory metadata for +// gnu/solaris style dumpdirs. +DirWriter.prototype.write = function () { + return true +} + +DirWriter.prototype.end = function () { + this._ended = true + this._process() +} + +DirWriter.prototype.add = function (entry) { + var me = this + + // console.error("\tadd", entry._path, "->", me._path) + collect(entry) + if (!me.ready || me._currentEntry) { + me._buffer.push(entry) + return false + } + + // create a new writer, and pipe the incoming entry into it. + if (me._ended) { + return me.error("add after end") + } + + me._buffer.push(entry) + me._process() + + return 0 === this._buffer.length +} + +DirWriter.prototype._process = function () { + var me = this + + // console.error("DW Process p=%j", me._processing, me.basename) + + if (me._processing) return + + var entry = me._buffer.shift() + if (!entry) { + // console.error("DW Drain") + me.emit("drain") + if (me._ended) me._finish() + return + } + + me._processing = true + // console.error("DW Entry", entry._path) + + me.emit("entry", entry) + + // ok, add this entry + // + // don't allow recursive copying + var p = entry + do { + var pp = p._path || p.path + if (pp === me.root._path || pp === me._path || + (pp && pp.indexOf(me._path) === 0)) { + // console.error("DW Exit (recursive)", entry.basename, me._path) + me._processing = false + if (entry._collected) entry.pipe() + return me._process() + } + } while (p = p.parent) + + // console.error("DW not recursive") + + // chop off the entry's root dir, replace with ours + var props = { parent: me + , root: me.root || me + , type: entry.type + , depth: me.depth + 1 } + + var p = entry._path || entry.path || entry.props.path + if (entry.parent) { + p = p.substr(entry.parent._path.length + 1) + } + // get rid of any ../../ shenanigans + props.path = path.join(me.path, path.join("/", p)) + + // if i have a filter, the child should inherit it. + props.filter = me.filter + + // all the rest of the stuff, copy over from the source. + Object.keys(entry.props).forEach(function (k) { + if (!props.hasOwnProperty(k)) { + props[k] = entry.props[k] + } + }) + + // not sure at this point what kind of writer this is. + var child = me._currentChild = new Writer(props) + child.on("ready", function () { + // console.error("DW Child Ready", child.type, child._path) + // console.error(" resuming", entry._path) + entry.pipe(child) + entry.resume() + }) + + // XXX Make this work in node. + // Long filenames should not break stuff. + child.on("error", function (er) { + if (child._swallowErrors) { + me.warn(er) + child.emit("end") + child.emit("close") + } else { + me.emit("error", er) + } + }) + + // we fire _end internally *after* end, so that we don't move on + // until any "end" listeners have had their chance to do stuff. + child.on("close", onend) + var ended = false + function onend () { + if (ended) return + ended = true + // console.error("* DW Child end", child.basename) + me._currentChild = null + me._processing = false + me._process() + } +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/file-reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/file-reader.js new file mode 100644 index 000000000..e53718ad6 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/file-reader.js @@ -0,0 +1,147 @@ +// Basically just a wrapper around an fs.ReadStream + +module.exports = FileReader + +var fs = require("../../graceful-fs/graceful-fs.js") + , fstream = require("../fstream.js") + , Reader = fstream.Reader + , inherits = require("../../inherits/inherits.js") + , mkdir = require("../../mkdirp") + , Reader = require("./reader.js") + , EOF = {EOF: true} + , CLOSE = {CLOSE: true} + +inherits(FileReader, Reader) + +function FileReader (props) { + // console.error(" FR create", props.path, props.size, new Error().stack) + var me = this + if (!(me instanceof FileReader)) throw new Error( + "FileReader must be called as constructor.") + + // should already be established as a File type + // XXX Todo: preserve hardlinks by tracking dev+inode+nlink, + // with a HardLinkReader class. + if (!((props.type === "Link" && props.Link) || + (props.type === "File" && props.File))) { + throw new Error("Non-file type "+ props.type) + } + + me._buffer = [] + me._bytesEmitted = 0 + Reader.call(me, props) +} + +FileReader.prototype._getStream = function () { + var me = this + , stream = me._stream = fs.createReadStream(me._path, me.props) + + if (me.props.blksize) { + stream.bufferSize = me.props.blksize + } + + stream.on("open", me.emit.bind(me, "open")) + + stream.on("data", function (c) { + // console.error("\t\t%d %s", c.length, me.basename) + me._bytesEmitted += c.length + // no point saving empty chunks + if (!c.length) return + else if (me._paused || me._buffer.length) { + me._buffer.push(c) + me._read() + } else me.emit("data", c) + }) + + stream.on("end", function () { + if (me._paused || me._buffer.length) { + // console.error("FR Buffering End", me._path) + me._buffer.push(EOF) + me._read() + } else { + me.emit("end") + } + + if (me._bytesEmitted !== me.props.size) { + me.error("Didn't get expected byte count\n"+ + "expect: "+me.props.size + "\n" + + "actual: "+me._bytesEmitted) + } + }) + + stream.on("close", function () { + if (me._paused || me._buffer.length) { + // console.error("FR Buffering Close", me._path) + me._buffer.push(CLOSE) + me._read() + } else { + // console.error("FR close 1", me._path) + me.emit("close") + } + }) + + me._read() +} + +FileReader.prototype._read = function () { + var me = this + // console.error("FR _read", me._path) + if (me._paused) { + // console.error("FR _read paused", me._path) + return + } + + if (!me._stream) { + // console.error("FR _getStream calling", me._path) + return me._getStream() + } + + // clear out the buffer, if there is one. + if (me._buffer.length) { + // console.error("FR _read has buffer", me._buffer.length, me._path) + var buf = me._buffer + for (var i = 0, l = buf.length; i < l; i ++) { + var c = buf[i] + if (c === EOF) { + // console.error("FR Read emitting buffered end", me._path) + me.emit("end") + } else if (c === CLOSE) { + // console.error("FR Read emitting buffered close", me._path) + me.emit("close") + } else { + // console.error("FR Read emitting buffered data", me._path) + me.emit("data", c) + } + + if (me._paused) { + // console.error("FR Read Re-pausing at "+i, me._path) + me._buffer = buf.slice(i) + return + } + } + me._buffer.length = 0 + } + // console.error("FR _read done") + // that's about all there is to it. +} + +FileReader.prototype.pause = function (who) { + var me = this + // console.error("FR Pause", me._path) + if (me._paused) return + who = who || me + me._paused = true + if (me._stream) me._stream.pause() + me.emit("pause", who) +} + +FileReader.prototype.resume = function (who) { + var me = this + // console.error("FR Resume", me._path) + if (!me._paused) return + who = who || me + me.emit("resume", who) + me._paused = false + if (me._stream) me._stream.resume() + me._read() +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/file-writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/file-writer.js new file mode 100644 index 000000000..70bb86d79 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/file-writer.js @@ -0,0 +1,95 @@ +module.exports = FileWriter + +var fs = require("../../graceful-fs/graceful-fs.js") + , mkdir = require("../../mkdirp") + , Writer = require("./writer.js") + , inherits = require("../../inherits/inherits.js") + , EOF = {} + +inherits(FileWriter, Writer) + +function FileWriter (props) { + var me = this + if (!(me instanceof FileWriter)) throw new Error( + "FileWriter must be called as constructor.") + + // should already be established as a File type + if (props.type !== "File" || !props.File) { + throw new Error("Non-file type "+ props.type) + } + + me._buffer = [] + me._bytesWritten = 0 + + Writer.call(this, props) +} + +FileWriter.prototype._create = function () { + var me = this + if (me._stream) return + + var so = {} + if (me.props.flags) so.flags = me.props.flags + so.mode = Writer.filemode + if (me._old && me._old.blksize) so.bufferSize = me._old.blksize + + me._stream = fs.createWriteStream(me._path, so) + + me._stream.on("open", function (fd) { + me.ready = true + me._buffer.forEach(function (c) { + if (c === EOF) me._stream.end() + else me._stream.write(c) + }) + me.emit("ready") + }) + + me._stream.on("drain", function () { me.emit("drain") }) + + me._stream.on("close", function () { + // console.error("\n\nFW Stream Close", me._path, me.size) + me._finish() + }) +} + +FileWriter.prototype.write = function (c) { + var me = this + + me._bytesWritten += c.length + + if (!me.ready) { + me._buffer.push(c) + return false + } + + var ret = me._stream.write(c) + // console.error("\t-- fw wrote, _stream says", ret, me._stream._queue.length) + + // allow 2 buffered writes, because otherwise there's just too + // much stop and go bs. + return ret || (me._stream._queue && me._stream._queue.length <= 2) +} + +FileWriter.prototype.end = function (c) { + var me = this + + if (c) me.write(c) + + if (!me.ready) { + me._buffer.push(EOF) + return false + } + + return me._stream.end() +} + +FileWriter.prototype._finish = function () { + var me = this + if (typeof me.size === "number" && me._bytesWritten != me.size) { + me.error( + "Did not get expected byte count.\n" + + "expect: " + me.size + "\n" + + "actual: " + me._bytesWritten) + } + Writer.prototype._finish.call(me) +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/get-type.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/get-type.js new file mode 100644 index 000000000..cd65c41d8 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/get-type.js @@ -0,0 +1,32 @@ +module.exports = getType + +function getType (st) { + var types = + [ "Directory" + , "File" + , "SymbolicLink" + , "Link" // special for hardlinks from tarballs + , "BlockDevice" + , "CharacterDevice" + , "FIFO" + , "Socket" ] + , type + + if (st.type && -1 !== types.indexOf(st.type)) { + st[st.type] = true + return st.type + } + + for (var i = 0, l = types.length; i < l; i ++) { + type = types[i] + var is = st[type] || st["is" + type] + if (typeof is === "function") is = is.call(st) + if (is) { + st[type] = true + st.type = type + return type + } + } + + return null +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/link-reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/link-reader.js new file mode 100644 index 000000000..1d07e2fc7 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/link-reader.js @@ -0,0 +1,54 @@ +// Basically just a wrapper around an fs.readlink +// +// XXX: Enhance this to support the Link type, by keeping +// a lookup table of {:}, so that hardlinks +// can be preserved in tarballs. + +module.exports = LinkReader + +var fs = require("../../graceful-fs/graceful-fs.js") + , fstream = require("../fstream.js") + , inherits = require("../../inherits/inherits.js") + , mkdir = require("../../mkdirp") + , Reader = require("./reader.js") + +inherits(LinkReader, Reader) + +function LinkReader (props) { + var me = this + if (!(me instanceof LinkReader)) throw new Error( + "LinkReader must be called as constructor.") + + if (!((props.type === "Link" && props.Link) || + (props.type === "SymbolicLink" && props.SymbolicLink))) { + throw new Error("Non-link type "+ props.type) + } + + Reader.call(me, props) +} + +// When piping a LinkReader into a LinkWriter, we have to +// already have the linkpath property set, so that has to +// happen *before* the "ready" event, which means we need to +// override the _stat method. +LinkReader.prototype._stat = function (currentStat) { + var me = this + fs.readlink(me._path, function (er, linkpath) { + if (er) return me.error(er) + me.linkpath = me.props.linkpath = linkpath + me.emit("linkpath", linkpath) + Reader.prototype._stat.call(me, currentStat) + }) +} + +LinkReader.prototype._read = function () { + var me = this + if (me._paused) return + // basically just a no-op, since we got all the info we need + // from the _stat method + if (!me._ended) { + me.emit("end") + me.emit("close") + me._ended = true + } +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/link-writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/link-writer.js new file mode 100644 index 000000000..c652eb312 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/link-writer.js @@ -0,0 +1,95 @@ + +module.exports = LinkWriter + +var fs = require("../../graceful-fs/graceful-fs.js") + , Writer = require("./writer.js") + , inherits = require("../../inherits/inherits.js") + , path = require("path") + , rimraf = require("../../rimraf/rimraf.js") + +inherits(LinkWriter, Writer) + +function LinkWriter (props) { + var me = this + if (!(me instanceof LinkWriter)) throw new Error( + "LinkWriter must be called as constructor.") + + // should already be established as a Link type + if (!((props.type === "Link" && props.Link) || + (props.type === "SymbolicLink" && props.SymbolicLink))) { + throw new Error("Non-link type "+ props.type) + } + + if (props.linkpath === "") props.linkpath = "." + if (!props.linkpath) { + me.error("Need linkpath property to create " + props.type) + } + + Writer.call(this, props) +} + +LinkWriter.prototype._create = function () { + // console.error(" LW _create") + var me = this + , hard = me.type === "Link" || process.platform === "win32" + , link = hard ? "link" : "symlink" + , lp = hard ? path.resolve(me.dirname, me.linkpath) : me.linkpath + + // can only change the link path by clobbering + // For hard links, let's just assume that's always the case, since + // there's no good way to read them if we don't already know. + if (hard) return clobber(me, lp, link) + + fs.readlink(me._path, function (er, p) { + // only skip creation if it's exactly the same link + if (p && p === lp) return finish(me) + clobber(me, lp, link) + }) +} + +function clobber (me, lp, link) { + rimraf(me._path, function (er) { + if (er) return me.error(er) + create(me, lp, link) + }) +} + +function create (me, lp, link) { + fs[link](lp, me._path, function (er) { + // if this is a hard link, and we're in the process of writing out a + // directory, it's very possible that the thing we're linking to + // doesn't exist yet (especially if it was intended as a symlink), + // so swallow ENOENT errors here and just soldier in. + // Additionally, an EPERM or EACCES can happen on win32 if it's trying + // to make a link to a directory. Again, just skip it. + // A better solution would be to have fs.symlink be supported on + // windows in some nice fashion. + if (er) { + if ((er.code === "ENOENT" || + er.code === "EACCES" || + er.code === "EPERM" ) && process.platform === "win32") { + me.ready = true + me.emit("ready") + me.emit("end") + me.emit("close") + me.end = me._finish = function () {} + } else return me.error(er) + } + finish(me) + }) +} + +function finish (me) { + me.ready = true + me.emit("ready") + if (me._ended && !me._finished) me._finish() +} + +LinkWriter.prototype.end = function () { + // console.error("LW finish in end") + this._ended = true + if (this.ready) { + this._finished = true + this._finish() + } +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/proxy-reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/proxy-reader.js new file mode 100644 index 000000000..a51ebdf72 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/proxy-reader.js @@ -0,0 +1,93 @@ +// A reader for when we don't yet know what kind of thing +// the thing is. + +module.exports = ProxyReader + +var Reader = require("./reader.js") + , getType = require("./get-type.js") + , inherits = require("../../inherits/inherits.js") + , fs = require("../../graceful-fs/graceful-fs.js") + +inherits(ProxyReader, Reader) + +function ProxyReader (props) { + var me = this + if (!(me instanceof ProxyReader)) throw new Error( + "ProxyReader must be called as constructor.") + + me.props = props + me._buffer = [] + me.ready = false + + Reader.call(me, props) +} + +ProxyReader.prototype._stat = function () { + var me = this + , props = me.props + // stat the thing to see what the proxy should be. + , stat = props.follow ? "stat" : "lstat" + + fs[stat](props.path, function (er, current) { + var type + if (er || !current) { + type = "File" + } else { + type = getType(current) + } + + props[type] = true + props.type = me.type = type + + me._old = current + me._addProxy(Reader(props, current)) + }) +} + +ProxyReader.prototype._addProxy = function (proxy) { + var me = this + if (me._proxyTarget) { + return me.error("proxy already set") + } + + me._proxyTarget = proxy + proxy._proxy = me + + ; [ "error" + , "data" + , "end" + , "close" + , "linkpath" + , "entry" + , "entryEnd" + , "child" + , "childEnd" + , "warn" + , "stat" + ].forEach(function (ev) { + // console.error("~~ proxy event", ev, me.path) + proxy.on(ev, me.emit.bind(me, ev)) + }) + + me.emit("proxy", proxy) + + proxy.on("ready", function () { + // console.error("~~ proxy is ready!", me.path) + me.ready = true + me.emit("ready") + }) + + var calls = me._buffer + me._buffer.length = 0 + calls.forEach(function (c) { + proxy[c[0]].apply(proxy, c[1]) + }) +} + +ProxyReader.prototype.pause = function () { + return this._proxyTarget ? this._proxyTarget.pause() : false +} + +ProxyReader.prototype.resume = function () { + return this._proxyTarget ? this._proxyTarget.resume() : false +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/proxy-writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/proxy-writer.js new file mode 100644 index 000000000..2e6bae4e1 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/proxy-writer.js @@ -0,0 +1,109 @@ +// A writer for when we don't know what kind of thing +// the thing is. That is, it's not explicitly set, +// so we're going to make it whatever the thing already +// is, or "File" +// +// Until then, collect all events. + +module.exports = ProxyWriter + +var Writer = require("./writer.js") + , getType = require("./get-type.js") + , inherits = require("../../inherits/inherits.js") + , collect = require("./collect.js") + , fs = require("fs") + +inherits(ProxyWriter, Writer) + +function ProxyWriter (props) { + var me = this + if (!(me instanceof ProxyWriter)) throw new Error( + "ProxyWriter must be called as constructor.") + + me.props = props + me._needDrain = false + + Writer.call(me, props) +} + +ProxyWriter.prototype._stat = function () { + var me = this + , props = me.props + // stat the thing to see what the proxy should be. + , stat = props.follow ? "stat" : "lstat" + + fs[stat](props.path, function (er, current) { + var type + if (er || !current) { + type = "File" + } else { + type = getType(current) + } + + props[type] = true + props.type = me.type = type + + me._old = current + me._addProxy(Writer(props, current)) + }) +} + +ProxyWriter.prototype._addProxy = function (proxy) { + // console.error("~~ set proxy", this.path) + var me = this + if (me._proxy) { + return me.error("proxy already set") + } + + me._proxy = proxy + ; [ "ready" + , "error" + , "close" + , "pipe" + , "drain" + , "warn" + ].forEach(function (ev) { + proxy.on(ev, me.emit.bind(me, ev)) + }) + + me.emit("proxy", proxy) + + var calls = me._buffer + calls.forEach(function (c) { + // console.error("~~ ~~ proxy buffered call", c[0], c[1]) + proxy[c[0]].call(proxy, c[1]) + }) + me._buffer.length = 0 + if (me._needsDrain) me.emit("drain") +} + +ProxyWriter.prototype.add = function (entry) { + // console.error("~~ proxy add") + collect(entry) + + if (!this._proxy) { + this._buffer.push(["add", [entry]]) + this._needDrain = true + return false + } + return this._proxy.add(entry) +} + +ProxyWriter.prototype.write = function (c) { + // console.error("~~ proxy write") + if (!this._proxy) { + this._buffer.push(["write", [c]]) + this._needDrain = true + return false + } + return this._proxy.write(c) +} + +ProxyWriter.prototype.end = function (c) { + // console.error("~~ proxy end") + if (!this._proxy) { + this._buffer.push(["end", c]) + return false + } + return this._proxy.end(c) +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/reader.js new file mode 100644 index 000000000..42a870143 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/reader.js @@ -0,0 +1,258 @@ + +module.exports = Reader + +var fs = require("../../graceful-fs/graceful-fs.js") + , Stream = require("stream").Stream + , inherits = require("../../inherits/inherits.js") + , path = require("path") + , getType = require("./get-type.js") + , hardLinks = Reader.hardLinks = {} + , Abstract = require("./abstract.js") + +// Must do this *before* loading the child classes +inherits(Reader, Abstract) + +var DirReader = require("./dir-reader.js") + , FileReader = require("./file-reader.js") + , LinkReader = require("./link-reader.js") + , SocketReader = require("./socket-reader.js") + , ProxyReader = require("./proxy-reader.js") + +function Reader (props, currentStat) { + var me = this + if (!(me instanceof Reader)) return new Reader(props, currentStat) + + if (typeof props === "string") { + props = { path: props } + } + + if (!props.path) { + me.error("Must provide a path", null, true) + } + + // polymorphism. + // call fstream.Reader(dir) to get a DirReader object, etc. + // Note that, unlike in the Writer case, ProxyReader is going + // to be the *normal* state of affairs, since we rarely know + // the type of a file prior to reading it. + + + var type + , ClassType + + if (props.type && typeof props.type === "function") { + type = props.type + ClassType = type + } else { + type = getType(props) + ClassType = Reader + } + + if (currentStat && !type) { + type = getType(currentStat) + props[type] = true + props.type = type + } + + switch (type) { + case "Directory": + ClassType = DirReader + break + + case "Link": + // XXX hard links are just files. + // However, it would be good to keep track of files' dev+inode + // and nlink values, and create a HardLinkReader that emits + // a linkpath value of the original copy, so that the tar + // writer can preserve them. + // ClassType = HardLinkReader + // break + + case "File": + ClassType = FileReader + break + + case "SymbolicLink": + ClassType = LinkReader + break + + case "Socket": + ClassType = SocketReader + break + + case null: + ClassType = ProxyReader + break + } + + if (!(me instanceof ClassType)) { + return new ClassType(props) + } + + Abstract.call(me) + + me.readable = true + me.writable = false + + me.type = type + me.props = props + me.depth = props.depth = props.depth || 0 + me.parent = props.parent || null + me.root = props.root || (props.parent && props.parent.root) || me + + me._path = me.path = path.resolve(props.path) + if (process.platform === "win32") { + me.path = me._path = me.path.replace(/\?/g, "_") + if (me._path.length >= 260) { + // how DOES one create files on the moon? + // if the path has spaces in it, then UNC will fail. + me._swallowErrors = true + //if (me._path.indexOf(" ") === -1) { + me._path = "\\\\?\\" + me.path.replace(/\//g, "\\") + //} + } + } + me.basename = props.basename = path.basename(me.path) + me.dirname = props.dirname = path.dirname(me.path) + + // these have served their purpose, and are now just noisy clutter + props.parent = props.root = null + + // console.error("\n\n\n%s setting size to", props.path, props.size) + me.size = props.size + me.filter = typeof props.filter === "function" ? props.filter : null + if (props.sort === "alpha") props.sort = alphasort + + // start the ball rolling. + // this will stat the thing, and then call me._read() + // to start reading whatever it is. + // console.error("calling stat", props.path, currentStat) + me._stat(currentStat) +} + +function alphasort (a, b) { + return a === b ? 0 + : a.toLowerCase() > b.toLowerCase() ? 1 + : a.toLowerCase() < b.toLowerCase() ? -1 + : a > b ? 1 + : -1 +} + +Reader.prototype._stat = function (currentStat) { + var me = this + , props = me.props + , stat = props.follow ? "stat" : "lstat" + + // console.error("Reader._stat", me._path, currentStat) + if (currentStat) process.nextTick(statCb.bind(null, null, currentStat)) + else fs[stat](me._path, statCb) + + + function statCb (er, props_) { + // console.error("Reader._stat, statCb", me._path, props_, props_.nlink) + if (er) return me.error(er) + + Object.keys(props_).forEach(function (k) { + props[k] = props_[k] + }) + + // if it's not the expected size, then abort here. + if (undefined !== me.size && props.size !== me.size) { + return me.error("incorrect size") + } + me.size = props.size + + var type = getType(props) + // special little thing for handling hardlinks. + if (type !== "Directory" && props.nlink && props.nlink > 1) { + var k = props.dev + ":" + props.ino + // console.error("Reader has nlink", me._path, k) + if (hardLinks[k] === me._path || !hardLinks[k]) hardLinks[k] = me._path + else { + // switch into hardlink mode. + type = me.type = me.props.type = "Link" + me.Link = me.props.Link = true + me.linkpath = me.props.linkpath = hardLinks[k] + // console.error("Hardlink detected, switching mode", me._path, me.linkpath) + // Setting __proto__ would arguably be the "correct" + // approach here, but that just seems too wrong. + me._stat = me._read = LinkReader.prototype._read + } + } + + if (me.type && me.type !== type) { + me.error("Unexpected type: " + type) + } + + // if the filter doesn't pass, then just skip over this one. + // still have to emit end so that dir-walking can move on. + if (me.filter) { + var who = me._proxy || me + // special handling for ProxyReaders + if (!me.filter.call(who, who, props)) { + if (!me._disowned) { + me.abort() + me.emit("end") + me.emit("close") + } + return + } + } + + // last chance to abort or disown before the flow starts! + var events = ["_stat", "stat", "ready"] + var e = 0 + ;(function go () { + if (me._aborted) { + me.emit("end") + me.emit("close") + return + } + + if (me._paused) { + me.once("resume", go) + return + } + + var ev = events[e ++] + if (!ev) return me._read() + me.emit(ev, props) + go() + })() + } +} + +Reader.prototype.pipe = function (dest, opts) { + var me = this + if (typeof dest.add === "function") { + // piping to a multi-compatible, and we've got directory entries. + me.on("entry", function (entry) { + var ret = dest.add(entry) + if (false === ret) { + me.pause() + } + }) + } + + // console.error("R Pipe apply Stream Pipe") + return Stream.prototype.pipe.apply(this, arguments) +} + +Reader.prototype.pause = function (who) { + this._paused = true + who = who || this + this.emit("pause", who) + if (this._stream) this._stream.pause(who) +} + +Reader.prototype.resume = function (who) { + this._paused = false + who = who || this + this.emit("resume", who) + if (this._stream) this._stream.resume(who) + this._read() +} + +Reader.prototype._read = function () { + this.error("Cannot read unknown type: "+this.type) +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/socket-reader.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/socket-reader.js new file mode 100644 index 000000000..1de8ce9a1 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/socket-reader.js @@ -0,0 +1,38 @@ +// Just get the stats, and then don't do anything. +// You can't really "read" from a socket. You "connect" to it. +// Mostly, this is here so that reading a dir with a socket in it +// doesn't blow up. + +module.exports = SocketReader + +var fs = require("../../graceful-fs/graceful-fs.js") + , fstream = require("../fstream.js") + , inherits = require("../../inherits/inherits.js") + , mkdir = require("../../mkdirp") + , Reader = require("./reader.js") + +inherits(SocketReader, Reader) + +function SocketReader (props) { + var me = this + if (!(me instanceof SocketReader)) throw new Error( + "SocketReader must be called as constructor.") + + if (!(props.type === "Socket" && props.Socket)) { + throw new Error("Non-socket type "+ props.type) + } + + Reader.call(me, props) +} + +SocketReader.prototype._read = function () { + var me = this + if (me._paused) return + // basically just a no-op, since we got all the info we have + // from the _stat method + if (!me._ended) { + me.emit("end") + me.emit("close") + me._ended = true + } +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/writer.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/writer.js new file mode 100644 index 000000000..decc20e82 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/fstream/lib/writer.js @@ -0,0 +1,389 @@ + +module.exports = Writer + +var fs = require("../../graceful-fs/graceful-fs.js") + , inherits = require("../../inherits/inherits.js") + , rimraf = require("../../rimraf/rimraf.js") + , mkdir = require("../../mkdirp") + , path = require("path") + , umask = process.platform === "win32" ? 0 : process.umask() + , getType = require("./get-type.js") + , Abstract = require("./abstract.js") + +// Must do this *before* loading the child classes +inherits(Writer, Abstract) + +Writer.dirmode = 0777 & (~umask) +Writer.filemode = 0666 & (~umask) + +var DirWriter = require("./dir-writer.js") + , LinkWriter = require("./link-writer.js") + , FileWriter = require("./file-writer.js") + , ProxyWriter = require("./proxy-writer.js") + +// props is the desired state. current is optionally the current stat, +// provided here so that subclasses can avoid statting the target +// more than necessary. +function Writer (props, current) { + var me = this + + if (typeof props === "string") { + props = { path: props } + } + + if (!props.path) me.error("Must provide a path", null, true) + + // polymorphism. + // call fstream.Writer(dir) to get a DirWriter object, etc. + var type = getType(props) + , ClassType = Writer + + switch (type) { + case "Directory": + ClassType = DirWriter + break + case "File": + ClassType = FileWriter + break + case "Link": + case "SymbolicLink": + ClassType = LinkWriter + break + case null: + // Don't know yet what type to create, so we wrap in a proxy. + ClassType = ProxyWriter + break + } + + if (!(me instanceof ClassType)) return new ClassType(props) + + // now get down to business. + + Abstract.call(me) + + // props is what we want to set. + // set some convenience properties as well. + me.type = props.type + me.props = props + me.depth = props.depth || 0 + me.clobber = false === props.clobber ? props.clobber : true + me.parent = props.parent || null + me.root = props.root || (props.parent && props.parent.root) || me + + me._path = me.path = path.resolve(props.path) + if (process.platform === "win32") { + me.path = me._path = me.path.replace(/\?/g, "_") + if (me._path.length >= 260) { + me._swallowErrors = true + me._path = "\\\\?\\" + me.path.replace(/\//g, "\\") + } + } + me.basename = path.basename(props.path) + me.dirname = path.dirname(props.path) + me.linkpath = props.linkpath || null + + props.parent = props.root = null + + // console.error("\n\n\n%s setting size to", props.path, props.size) + me.size = props.size + + if (typeof props.mode === "string") { + props.mode = parseInt(props.mode, 8) + } + + me.readable = false + me.writable = true + + // buffer until ready, or while handling another entry + me._buffer = [] + me.ready = false + + me.filter = typeof props.filter === "function" ? props.filter: null + + // start the ball rolling. + // this checks what's there already, and then calls + // me._create() to call the impl-specific creation stuff. + me._stat(current) +} + +// Calling this means that it's something we can't create. +// Just assert that it's already there, otherwise raise a warning. +Writer.prototype._create = function () { + var me = this + fs[me.props.follow ? "stat" : "lstat"](me._path, function (er, current) { + if (er) { + return me.warn("Cannot create " + me._path + "\n" + + "Unsupported type: "+me.type, "ENOTSUP") + } + me._finish() + }) +} + +Writer.prototype._stat = function (current) { + var me = this + , props = me.props + , stat = props.follow ? "stat" : "lstat" + , who = me._proxy || me + + if (current) statCb(null, current) + else fs[stat](me._path, statCb) + + function statCb (er, current) { + if (me.filter && !me.filter.call(who, who, current)) { + me._aborted = true + me.emit("end") + me.emit("close") + return + } + + // if it's not there, great. We'll just create it. + // if it is there, then we'll need to change whatever differs + if (er || !current) { + return create(me) + } + + me._old = current + var currentType = getType(current) + + // if it's a type change, then we need to clobber or error. + // if it's not a type change, then let the impl take care of it. + if (currentType !== me.type) { + return rimraf(me._path, function (er) { + if (er) return me.error(er) + me._old = null + create(me) + }) + } + + // otherwise, just handle in the app-specific way + // this creates a fs.WriteStream, or mkdir's, or whatever + create(me) + } +} + +function create (me) { + // console.error("W create", me._path, Writer.dirmode) + + // XXX Need to clobber non-dirs that are in the way, + // unless { clobber: false } in the props. + mkdir(path.dirname(me._path), Writer.dirmode, function (er, made) { + // console.error("W created", path.dirname(me._path), er) + if (er) return me.error(er) + + // later on, we have to set the mode and owner for these + me._madeDir = made + return me._create() + }) +} + +function endChmod (me, want, current, path, cb) { + var wantMode = want.mode + , chmod = want.follow || me.type !== "SymbolicLink" + ? "chmod" : "lchmod" + + if (!fs[chmod]) return cb() + if (typeof wantMode !== "number") return cb() + + var curMode = current.mode & 0777 + wantMode = wantMode & 0777 + if (wantMode === curMode) return cb() + + fs[chmod](path, wantMode, cb) +} + + +function endChown (me, want, current, path, cb) { + // Don't even try it unless root. Too easy to EPERM. + if (process.platform === "win32") return cb() + if (!process.getuid || !process.getuid() === 0) return cb() + if (typeof want.uid !== "number" && + typeof want.gid !== "number" ) return cb() + + if (current.uid === want.uid && + current.gid === want.gid) return cb() + + var chown = (me.props.follow || me.type !== "SymbolicLink") + ? "chown" : "lchown" + if (!fs[chown]) return cb() + + if (typeof want.uid !== "number") want.uid = current.uid + if (typeof want.gid !== "number") want.gid = current.gid + + fs[chown](path, want.uid, want.gid, cb) +} + +function endUtimes (me, want, current, path, cb) { + if (!fs.utimes || process.platform === "win32") return cb() + + var utimes = (want.follow || me.type !== "SymbolicLink") + ? "utimes" : "lutimes" + + if (utimes === "lutimes" && !fs[utimes]) { + utimes = "utimes" + } + + if (!fs[utimes]) return cb() + + var curA = current.atime + , curM = current.mtime + , meA = want.atime + , meM = want.mtime + + if (meA === undefined) meA = curA + if (meM === undefined) meM = curM + + if (!isDate(meA)) meA = new Date(meA) + if (!isDate(meM)) meA = new Date(meM) + + if (meA.getTime() === curA.getTime() && + meM.getTime() === curM.getTime()) return cb() + + fs[utimes](path, meA, meM, cb) +} + + +// XXX This function is beastly. Break it up! +Writer.prototype._finish = function () { + var me = this + + // console.error(" W Finish", me._path, me.size) + + // set up all the things. + // At this point, we're already done writing whatever we've gotta write, + // adding files to the dir, etc. + var todo = 0 + var errState = null + var done = false + + if (me._old) { + // the times will almost *certainly* have changed. + // adds the utimes syscall, but remove another stat. + me._old.atime = new Date(0) + me._old.mtime = new Date(0) + // console.error(" W Finish Stale Stat", me._path, me.size) + setProps(me._old) + } else { + var stat = me.props.follow ? "stat" : "lstat" + // console.error(" W Finish Stating", me._path, me.size) + fs[stat](me._path, function (er, current) { + // console.error(" W Finish Stated", me._path, me.size, current) + if (er) { + // if we're in the process of writing out a + // directory, it's very possible that the thing we're linking to + // doesn't exist yet (especially if it was intended as a symlink), + // so swallow ENOENT errors here and just soldier on. + if (er.code === "ENOENT" && + (me.type === "Link" || me.type === "SymbolicLink") && + process.platform === "win32") { + me.ready = true + me.emit("ready") + me.emit("end") + me.emit("close") + me.end = me._finish = function () {} + return + } else return me.error(er) + } + setProps(me._old = current) + }) + } + + return + + function setProps (current) { + endChmod(me, me.props, current, me._path, next("chmod")) + endChown(me, me.props, current, me._path, next("chown")) + endUtimes(me, me.props, current, me._path, next("chown")) + } + + function next (what) { + todo ++ + return function (er) { + // console.error(" W Finish", what, todo) + if (errState) return + if (er) { + er.fstream_finish_call = what + return me.error(errState = er) + } + if (--todo > 0) return + if (done) return + done = true + + // we may still need to set the mode/etc. on some parent dirs + // that were created previously. delay end/close until then. + if (!me._madeDir) return end() + else endMadeDir(me, me._path, end) + + function end (er) { + if (er) { + er.fstream_finish_call = "setupMadeDir" + return me.error(er) + } + // all the props have been set, so we're completely done. + me.emit("end") + me.emit("close") + } + } + } +} + +function endMadeDir (me, p, cb) { + var made = me._madeDir + // everything *between* made and path.dirname(me._path) + // needs to be set up. Note that this may just be one dir. + var d = path.dirname(p) + + endMadeDir_(me, d, function (er) { + if (er) return cb(er) + if (d === made) { + return cb() + } + endMadeDir(me, d, cb) + }) +} + +function endMadeDir_ (me, p, cb) { + var dirProps = {} + Object.keys(me.props).forEach(function (k) { + dirProps[k] = me.props[k] + + // only make non-readable dirs if explicitly requested. + if (k === "mode" && me.type !== "Directory") { + dirProps[k] = dirProps[k] | 0111 + } + }) + + var todo = 3 + , errState = null + fs.stat(p, function (er, current) { + if (er) return cb(errState = er) + endChmod(me, dirProps, current, p, next) + endChown(me, dirProps, current, p, next) + endUtimes(me, dirProps, current, p, next) + }) + + function next (er) { + if (errState) return + if (er) return cb(errState = er) + if (-- todo === 0) return cb() + } +} + +Writer.prototype.pipe = function () { + this.error("Can't pipe from writable stream") +} + +Writer.prototype.add = function () { + this.error("Cannot add to non-Directory type") +} + +Writer.prototype.write = function () { + return true +} + +function objectToString (d) { + return Object.prototype.toString.call(d) +} + +function isDate(d) { + return typeof d === 'object' && objectToString(d) === '[object Date]'; +} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/graceful-fs/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/graceful-fs/LICENSE diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/graceful-fs/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/graceful-fs/README.md new file mode 100644 index 000000000..7d2e681e3 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/graceful-fs/README.md @@ -0,0 +1,5 @@ +Just like node's `fs` module, but it does an incremental back-off when +EMFILE is encountered. + +Useful in asynchronous situations where one needs to try to open lots +and lots of files. diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/graceful-fs/graceful-fs.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/graceful-fs/graceful-fs.js new file mode 100644 index 000000000..be9951eac --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/graceful-fs/graceful-fs.js @@ -0,0 +1,312 @@ +// this keeps a queue of opened file descriptors, and will make +// fs operations wait until some have closed before trying to open more. + +var fs = require("fs") + +// there is such a thing as TOO graceful. +if (fs.open === gracefulOpen) return + +var queue = [] + , constants = require("constants") + +exports = module.exports = fs +fs._curOpen = 0 + +fs.MIN_MAX_OPEN = 64 +fs.MAX_OPEN = 1024 + +var originalOpen = fs.open + , originalOpenSync = fs.openSync + , originalClose = fs.close + , originalCloseSync = fs.closeSync + + +// prevent EMFILE errors +function OpenReq (path, flags, mode, cb) { + this.path = path + this.flags = flags + this.mode = mode + this.cb = cb +} + +function noop () {} + +fs.open = gracefulOpen + +function gracefulOpen (path, flags, mode, cb) { + if (typeof mode === "function") cb = mode, mode = null + if (typeof cb !== "function") cb = noop + + if (fs._curOpen >= fs.MAX_OPEN) { + queue.push(new OpenReq(path, flags, mode, cb)) + setTimeout(flush) + return + } + open(path, flags, mode, function (er, fd) { + if (er && er.code === "EMFILE" && fs._curOpen > fs.MIN_MAX_OPEN) { + // that was too many. reduce max, get back in queue. + // this should only happen once in a great while, and only + // if the ulimit -n is set lower than 1024. + fs.MAX_OPEN = fs._curOpen - 1 + return fs.open(path, flags, mode, cb) + } + cb(er, fd) + }) +} + +function open (path, flags, mode, cb) { + cb = cb || noop + fs._curOpen ++ + originalOpen.call(fs, path, flags, mode, function (er, fd) { + if (er) onclose() + cb(er, fd) + }) +} + +fs.openSync = function (path, flags, mode) { + var ret + ret = originalOpenSync.call(fs, path, flags, mode) + fs._curOpen ++ + return ret +} + +function onclose () { + fs._curOpen -- + flush() +} + +function flush () { + while (fs._curOpen < fs.MAX_OPEN) { + var req = queue.shift() + if (!req) return + open(req.path, req.flags || "r", req.mode || 0777, req.cb) + } +} + +fs.close = function (fd, cb) { + cb = cb || noop + originalClose.call(fs, fd, function (er) { + onclose() + cb(er) + }) +} + +fs.closeSync = function (fd) { + onclose() + return originalCloseSync.call(fs, fd) +} + + +// (re-)implement some things that are known busted or missing. + +var constants = require("constants") + +// 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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/inherits/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/README.md rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/inherits/README.md diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/inherits.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/inherits/inherits.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/inherits.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/inherits/inherits.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/mkdirp/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/mkdirp/LICENSE diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/mkdirp/README.markdown b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/mkdirp/README.markdown new file mode 100644 index 000000000..40de04f71 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/mkdirp/README.markdown @@ -0,0 +1,61 @@ +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 +------ + 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())`. + +`cb(err, made)` fires with the error or the first directory `made` +that had to be created, if any. + +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())`. + +Returns the first directory that had to be created, if any. + +install +======= + +With [npm](http://npmjs.org) do: + + npm install mkdirp + +license +======= + +MIT/X11 diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/index.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/mkdirp/index.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/index.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/mkdirp/index.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/rimraf/AUTHORS b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/rimraf/AUTHORS new file mode 100644 index 000000000..247b75437 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/rimraf/AUTHORS @@ -0,0 +1,6 @@ +# Authors sorted by whether or not they're me. +Isaac Z. Schlueter (http://blog.izs.me) +Wayne Larsen (http://github.com/wvl) +ritch +Marcel Laverdet +Yosef Dinerstein diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/rimraf/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/rimraf/LICENSE diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/rimraf/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/rimraf/README.md new file mode 100644 index 000000000..96ce9b2a0 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/rimraf/README.md @@ -0,0 +1,21 @@ +A `rm -rf` for node. + +Install with `npm install rimraf`, or just drop rimraf.js somewhere. + +## API + +`rimraf(f, callback)` + +The callback will be called with an error if there is one. Certain +errors are handled for you: + +* `EBUSY` - rimraf will back off a maximum of opts.maxBusyTries times + before giving up. +* `EMFILE` - If too many file descriptors get opened, rimraf will + patiently wait until more become available. + + +## rimraf.sync + +It can remove stuff synchronously, too. But that's not so good. Use +the async API. It's better. diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/rimraf/rimraf.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/rimraf/rimraf.js new file mode 100644 index 000000000..bef2e0625 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/tar/vendor/rimraf/rimraf.js @@ -0,0 +1,161 @@ +module.exports = rimraf +rimraf.sync = rimrafSync + +var path = require("path") + , fs + +try { + // optional dependency + fs = require("../../graceful-fs/graceful-fs.js") +} catch (er) { + fs = require("fs") +} + +var lstat = "lstat" +if (process.platform === "win32") { + // not reliable on windows prior to 0.7.9 + var v = process.version.replace(/^v/, '').split(/\.|-/).map(Number) + if (v[0] === 0 && (v[1] < 7 || v[1] == 7 && v[2] < 9)) { + lstat = "stat" + } +} +if (!fs[lstat]) lstat = "stat" +var lstatSync = lstat + "Sync" + +// for EMFILE handling +var timeout = 0 +exports.EMFILE_MAX = 1000 +exports.BUSYTRIES_MAX = 3 + +function rimraf (p, cb) { + + if (!cb) throw new Error("No callback passed to rimraf()") + + var busyTries = 0 + + rimraf_(p, function CB (er) { + if (er) { + if (er.code === "EBUSY" && busyTries < exports.BUSYTRIES_MAX) { + busyTries ++ + var time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(function () { + rimraf_(p, CB) + }, time) + } + + // this one won't happen if graceful-fs is used. + if (er.code === "EMFILE" && timeout < exports.EMFILE_MAX) { + return setTimeout(function () { + rimraf_(p, CB) + }, timeout ++) + } + + // already gone + if (er.code === "ENOENT") er = null + } + + timeout = 0 + cb(er) + }) +} + +function rimraf_ (p, cb) { + fs[lstat](p, function (er, s) { + if (er) { + // already gone + if (er.code === "ENOENT") return cb() + // some other kind of error, permissions, etc. + return cb(er) + } + + return rm_(p, s, false, cb) + }) +} + + +var myGid = function myGid () { + var g = process.getuid && process.getgid() + myGid = function myGid () { return g } + return g +} + +var myUid = function myUid () { + var u = process.getuid && process.getuid() + myUid = function myUid () { return u } + return u +} + + +function writable (s) { + var mode = s.mode || 0777 + , uid = myUid() + , gid = myGid() + return (mode & 0002) + || (gid === s.gid && (mode & 0020)) + || (uid === s.uid && (mode & 0200)) +} + +function rm_ (p, s, didWritableCheck, cb) { + if (!didWritableCheck && !writable(s)) { + // make file writable + // user/group/world, doesn't matter at this point + // since it's about to get nuked. + return fs.chmod(p, s.mode | 0222, function (er) { + if (er) return cb(er) + rm_(p, s, true, cb) + }) + } + + if (!s.isDirectory()) { + return fs.unlink(p, cb) + } + + // directory + fs.readdir(p, function (er, files) { + if (er) return cb(er) + asyncForEach(files.map(function (f) { + return path.join(p, f) + }), function (file, cb) { + rimraf(file, cb) + }, function (er) { + if (er) return cb(er) + fs.rmdir(p, cb) + }) + }) +} + +function asyncForEach (list, fn, cb) { + if (!list.length) cb() + var c = list.length + , errState = null + list.forEach(function (item, i, list) { + fn(item, function (er) { + if (errState) return + if (er) return cb(errState = er) + if (-- c === 0) return cb() + }) + }) +} + +// this looks simpler, but it will fail with big directory trees, +// or on slow stupid awful cygwin filesystems +function rimrafSync (p) { + try { + var s = fs[lstatSync](p) + } catch (er) { + if (er.code === "ENOENT") return + throw er + } + + if (!writable(s)) { + fs.chmodSync(p, s.mode | 0222) + } + + if (!s.isDirectory()) return fs.unlinkSync(p) + + fs.readdirSync(p).forEach(function (f) { + rimrafSync(path.join(p, f)) + }) + fs.rmdirSync(p) +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/underscore/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/underscore/LICENSE new file mode 100644 index 000000000..0d8dbe40b --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/underscore/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2009-2013 Jeremy Ashkenas, DocumentCloud + +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/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/underscore/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/underscore/README.md new file mode 100644 index 000000000..b1f3e50a8 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/underscore/README.md @@ -0,0 +1,19 @@ + __ + /\ \ __ + __ __ ___ \_\ \ __ _ __ ____ ___ ___ _ __ __ /\_\ ____ + /\ \/\ \ /' _ `\ /'_ \ /'__`\/\ __\/ ,__\ / ___\ / __`\/\ __\/'__`\ \/\ \ /',__\ + \ \ \_\ \/\ \/\ \/\ \ \ \/\ __/\ \ \//\__, `\/\ \__//\ \ \ \ \ \//\ __/ __ \ \ \/\__, `\ + \ \____/\ \_\ \_\ \___,_\ \____\\ \_\\/\____/\ \____\ \____/\ \_\\ \____\/\_\ _\ \ \/\____/ + \/___/ \/_/\/_/\/__,_ /\/____/ \/_/ \/___/ \/____/\/___/ \/_/ \/____/\/_//\ \_\ \/___/ + \ \____/ + \/___/ + +Underscore.js is a utility-belt library for JavaScript that provides +support for the usual functional suspects (each, map, reduce, filter...) +without extending any core JavaScript objects. + +For Docs, License, Tests, and pre-packed downloads, see: +http://underscorejs.org + +Many thanks to our contributors: +https://github.com/documentcloud/underscore/contributors diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/underscore/underscore.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/underscore/underscore.js new file mode 100644 index 000000000..a12f0d96c --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/lodash/vendor/underscore/underscore.js @@ -0,0 +1,1226 @@ +// Underscore.js 1.4.4 +// http://underscorejs.org +// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc. +// Underscore may be freely distributed under the MIT license. + +(function() { + + // Baseline setup + // -------------- + + // Establish the root object, `window` in the browser, or `global` on the server. + var root = this; + + // Save the previous value of the `_` variable. + var previousUnderscore = root._; + + // Establish the object that gets returned to break out of a loop iteration. + var breaker = {}; + + // Save bytes in the minified (but not gzipped) version: + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; + + // Create quick reference variables for speed access to core prototypes. + var push = ArrayProto.push, + slice = ArrayProto.slice, + concat = ArrayProto.concat, + toString = ObjProto.toString, + hasOwnProperty = ObjProto.hasOwnProperty; + + // All **ECMAScript 5** native function implementations that we hope to use + // are declared here. + var + nativeForEach = ArrayProto.forEach, + nativeMap = ArrayProto.map, + nativeReduce = ArrayProto.reduce, + nativeReduceRight = ArrayProto.reduceRight, + nativeFilter = ArrayProto.filter, + nativeEvery = ArrayProto.every, + nativeSome = ArrayProto.some, + nativeIndexOf = ArrayProto.indexOf, + nativeLastIndexOf = ArrayProto.lastIndexOf, + nativeIsArray = Array.isArray, + nativeKeys = Object.keys, + nativeBind = FuncProto.bind; + + // Create a safe reference to the Underscore object for use below. + var _ = function(obj) { + if (obj instanceof _) return obj; + if (!(this instanceof _)) return new _(obj); + this._wrapped = obj; + }; + + // Export the Underscore object for **Node.js**, with + // backwards-compatibility for the old `require()` API. If we're in + // the browser, add `_` as a global object via a string identifier, + // for Closure Compiler "advanced" mode. + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = _; + } + exports._ = _; + } else { + root._ = _; + } + + // Current version. + _.VERSION = '1.4.4'; + + // Collection Functions + // -------------------- + + // The cornerstone, an `each` implementation, aka `forEach`. + // Handles objects with the built-in `forEach`, arrays, and raw objects. + // Delegates to **ECMAScript 5**'s native `forEach` if available. + var each = _.each = _.forEach = function(obj, iterator, context) { + if (obj == null) return; + if (nativeForEach && obj.forEach === nativeForEach) { + obj.forEach(iterator, context); + } else if (obj.length === +obj.length) { + for (var i = 0, l = obj.length; i < l; i++) { + if (iterator.call(context, obj[i], i, obj) === breaker) return; + } + } else { + for (var key in obj) { + if (_.has(obj, key)) { + if (iterator.call(context, obj[key], key, obj) === breaker) return; + } + } + } + }; + + // Return the results of applying the iterator to each element. + // Delegates to **ECMAScript 5**'s native `map` if available. + _.map = _.collect = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); + each(obj, function(value, index, list) { + results[results.length] = iterator.call(context, value, index, list); + }); + return results; + }; + + var reduceError = 'Reduce of empty array with no initial value'; + + // **Reduce** builds up a single result from a list of values, aka `inject`, + // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. + _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { + var initial = arguments.length > 2; + if (obj == null) obj = []; + if (nativeReduce && obj.reduce === nativeReduce) { + if (context) iterator = _.bind(iterator, context); + return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); + } + each(obj, function(value, index, list) { + if (!initial) { + memo = value; + initial = true; + } else { + memo = iterator.call(context, memo, value, index, list); + } + }); + if (!initial) throw new TypeError(reduceError); + return memo; + }; + + // The right-associative version of reduce, also known as `foldr`. + // Delegates to **ECMAScript 5**'s native `reduceRight` if available. + _.reduceRight = _.foldr = function(obj, iterator, memo, context) { + var initial = arguments.length > 2; + if (obj == null) obj = []; + if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { + if (context) iterator = _.bind(iterator, context); + return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); + } + var length = obj.length; + if (length !== +length) { + var keys = _.keys(obj); + length = keys.length; + } + each(obj, function(value, index, list) { + index = keys ? keys[--length] : --length; + if (!initial) { + memo = obj[index]; + initial = true; + } else { + memo = iterator.call(context, memo, obj[index], index, list); + } + }); + if (!initial) throw new TypeError(reduceError); + return memo; + }; + + // Return the first value which passes a truth test. Aliased as `detect`. + _.find = _.detect = function(obj, iterator, context) { + var result; + any(obj, function(value, index, list) { + if (iterator.call(context, value, index, list)) { + result = value; + return true; + } + }); + return result; + }; + + // Return all the elements that pass a truth test. + // Delegates to **ECMAScript 5**'s native `filter` if available. + // Aliased as `select`. + _.filter = _.select = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); + each(obj, function(value, index, list) { + if (iterator.call(context, value, index, list)) results[results.length] = value; + }); + return results; + }; + + // Return all the elements for which a truth test fails. + _.reject = function(obj, iterator, context) { + return _.filter(obj, function(value, index, list) { + return !iterator.call(context, value, index, list); + }, context); + }; + + // Determine whether all of the elements match a truth test. + // Delegates to **ECMAScript 5**'s native `every` if available. + // Aliased as `all`. + _.every = _.all = function(obj, iterator, context) { + iterator || (iterator = _.identity); + var result = true; + if (obj == null) return result; + if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); + each(obj, function(value, index, list) { + if (!(result = result && iterator.call(context, value, index, list))) return breaker; + }); + return !!result; + }; + + // Determine if at least one element in the object matches a truth test. + // Delegates to **ECMAScript 5**'s native `some` if available. + // Aliased as `any`. + var any = _.some = _.any = function(obj, iterator, context) { + iterator || (iterator = _.identity); + var result = false; + if (obj == null) return result; + if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); + each(obj, function(value, index, list) { + if (result || (result = iterator.call(context, value, index, list))) return breaker; + }); + return !!result; + }; + + // Determine if the array or object contains a given value (using `===`). + // Aliased as `include`. + _.contains = _.include = function(obj, target) { + if (obj == null) return false; + if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; + return any(obj, function(value) { + return value === target; + }); + }; + + // Invoke a method (with arguments) on every item in a collection. + _.invoke = function(obj, method) { + var args = slice.call(arguments, 2); + var isFunc = _.isFunction(method); + return _.map(obj, function(value) { + return (isFunc ? method : value[method]).apply(value, args); + }); + }; + + // Convenience version of a common use case of `map`: fetching a property. + _.pluck = function(obj, key) { + return _.map(obj, function(value){ return value[key]; }); + }; + + // Convenience version of a common use case of `filter`: selecting only objects + // containing specific `key:value` pairs. + _.where = function(obj, attrs, first) { + if (_.isEmpty(attrs)) return first ? null : []; + return _[first ? 'find' : 'filter'](obj, function(value) { + for (var key in attrs) { + if (attrs[key] !== value[key]) return false; + } + return true; + }); + }; + + // Convenience version of a common use case of `find`: getting the first object + // containing specific `key:value` pairs. + _.findWhere = function(obj, attrs) { + return _.where(obj, attrs, true); + }; + + // Return the maximum element or (element-based computation). + // Can't optimize arrays of integers longer than 65,535 elements. + // See: https://bugs.webkit.org/show_bug.cgi?id=80797 + _.max = function(obj, iterator, context) { + if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { + return Math.max.apply(Math, obj); + } + if (!iterator && _.isEmpty(obj)) return -Infinity; + var result = {computed : -Infinity, value: -Infinity}; + each(obj, function(value, index, list) { + var computed = iterator ? iterator.call(context, value, index, list) : value; + computed >= result.computed && (result = {value : value, computed : computed}); + }); + return result.value; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iterator, context) { + if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { + return Math.min.apply(Math, obj); + } + if (!iterator && _.isEmpty(obj)) return Infinity; + var result = {computed : Infinity, value: Infinity}; + each(obj, function(value, index, list) { + var computed = iterator ? iterator.call(context, value, index, list) : value; + computed < result.computed && (result = {value : value, computed : computed}); + }); + return result.value; + }; + + // Shuffle an array. + _.shuffle = function(obj) { + var rand; + var index = 0; + var shuffled = []; + each(obj, function(value) { + rand = _.random(index++); + shuffled[index - 1] = shuffled[rand]; + shuffled[rand] = value; + }); + return shuffled; + }; + + // An internal function to generate lookup iterators. + var lookupIterator = function(value) { + return _.isFunction(value) ? value : function(obj){ return obj[value]; }; + }; + + // Sort the object's values by a criterion produced by an iterator. + _.sortBy = function(obj, value, context) { + var iterator = lookupIterator(value); + return _.pluck(_.map(obj, function(value, index, list) { + return { + value : value, + index : index, + criteria : iterator.call(context, value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria; + var b = right.criteria; + if (a !== b) { + if (a > b || a === void 0) return 1; + if (a < b || b === void 0) return -1; + } + return left.index < right.index ? -1 : 1; + }), 'value'); + }; + + // An internal function used for aggregate "group by" operations. + var group = function(obj, value, context, behavior) { + var result = {}; + var iterator = lookupIterator(value || _.identity); + each(obj, function(value, index) { + var key = iterator.call(context, value, index, obj); + behavior(result, key, value); + }); + return result; + }; + + // Groups the object's values by a criterion. Pass either a string attribute + // to group by, or a function that returns the criterion. + _.groupBy = function(obj, value, context) { + return group(obj, value, context, function(result, key, value) { + (_.has(result, key) ? result[key] : (result[key] = [])).push(value); + }); + }; + + // Counts instances of an object that group by a certain criterion. Pass + // either a string attribute to count by, or a function that returns the + // criterion. + _.countBy = function(obj, value, context) { + return group(obj, value, context, function(result, key) { + if (!_.has(result, key)) result[key] = 0; + result[key]++; + }); + }; + + // Use a comparator function to figure out the smallest index at which + // an object should be inserted so as to maintain order. Uses binary search. + _.sortedIndex = function(array, obj, iterator, context) { + iterator = iterator == null ? _.identity : lookupIterator(iterator); + var value = iterator.call(context, obj); + var low = 0, high = array.length; + while (low < high) { + var mid = (low + high) >>> 1; + iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; + } + return low; + }; + + // Safely convert anything iterable into a real, live array. + _.toArray = function(obj) { + if (!obj) return []; + if (_.isArray(obj)) return slice.call(obj); + if (obj.length === +obj.length) return _.map(obj, _.identity); + return _.values(obj); + }; + + // Return the number of elements in an object. + _.size = function(obj) { + if (obj == null) return 0; + return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; + }; + + // Array Functions + // --------------- + + // Get the first element of an array. Passing **n** will return the first N + // values in the array. Aliased as `head` and `take`. The **guard** check + // allows it to work with `_.map`. + _.first = _.head = _.take = function(array, n, guard) { + if (array == null) return void 0; + return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; + }; + + // Returns everything but the last entry of the array. Especially useful on + // the arguments object. Passing **n** will return all the values in + // the array, excluding the last N. The **guard** check allows it to work with + // `_.map`. + _.initial = function(array, n, guard) { + return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); + }; + + // Get the last element of an array. Passing **n** will return the last N + // values in the array. The **guard** check allows it to work with `_.map`. + _.last = function(array, n, guard) { + if (array == null) return void 0; + if ((n != null) && !guard) { + return slice.call(array, Math.max(array.length - n, 0)); + } else { + return array[array.length - 1]; + } + }; + + // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. + // Especially useful on the arguments object. Passing an **n** will return + // the rest N values in the array. The **guard** + // check allows it to work with `_.map`. + _.rest = _.tail = _.drop = function(array, n, guard) { + return slice.call(array, (n == null) || guard ? 1 : n); + }; + + // Trim out all falsy values from an array. + _.compact = function(array) { + return _.filter(array, _.identity); + }; + + // Internal implementation of a recursive `flatten` function. + var flatten = function(input, shallow, output) { + each(input, function(value) { + if (_.isArray(value)) { + shallow ? push.apply(output, value) : flatten(value, shallow, output); + } else { + output.push(value); + } + }); + return output; + }; + + // Return a completely flattened version of an array. + _.flatten = function(array, shallow) { + return flatten(array, shallow, []); + }; + + // Return a version of the array that does not contain the specified value(s). + _.without = function(array) { + return _.difference(array, slice.call(arguments, 1)); + }; + + // Produce a duplicate-free version of the array. If the array has already + // been sorted, you have the option of using a faster algorithm. + // Aliased as `unique`. + _.uniq = _.unique = function(array, isSorted, iterator, context) { + if (_.isFunction(isSorted)) { + context = iterator; + iterator = isSorted; + isSorted = false; + } + var initial = iterator ? _.map(array, iterator, context) : array; + var results = []; + var seen = []; + each(initial, function(value, index) { + if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { + seen.push(value); + results.push(array[index]); + } + }); + return results; + }; + + // Produce an array that contains the union: each distinct element from all of + // the passed-in arrays. + _.union = function() { + return _.uniq(concat.apply(ArrayProto, arguments)); + }; + + // Produce an array that contains every item shared between all the + // passed-in arrays. + _.intersection = function(array) { + var rest = slice.call(arguments, 1); + return _.filter(_.uniq(array), function(item) { + return _.every(rest, function(other) { + return _.indexOf(other, item) >= 0; + }); + }); + }; + + // Take the difference between one array and a number of other arrays. + // Only the elements present in just the first array will remain. + _.difference = function(array) { + var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); + return _.filter(array, function(value){ return !_.contains(rest, value); }); + }; + + // Zip together multiple lists into a single array -- elements that share + // an index go together. + _.zip = function() { + var args = slice.call(arguments); + var length = _.max(_.pluck(args, 'length')); + var results = new Array(length); + for (var i = 0; i < length; i++) { + results[i] = _.pluck(args, "" + i); + } + return results; + }; + + // Converts lists into objects. Pass either a single array of `[key, value]` + // pairs, or two parallel arrays of the same length -- one of keys, and one of + // the corresponding values. + _.object = function(list, values) { + if (list == null) return {}; + var result = {}; + for (var i = 0, l = list.length; i < l; i++) { + if (values) { + result[list[i]] = values[i]; + } else { + result[list[i][0]] = list[i][1]; + } + } + return result; + }; + + // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), + // we need this function. Return the position of the first occurrence of an + // item in an array, or -1 if the item is not included in the array. + // Delegates to **ECMAScript 5**'s native `indexOf` if available. + // If the array is large and already in sort order, pass `true` + // for **isSorted** to use binary search. + _.indexOf = function(array, item, isSorted) { + if (array == null) return -1; + var i = 0, l = array.length; + if (isSorted) { + if (typeof isSorted == 'number') { + i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted); + } else { + i = _.sortedIndex(array, item); + return array[i] === item ? i : -1; + } + } + if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); + for (; i < l; i++) if (array[i] === item) return i; + return -1; + }; + + // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. + _.lastIndexOf = function(array, item, from) { + if (array == null) return -1; + var hasIndex = from != null; + if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { + return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); + } + var i = (hasIndex ? from : array.length); + while (i--) if (array[i] === item) return i; + return -1; + }; + + // Generate an integer Array containing an arithmetic progression. A port of + // the native Python `range()` function. See + // [the Python documentation](http://docs.python.org/library/functions.html#range). + _.range = function(start, stop, step) { + if (arguments.length <= 1) { + stop = start || 0; + start = 0; + } + step = arguments[2] || 1; + + var len = Math.max(Math.ceil((stop - start) / step), 0); + var idx = 0; + var range = new Array(len); + + while(idx < len) { + range[idx++] = start; + start += step; + } + + return range; + }; + + // Function (ahem) Functions + // ------------------ + + // Create a function bound to a given object (assigning `this`, and arguments, + // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if + // available. + _.bind = function(func, context) { + if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + var args = slice.call(arguments, 2); + return function() { + return func.apply(context, args.concat(slice.call(arguments))); + }; + }; + + // Partially apply a function by creating a version that has had some of its + // arguments pre-filled, without changing its dynamic `this` context. + _.partial = function(func) { + var args = slice.call(arguments, 1); + return function() { + return func.apply(this, args.concat(slice.call(arguments))); + }; + }; + + // Bind all of an object's methods to that object. Useful for ensuring that + // all callbacks defined on an object belong to it. + _.bindAll = function(obj) { + var funcs = slice.call(arguments, 1); + if (funcs.length === 0) funcs = _.functions(obj); + each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memo = {}; + hasher || (hasher = _.identity); + return function() { + var key = hasher.apply(this, arguments); + return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); + }; + }; + + // Delays a function for the given number of milliseconds, and then calls + // it with the arguments supplied. + _.delay = function(func, wait) { + var args = slice.call(arguments, 2); + return setTimeout(function(){ return func.apply(null, args); }, wait); + }; + + // Defers a function, scheduling it to run after the current call stack has + // cleared. + _.defer = function(func) { + return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); + }; + + // Returns a function, that, when invoked, will only be triggered at most once + // during a given window of time. + _.throttle = function(func, wait) { + var context, args, timeout, result; + var previous = 0; + var later = function() { + previous = new Date; + timeout = null; + result = func.apply(context, args); + }; + return function() { + var now = new Date; + var remaining = wait - (now - previous); + context = this; + args = arguments; + if (remaining <= 0) { + clearTimeout(timeout); + timeout = null; + previous = now; + result = func.apply(context, args); + } else if (!timeout) { + timeout = setTimeout(later, remaining); + } + return result; + }; + }; + + // Returns a function, that, as long as it continues to be invoked, will not + // be triggered. The function will be called after it stops being called for + // N milliseconds. If `immediate` is passed, trigger the function on the + // leading edge, instead of the trailing. + _.debounce = function(func, wait, immediate) { + var timeout, result; + return function() { + var context = this, args = arguments; + var later = function() { + timeout = null; + if (!immediate) result = func.apply(context, args); + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) result = func.apply(context, args); + return result; + }; + }; + + // Returns a function that will be executed at most one time, no matter how + // often you call it. Useful for lazy initialization. + _.once = function(func) { + var ran = false, memo; + return function() { + if (ran) return memo; + ran = true; + memo = func.apply(this, arguments); + func = null; + return memo; + }; + }; + + // Returns the first function passed as an argument to the second, + // allowing you to adjust arguments, run code before and after, and + // conditionally execute the original function. + _.wrap = function(func, wrapper) { + return function() { + var args = [func]; + push.apply(args, arguments); + return wrapper.apply(this, args); + }; + }; + + // Returns a function that is the composition of a list of functions, each + // consuming the return value of the function that follows. + _.compose = function() { + var funcs = arguments; + return function() { + var args = arguments; + for (var i = funcs.length - 1; i >= 0; i--) { + args = [funcs[i].apply(this, args)]; + } + return args[0]; + }; + }; + + // Returns a function that will only be executed after being called N times. + _.after = function(times, func) { + if (times <= 0) return func(); + return function() { + if (--times < 1) { + return func.apply(this, arguments); + } + }; + }; + + // Object Functions + // ---------------- + + // Retrieve the names of an object's properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = nativeKeys || function(obj) { + if (obj !== Object(obj)) throw new TypeError('Invalid object'); + var keys = []; + for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + var values = []; + for (var key in obj) if (_.has(obj, key)) values.push(obj[key]); + return values; + }; + + // Convert an object into a list of `[key, value]` pairs. + _.pairs = function(obj) { + var pairs = []; + for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]); + return pairs; + }; + + // Invert the keys and values of an object. The values must be serializable. + _.invert = function(obj) { + var result = {}; + for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key; + return result; + }; + + // Return a sorted list of the function names available on the object. + // Aliased as `methods` + _.functions = _.methods = function(obj) { + var names = []; + for (var key in obj) { + if (_.isFunction(obj[key])) names.push(key); + } + return names.sort(); + }; + + // Extend a given object with all the properties in passed-in object(s). + _.extend = function(obj) { + each(slice.call(arguments, 1), function(source) { + if (source) { + for (var prop in source) { + obj[prop] = source[prop]; + } + } + }); + return obj; + }; + + // Return a copy of the object only containing the whitelisted properties. + _.pick = function(obj) { + var copy = {}; + var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); + each(keys, function(key) { + if (key in obj) copy[key] = obj[key]; + }); + return copy; + }; + + // Return a copy of the object without the blacklisted properties. + _.omit = function(obj) { + var copy = {}; + var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); + for (var key in obj) { + if (!_.contains(keys, key)) copy[key] = obj[key]; + } + return copy; + }; + + // Fill in a given object with default properties. + _.defaults = function(obj) { + each(slice.call(arguments, 1), function(source) { + if (source) { + for (var prop in source) { + if (obj[prop] == null) obj[prop] = source[prop]; + } + } + }); + return obj; + }; + + // Create a (shallow-cloned) duplicate of an object. + _.clone = function(obj) { + if (!_.isObject(obj)) return obj; + return _.isArray(obj) ? obj.slice() : _.extend({}, obj); + }; + + // Invokes interceptor with the obj, and then returns obj. + // The primary purpose of this method is to "tap into" a method chain, in + // order to perform operations on intermediate results within the chain. + _.tap = function(obj, interceptor) { + interceptor(obj); + return obj; + }; + + // Internal recursive comparison function for `isEqual`. + var eq = function(a, b, aStack, bStack) { + // Identical objects are equal. `0 === -0`, but they aren't identical. + // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. + if (a === b) return a !== 0 || 1 / a == 1 / b; + // A strict comparison is necessary because `null == undefined`. + if (a == null || b == null) return a === b; + // Unwrap any wrapped objects. + if (a instanceof _) a = a._wrapped; + if (b instanceof _) b = b._wrapped; + // Compare `[[Class]]` names. + var className = toString.call(a); + if (className != toString.call(b)) return false; + switch (className) { + // Strings, numbers, dates, and booleans are compared by value. + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return a == String(b); + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for + // other numeric values. + return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + return +a == +b; + // RegExps are compared by their source patterns and flags. + case '[object RegExp]': + return a.source == b.source && + a.global == b.global && + a.multiline == b.multiline && + a.ignoreCase == b.ignoreCase; + } + if (typeof a != 'object' || typeof b != 'object') return false; + // Assume equality for cyclic structures. The algorithm for detecting cyclic + // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + if (aStack[length] == a) return bStack[length] == b; + } + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + var size = 0, result = true; + // Recursively compare objects and arrays. + if (className == '[object Array]') { + // Compare array lengths to determine if a deep comparison is necessary. + size = a.length; + result = size == b.length; + if (result) { + // Deep compare the contents, ignoring non-numeric properties. + while (size--) { + if (!(result = eq(a[size], b[size], aStack, bStack))) break; + } + } + } else { + // Objects with different constructors are not equivalent, but `Object`s + // from different frames are. + var aCtor = a.constructor, bCtor = b.constructor; + if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && + _.isFunction(bCtor) && (bCtor instanceof bCtor))) { + return false; + } + // Deep compare objects. + for (var key in a) { + if (_.has(a, key)) { + // Count the expected number of properties. + size++; + // Deep compare each member. + if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; + } + } + // Ensure that both objects contain the same number of properties. + if (result) { + for (key in b) { + if (_.has(b, key) && !(size--)) break; + } + result = !size; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + return result; + }; + + // Perform a deep comparison to check if two objects are equal. + _.isEqual = function(a, b) { + return eq(a, b, [], []); + }; + + // Is a given array, string, or object empty? + // An "empty" object has no enumerable own-properties. + _.isEmpty = function(obj) { + if (obj == null) return true; + if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; + for (var key in obj) if (_.has(obj, key)) return false; + return true; + }; + + // Is a given value a DOM element? + _.isElement = function(obj) { + return !!(obj && obj.nodeType === 1); + }; + + // Is a given value an array? + // Delegates to ECMA5's native Array.isArray + _.isArray = nativeIsArray || function(obj) { + return toString.call(obj) == '[object Array]'; + }; + + // Is a given variable an object? + _.isObject = function(obj) { + return obj === Object(obj); + }; + + // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. + each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { + _['is' + name] = function(obj) { + return toString.call(obj) == '[object ' + name + ']'; + }; + }); + + // Define a fallback version of the method in browsers (ahem, IE), where + // there isn't any inspectable "Arguments" type. + if (!_.isArguments(arguments)) { + _.isArguments = function(obj) { + return !!(obj && _.has(obj, 'callee')); + }; + } + + // Optimize `isFunction` if appropriate. + if (typeof (/./) !== 'function') { + _.isFunction = function(obj) { + return typeof obj === 'function'; + }; + } + + // Is a given object a finite number? + _.isFinite = function(obj) { + return isFinite(obj) && !isNaN(parseFloat(obj)); + }; + + // Is the given value `NaN`? (NaN is the only number which does not equal itself). + _.isNaN = function(obj) { + return _.isNumber(obj) && obj != +obj; + }; + + // Is a given value a boolean? + _.isBoolean = function(obj) { + return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; + }; + + // Is a given value equal to null? + _.isNull = function(obj) { + return obj === null; + }; + + // Is a given variable undefined? + _.isUndefined = function(obj) { + return obj === void 0; + }; + + // Shortcut function for checking if an object has a given property directly + // on itself (in other words, not on a prototype). + _.has = function(obj, key) { + return hasOwnProperty.call(obj, key); + }; + + // Utility Functions + // ----------------- + + // Run Underscore.js in *noConflict* mode, returning the `_` variable to its + // previous owner. Returns a reference to the Underscore object. + _.noConflict = function() { + root._ = previousUnderscore; + return this; + }; + + // Keep the identity function around for default iterators. + _.identity = function(value) { + return value; + }; + + // Run a function **n** times. + _.times = function(n, iterator, context) { + var accum = Array(n); + for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); + return accum; + }; + + // Return a random integer between min and max (inclusive). + _.random = function(min, max) { + if (max == null) { + max = min; + min = 0; + } + return min + Math.floor(Math.random() * (max - min + 1)); + }; + + // List of HTML entities for escaping. + var entityMap = { + escape: { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '/': '/' + } + }; + entityMap.unescape = _.invert(entityMap.escape); + + // Regexes containing the keys and values listed immediately above. + var entityRegexes = { + escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), + unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') + }; + + // Functions for escaping and unescaping strings to/from HTML interpolation. + _.each(['escape', 'unescape'], function(method) { + _[method] = function(string) { + if (string == null) return ''; + return ('' + string).replace(entityRegexes[method], function(match) { + return entityMap[method][match]; + }); + }; + }); + + // If the value of the named property is a function then invoke it; + // otherwise, return it. + _.result = function(object, property) { + if (object == null) return null; + var value = object[property]; + return _.isFunction(value) ? value.call(object) : value; + }; + + // Add your own custom functions to the Underscore object. + _.mixin = function(obj) { + each(_.functions(obj), function(name){ + var func = _[name] = obj[name]; + _.prototype[name] = function() { + var args = [this._wrapped]; + push.apply(args, arguments); + return result.call(this, func.apply(_, args)); + }; + }); + }; + + // Generate a unique integer id (unique within the entire client session). + // Useful for temporary DOM ids. + var idCounter = 0; + _.uniqueId = function(prefix) { + var id = ++idCounter + ''; + return prefix ? prefix + id : id; + }; + + // By default, Underscore uses ERB-style template delimiters, change the + // following template settings to use alternative delimiters. + _.templateSettings = { + evaluate : /<%([\s\S]+?)%>/g, + interpolate : /<%=([\s\S]+?)%>/g, + escape : /<%-([\s\S]+?)%>/g + }; + + // When customizing `templateSettings`, if you don't want to define an + // interpolation, evaluation or escaping regex, we need one that is + // guaranteed not to match. + var noMatch = /(.)^/; + + // Certain characters need to be escaped so that they can be put into a + // string literal. + var escapes = { + "'": "'", + '\\': '\\', + '\r': 'r', + '\n': 'n', + '\t': 't', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; + + // JavaScript micro-templating, similar to John Resig's implementation. + // Underscore templating handles arbitrary delimiters, preserves whitespace, + // and correctly escapes quotes within interpolated code. + _.template = function(text, data, settings) { + var render; + settings = _.defaults({}, settings, _.templateSettings); + + // Combine delimiters into one regular expression via alternation. + var matcher = new RegExp([ + (settings.escape || noMatch).source, + (settings.interpolate || noMatch).source, + (settings.evaluate || noMatch).source + ].join('|') + '|$', 'g'); + + // Compile the template source, escaping string literals appropriately. + var index = 0; + var source = "__p+='"; + text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { + source += text.slice(index, offset) + .replace(escaper, function(match) { return '\\' + escapes[match]; }); + + if (escape) { + source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; + } + if (interpolate) { + source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; + } + if (evaluate) { + source += "';\n" + evaluate + "\n__p+='"; + } + index = offset + match.length; + return match; + }); + source += "';\n"; + + // If a variable is not specified, place data values in local scope. + if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; + + source = "var __t,__p='',__j=Array.prototype.join," + + "print=function(){__p+=__j.call(arguments,'');};\n" + + source + "return __p;\n"; + + try { + render = new Function(settings.variable || 'obj', '_', source); + } catch (e) { + e.source = source; + throw e; + } + + if (data) return render(data, _); + var template = function(data) { + return render.call(this, data, _); + }; + + // Provide the compiled function source as a convenience for precompilation. + template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; + + return template; + }; + + // Add a "chain" function, which will delegate to the wrapper. + _.chain = function(obj) { + return _(obj).chain(); + }; + + // OOP + // --------------- + // If Underscore is called as a function, it returns a wrapped object that + // can be used OO-style. This wrapper holds altered versions of all the + // underscore functions. Wrapped objects may be chained. + + // Helper function to continue chaining intermediate results. + var result = function(obj) { + return this._chain ? _(obj).chain() : obj; + }; + + // Add all of the Underscore functions to the wrapper object. + _.mixin(_); + + // Add all mutator Array functions to the wrapper. + each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + var obj = this._wrapped; + method.apply(obj, arguments); + if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; + return result.call(this, obj); + }; + }); + + // Add all accessor Array functions to the wrapper. + each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + return result.call(this, method.apply(this._wrapped, arguments)); + }; + }); + + _.extend(_.prototype, { + + // Start chaining a wrapped Underscore object. + chain: function() { + this._chain = true; + return this; + }, + + // Extracts the result from a wrapped and chained object. + value: function() { + return this._wrapped; + } + + }); + +}).call(this); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/.npmignore b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/.npmignore similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/.npmignore rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/.npmignore diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/.travis.yml b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/.travis.yml similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/.travis.yml rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/.travis.yml diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/LICENSE new file mode 100644 index 000000000..432d1aeb0 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/LICENSE @@ -0,0 +1,21 @@ +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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/examples/pow.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/examples/pow.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/examples/pow.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/examples/pow.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/index.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/index.js new file mode 100644 index 000000000..fda6de8a2 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/index.js @@ -0,0 +1,82 @@ +var path = require('path'); +var fs = require('fs'); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, mode, f, made) { + if (typeof mode === 'function' || mode === undefined) { + f = mode; + mode = 0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + if (typeof mode === 'string') mode = parseInt(mode, 8); + p = path.resolve(p); + + fs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), mode, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, mode, 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: + fs.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, mode, made) { + if (mode === undefined) { + mode = 0777 & (~process.umask()); + } + if (!made) made = null; + + if (typeof mode === 'string') mode = parseInt(mode, 8); + p = path.resolve(p); + + try { + fs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), mode, made); + sync(p, mode, 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 = fs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/package.json new file mode 100644 index 000000000..549e2c203 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/package.json @@ -0,0 +1,30 @@ +{ + "name": "mkdirp", + "description": "Recursively mkdir, like `mkdir -p`", + "version": "0.3.5", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "main": "./index", + "keywords": [ + "mkdir", + "directory" + ], + "repository": { + "type": "git", + "url": "http://github.com/substack/node-mkdirp.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "devDependencies": { + "tap": "~0.4.0" + }, + "license": "MIT", + "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, mode, cb)\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\n`cb(err, made)` fires with the error or the first directory `made`\nthat had to be created, if any.\n\n## mkdirp.sync(dir, mode)\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\nReturns the first directory that had to be created, if any.\n\n# install\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install mkdirp\n```\n\n# license\n\nMIT\n", + "readmeFilename": "readme.markdown", + "_id": "mkdirp@0.3.5", + "_from": "mkdirp@~0.3.4" +} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/readme.markdown b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/readme.markdown similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/readme.markdown rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/readme.markdown diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/chmod.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/chmod.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/chmod.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/chmod.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/clobber.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/clobber.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/clobber.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/clobber.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/mkdirp.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/mkdirp.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/mkdirp.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/mkdirp.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/perm.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/perm.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/perm.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/perm.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/perm_sync.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/perm_sync.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/perm_sync.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/perm_sync.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/race.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/race.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/race.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/race.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/rel.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/rel.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/rel.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/rel.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/return.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/return.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/return.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/return.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/return_sync.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/return_sync.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/return_sync.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/return_sync.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/root.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/root.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/root.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/root.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/sync.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/sync.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/sync.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/sync.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/umask.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/umask.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/umask.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/umask.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/umask_sync.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/umask_sync.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/test/umask_sync.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/mkdirp/test/umask_sync.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/.npmignore b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/.npmignore similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/.npmignore rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/.npmignore diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/LICENSE diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/README.md rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/README.md diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/bin/nopt.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/bin/nopt.js new file mode 100755 index 000000000..df90c729a --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/bin/nopt.js @@ -0,0 +1,44 @@ +#!/usr/bin/env node +var nopt = require("../lib/nopt") + , types = { num: Number + , bool: Boolean + , help: Boolean + , list: Array + , "num-list": [Number, Array] + , "str-list": [String, Array] + , "bool-list": [Boolean, Array] + , str: String } + , shorthands = { s: [ "--str", "astring" ] + , b: [ "--bool" ] + , nb: [ "--no-bool" ] + , tft: [ "--bool-list", "--no-bool-list", "--bool-list", "true" ] + , "?": ["--help"] + , h: ["--help"] + , H: ["--help"] + , n: [ "--num", "125" ] } + , parsed = nopt( types + , shorthands + , process.argv + , 2 ) + +console.log("parsed", parsed) + +if (parsed.help) { + console.log("") + console.log("nopt cli tester") + console.log("") + console.log("types") + console.log(Object.keys(types).map(function M (t) { + var type = types[t] + if (Array.isArray(type)) { + return [t, type.map(function (type) { return type.name })] + } + return [t, type && type.name] + }).reduce(function (s, i) { + s[i[0]] = i[1] + return s + }, {})) + console.log("") + console.log("shorthands") + console.log(shorthands) +} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/examples/my-program.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/examples/my-program.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/examples/my-program.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/examples/my-program.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/lib/nopt.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/lib/nopt.js new file mode 100644 index 000000000..5763860ad --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/lib/nopt.js @@ -0,0 +1,555 @@ +// info about each config option. + +var debug = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG + ? function () { console.error.apply(console, arguments) } + : function () {} + +var url = require("url") + , path = require("path") + , Stream = require("stream").Stream + , abbrev = require("abbrev") + +module.exports = exports = nopt +exports.clean = clean + +exports.typeDefs = + { String : { type: String, validate: validateString } + , Boolean : { type: Boolean, validate: validateBoolean } + , url : { type: url, validate: validateUrl } + , Number : { type: Number, validate: validateNumber } + , path : { type: path, validate: validatePath } + , Stream : { type: Stream, validate: validateStream } + , Date : { type: Date, validate: validateDate } + } + +function nopt (types, shorthands, args, slice) { + args = args || process.argv + types = types || {} + shorthands = shorthands || {} + if (typeof slice !== "number") slice = 2 + + debug(types, shorthands, args, slice) + + args = args.slice(slice) + var data = {} + , key + , remain = [] + , cooked = args + , original = args.slice(0) + + parse(args, data, remain, types, shorthands) + // now data is full + clean(data, types, exports.typeDefs) + data.argv = {remain:remain,cooked:cooked,original:original} + Object.defineProperty(data.argv, 'toString', { value: function () { + return this.original.map(JSON.stringify).join(" ") + }, enumerable: false }) + return data +} + +function clean (data, types, typeDefs) { + typeDefs = typeDefs || exports.typeDefs + var remove = {} + , typeDefault = [false, true, null, String, Number] + + Object.keys(data).forEach(function (k) { + if (k === "argv") return + var val = data[k] + , isArray = Array.isArray(val) + , type = types[k] + if (!isArray) val = [val] + if (!type) type = typeDefault + if (type === Array) type = typeDefault.concat(Array) + if (!Array.isArray(type)) type = [type] + + debug("val=%j", val) + debug("types=", type) + val = val.map(function (val) { + // if it's an unknown value, then parse false/true/null/numbers/dates + if (typeof val === "string") { + debug("string %j", val) + val = val.trim() + if ((val === "null" && ~type.indexOf(null)) + || (val === "true" && + (~type.indexOf(true) || ~type.indexOf(Boolean))) + || (val === "false" && + (~type.indexOf(false) || ~type.indexOf(Boolean)))) { + val = JSON.parse(val) + debug("jsonable %j", val) + } else if (~type.indexOf(Number) && !isNaN(val)) { + debug("convert to number", val) + val = +val + } else if (~type.indexOf(Date) && !isNaN(Date.parse(val))) { + debug("convert to date", val) + val = new Date(val) + } + } + + if (!types.hasOwnProperty(k)) { + return val + } + + // allow `--no-blah` to set 'blah' to null if null is allowed + if (val === false && ~type.indexOf(null) && + !(~type.indexOf(false) || ~type.indexOf(Boolean))) { + val = null + } + + var d = {} + d[k] = val + debug("prevalidated val", d, val, types[k]) + if (!validate(d, k, val, types[k], typeDefs)) { + if (exports.invalidHandler) { + exports.invalidHandler(k, val, types[k], data) + } else if (exports.invalidHandler !== false) { + debug("invalid: "+k+"="+val, types[k]) + } + return remove + } + debug("validated val", d, val, types[k]) + return d[k] + }).filter(function (val) { return val !== remove }) + + if (!val.length) delete data[k] + else if (isArray) { + debug(isArray, data[k], val) + data[k] = val + } else data[k] = val[0] + + debug("k=%s val=%j", k, val, data[k]) + }) +} + +function validateString (data, k, val) { + data[k] = String(val) +} + +function validatePath (data, k, val) { + data[k] = path.resolve(String(val)) + return true +} + +function validateNumber (data, k, val) { + debug("validate Number %j %j %j", k, val, isNaN(val)) + if (isNaN(val)) return false + data[k] = +val +} + +function validateDate (data, k, val) { + debug("validate Date %j %j %j", k, val, Date.parse(val)) + var s = Date.parse(val) + if (isNaN(s)) return false + data[k] = new Date(val) +} + +function validateBoolean (data, k, val) { + if (val instanceof Boolean) val = val.valueOf() + else if (typeof val === "string") { + if (!isNaN(val)) val = !!(+val) + else if (val === "null" || val === "false") val = false + else val = true + } else val = !!val + data[k] = val +} + +function validateUrl (data, k, val) { + val = url.parse(String(val)) + if (!val.host) return false + data[k] = val.href +} + +function validateStream (data, k, val) { + if (!(val instanceof Stream)) return false + data[k] = val +} + +function validate (data, k, val, type, typeDefs) { + // arrays are lists of types. + if (Array.isArray(type)) { + for (var i = 0, l = type.length; i < l; i ++) { + if (type[i] === Array) continue + if (validate(data, k, val, type[i], typeDefs)) return true + } + delete data[k] + return false + } + + // an array of anything? + if (type === Array) return true + + // NaN is poisonous. Means that something is not allowed. + if (type !== type) { + debug("Poison NaN", k, val, type) + delete data[k] + return false + } + + // explicit list of values + if (val === type) { + debug("Explicitly allowed %j", val) + // if (isArray) (data[k] = data[k] || []).push(val) + // else data[k] = val + data[k] = val + return true + } + + // now go through the list of typeDefs, validate against each one. + var ok = false + , types = Object.keys(typeDefs) + for (var i = 0, l = types.length; i < l; i ++) { + debug("test type %j %j %j", k, val, types[i]) + var t = typeDefs[types[i]] + if (t && type === t.type) { + var d = {} + ok = false !== t.validate(d, k, val) + val = d[k] + if (ok) { + // if (isArray) (data[k] = data[k] || []).push(val) + // else data[k] = val + data[k] = val + break + } + } + } + debug("OK? %j (%j %j %j)", ok, k, val, types[i]) + + if (!ok) delete data[k] + return ok +} + +function parse (args, data, remain, types, shorthands) { + debug("parse", args, data, remain) + + var key = null + , abbrevs = abbrev(Object.keys(types)) + , shortAbbr = abbrev(Object.keys(shorthands)) + + for (var i = 0; i < args.length; i ++) { + var arg = args[i] + debug("arg", arg) + + if (arg.match(/^-{2,}$/)) { + // done with keys. + // the rest are args. + remain.push.apply(remain, args.slice(i + 1)) + args[i] = "--" + break + } + var hadEq = false + if (arg.charAt(0) === "-") { + if (arg.indexOf("=") !== -1) { + hadEq = true + var v = arg.split("=") + arg = v.shift() + v = v.join("=") + args.splice.apply(args, [i, 1].concat([arg, v])) + } + // see if it's a shorthand + // if so, splice and back up to re-parse it. + var shRes = resolveShort(arg, shorthands, shortAbbr, abbrevs) + debug("arg=%j shRes=%j", arg, shRes) + if (shRes) { + debug(arg, shRes) + args.splice.apply(args, [i, 1].concat(shRes)) + if (arg !== shRes[0]) { + i -- + continue + } + } + arg = arg.replace(/^-+/, "") + var no = null + while (arg.toLowerCase().indexOf("no-") === 0) { + no = !no + arg = arg.substr(3) + } + + if (abbrevs[arg]) arg = abbrevs[arg] + + var isArray = types[arg] === Array || + Array.isArray(types[arg]) && types[arg].indexOf(Array) !== -1 + + var val + , la = args[i + 1] + + var isBool = typeof no === 'boolean' || + types[arg] === Boolean || + Array.isArray(types[arg]) && types[arg].indexOf(Boolean) !== -1 || + (typeof types[arg] === 'undefined' && !hadEq) || + (la === "false" && + (types[arg] === null || + Array.isArray(types[arg]) && ~types[arg].indexOf(null))) + + if (isBool) { + // just set and move along + val = !no + // however, also support --bool true or --bool false + if (la === "true" || la === "false") { + val = JSON.parse(la) + la = null + if (no) val = !val + i ++ + } + + // also support "foo":[Boolean, "bar"] and "--foo bar" + if (Array.isArray(types[arg]) && la) { + if (~types[arg].indexOf(la)) { + // an explicit type + val = la + i ++ + } else if ( la === "null" && ~types[arg].indexOf(null) ) { + // null allowed + val = null + i ++ + } else if ( !la.match(/^-{2,}[^-]/) && + !isNaN(la) && + ~types[arg].indexOf(Number) ) { + // number + val = +la + i ++ + } else if ( !la.match(/^-[^-]/) && ~types[arg].indexOf(String) ) { + // string + val = la + i ++ + } + } + + if (isArray) (data[arg] = data[arg] || []).push(val) + else data[arg] = val + + continue + } + + if (la && la.match(/^-{2,}$/)) { + la = undefined + i -- + } + + val = la === undefined ? true : la + if (isArray) (data[arg] = data[arg] || []).push(val) + else data[arg] = val + + i ++ + continue + } + remain.push(arg) + } +} + +function resolveShort (arg, shorthands, shortAbbr, abbrevs) { + // handle single-char shorthands glommed together, like + // npm ls -glp, but only if there is one dash, and only if + // all of the chars are single-char shorthands, and it's + // not a match to some other abbrev. + arg = arg.replace(/^-+/, '') + if (abbrevs[arg] && !shorthands[arg]) { + return null + } + if (shortAbbr[arg]) { + arg = shortAbbr[arg] + } else { + var singles = shorthands.___singles + if (!singles) { + singles = Object.keys(shorthands).filter(function (s) { + return s.length === 1 + }).reduce(function (l,r) { l[r] = true ; return l }, {}) + shorthands.___singles = singles + } + var chrs = arg.split("").filter(function (c) { + return singles[c] + }) + if (chrs.join("") === arg) return chrs.map(function (c) { + return shorthands[c] + }).reduce(function (l, r) { + return l.concat(r) + }, []) + } + + if (shorthands[arg] && !Array.isArray(shorthands[arg])) { + shorthands[arg] = shorthands[arg].split(/\s+/) + } + return shorthands[arg] +} + +if (module === require.main) { +var assert = require("assert") + , util = require("util") + + , shorthands = + { s : ["--loglevel", "silent"] + , d : ["--loglevel", "info"] + , dd : ["--loglevel", "verbose"] + , ddd : ["--loglevel", "silly"] + , noreg : ["--no-registry"] + , reg : ["--registry"] + , "no-reg" : ["--no-registry"] + , silent : ["--loglevel", "silent"] + , verbose : ["--loglevel", "verbose"] + , h : ["--usage"] + , H : ["--usage"] + , "?" : ["--usage"] + , help : ["--usage"] + , v : ["--version"] + , f : ["--force"] + , desc : ["--description"] + , "no-desc" : ["--no-description"] + , "local" : ["--no-global"] + , l : ["--long"] + , p : ["--parseable"] + , porcelain : ["--parseable"] + , g : ["--global"] + } + + , types = + { aoa: Array + , nullstream: [null, Stream] + , date: Date + , str: String + , browser : String + , cache : path + , color : ["always", Boolean] + , depth : Number + , description : Boolean + , dev : Boolean + , editor : path + , force : Boolean + , global : Boolean + , globalconfig : path + , group : [String, Number] + , gzipbin : String + , logfd : [Number, Stream] + , loglevel : ["silent","win","error","warn","info","verbose","silly"] + , long : Boolean + , "node-version" : [false, String] + , npaturl : url + , npat : Boolean + , "onload-script" : [false, String] + , outfd : [Number, Stream] + , parseable : Boolean + , pre: Boolean + , prefix: path + , proxy : url + , "rebuild-bundle" : Boolean + , registry : url + , searchopts : String + , searchexclude: [null, String] + , shell : path + , t: [Array, String] + , tag : String + , tar : String + , tmp : path + , "unsafe-perm" : Boolean + , usage : Boolean + , user : String + , username : String + , userconfig : path + , version : Boolean + , viewer: path + , _exit : Boolean + } + +; [["-v", {version:true}, []] + ,["---v", {version:true}, []] + ,["ls -s --no-reg connect -d", + {loglevel:"info",registry:null},["ls","connect"]] + ,["ls ---s foo",{loglevel:"silent"},["ls","foo"]] + ,["ls --registry blargle", {}, ["ls"]] + ,["--no-registry", {registry:null}, []] + ,["--no-color true", {color:false}, []] + ,["--no-color false", {color:true}, []] + ,["--no-color", {color:false}, []] + ,["--color false", {color:false}, []] + ,["--color --logfd 7", {logfd:7,color:true}, []] + ,["--color=true", {color:true}, []] + ,["--logfd=10", {logfd:10}, []] + ,["--tmp=/tmp -tar=gtar",{tmp:"/tmp",tar:"gtar"},[]] + ,["--tmp=tmp -tar=gtar", + {tmp:path.resolve(process.cwd(), "tmp"),tar:"gtar"},[]] + ,["--logfd x", {}, []] + ,["a -true -- -no-false", {true:true},["a","-no-false"]] + ,["a -no-false", {false:false},["a"]] + ,["a -no-no-true", {true:true}, ["a"]] + ,["a -no-no-no-false", {false:false}, ["a"]] + ,["---NO-no-No-no-no-no-nO-no-no"+ + "-No-no-no-no-no-no-no-no-no"+ + "-no-no-no-no-NO-NO-no-no-no-no-no-no"+ + "-no-body-can-do-the-boogaloo-like-I-do" + ,{"body-can-do-the-boogaloo-like-I-do":false}, []] + ,["we are -no-strangers-to-love "+ + "--you-know=the-rules --and=so-do-i "+ + "---im-thinking-of=a-full-commitment "+ + "--no-you-would-get-this-from-any-other-guy "+ + "--no-gonna-give-you-up "+ + "-no-gonna-let-you-down=true "+ + "--no-no-gonna-run-around false "+ + "--desert-you=false "+ + "--make-you-cry false "+ + "--no-tell-a-lie "+ + "--no-no-and-hurt-you false" + ,{"strangers-to-love":false + ,"you-know":"the-rules" + ,"and":"so-do-i" + ,"you-would-get-this-from-any-other-guy":false + ,"gonna-give-you-up":false + ,"gonna-let-you-down":false + ,"gonna-run-around":false + ,"desert-you":false + ,"make-you-cry":false + ,"tell-a-lie":false + ,"and-hurt-you":false + },["we", "are"]] + ,["-t one -t two -t three" + ,{t: ["one", "two", "three"]} + ,[]] + ,["-t one -t null -t three four five null" + ,{t: ["one", "null", "three"]} + ,["four", "five", "null"]] + ,["-t foo" + ,{t:["foo"]} + ,[]] + ,["--no-t" + ,{t:["false"]} + ,[]] + ,["-no-no-t" + ,{t:["true"]} + ,[]] + ,["-aoa one -aoa null -aoa 100" + ,{aoa:["one", null, 100]} + ,[]] + ,["-str 100" + ,{str:"100"} + ,[]] + ,["--color always" + ,{color:"always"} + ,[]] + ,["--no-nullstream" + ,{nullstream:null} + ,[]] + ,["--nullstream false" + ,{nullstream:null} + ,[]] + ,["--notadate=2011-01-25" + ,{notadate: "2011-01-25"} + ,[]] + ,["--date 2011-01-25" + ,{date: new Date("2011-01-25")} + ,[]] + ].forEach(function (test) { + var argv = test[0].split(/\s+/) + , opts = test[1] + , rem = test[2] + , actual = nopt(types, shorthands, argv, 0) + , parsed = actual.argv + delete actual.argv + console.log(util.inspect(actual, false, 2, true), parsed.remain) + for (var i in opts) { + var e = JSON.stringify(opts[i]) + , a = JSON.stringify(actual[i] === undefined ? null : actual[i]) + if (e && typeof e === "object") { + assert.deepEqual(e, a) + } else { + assert.equal(e, a) + } + } + assert.deepEqual(rem, parsed.remain) + }) +} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/node_modules/abbrev/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/LICENSE rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/node_modules/abbrev/LICENSE diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/node_modules/abbrev/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/node_modules/abbrev/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/node_modules/abbrev/README.md rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/node_modules/abbrev/README.md diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/node_modules/abbrev/lib/abbrev.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/node_modules/abbrev/lib/abbrev.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/node_modules/abbrev/lib/abbrev.js rename to node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/node_modules/abbrev/lib/abbrev.js diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/node_modules/abbrev/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/node_modules/abbrev/package.json new file mode 100644 index 000000000..3056f1e21 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/node_modules/abbrev/package.json @@ -0,0 +1,25 @@ +{ + "name": "abbrev", + "version": "1.0.4", + "description": "Like ruby's abbrev module, but in js", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me" + }, + "main": "./lib/abbrev.js", + "scripts": { + "test": "node lib/abbrev.js" + }, + "repository": { + "type": "git", + "url": "http://github.com/isaacs/abbrev-js" + }, + "license": { + "type": "MIT", + "url": "https://github.com/isaacs/abbrev-js/raw/master/LICENSE" + }, + "readme": "# abbrev-js\n\nJust like [ruby's Abbrev](http://apidock.com/ruby/Abbrev).\n\nUsage:\n\n var abbrev = require(\"abbrev\");\n abbrev(\"foo\", \"fool\", \"folding\", \"flop\");\n \n // returns:\n { fl: 'flop'\n , flo: 'flop'\n , flop: 'flop'\n , fol: 'folding'\n , fold: 'folding'\n , foldi: 'folding'\n , foldin: 'folding'\n , folding: 'folding'\n , foo: 'foo'\n , fool: 'fool'\n }\n\nThis is handy for command-line scripts, or other cases where you want to be able to accept shorthands.\n", + "readmeFilename": "README.md", + "_id": "abbrev@1.0.4", + "_from": "abbrev@1" +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/package.json b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/package.json new file mode 100644 index 000000000..6ab61d5aa --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/nopt/package.json @@ -0,0 +1,32 @@ +{ + "name": "nopt", + "version": "2.0.0", + "description": "Option parsing for Node, supporting types, shorthands, etc. Used by npm.", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "main": "lib/nopt.js", + "scripts": { + "test": "node lib/nopt.js" + }, + "repository": { + "type": "git", + "url": "http://github.com/isaacs/nopt" + }, + "bin": { + "nopt": "./bin/nopt.js" + }, + "license": { + "type": "MIT", + "url": "https://github.com/isaacs/nopt/raw/master/LICENSE" + }, + "dependencies": { + "abbrev": "1" + }, + "readme": "If you want to write an option parser, and have it be good, there are\ntwo ways to do it. The Right Way, and the Wrong Way.\n\nThe Wrong Way is to sit down and write an option parser. We've all done\nthat.\n\nThe Right Way is to write some complex configurable program with so many\noptions that you go half-insane just trying to manage them all, and put\nit off with duct-tape solutions until you see exactly to the core of the\nproblem, and finally snap and write an awesome option parser.\n\nIf you want to write an option parser, don't write an option parser.\nWrite a package manager, or a source control system, or a service\nrestarter, or an operating system. You probably won't end up with a\ngood one of those, but if you don't give up, and you are relentless and\ndiligent enough in your procrastination, you may just end up with a very\nnice option parser.\n\n## USAGE\n\n // my-program.js\n var nopt = require(\"nopt\")\n , Stream = require(\"stream\").Stream\n , path = require(\"path\")\n , knownOpts = { \"foo\" : [String, null]\n , \"bar\" : [Stream, Number]\n , \"baz\" : path\n , \"bloo\" : [ \"big\", \"medium\", \"small\" ]\n , \"flag\" : Boolean\n , \"pick\" : Boolean\n , \"many\" : [String, Array]\n }\n , shortHands = { \"foofoo\" : [\"--foo\", \"Mr. Foo\"]\n , \"b7\" : [\"--bar\", \"7\"]\n , \"m\" : [\"--bloo\", \"medium\"]\n , \"p\" : [\"--pick\"]\n , \"f\" : [\"--flag\"]\n }\n // everything is optional.\n // knownOpts and shorthands default to {}\n // arg list defaults to process.argv\n // slice defaults to 2\n , parsed = nopt(knownOpts, shortHands, process.argv, 2)\n console.log(parsed)\n\nThis would give you support for any of the following:\n\n```bash\n$ node my-program.js --foo \"blerp\" --no-flag\n{ \"foo\" : \"blerp\", \"flag\" : false }\n\n$ node my-program.js ---bar 7 --foo \"Mr. Hand\" --flag\n{ bar: 7, foo: \"Mr. Hand\", flag: true }\n\n$ node my-program.js --foo \"blerp\" -f -----p\n{ foo: \"blerp\", flag: true, pick: true }\n\n$ node my-program.js -fp --foofoo\n{ foo: \"Mr. Foo\", flag: true, pick: true }\n\n$ node my-program.js --foofoo -- -fp # -- stops the flag parsing.\n{ foo: \"Mr. Foo\", argv: { remain: [\"-fp\"] } }\n\n$ node my-program.js --blatzk 1000 -fp # unknown opts are ok.\n{ blatzk: 1000, flag: true, pick: true }\n\n$ node my-program.js --blatzk true -fp # but they need a value\n{ blatzk: true, flag: true, pick: true }\n\n$ node my-program.js --no-blatzk -fp # unless they start with \"no-\"\n{ blatzk: false, flag: true, pick: true }\n\n$ node my-program.js --baz b/a/z # known paths are resolved.\n{ baz: \"/Users/isaacs/b/a/z\" }\n\n# if Array is one of the types, then it can take many\n# values, and will always be an array. The other types provided\n# specify what types are allowed in the list.\n\n$ node my-program.js --many 1 --many null --many foo\n{ many: [\"1\", \"null\", \"foo\"] }\n\n$ node my-program.js --many foo\n{ many: [\"foo\"] }\n```\n\nRead the tests at the bottom of `lib/nopt.js` for more examples of\nwhat this puppy can do.\n\n## Types\n\nThe following types are supported, and defined on `nopt.typeDefs`\n\n* String: A normal string. No parsing is done.\n* path: A file system path. Gets resolved against cwd if not absolute.\n* url: A url. If it doesn't parse, it isn't accepted.\n* Number: Must be numeric.\n* Date: Must parse as a date. If it does, and `Date` is one of the options,\n then it will return a Date object, not a string.\n* Boolean: Must be either `true` or `false`. If an option is a boolean,\n then it does not need a value, and its presence will imply `true` as\n the value. To negate boolean flags, do `--no-whatever` or `--whatever\n false`\n* NaN: Means that the option is strictly not allowed. Any value will\n fail.\n* Stream: An object matching the \"Stream\" class in node. Valuable\n for use when validating programmatically. (npm uses this to let you\n supply any WriteStream on the `outfd` and `logfd` config options.)\n* Array: If `Array` is specified as one of the types, then the value\n will be parsed as a list of options. This means that multiple values\n can be specified, and that the value will always be an array.\n\nIf a type is an array of values not on this list, then those are\nconsidered valid values. For instance, in the example above, the\n`--bloo` option can only be one of `\"big\"`, `\"medium\"`, or `\"small\"`,\nand any other value will be rejected.\n\nWhen parsing unknown fields, `\"true\"`, `\"false\"`, and `\"null\"` will be\ninterpreted as their JavaScript equivalents, and numeric values will be\ninterpreted as a number.\n\nYou can also mix types and values, or multiple types, in a list. For\ninstance `{ blah: [Number, null] }` would allow a value to be set to\neither a Number or null. When types are ordered, this implies a\npreference, and the first type that can be used to properly interpret\nthe value will be used.\n\nTo define a new type, add it to `nopt.typeDefs`. Each item in that\nhash is an object with a `type` member and a `validate` method. The\n`type` member is an object that matches what goes in the type list. The\n`validate` method is a function that gets called with `validate(data,\nkey, val)`. Validate methods should assign `data[key]` to the valid\nvalue of `val` if it can be handled properly, or return boolean\n`false` if it cannot.\n\nYou can also call `nopt.clean(data, types, typeDefs)` to clean up a\nconfig object and remove its invalid properties.\n\n## Error Handling\n\nBy default, nopt outputs a warning to standard error when invalid\noptions are found. You can change this behavior by assigning a method\nto `nopt.invalidHandler`. This method will be called with\nthe offending `nopt.invalidHandler(key, val, types)`.\n\nIf no `nopt.invalidHandler` is assigned, then it will console.error\nits whining. If it is assigned to boolean `false` then the warning is\nsuppressed.\n\n## Abbreviations\n\nYes, they are supported. If you define options like this:\n\n```javascript\n{ \"foolhardyelephants\" : Boolean\n, \"pileofmonkeys\" : Boolean }\n```\n\nThen this will work:\n\n```bash\nnode program.js --foolhar --pil\nnode program.js --no-f --pileofmon\n# etc.\n```\n\n## Shorthands\n\nShorthands are a hash of shorter option names to a snippet of args that\nthey expand to.\n\nIf multiple one-character shorthands are all combined, and the\ncombination does not unambiguously match any other option or shorthand,\nthen they will be broken up into their constituent parts. For example:\n\n```json\n{ \"s\" : [\"--loglevel\", \"silent\"]\n, \"g\" : \"--global\"\n, \"f\" : \"--force\"\n, \"p\" : \"--parseable\"\n, \"l\" : \"--long\"\n}\n```\n\n```bash\nnpm ls -sgflp\n# just like doing this:\nnpm ls --loglevel silent --global --force --long --parseable\n```\n\n## The Rest of the args\n\nThe config object returned by nopt is given a special member called\n`argv`, which is an object with the following fields:\n\n* `remain`: The remaining args after all the parsing has occurred.\n* `original`: The args as they originally appeared.\n* `cooked`: The args after flags and shorthands are expanded.\n\n## Slicing\n\nNode programs are called with more or less the exact argv as it appears\nin C land, after the v8 and node-specific options have been plucked off.\nAs such, `argv[0]` is always `node` and `argv[1]` is always the\nJavaScript program being run.\n\nThat's usually not very useful to you. So they're sliced off by\ndefault. If you want them, then you can pass in `0` as the last\nargument, or any other number that you'd like to slice off the start of\nthe list.\n", + "readmeFilename": "README.md", + "_id": "nopt@2.0.0", + "_from": "nopt@~2.0.0" +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/.jshintrc b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/.jshintrc new file mode 100644 index 000000000..97c9f795f --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/.jshintrc @@ -0,0 +1,63 @@ +{ + "predef": [ + "console", + "require", + "define", + "describe", + "it", + "before", + "beforEach", + "after", + "afterEach" + ], + + "node": true, + "devel": true, + + "bitwise": true, + "curly": true, + "eqeqeq": true, + "forin": false, + "immed": true, + "latedef": false, + "newcap": true, + "noarg": true, + "noempty": false, + "nonew": true, + "plusplus": false, + "regexp": true, + "undef": true, + "unused": true, + "quotmark": "single", + "strict": true, + "trailing": true, + + "asi": false, + "boss": false, + "debug": false, + "eqnull": true, + "es5": false, + "esnext": false, + "evil": false, + "expr": false, + "funcscope": false, + "globalstrict": false, + "iterator": false, + "lastsemic": false, + "laxbreak": false, + "laxcomma": false, + "loopfunc": true, + "multistr": false, + "onecase": true, + "regexdash": false, + "scripturl": false, + "smarttabs": false, + "shadow": false, + "sub": false, + "supernew": false, + "validthis": false, + + "nomen": false, + "onevar": false, + "white": true +} diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/.npmignore b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/.npmignore new file mode 100644 index 000000000..8514c5cf3 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/.npmignore @@ -0,0 +1,54 @@ +# Compiled source # +################### +*.com +*.class +*.dll +*.exe +*.o +*.so + +# OS generated files # +###################### +.DS_Store* +ehthumbs.db +Icon? +Thumbs.db +Desktop.ini +.Spotlight-V100 +.Trashes +._* + +# NetBeans # +############ +nbsettings/ +nbproject/ +nbbuild/ +nbdist/ +nbactions.xml +nb-configuration.xml + +# Textmate # +############ +*.tmproj +*.tmproject +tmtags + +# VIM # +####### +.*.sw[a-z] +*.un~ +Session.vim + +# Sublime TextEditor # +###################### +*.sublime-project + +# Eclipse # +###################### +/.project +/.settings + +# Node # +###################### +node_modules +npm-debug.* diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/.travis.yml b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/.travis.yml new file mode 100644 index 000000000..59811ddc3 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.7 + - 0.8 \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/LICENSE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/LICENSE new file mode 100644 index 000000000..92b561cd3 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2012 IndigoUnited + +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/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/README.md new file mode 100644 index 000000000..53c12ae24 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/README.md @@ -0,0 +1,158 @@ +# promptly # +--- + +[![Build Status](https://secure.travis-ci.org/IndigoUnited/node-promptly.png)](http://travis-ci.org/IndigoUnited/node-promptly.png) + +Simple command line prompting utility. + +## Installation ## + +`$ npm install promptly` + + +## API ## + + +Note that the `options` argument is optional for all the commands. + + +### .prompt(message, opts, fn) ### + +Prompts for a value, printing the `message` and waiting for the input. +When done, calls `fn` with `error` and `value`. + +Default options: +```js +{ + // The default value. If not supplied, the input is mandatory + 'default': null, + // Automatically trim the input + 'trim': true, + // A validator or an array of validators. + 'validator': null, + // Automatically retry if a validator fails + 'retry': true, + // Do not print what the user types + 'silent': false, + // Input and output streams to read and write to + 'input': process.stdin, + 'output': process.stdout +} +``` + +The validators have two purposes: +```js +function (value) { + // Validation example, throwing an error when invalid + if (value.length !== 2) { + throw new Error('Length must be 2'); + } + + // Parse the value, modifying it + return value.replace('aa', 'bb'); +} +``` + +Example usages + +Ask for a name: +```js +promptly.prompt('Name: ', function (err, value) { + // err is always null in this case, because no validators are set + console.log(value); +}); +``` + +Ask for a name with a constraint (non-empty value and length > 2): + +```js +var validator = function (value) { + if (value.length < 2) { + throw new Error('Min length of 2'); + } + + return value; +}; + +promptly.prompt('Name: ', { validator: validator }, function (err, value) { + // Since retry is true by default, err is always null + // because promptly will be prompting for a name until it validates + // Between each prompt, the error message from the validator will be printed + console.log('Name is:', value); +}); +``` + +Same as above but do not retry automatically: + +```js +var validator = function (value) { + if (value.length < 2) { + throw new Error('Min length of 2'); + } + + return value; +}; + +promptly.prompt('Name: ', { validator: validator, retry: false }, function (err, value) { + if (err) { + console.error('Invalid name:', e.message); + // Manually call retry + // The passed error has a retry method to easily prompt again. + return err.retry(); + } + + console.log('Name is:', value); +}); +``` + +### .confirm(message, opts, fn) ### + +Ask the user to confirm something. +Calls `fn` with `error` and `value` (true or false). + +Truthy values are: `y`, `yes` and `1`. +Falsy values are `n`, `no`, and `0`. +Comparison is made in a case insensitive way. + +Example usage: + +```js +promptly.confirm('Are you sure? ', function (err, value) { + console.log('Answer:', value); +}); +``` + + +### .choose(message, choices, opts, fn) ### + +Ask the user to choose between multiple `choices` (array of choices). +Calls `fn` with `error` and `value`. + +Example usage: + +```js +promptly.choose('Do you want an apple or an orange? ', ['apple', 'orange'], function (err, value) { + console.log('Answer:', value); +}); +``` + + +### .password(message, opts, fn) ### + +Prompts for a password, printing the `message` and waiting for the input. +When available, calls `fn` with `error` and `value`. + +The available options are the same, except that `trim` and `silent` default to `false` and `default` is an empty string (to allow empty passwords). + +Example usage: + +```js +promptly.password('Type a password: ', function (err, value) { + console.log('Password is:', value); +}); +``` + + +## License ## + +Released under the [MIT License](http://www.opensource.org/licenses/mit-license.php). diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/index.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/index.js new file mode 100644 index 000000000..5a6982f44 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/index.js @@ -0,0 +1,175 @@ +'use strict'; + +var read = require('read'); +var promptly = module.exports; + +promptly.prompt = function (message, opts, fn) { + // Arguments parsing + if (typeof opts === 'function') { + fn = opts; + opts = {}; + } else { + opts = opts || {}; + } + + if (opts.trim === undefined) { + opts.trim = true; + } + if (opts.retry === undefined) { + opts.retry = true; + } + + // Setup read's options + var readOpts = { + prompt: message, + input: opts.input || process.stdin, + output: opts.output || process.stdout, + silent: opts.silent + }; + + // Use readline question + read(readOpts, function (err, data) { + // Ignore the error attribute + // It is set on SIGINT or if timeout reached (we are not using timeout) + if (err) { + return; + } + + // Trim? + if (opts.trim) { + data = data.trim(); + } + + // Mandatory? + if (opts['default'] == null && !data) { + return promptly.prompt(message, opts, fn); + } else { + data = data || opts['default']; + } + + // Validator verification + if (opts.validator) { + if (!Array.isArray(opts.validator)) { + opts.validator = [opts.validator]; + } + + var x; + var length = opts.validator.length; + + for (x = 0; x < length; x += 1) { + try { + data = opts.validator[x](data); + } catch (e) { + // Retry automatically if the retry option is enabled + if (opts.retry) { + if (e.message) { + readOpts.output.write(e.message + '\n'); + } + + return promptly.prompt(message, opts, fn); + } + + e.retry = promptly.prompt.bind(promptly, message, opts, fn); + + return fn(e); + } + } + } + + // Everything ok + fn(null, data); + }); +}; + +promptly.password = function (message, opts, fn) { + // Arguments parsing + if (typeof opts === 'function') { + fn = opts; + opts = {}; + } else { + opts = opts || {}; + } + + // Set default options + if (opts.silent === undefined) { + opts.silent = true; + } + if (opts.trim === undefined) { + opts.trim = false; + } + if (opts['default'] === undefined) { + opts['default'] = ''; + } + + // Use prompt() + promptly.prompt(message, opts, fn); +}; + +promptly.confirm = function (message, opts, fn) { + // Arguments parsing + if (typeof opts === 'function') { + fn = opts; + opts = {}; + } else { + opts = opts || {}; + } + + opts.validator = opts.validator || []; + if (!Array.isArray(opts.validator)) { + opts.validator = [opts.validator]; + } + + // Push the validator that will coerse boolean values + var validator = function (value) { + if (typeof value === 'string') { + value = value.toLowerCase(); + } + + switch (value) { + case 'y': + case 'yes': + case '1': + case true: + return true; + case 'n': + case 'no': + case '0': + case false: + return false; + } + + throw new Error(); + }; + opts.validator.push(validator); + + // Use choose() with true, false + promptly.choose(message, [true, false], opts, fn); +}; + +promptly.choose = function (message, choices, opts, fn) { + // Arguments parsing + if (typeof opts === 'function') { + fn = opts; + opts = {}; + } else { + opts = opts || {}; + } + + opts.validator = opts.validator || []; + if (!Array.isArray(opts.validator)) { + opts.validator = [opts.validator]; + } + + // Push the choice validator + var validator = function (value) { + if (choices.indexOf(value) === -1) { + throw new Error('Invalid choice: ' + value); + } + + return value; + }; + opts.validator.push(validator); + + // Use prompt() + promptly.prompt(message, opts, fn); +}; \ No newline at end of file diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/.npmignore b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/.npmignore new file mode 100644 index 000000000..0db216bfa --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/.npmignore @@ -0,0 +1,2 @@ +npm-debug.log +node_modules diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/LICENCE b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/LICENCE new file mode 100644 index 000000000..74489e2e2 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/LICENCE @@ -0,0 +1,25 @@ +Copyright (c) Isaac Z. Schlueter +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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/README.md b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/README.md new file mode 100644 index 000000000..2edefdf47 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/README.md @@ -0,0 +1,53 @@ +## read + +For reading user input from stdin. + +Similar to the `readline` builtin's `question()` method, but with a +few more features. + +## USAGE + +```javascript +var read = require("read") +read(options, callback) +``` + +The callback gets called with either the user input, or the default +specified, or an error, as `callback(error, result, isDefault)` +node style. + +## OPTIONS + +Every option is optional. + +* `prompt` What to write to stdout before reading input. +* `silent` Don't echo the output as the user types it. +* `replace` Replace silenced characters with the supplied character value. +* `timeout` Number of ms to wait for user input before giving up. +* `default` The default value if the user enters nothing. +* `edit` Allow the user to edit the default value. +* `terminal` Treat the output as a TTY, whether it is or not. +* `stdin` Readable stream to get input data from. (default `process.stdin`) +* `stdout` Writeable stream to write prompts to. (default: `process.stdout`) + +If silent is true, and the input is a TTY, then read will set raw +mode, and read character by character. + +## COMPATIBILITY + +This module works sort of with node 0.6. It does not work with node +versions less than 0.6. It is best on node 0.8. + +On node version 0.6, it will remove all listeners on the input +stream's `data` and `keypress` events, because the readline module did +not fully clean up after itself in that version of node, and did not +make it possible to clean up after it in a way that has no potential +for side effects. + +Additionally, some of the readline options (like `terminal`) will not +function in versions of node before 0.8, because they were not +implemented in the builtin readline module. + +## CONTRIBUTING + +Patches welcome. diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/example/example.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/example/example.js new file mode 100644 index 000000000..cf213bf88 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/example/example.js @@ -0,0 +1,13 @@ +var read = require("../lib/read.js") + +read({prompt: "Username: ", default: "test-user" }, function (er, user) { + read({prompt: "Password: ", default: "test-pass", silent: true }, function (er, pass) { + read({prompt: "Password again: ", default: "test-pass", silent: true }, function (er, pass2) { + console.error({user: user, + pass: pass, + verify: pass2, + passMatch: (pass === pass2)}) + console.error("the program should exit now") + }) + }) +}) diff --git a/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/lib/read.js b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/lib/read.js new file mode 100644 index 000000000..4b8a422d9 --- /dev/null +++ b/node/node_modules/grunt-bower-task/node_modules/bower/node_modules/promptly/node_modules/read/lib/read.js @@ -0,0 +1,112 @@ + +module.exports = read + +var readline = require('readline') +var Mute = require('mute-stream') + +function read (opts, cb) { + if (opts.num) { + throw new Error('read() no longer accepts a char number limit') + } + + if (typeof opts.default !== 'undefined' && + typeof opts.default !== 'string' && + typeof opts.default !== 'number') { + throw new Error('default value must be string or number') + } + + var input = opts.input || process.stdin + var output = opts.output || process.stdout + var m = new Mute({ replace: opts.replace }) + m.pipe(output, {end: false}) + output = m + var def = opts.default || '' + var terminal = !!(opts.terminal || output.isTTY) + var rlOpts = { input: input, output: output, terminal: terminal } + + if (process.version.match(/^v0\.6/)) { + var rl = readline.createInterface(rlOpts.input, rlOpts.output) + } else { + var rl = readline.createInterface(rlOpts) + } + + var prompt = (opts.prompt || '').trim() + ' ' + var silent = opts.silent + var editDef = false + var timeout = opts.timeout + + if (def) { + if (silent) { + prompt += '(
      + + diff --git a/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/coverage.header.html b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/coverage.header.html new file mode 100644 index 000000000..0885679aa --- /dev/null +++ b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/coverage.header.html @@ -0,0 +1,37 @@ + + + + +Esprima: Coverage Analysis Report + + + + +
      + + + +

      Coverage Analysis ensures systematic exercise of the parser

      + +

      Note: This is not a live (in-browser) code coverage report. +The analysis is performed offline +(using node-cover).
      + diff --git a/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/coverage.html b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/coverage.html new file mode 100644 index 000000000..696c682a8 --- /dev/null +++ b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/coverage.html @@ -0,0 +1,4676 @@ + + + + +Esprima: Coverage Analysis Report + + + + +

      + + + +

      Coverage Analysis ensures systematic exercise of the parser

      + +

      Note: This is not a live (in-browser) code coverage report. +The analysis is performed offline +(using node-cover).
      + +Tested revision: b61b064 + (dated 4 Aug 2012 ).

      +
      +/*
      +    Copyright (C) 2012 Ariya Hidayat 
      +    Copyright (C) 2012 Mathias Bynens 
      +    Copyright (C) 2012 Joost-Wim Boekesteijn 
      +    Copyright (C) 2012 Kris Kowal 
      +    Copyright (C) 2012 Yusuke Suzuki 
      +    Copyright (C) 2012 Arpad Borsos 
      +    Copyright (C) 2011 Ariya Hidayat 
      +  
      +    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.
      +  
      +    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  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.
      +  */
      +  
      +  /*jslint bitwise:true plusplus:true */
      +  /*global esprima:true, define:true, exports:true, window: true,
      +  throwError: true, createLiteral: true, generateStatement: true,
      +  parseAssignmentExpression: true, parseBlock: true,
      +  parseClassExpression: true, parseClassDeclaration: true, parseExpression: true,
      +  parseFunctionDeclaration: true, parseFunctionExpression: true,
      +  parseFunctionSourceElements: true, parseVariableIdentifier: true,
      +  parseImportSpecifier: true,
      +  parseLeftHandSideExpression: true,
      +  parseStatement: true, parseSourceElement: true, parseModuleBlock: true, parseConciseBody: true,
      +  parseYieldExpression: true
      +  */
      +  
      +  (function (factory) {
      +      'use strict';
      +  
      +      // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
      +      // and plain browser loading,
      +      if (typeof define === 'function' && define.amd) {
      +          define(['exports'], factory);
      +      } else if (typeof exports !== 'undefined') {
      +          factory(exports);
      +      } else {
      +          factory((window.esprima = {}));
      +      }
      +  }(function (exports) {
      +      'use strict';
      +  
      +      var Token,
      +          TokenName,
      +          Syntax,
      +          PropertyKind,
      +          Messages,
      +          Regex,
      +          source,
      +          strict,
      +          yieldAllowed,
      +          yieldFound,
      +          index,
      +          lineNumber,
      +          lineStart,
      +          length,
      +          buffer,
      +          state,
      +          extra;
      +  
      +      Token = {
      +          BooleanLiteral: 1,
      +          EOF: 2,
      +          Identifier: 3,
      +          Keyword: 4,
      +          NullLiteral: 5,
      +          NumericLiteral: 6,
      +          Punctuator: 7,
      +          StringLiteral: 8
      +      };
      +  
      +      TokenName = {};
      +      TokenName[Token.BooleanLiteral] = 'Boolean';
      +      TokenName[Token.EOF] = '';
      +      TokenName[Token.Identifier] = 'Identifier';
      +      TokenName[Token.Keyword] = 'Keyword';
      +      TokenName[Token.NullLiteral] = 'Null';
      +      TokenName[Token.NumericLiteral] = 'Numeric';
      +      TokenName[Token.Punctuator] = 'Punctuator';
      +      TokenName[Token.StringLiteral] = 'String';
      +  
      +      Syntax = {
      +          ArrayExpression: 'ArrayExpression',
      +          ArrayPattern: 'ArrayPattern',
      +          ArrowFunctionExpression: 'ArrowFunctionExpression',
      +          AssignmentExpression: 'AssignmentExpression',
      +          BinaryExpression: 'BinaryExpression',
      +          BlockStatement: 'BlockStatement',
      +          BreakStatement: 'BreakStatement',
      +          CallExpression: 'CallExpression',
      +          CatchClause: 'CatchClause',
      +          ClassBody: 'ClassBody',
      +          ClassDeclaration: 'ClassDeclaration',
      +          ClassExpression: 'ClassExpression',
      +          MethodDefinition: 'MethodDefinition',
      +          ClassHeritage: 'ClassHeritage',
      +          ConditionalExpression: 'ConditionalExpression',
      +          ContinueStatement: 'ContinueStatement',
      +          DebuggerStatement: 'DebuggerStatement',
      +          DoWhileStatement: 'DoWhileStatement',
      +          EmptyStatement: 'EmptyStatement',
      +          ExportDeclaration: 'ExportDeclaration',
      +          ExportSpecifier: 'ExportSpecifier',
      +          ExportSpecifierSet: 'ExportSpecifierSet',
      +          ExpressionStatement: 'ExpressionStatement',
      +          ForInStatement: 'ForInStatement',
      +          ForOfStatement: 'ForOfStatement',
      +          ForStatement: 'ForStatement',
      +          FunctionDeclaration: 'FunctionDeclaration',
      +          FunctionExpression: 'FunctionExpression',
      +          Glob: 'Glob',
      +          Identifier: 'Identifier',
      +          IfStatement: 'IfStatement',
      +          ImportDeclaration: 'ImportDeclaration',
      +          ImportSpecifier: 'ImportSpecifier',
      +          LabeledStatement: 'LabeledStatement',
      +          Literal: 'Literal',
      +          LogicalExpression: 'LogicalExpression',
      +          MemberExpression: 'MemberExpression',
      +          ModuleDeclaration: 'ModuleDeclaration',
      +          NewExpression: 'NewExpression',
      +          ObjectExpression: 'ObjectExpression',
      +          ObjectPattern: 'ObjectPattern',
      +          Path:  'Path',
      +          Program: 'Program',
      +          Property: 'Property',
      +          ReturnStatement: 'ReturnStatement',
      +          SequenceExpression: 'SequenceExpression',
      +          SwitchCase: 'SwitchCase',
      +          SwitchStatement: 'SwitchStatement',
      +          ThisExpression: 'ThisExpression',
      +          ThrowStatement: 'ThrowStatement',
      +          TryStatement: 'TryStatement',
      +          UnaryExpression: 'UnaryExpression',
      +          UpdateExpression: 'UpdateExpression',
      +          VariableDeclaration: 'VariableDeclaration',
      +          VariableDeclarator: 'VariableDeclarator',
      +          WhileStatement: 'WhileStatement',
      +          WithStatement: 'WithStatement',
      +          YieldExpression: 'YieldExpression'
      +      };
      +  
      +      PropertyKind = {
      +          Data: 1,
      +          Get: 2,
      +          Set: 4
      +      };
      +  
      +      // Error messages should be identical to V8.
      +      Messages = {
      +          UnexpectedToken:  'Unexpected token %0',
      +          UnexpectedNumber:  'Unexpected number',
      +          UnexpectedString:  'Unexpected string',
      +          UnexpectedIdentifier:  'Unexpected identifier',
      +          UnexpectedReserved:  'Unexpected reserved word',
      +          UnexpectedEOS:  'Unexpected end of input',
      +          NewlineAfterThrow:  'Illegal newline after throw',
      +          InvalidRegExp: 'Invalid regular expression',
      +          UnterminatedRegExp:  'Invalid regular expression: missing /',
      +          InvalidLHSInAssignment:  'Invalid left-hand side in assignment',
      +          InvalidLHSInForIn:  'Invalid left-hand side in for-in',
      +          MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
      +          NoCatchOrFinally:  'Missing catch or finally after try',
      +          UnknownLabel: 'Undefined label \'%0\'',
      +          Redeclaration: '%0 \'%1\' has already been declared',
      +          IllegalContinue: 'Illegal continue statement',
      +          IllegalBreak: 'Illegal break statement',
      +          IllegalReturn: 'Illegal return statement',
      +          IllegalYield: 'Illegal yield expression',
      +          StrictModeWith:  'Strict mode code may not include a with statement',
      +          StrictCatchVariable:  'Catch variable may not be eval or arguments in strict mode',
      +          StrictVarName:  'Variable name may not be eval or arguments in strict mode',
      +          StrictParamName:  'Parameter name eval or arguments is not allowed in strict mode',
      +          StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
      +          StrictFunctionName:  'Function name may not be eval or arguments in strict mode',
      +          StrictOctalLiteral:  'Octal literals are not allowed in strict mode.',
      +          StrictDelete:  'Delete of an unqualified identifier in strict mode.',
      +          StrictDuplicateProperty:  'Duplicate data property in object literal not allowed in strict mode',
      +          AccessorDataProperty:  'Object literal may not have data and accessor property with the same name',
      +          AccessorGetSet:  'Object literal may not have multiple get/set accessors with the same name',
      +          StrictLHSAssignment:  'Assignment to eval or arguments is not allowed in strict mode',
      +          StrictLHSPostfix:  'Postfix increment/decrement may not have eval or arguments operand in strict mode',
      +          StrictLHSPrefix:  'Prefix increment/decrement may not have eval or arguments operand in strict mode',
      +          StrictReservedWord:  'Use of future reserved word in strict mode',
      +          NoFromAfterImport: 'Missing from after import',
      +          NoYieldInGenerator: 'Missing yield in generator'
      +      };
      +  
      +      // See also tools/generate-unicode-regex.py.
      +      Regex = {
      +          NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
      +          NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]')
      +      };
      +  
      +      // Ensure the condition is true, otherwise throw an error.
      +      // This is only to have a better contract semantic, i.e. another safety net
      +      // to catch a logic error. The condition shall be fulfilled in normal case.
      +      // Do NOT use this to enforce a certain condition on any user input.
      +  
      +      function assert(condition, message) {
      +          if (!condition) {
      +              throw new Error('ASSERT: ' + message);
      +          }
      +      }
      +  
      +      function sliceSource(from, to) {
      +          return source.slice(from, to);
      +      }
      +  
      +      if (typeof 'esprima'[0] === 'undefined') {
      +          sliceSource = function sliceArraySource(from, to) {
      +              return source.slice(from, to).join('');
      +          };
      +      }
      +  
      +      function isDecimalDigit(ch) {
      +          return '0123456789'.indexOf(ch) >= 0;
      +      }
      +  
      +      function isHexDigit(ch) {
      +          return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
      +      }
      +  
      +      function isOctalDigit(ch) {
      +          return '01234567'.indexOf(ch) >= 0;
      +      }
      +  
      +  
      +      // 7.2 White Space
      +  
      +      function isWhiteSpace(ch) {
      +          return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') ||
      +              (ch === '\u000C') || (ch === '\u00A0') ||
      +              (ch.charCodeAt(0) >= 0x1680 &&
      +               '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0);
      +      }
      +  
      +      // 7.3 Line Terminators
      +  
      +      function isLineTerminator(ch) {
      +          return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029');
      +      }
      +  
      +      // 7.6 Identifier Names and Identifiers
      +  
      +      function isIdentifierStart(ch) {
      +          return (ch === '$') || (ch === '_') || (ch === '\\') ||
      +              (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
      +              ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch));
      +      }
      +  
      +      function isIdentifierPart(ch) {
      +          return (ch === '$') || (ch === '_') || (ch === '\\') ||
      +              (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
      +              ((ch >= '0') && (ch <= '9')) ||
      +              ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch));
      +      }
      +  
      +      // 7.6.1.2 Future Reserved Words
      +  
      +      function isFutureReservedWord(id) {
      +          switch (id) {
      +  
      +          // Future reserved words.
      +          case 'class':
      +          case 'enum':
      +          case 'export':
      +          case 'extends':
      +          case 'import':
      +          case 'super':
      +              return true;
      +          }
      +  
      +          return false;
      +      }
      +  
      +      function isStrictModeReservedWord(id) {
      +          switch (id) {
      +  
      +          // Strict Mode reserved words.
      +          case 'implements':
      +          case 'interface':
      +          case 'package':
      +          case 'private':
      +          case 'protected':
      +          case 'public':
      +          case 'static':
      +          case 'yield':
      +          case 'let':
      +              return true;
      +          }
      +  
      +          return false;
      +      }
      +  
      +      function isRestrictedWord(id) {
      +          return id === 'eval' || id === 'arguments';
      +      }
      +  
      +      // 7.6.1.1 Keywords
      +  
      +      function isKeyword(id) {
      +          var keyword = false;
      +          switch (id.length) {
      +          case 2:
      +              keyword = (id === 'if') || (id === 'in') || (id === 'do');
      +              break;
      +          case 3:
      +              keyword = (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try');
      +              break;
      +          case 4:
      +              keyword = (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with');
      +              break;
      +          case 5:
      +              keyword = (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw');
      +              break;
      +          case 6:
      +              keyword = (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch');
      +              break;
      +          case 7:
      +              keyword = (id === 'default') || (id === 'finally');
      +              break;
      +          case 8:
      +              keyword = (id === 'function') || (id === 'continue') || (id === 'debugger');
      +              break;
      +          case 10:
      +              keyword = (id === 'instanceof');
      +              break;
      +          }
      +  
      +          if (keyword) {
      +              return true;
      +          }
      +  
      +          switch (id) {
      +          // Future reserved words.
      +          // 'const' is specialized as Keyword in V8.
      +          case 'const':
      +              return true;
      +  
      +          // For compatiblity to SpiderMonkey and ES.next
      +          case 'yield':
      +          case 'let':
      +              return true;
      +          }
      +  
      +          if (strict && isStrictModeReservedWord(id)) {
      +              return true;
      +          }
      +  
      +          return isFutureReservedWord(id);
      +      }
      +  
      +      // Return the next character and move forward.
      +  
      +      function nextChar() {
      +          return source[index++];
      +      }
      +  
      +      // 7.4 Comments
      +  
      +      function skipComment() {
      +          var ch, blockComment, lineComment;
      +  
      +          blockComment = false;
      +          lineComment = false;
      +  
      +          while (index < length) {
      +              ch = source[index];
      +  
      +              if (lineComment) {
      +                  ch = nextChar();
      +                  if (isLineTerminator(ch)) {
      +                      lineComment = false;
      +                      if (ch === '\r' && source[index] === '\n') {
      +                          ++index;
      +                      }
      +                      ++lineNumber;
      +                      lineStart = index;
      +                  }
      +              } else if (blockComment) {
      +                  if (isLineTerminator(ch)) {
      +                      if (ch === '\r' && source[index + 1] === '\n') {
      +                          ++index;
      +                      }
      +                      ++lineNumber;
      +                      ++index;
      +                      lineStart = index;
      +                      if (index >= length) {
      +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                      }
      +                  } else {
      +                      ch = nextChar();
      +                      if (index >= length) {
      +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                      }
      +                      if (ch === '*') {
      +                          ch = source[index];
      +                          if (ch === '/') {
      +                              ++index;
      +                              blockComment = false;
      +                          }
      +                      }
      +                  }
      +              } else if (ch === '/') {
      +                  ch = source[index + 1];
      +                  if (ch === '/') {
      +                      index += 2;
      +                      lineComment = true;
      +                  } else if (ch === '*') {
      +                      index += 2;
      +                      blockComment = true;
      +                      if (index >= length) {
      +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                      }
      +                  } else {
      +                      break;
      +                  }
      +              } else if (isWhiteSpace(ch)) {
      +                  ++index;
      +              } else if (isLineTerminator(ch)) {
      +                  ++index;
      +                  if (ch ===  '\r' && source[index] === '\n') {
      +                      ++index;
      +                  }
      +                  ++lineNumber;
      +                  lineStart = index;
      +              } else {
      +                  break;
      +              }
      +          }
      +      }
      +  
      +      function scanHexEscape(prefix) {
      +          var i, len, ch, code = 0;
      +  
      +          len = (prefix === 'u') ? 4 : 2;
      +          for (i = 0; i < len; ++i) {
      +              if (index < length && isHexDigit(source[index])) {
      +                  ch = nextChar();
      +                  code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
      +              } else {
      +                  return '';
      +              }
      +          }
      +          return String.fromCharCode(code);
      +      }
      +  
      +      function scanUnicodeCodePointEscape() {
      +          var ch, code, cu1, cu2;
      +  
      +          ch = source[index];
      +          code = 0;
      +  
      +          // At least, one hex digit is required.
      +          if (ch === '}') {
      +              throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +          }
      +  
      +          while (index < length) {
      +              ch = nextChar();
      +              if (!isHexDigit(ch)) {
      +                  break;
      +              }
      +              code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
      +          }
      +  
      +          if (code > 0x10FFFF || ch !== '}') {
      +              throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +          }
      +  
      +          // UTF-16 Encoding
      +          if (code <= 0xFFFF) {
      +              return String.fromCharCode(code);
      +          }
      +          cu1 = ((code - 0x10000) >> 10) + 0xD800;
      +          cu2 = ((code - 0x10000) & 1023) + 0xDC00;
      +          return String.fromCharCode(cu1, cu2);
      +      }
      +  
      +      function scanIdentifier() {
      +          var ch, start, id, restore;
      +  
      +          ch = source[index];
      +          if (!isIdentifierStart(ch)) {
      +              return;
      +          }
      +  
      +          start = index;
      +          if (ch === '\\') {
      +              ++index;
      +              if (source[index] !== 'u') {
      +                  return;
      +              }
      +              ++index;
      +              restore = index;
      +              ch = scanHexEscape('u');
      +              if (ch) {
      +                  if (ch === '\\' || !isIdentifierStart(ch)) {
      +                      return;
      +                  }
      +                  id = ch;
      +              } else {
      +                  index = restore;
      +                  id = 'u';
      +              }
      +          } else {
      +              id = nextChar();
      +          }
      +  
      +          while (index < length) {
      +              ch = source[index];
      +              if (!isIdentifierPart(ch)) {
      +                  break;
      +              }
      +              if (ch === '\\') {
      +                  ++index;
      +                  if (source[index] !== 'u') {
      +                      return;
      +                  }
      +                  ++index;
      +                  restore = index;
      +                  ch = scanHexEscape('u');
      +                  if (ch) {
      +                      if (ch === '\\' || !isIdentifierPart(ch)) {
      +                          return;
      +                      }
      +                      id += ch;
      +                  } else {
      +                      index = restore;
      +                      id += 'u';
      +                  }
      +              } else {
      +                  id += nextChar();
      +              }
      +          }
      +  
      +          // There is no keyword or literal with only one character.
      +          // Thus, it must be an identifier.
      +          if (id.length === 1) {
      +              return {
      +                  type: Token.Identifier,
      +                  value: id,
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          if (isKeyword(id)) {
      +              return {
      +                  type: Token.Keyword,
      +                  value: id,
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          // 7.8.1 Null Literals
      +  
      +          if (id === 'null') {
      +              return {
      +                  type: Token.NullLiteral,
      +                  value: id,
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          // 7.8.2 Boolean Literals
      +  
      +          if (id === 'true' || id === 'false') {
      +              return {
      +                  type: Token.BooleanLiteral,
      +                  value: id,
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          return {
      +              type: Token.Identifier,
      +              value: id,
      +              lineNumber: lineNumber,
      +              lineStart: lineStart,
      +              range: [start, index]
      +          };
      +      }
      +  
      +      // 7.7 Punctuators
      +  
      +      function scanPunctuator() {
      +          var start = index,
      +              ch1 = source[index],
      +              ch2,
      +              ch3,
      +              ch4;
      +  
      +          // Check for most common single-character punctuators.
      +  
      +          if (ch1 === ';' || ch1 === '{' || ch1 === '}') {
      +              ++index;
      +              return {
      +                  type: Token.Punctuator,
      +                  value: ch1,
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          if (ch1 === ',' || ch1 === '(' || ch1 === ')') {
      +              ++index;
      +              return {
      +                  type: Token.Punctuator,
      +                  value: ch1,
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          // Dot (.) can also start a floating-point number, hence the need
      +          // to check the next character.
      +  
      +          ch2 = source[index + 1];
      +          if (ch1 === '.' && !isDecimalDigit(ch2)) {
      +              return {
      +                  type: Token.Punctuator,
      +                  value: nextChar(),
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          // Peek more characters.
      +  
      +          ch3 = source[index + 2];
      +          ch4 = source[index + 3];
      +  
      +          // 4-character punctuator: >>>=
      +  
      +          if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
      +              if (ch4 === '=') {
      +                  index += 4;
      +                  return {
      +                      type: Token.Punctuator,
      +                      value: '>>>=',
      +                      lineNumber: lineNumber,
      +                      lineStart: lineStart,
      +                      range: [start, index]
      +                  };
      +              }
      +          }
      +  
      +          // 3-character punctuators: === !== >>> <<= >>=
      +  
      +          if (ch1 === '=' && ch2 === '=' && ch3 === '=') {
      +              index += 3;
      +              return {
      +                  type: Token.Punctuator,
      +                  value: '===',
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          if (ch1 === '!' && ch2 === '=' && ch3 === '=') {
      +              index += 3;
      +              return {
      +                  type: Token.Punctuator,
      +                  value: '!==',
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
      +              index += 3;
      +              return {
      +                  type: Token.Punctuator,
      +                  value: '>>>',
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
      +              index += 3;
      +              return {
      +                  type: Token.Punctuator,
      +                  value: '<<=',
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
      +              index += 3;
      +              return {
      +                  type: Token.Punctuator,
      +                  value: '>>=',
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          // 2-character punctuators: <= >= == != ++ -- << >> && ||
      +          // += -= *= %= &= |= ^= /=
      +  
      +          if (ch2 === '=') {
      +              if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
      +                  index += 2;
      +                  return {
      +                      type: Token.Punctuator,
      +                      value: ch1 + ch2,
      +                      lineNumber: lineNumber,
      +                      lineStart: lineStart,
      +                      range: [start, index]
      +                  };
      +              }
      +          }
      +  
      +          if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) {
      +              if ('+-<>&|'.indexOf(ch2) >= 0) {
      +                  index += 2;
      +                  return {
      +                      type: Token.Punctuator,
      +                      value: ch1 + ch2,
      +                      lineNumber: lineNumber,
      +                      lineStart: lineStart,
      +                      range: [start, index]
      +                  };
      +              }
      +          }
      +  
      +          if (ch1 === '=' && ch2 === '>') {
      +              index += 2;
      +              return {
      +                  type: Token.Punctuator,
      +                  value: '=>',
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +  
      +          // The remaining 1-character punctuators.
      +  
      +          if ('[]<>+-*%&|^!~?:=/'.indexOf(ch1) >= 0) {
      +              return {
      +                  type: Token.Punctuator,
      +                  value: nextChar(),
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [start, index]
      +              };
      +          }
      +      }
      +  
      +      // 7.8.3 Numeric Literals
      +  
      +      function scanNumericLiteral() {
      +          var number, start, ch, octal;
      +  
      +          ch = source[index];
      +          assert(isDecimalDigit(ch) || (ch === '.'),
      +              'Numeric literal must start with a decimal digit or a decimal point');
      +  
      +          start = index;
      +          number = '';
      +          if (ch !== '.') {
      +              number = nextChar();
      +              ch = source[index];
      +  
      +              // Hex number starts with '0x'.
      +              // Octal number starts with '0'.
      +              // Octal number in ES6 starts with '0o'.
      +              // Binary number in ES6 starts with '0b'.
      +              if (number === '0') {
      +                  if (ch === 'x' || ch === 'X') {
      +                      number += nextChar();
      +                      while (index < length) {
      +                          ch = source[index];
      +                          if (!isHexDigit(ch)) {
      +                              break;
      +                          }
      +                          number += nextChar();
      +                      }
      +  
      +                      if (number.length <= 2) {
      +                          // only 0x
      +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                      }
      +  
      +                      if (index < length) {
      +                          ch = source[index];
      +                          if (isIdentifierStart(ch)) {
      +                              throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                          }
      +                      }
      +                      return {
      +                          type: Token.NumericLiteral,
      +                          value: parseInt(number, 16),
      +                          lineNumber: lineNumber,
      +                          lineStart: lineStart,
      +                          range: [start, index]
      +                      };
      +                  } else if (ch === 'b' || ch === 'B') {
      +                      nextChar();
      +                      number = '';
      +  
      +                      while (index < length) {
      +                          ch = source[index];
      +                          if (ch !== '0' && ch !== '1') {
      +                              break;
      +                          }
      +                          number += nextChar();
      +                      }
      +  
      +                      if (number.length === 0) {
      +                          // only 0b or 0B
      +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                      }
      +  
      +                      if (index < length) {
      +                          ch = source[index];
      +                          if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
      +                              throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                          }
      +                      }
      +                      return {
      +                          type: Token.NumericLiteral,
      +                          value: parseInt(number, 2),
      +                          lineNumber: lineNumber,
      +                          lineStart: lineStart,
      +                          range: [start, index]
      +                      };
      +                  } else if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) {
      +                      if (isOctalDigit(ch)) {
      +                          octal = true;
      +                          number = nextChar();
      +                      } else {
      +                          octal = false;
      +                          nextChar();
      +                          number = '';
      +                      }
      +  
      +                      while (index < length) {
      +                          ch = source[index];
      +                          if (!isOctalDigit(ch)) {
      +                              break;
      +                          }
      +                          number += nextChar();
      +                      }
      +  
      +                      if (number.length === 0) {
      +                          // only 0o or 0O
      +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                      }
      +  
      +                      if (index < length) {
      +                          ch = source[index];
      +                          if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
      +                              throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                          }
      +                      }
      +  
      +                      return {
      +                          type: Token.NumericLiteral,
      +                          value: parseInt(number, 8),
      +                          octal: octal,
      +                          lineNumber: lineNumber,
      +                          lineStart: lineStart,
      +                          range: [start, index]
      +                      };
      +                  }
      +  
      +                  // decimal number starts with '0' such as '09' is illegal.
      +                  if (isDecimalDigit(ch)) {
      +                      throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                  }
      +              }
      +  
      +              while (index < length) {
      +                  ch = source[index];
      +                  if (!isDecimalDigit(ch)) {
      +                      break;
      +                  }
      +                  number += nextChar();
      +              }
      +          }
      +  
      +          if (ch === '.') {
      +              number += nextChar();
      +              while (index < length) {
      +                  ch = source[index];
      +                  if (!isDecimalDigit(ch)) {
      +                      break;
      +                  }
      +                  number += nextChar();
      +              }
      +          }
      +  
      +          if (ch === 'e' || ch === 'E') {
      +              number += nextChar();
      +  
      +              ch = source[index];
      +              if (ch === '+' || ch === '-') {
      +                  number += nextChar();
      +              }
      +  
      +              ch = source[index];
      +              if (isDecimalDigit(ch)) {
      +                  number += nextChar();
      +                  while (index < length) {
      +                      ch = source[index];
      +                      if (!isDecimalDigit(ch)) {
      +                          break;
      +                      }
      +                      number += nextChar();
      +                  }
      +              } else {
      +                  ch = 'character ' + ch;
      +                  if (index >= length) {
      +                      ch = '';
      +                  }
      +                  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +              }
      +          }
      +  
      +          if (index < length) {
      +              ch = source[index];
      +              if (isIdentifierStart(ch)) {
      +                  throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +              }
      +          }
      +  
      +          return {
      +              type: Token.NumericLiteral,
      +              value: parseFloat(number),
      +              lineNumber: lineNumber,
      +              lineStart: lineStart,
      +              range: [start, index]
      +          };
      +      }
      +  
      +      // 7.8.4 String Literals
      +  
      +      function scanStringLiteral() {
      +          var str = '', quote, start, ch, code, unescaped, restore, octal = false;
      +  
      +          quote = source[index];
      +          assert((quote === '\'' || quote === '"'),
      +              'String literal must starts with a quote');
      +  
      +          start = index;
      +          ++index;
      +  
      +          while (index < length) {
      +              ch = nextChar();
      +  
      +              if (ch === quote) {
      +                  quote = '';
      +                  break;
      +              } else if (ch === '\\') {
      +                  ch = nextChar();
      +                  if (!isLineTerminator(ch)) {
      +                      switch (ch) {
      +                      case 'n':
      +                          str += '\n';
      +                          break;
      +                      case 'r':
      +                          str += '\r';
      +                          break;
      +                      case 't':
      +                          str += '\t';
      +                          break;
      +                      case 'u':
      +                      case 'x':
      +                          if (source[index] === '{') {
      +                              ++index;
      +                              str += scanUnicodeCodePointEscape();
      +                          } else {
      +                              restore = index;
      +                              unescaped = scanHexEscape(ch);
      +                              if (unescaped) {
      +                                  str += unescaped;
      +                              } else {
      +                                  index = restore;
      +                                  str += ch;
      +                              }
      +                          }
      +                          break;
      +                      case 'b':
      +                          str += '\b';
      +                          break;
      +                      case 'f':
      +                          str += '\f';
      +                          break;
      +                      case 'v':
      +                          str += '\v';
      +                          break;
      +  
      +                      default:
      +                          if (isOctalDigit(ch)) {
      +                              code = '01234567'.indexOf(ch);
      +  
      +                              // \0 is not octal escape sequence
      +                              if (code !== 0) {
      +                                  octal = true;
      +                              }
      +  
      +                              if (index < length && isOctalDigit(source[index])) {
      +                                  octal = true;
      +                                  code = code * 8 + '01234567'.indexOf(nextChar());
      +  
      +                                  // 3 digits are only allowed when string starts
      +                                  // with 0, 1, 2, 3
      +                                  if ('0123'.indexOf(ch) >= 0 &&
      +                                          index < length &&
      +                                          isOctalDigit(source[index])) {
      +                                      code = code * 8 + '01234567'.indexOf(nextChar());
      +                                  }
      +                              }
      +                              str += String.fromCharCode(code);
      +                          } else {
      +                              str += ch;
      +                          }
      +                          break;
      +                      }
      +                  } else {
      +                      ++lineNumber;
      +                      if (ch ===  '\r' && source[index] === '\n') {
      +                          ++index;
      +                      }
      +                  }
      +              } else if (isLineTerminator(ch)) {
      +                  break;
      +              } else {
      +                  str += ch;
      +              }
      +          }
      +  
      +          if (quote !== '') {
      +              throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +          }
      +  
      +          return {
      +              type: Token.StringLiteral,
      +              value: str,
      +              octal: octal,
      +              lineNumber: lineNumber,
      +              lineStart: lineStart,
      +              range: [start, index]
      +          };
      +      }
      +  
      +      function scanRegExp() {
      +          var str = '', ch, start, pattern, flags, value, classMarker = false, restore;
      +  
      +          buffer = null;
      +          skipComment();
      +  
      +          start = index;
      +          ch = source[index];
      +          assert(ch === '/', 'Regular expression literal must start with a slash');
      +          str = nextChar();
      +  
      +          while (index < length) {
      +              ch = nextChar();
      +              str += ch;
      +              if (classMarker) {
      +                  if (ch === ']') {
      +                      classMarker = false;
      +                  }
      +              } else {
      +                  if (ch === '\\') {
      +                      ch = nextChar();
      +                      // ECMA-262 7.8.5
      +                      if (isLineTerminator(ch)) {
      +                          throwError({}, Messages.UnterminatedRegExp);
      +                      }
      +                      str += ch;
      +                  } else if (ch === '/') {
      +                      break;
      +                  } else if (ch === '[') {
      +                      classMarker = true;
      +                  } else if (isLineTerminator(ch)) {
      +                      throwError({}, Messages.UnterminatedRegExp);
      +                  }
      +              }
      +          }
      +  
      +          if (str.length === 1) {
      +              throwError({}, Messages.UnterminatedRegExp);
      +          }
      +  
      +          // Exclude leading and trailing slash.
      +          pattern = str.substr(1, str.length - 2);
      +  
      +          flags = '';
      +          while (index < length) {
      +              ch = source[index];
      +              if (!isIdentifierPart(ch)) {
      +                  break;
      +              }
      +  
      +              ++index;
      +              if (ch === '\\' && index < length) {
      +                  ch = source[index];
      +                  if (ch === 'u') {
      +                      ++index;
      +                      restore = index;
      +                      ch = scanHexEscape('u');
      +                      if (ch) {
      +                          flags += ch;
      +                          str += '\\u';
      +                          for (; restore < index; ++restore) {
      +                              str += source[restore];
      +                          }
      +                      } else {
      +                          index = restore;
      +                          flags += 'u';
      +                          str += '\\u';
      +                      }
      +                  } else {
      +                      str += '\\';
      +                  }
      +              } else {
      +                  flags += ch;
      +                  str += ch;
      +              }
      +          }
      +  
      +          try {
      +              value = new RegExp(pattern, flags);
      +          } catch (e) {
      +              throwError({}, Messages.InvalidRegExp);
      +          }
      +  
      +          return {
      +              literal: str,
      +              value: value,
      +              range: [start, index]
      +          };
      +      }
      +  
      +      function isIdentifierName(token) {
      +          return token.type === Token.Identifier ||
      +              token.type === Token.Keyword ||
      +              token.type === Token.BooleanLiteral ||
      +              token.type === Token.NullLiteral;
      +      }
      +  
      +      function advance() {
      +          var ch, token;
      +  
      +          skipComment();
      +  
      +          if (index >= length) {
      +              return {
      +                  type: Token.EOF,
      +                  lineNumber: lineNumber,
      +                  lineStart: lineStart,
      +                  range: [index, index]
      +              };
      +          }
      +  
      +          token = scanPunctuator();
      +          if (typeof token !== 'undefined') {
      +              return token;
      +          }
      +  
      +          ch = source[index];
      +  
      +          if (ch === '\'' || ch === '"') {
      +              return scanStringLiteral();
      +          }
      +  
      +          if (ch === '.' || isDecimalDigit(ch)) {
      +              return scanNumericLiteral();
      +          }
      +  
      +          token = scanIdentifier();
      +          if (typeof token !== 'undefined') {
      +              return token;
      +          }
      +  
      +          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +      }
      +  
      +      function lex() {
      +          var token;
      +  
      +          if (buffer) {
      +              index = buffer.range[1];
      +              lineNumber = buffer.lineNumber;
      +              lineStart = buffer.lineStart;
      +              token = buffer;
      +              buffer = null;
      +              return token;
      +          }
      +  
      +          buffer = null;
      +          return advance();
      +      }
      +  
      +      function lookahead() {
      +          var pos, line, start;
      +  
      +          if (buffer !== null) {
      +              return buffer;
      +          }
      +  
      +          pos = index;
      +          line = lineNumber;
      +          start = lineStart;
      +          buffer = advance();
      +          index = pos;
      +          lineNumber = line;
      +          lineStart = start;
      +  
      +          return buffer;
      +      }
      +  
      +      function lookahead2() {
      +          var adv, pos, line, start, result;
      +  
      +          // If we are collecting the tokens, don't grab the next one yet.
      +          adv = (typeof extra.advance === 'function') ? extra.advance : advance;
      +  
      +          pos = index;
      +          line = lineNumber;
      +          start = lineStart;
      +  
      +          // Scan for the next immediate token.
      +          if (buffer === null) {
      +              buffer = adv();
      +          }
      +          index = buffer.range[1];
      +          lineNumber = buffer.lineNumber;
      +          lineStart = buffer.lineStart;
      +  
      +          // Grab the token right after.
      +          result = adv();
      +          index = pos;
      +          lineNumber = line;
      +          lineStart = start;
      +  
      +          return result;
      +      }
      +  
      +      // Return true if there is a line terminator before the next token.
      +  
      +      function peekLineTerminator() {
      +          var pos, line, start, found;
      +  
      +          pos = index;
      +          line = lineNumber;
      +          start = lineStart;
      +          skipComment();
      +          found = lineNumber !== line;
      +          index = pos;
      +          lineNumber = line;
      +          lineStart = start;
      +  
      +          return found;
      +      }
      +  
      +      // Throw an exception
      +  
      +      function throwError(token, messageFormat) {
      +          var error,
      +              args = Array.prototype.slice.call(arguments, 2),
      +              msg = messageFormat.replace(
      +                  /%(\d)/g,
      +                  function (whole, index) {
      +                      return args[index] || '';
      +                  }
      +              );
      +  
      +          if (typeof token.lineNumber === 'number') {
      +              error = new Error('Line ' + token.lineNumber + ': ' + msg);
      +              error.index = token.range[0];
      +              error.lineNumber = token.lineNumber;
      +              error.column = token.range[0] - lineStart + 1;
      +          } else {
      +              error = new Error('Line ' + lineNumber + ': ' + msg);
      +              error.index = index;
      +              error.lineNumber = lineNumber;
      +              error.column = index - lineStart + 1;
      +          }
      +  
      +          throw error;
      +      }
      +  
      +      function throwErrorTolerant() {
      +          try {
      +              throwError.apply(null, arguments);
      +          } catch (e) {
      +              if (extra.errors) {
      +                  extra.errors.push(e);
      +              } else {
      +                  throw e;
      +              }
      +          }
      +      }
      +  
      +  
      +      // Throw an exception because of the token.
      +  
      +      function throwUnexpected(token) {
      +          if (token.type === Token.EOF) {
      +              throwError(token, Messages.UnexpectedEOS);
      +          }
      +  
      +          if (token.type === Token.NumericLiteral) {
      +              throwError(token, Messages.UnexpectedNumber);
      +          }
      +  
      +          if (token.type === Token.StringLiteral) {
      +              throwError(token, Messages.UnexpectedString);
      +          }
      +  
      +          if (token.type === Token.Identifier) {
      +              throwError(token, Messages.UnexpectedIdentifier);
      +          }
      +  
      +          if (token.type === Token.Keyword) {
      +              if (isFutureReservedWord(token.value)) {
      +                  throwError(token, Messages.UnexpectedReserved);
      +              } else if (strict && isStrictModeReservedWord(token.value)) {
      +                  throwError(token, Messages.StrictReservedWord);
      +              }
      +              throwError(token, Messages.UnexpectedToken, token.value);
      +          }
      +  
      +          // BooleanLiteral, NullLiteral, or Punctuator.
      +          throwError(token, Messages.UnexpectedToken, token.value);
      +      }
      +  
      +      // Expect the next token to match the specified punctuator.
      +      // If not, an exception will be thrown.
      +  
      +      function expect(value) {
      +          var token = lex();
      +          if (token.type !== Token.Punctuator || token.value !== value) {
      +              throwUnexpected(token);
      +          }
      +      }
      +  
      +      // Expect the next token to match the specified keyword.
      +      // If not, an exception will be thrown.
      +  
      +      function expectKeyword(keyword) {
      +          var token = lex();
      +          if (token.type !== Token.Keyword || token.value !== keyword) {
      +              throwUnexpected(token);
      +          }
      +      }
      +  
      +      // Return true if the next token matches the specified punctuator.
      +  
      +      function match(value) {
      +          var token = lookahead();
      +          return token.type === Token.Punctuator && token.value === value;
      +      }
      +  
      +      // Return true if the next token matches the specified keyword
      +  
      +      function matchKeyword(keyword) {
      +          var token = lookahead();
      +          return token.type === Token.Keyword && token.value === keyword;
      +      }
      +  
      +  
      +      // Return true if the next token matches the specified contextual keyword
      +  
      +      function matchContextualKeyword(keyword) {
      +          var token = lookahead();
      +          return token.type === Token.Identifier && token.value === keyword;
      +      }
      +  
      +      // Return true if the next token is an assignment operator
      +  
      +      function matchAssign() {
      +          var token = lookahead(),
      +              op = token.value;
      +  
      +          if (token.type !== Token.Punctuator) {
      +              return false;
      +          }
      +          return op === '=' ||
      +              op === '*=' ||
      +              op === '/=' ||
      +              op === '%=' ||
      +              op === '+=' ||
      +              op === '-=' ||
      +              op === '<<=' ||
      +              op === '>>=' ||
      +              op === '>>>=' ||
      +              op === '&=' ||
      +              op === '^=' ||
      +              op === '|=';
      +      }
      +  
      +      function consumeSemicolon() {
      +          var token, line;
      +  
      +          // Catch the very common case first.
      +          if (source[index] === ';') {
      +              lex();
      +              return;
      +          }
      +  
      +          line = lineNumber;
      +          skipComment();
      +          if (lineNumber !== line) {
      +              return;
      +          }
      +  
      +          if (match(';')) {
      +              lex();
      +              return;
      +          }
      +  
      +          token = lookahead();
      +          if (token.type !== Token.EOF && !match('}')) {
      +              throwUnexpected(token);
      +          }
      +          return;
      +      }
      +  
      +      // Return true if provided expression is LeftHandSideExpression
      +  
      +      function isLeftHandSide(expr) {
      +          return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
      +      }
      +  
      +      function isAssignableLeftHandSide(expr) {
      +          return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern;
      +      }
      +  
      +      // 11.1.4 Array Initialiser
      +  
      +      function parseArrayInitialiser() {
      +          var elements = [],
      +              undef;
      +  
      +          expect('[');
      +  
      +          while (!match(']')) {
      +              if (match(',')) {
      +                  lex();
      +                  elements.push(undef);
      +              } else {
      +                  elements.push(parseAssignmentExpression());
      +  
      +                  if (!match(']')) {
      +                      expect(',');
      +                  }
      +              }
      +          }
      +  
      +          expect(']');
      +  
      +          return {
      +              type: Syntax.ArrayExpression,
      +              elements: elements
      +          };
      +      }
      +  
      +      // 11.1.5 Object Initialiser
      +  
      +      function parsePropertyFunction(param, options) {
      +          var previousStrict, previousYieldAllowed, body;
      +  
      +          previousStrict = strict;
      +          previousYieldAllowed = yieldAllowed;
      +          yieldAllowed = options.generator;
      +          body = parseConciseBody();
      +          if (options.name && strict && isRestrictedWord(param[0].name)) {
      +              throwError(options.name, Messages.StrictParamName);
      +          }
      +          if (yieldAllowed && !yieldFound) {
      +              throwError({}, Messages.NoYieldInGenerator);
      +          }
      +          strict = previousStrict;
      +          yieldAllowed = previousYieldAllowed;
      +  
      +          return {
      +              type: Syntax.FunctionExpression,
      +              id: null,
      +              params: param,
      +              body: body,
      +              generator: options.generator
      +          };
      +      }
      +  
      +      function parsePropertyMethodFunction(options) {
      +          var token, previousStrict, param, params, paramSet, method;
      +  
      +          previousStrict = strict;
      +          strict = true;
      +          params = [];
      +  
      +          expect('(');
      +  
      +          if (!match(')')) {
      +              paramSet = {};
      +              while (index < length) {
      +                  token = lookahead();
      +                  param = parseVariableIdentifier();
      +                  if (isRestrictedWord(token.value)) {
      +                      throwError(token, Messages.StrictParamName);
      +                  }
      +                  if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
      +                      throwError(token, Messages.StrictParamDupe);
      +                  }
      +                  params.push(param);
      +                  paramSet[param.name] = true;
      +                  if (match(')')) {
      +                      break;
      +                  }
      +                  expect(',');
      +              }
      +          }
      +  
      +          expect(')');
      +  
      +          method = parsePropertyFunction(params, { generator: options.generator });
      +  
      +          strict = previousStrict;
      +  
      +          return method;
      +      }
      +  
      +      function parseObjectPropertyKey() {
      +          var token = lex();
      +  
      +          // Note: This function is called only from parseObjectProperty(), where
      +          // EOF and Punctuator tokens are already filtered out.
      +  
      +          if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
      +              if (strict && token.octal) {
      +                  throwError(token, Messages.StrictOctalLiteral);
      +              }
      +              return createLiteral(token);
      +          }
      +  
      +          return {
      +              type: Syntax.Identifier,
      +              name: token.value
      +          };
      +      }
      +  
      +      function parseObjectProperty() {
      +          var token, key, id, param;
      +  
      +          token = lookahead();
      +  
      +          if (token.type === Token.Identifier) {
      +  
      +              id = parseObjectPropertyKey();
      +  
      +              // Property Assignment: Getter and Setter.
      +  
      +              if (token.value === 'get' && !(match(':') || match('('))) {
      +                  key = parseObjectPropertyKey();
      +                  expect('(');
      +                  expect(')');
      +                  return {
      +                      type: Syntax.Property,
      +                      key: key,
      +                      value: parsePropertyFunction([], { generator: false }),
      +                      kind: 'get'
      +                  };
      +              } else if (token.value === 'set' && !(match(':') || match('('))) {
      +                  key = parseObjectPropertyKey();
      +                  expect('(');
      +                  token = lookahead();
      +                  param = [ parseVariableIdentifier() ];
      +                  expect(')');
      +                  return {
      +                      type: Syntax.Property,
      +                      key: key,
      +                      value: parsePropertyFunction(param, { generator: false, name: token }),
      +                      kind: 'set'
      +                  };
      +              } else {
      +                  if (match(':')) {
      +                      lex();
      +                      return {
      +                          type: Syntax.Property,
      +                          key: id,
      +                          value: parseAssignmentExpression(),
      +                          kind: 'init'
      +                      };
      +                  } else if (match('(')) {
      +                      return {
      +                          type: Syntax.Property,
      +                          key: id,
      +                          value: parsePropertyMethodFunction({ generator: false }),
      +                          kind: 'init',
      +                          method: true
      +                      };
      +                  } else {
      +                      return {
      +                          type: Syntax.Property,
      +                          key: id,
      +                          value: id,
      +                          kind: 'init',
      +                          shorthand: true
      +                      };
      +                  }
      +              }
      +          } else if (token.type === Token.EOF || token.type === Token.Punctuator) {
      +              if (!match('*')) {
      +                  throwUnexpected(token);
      +              }
      +              lex();
      +  
      +              id = parseObjectPropertyKey();
      +  
      +              if (!match('(')) {
      +                  throwUnexpected(lex());
      +              }
      +  
      +              return {
      +                  type: Syntax.Property,
      +                  key: id,
      +                  value: parsePropertyMethodFunction({ generator: true }),
      +                  kind: 'init',
      +                  method: true
      +              };
      +          } else {
      +              key = parseObjectPropertyKey();
      +              if (match(':')) {
      +                  lex();
      +                  return {
      +                      type: Syntax.Property,
      +                      key: key,
      +                      value: parseAssignmentExpression(),
      +                      kind: 'init'
      +                  };
      +              } else if (match('(')) {
      +                  return {
      +                      type: Syntax.Property,
      +                      key: key,
      +                      value: parsePropertyMethodFunction({ generator: false }),
      +                      kind: 'init',
      +                      method: true
      +                  };
      +              } else {
      +                  return {
      +                      type: Syntax.Property,
      +                      key: key,
      +                      value: key,
      +                      kind: 'init',
      +                      shorthand: true
      +                  };
      +              }
      +          }
      +      }
      +  
      +      function parseObjectInitialiser() {
      +          var properties = [], property, name, kind, map = {}, toString = String;
      +  
      +          expect('{');
      +  
      +          while (!match('}')) {
      +              property = parseObjectProperty();
      +  
      +              if (property.key.type === Syntax.Identifier) {
      +                  name = property.key.name;
      +              } else {
      +                  name = toString(property.key.value);
      +              }
      +              kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
      +              if (Object.prototype.hasOwnProperty.call(map, name)) {
      +                  if (map[name] === PropertyKind.Data) {
      +                      if (strict && kind === PropertyKind.Data) {
      +                          throwErrorTolerant({}, Messages.StrictDuplicateProperty);
      +                      } else if (kind !== PropertyKind.Data) {
      +                          throwError({}, Messages.AccessorDataProperty);
      +                      }
      +                  } else {
      +                      if (kind === PropertyKind.Data) {
      +                          throwError({}, Messages.AccessorDataProperty);
      +                      } else if (map[name] & kind) {
      +                          throwError({}, Messages.AccessorGetSet);
      +                      }
      +                  }
      +                  map[name] |= kind;
      +              } else {
      +                  map[name] = kind;
      +              }
      +  
      +              properties.push(property);
      +  
      +              if (!match('}')) {
      +                  expect(',');
      +              }
      +          }
      +  
      +          expect('}');
      +  
      +          return {
      +              type: Syntax.ObjectExpression,
      +              properties: properties
      +          };
      +      }
      +  
      +      // 11.1 Primary Expressions
      +  
      +      function parsePrimaryExpression() {
      +          var expr,
      +              token = lookahead(),
      +              type = token.type;
      +  
      +          if (type === Token.Identifier) {
      +              return {
      +                  type: Syntax.Identifier,
      +                  name: lex().value
      +              };
      +          }
      +  
      +          if (type === Token.StringLiteral || type === Token.NumericLiteral) {
      +              if (strict && token.octal) {
      +                  throwErrorTolerant(token, Messages.StrictOctalLiteral);
      +              }
      +              return createLiteral(lex());
      +          }
      +  
      +          if (type === Token.Keyword) {
      +              if (matchKeyword('this')) {
      +                  lex();
      +                  return {
      +                      type: Syntax.ThisExpression
      +                  };
      +              }
      +  
      +              if (matchKeyword('function')) {
      +                  return parseFunctionExpression();
      +              }
      +  
      +              if (matchKeyword('class')) {
      +                  return parseClassExpression();
      +              }
      +  
      +              if (matchKeyword('super')) {
      +                  lex();
      +                  return {
      +                      type: Syntax.Identifier,
      +                      name: 'super'
      +                  };
      +              }
      +          }
      +  
      +          if (type === Token.BooleanLiteral) {
      +              lex();
      +              token.value = (token.value === 'true');
      +              return createLiteral(token);
      +          }
      +  
      +          if (type === Token.NullLiteral) {
      +              lex();
      +              token.value = null;
      +              return createLiteral(token);
      +          }
      +  
      +          if (match('[')) {
      +              return parseArrayInitialiser();
      +          }
      +  
      +          if (match('{')) {
      +              return parseObjectInitialiser();
      +          }
      +  
      +          if (match('(')) {
      +              lex();
      +              state.lastParenthesized = expr = parseExpression();
      +              state.parenthesizedCount += 1;
      +              expect(')');
      +              return expr;
      +          }
      +  
      +          if (match('/') || match('/=')) {
      +              return createLiteral(scanRegExp());
      +          }
      +  
      +          return throwUnexpected(lex());
      +      }
      +  
      +      // 11.2 Left-Hand-Side Expressions
      +  
      +      function parseArguments() {
      +          var args = [];
      +  
      +          expect('(');
      +  
      +          if (!match(')')) {
      +              while (index < length) {
      +                  args.push(parseAssignmentExpression());
      +                  if (match(')')) {
      +                      break;
      +                  }
      +                  expect(',');
      +              }
      +          }
      +  
      +          expect(')');
      +  
      +          return args;
      +      }
      +  
      +      function parseNonComputedProperty() {
      +          var token = lex();
      +  
      +          if (!isIdentifierName(token)) {
      +              throwUnexpected(token);
      +          }
      +  
      +          return {
      +              type: Syntax.Identifier,
      +              name: token.value
      +          };
      +      }
      +  
      +      function parseNonComputedMember(object) {
      +          return {
      +              type: Syntax.MemberExpression,
      +              computed: false,
      +              object: object,
      +              property: parseNonComputedProperty()
      +          };
      +      }
      +  
      +      function parseComputedMember(object) {
      +          var property, expr;
      +  
      +          expect('[');
      +          property = parseExpression();
      +          expr = {
      +              type: Syntax.MemberExpression,
      +              computed: true,
      +              object: object,
      +              property: property
      +          };
      +          expect(']');
      +          return expr;
      +      }
      +  
      +      function parseCallMember(object) {
      +          return {
      +              type: Syntax.CallExpression,
      +              callee: object,
      +              'arguments': parseArguments()
      +          };
      +      }
      +  
      +      function parseNewExpression() {
      +          var expr;
      +  
      +          expectKeyword('new');
      +  
      +          expr = {
      +              type: Syntax.NewExpression,
      +              callee: parseLeftHandSideExpression(),
      +              'arguments': []
      +          };
      +  
      +          if (match('(')) {
      +              expr['arguments'] = parseArguments();
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      function parseLeftHandSideExpressionAllowCall() {
      +          var useNew, expr;
      +  
      +          useNew = matchKeyword('new');
      +          expr = useNew ? parseNewExpression() : parsePrimaryExpression();
      +  
      +          while (index < length) {
      +              if (match('.')) {
      +                  lex();
      +                  expr = parseNonComputedMember(expr);
      +              } else if (match('[')) {
      +                  expr = parseComputedMember(expr);
      +              } else if (match('(')) {
      +                  expr = parseCallMember(expr);
      +              } else {
      +                  break;
      +              }
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      function parseLeftHandSideExpression() {
      +          var useNew, expr;
      +  
      +          useNew = matchKeyword('new');
      +          expr = useNew ? parseNewExpression() : parsePrimaryExpression();
      +  
      +          while (index < length) {
      +              if (match('.')) {
      +                  lex();
      +                  expr = parseNonComputedMember(expr);
      +              } else if (match('[')) {
      +                  expr = parseComputedMember(expr);
      +              } else {
      +                  break;
      +              }
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      // 11.3 Postfix Expressions
      +  
      +      function parsePostfixExpression() {
      +          var expr = parseLeftHandSideExpressionAllowCall();
      +  
      +          if ((match('++') || match('--')) && !peekLineTerminator()) {
      +              // 11.3.1, 11.3.2
      +              if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
      +                  throwError({}, Messages.StrictLHSPostfix);
      +              }
      +  
      +              if (!isLeftHandSide(expr)) {
      +                  throwError({}, Messages.InvalidLHSInAssignment);
      +              }
      +  
      +              expr = {
      +                  type: Syntax.UpdateExpression,
      +                  operator: lex().value,
      +                  argument: expr,
      +                  prefix: false
      +              };
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      // 11.4 Unary Operators
      +  
      +      function parseUnaryExpression() {
      +          var token, expr;
      +  
      +          if (match('++') || match('--')) {
      +              token = lex();
      +              expr = parseUnaryExpression();
      +              // 11.4.4, 11.4.5
      +              if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
      +                  throwError({}, Messages.StrictLHSPrefix);
      +              }
      +  
      +              if (!isLeftHandSide(expr)) {
      +                  throwError({}, Messages.InvalidLHSInAssignment);
      +              }
      +  
      +              expr = {
      +                  type: Syntax.UpdateExpression,
      +                  operator: token.value,
      +                  argument: expr,
      +                  prefix: true
      +              };
      +              return expr;
      +          }
      +  
      +          if (match('+') || match('-') || match('~') || match('!')) {
      +              expr = {
      +                  type: Syntax.UnaryExpression,
      +                  operator: lex().value,
      +                  argument: parseUnaryExpression()
      +              };
      +              return expr;
      +          }
      +  
      +          if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
      +              expr = {
      +                  type: Syntax.UnaryExpression,
      +                  operator: lex().value,
      +                  argument: parseUnaryExpression()
      +              };
      +              if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
      +                  throwErrorTolerant({}, Messages.StrictDelete);
      +              }
      +              return expr;
      +          }
      +  
      +          return parsePostfixExpression();
      +      }
      +  
      +      // 11.5 Multiplicative Operators
      +  
      +      function parseMultiplicativeExpression() {
      +          var expr = parseUnaryExpression();
      +  
      +          while (match('*') || match('/') || match('%')) {
      +              expr = {
      +                  type: Syntax.BinaryExpression,
      +                  operator: lex().value,
      +                  left: expr,
      +                  right: parseUnaryExpression()
      +              };
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      // 11.6 Additive Operators
      +  
      +      function parseAdditiveExpression() {
      +          var expr = parseMultiplicativeExpression();
      +  
      +          while (match('+') || match('-')) {
      +              expr = {
      +                  type: Syntax.BinaryExpression,
      +                  operator: lex().value,
      +                  left: expr,
      +                  right: parseMultiplicativeExpression()
      +              };
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      // 11.7 Bitwise Shift Operators
      +  
      +      function parseShiftExpression() {
      +          var expr = parseAdditiveExpression();
      +  
      +          while (match('<<') || match('>>') || match('>>>')) {
      +              expr = {
      +                  type: Syntax.BinaryExpression,
      +                  operator: lex().value,
      +                  left: expr,
      +                  right: parseAdditiveExpression()
      +              };
      +          }
      +  
      +          return expr;
      +      }
      +      // 11.8 Relational Operators
      +  
      +      function parseRelationalExpression() {
      +          var expr, previousAllowIn;
      +  
      +          previousAllowIn = state.allowIn;
      +          state.allowIn = true;
      +  
      +          expr = parseShiftExpression();
      +  
      +          while (match('<') || match('>') || match('<=') || match('>=') || (previousAllowIn && matchKeyword('in')) || matchKeyword('instanceof')) {
      +              expr = {
      +                  type: Syntax.BinaryExpression,
      +                  operator: lex().value,
      +                  left: expr,
      +                  right: parseShiftExpression()
      +              };
      +          }
      +  
      +          state.allowIn = previousAllowIn;
      +          return expr;
      +      }
      +  
      +      // 11.9 Equality Operators
      +  
      +      function parseEqualityExpression() {
      +          var expr = parseRelationalExpression();
      +  
      +          while ((!peekLineTerminator() && (matchContextualKeyword('is') || matchContextualKeyword('isnt'))) || match('==') || match('!=') || match('===') || match('!==')) {
      +              expr = {
      +                  type: Syntax.BinaryExpression,
      +                  operator: lex().value,
      +                  left: expr,
      +                  right: parseRelationalExpression()
      +              };
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      // 11.10 Binary Bitwise Operators
      +  
      +      function parseBitwiseANDExpression() {
      +          var expr = parseEqualityExpression();
      +  
      +          while (match('&')) {
      +              lex();
      +              expr = {
      +                  type: Syntax.BinaryExpression,
      +                  operator: '&',
      +                  left: expr,
      +                  right: parseEqualityExpression()
      +              };
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      function parseBitwiseXORExpression() {
      +          var expr = parseBitwiseANDExpression();
      +  
      +          while (match('^')) {
      +              lex();
      +              expr = {
      +                  type: Syntax.BinaryExpression,
      +                  operator: '^',
      +                  left: expr,
      +                  right: parseBitwiseANDExpression()
      +              };
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      function parseBitwiseORExpression() {
      +          var expr = parseBitwiseXORExpression();
      +  
      +          while (match('|')) {
      +              lex();
      +              expr = {
      +                  type: Syntax.BinaryExpression,
      +                  operator: '|',
      +                  left: expr,
      +                  right: parseBitwiseXORExpression()
      +              };
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      // 11.11 Binary Logical Operators
      +  
      +      function parseLogicalANDExpression() {
      +          var expr = parseBitwiseORExpression();
      +  
      +          while (match('&&')) {
      +              lex();
      +              expr = {
      +                  type: Syntax.LogicalExpression,
      +                  operator: '&&',
      +                  left: expr,
      +                  right: parseBitwiseORExpression()
      +              };
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      function parseLogicalORExpression() {
      +          var expr = parseLogicalANDExpression();
      +  
      +          while (match('||')) {
      +              lex();
      +              expr = {
      +                  type: Syntax.LogicalExpression,
      +                  operator: '||',
      +                  left: expr,
      +                  right: parseLogicalANDExpression()
      +              };
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      // 11.12 Conditional Operator
      +  
      +      function parseConditionalExpression() {
      +          var expr, previousAllowIn, consequent;
      +  
      +          expr = parseLogicalORExpression();
      +  
      +          if (match('?')) {
      +              lex();
      +              previousAllowIn = state.allowIn;
      +              state.allowIn = true;
      +              consequent = parseAssignmentExpression();
      +              state.allowIn = previousAllowIn;
      +              expect(':');
      +  
      +              expr = {
      +                  type: Syntax.ConditionalExpression,
      +                  test: expr,
      +                  consequent: consequent,
      +                  alternate: parseAssignmentExpression()
      +              };
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      // 11.13 Assignment Operators
      +  
      +      function reinterpretAsAssignmentBindingPattern(expr) {
      +          var i, len, property, element;
      +  
      +          if (expr.type === Syntax.ObjectExpression) {
      +              expr.type = Syntax.ObjectPattern;
      +              for (i = 0, len = expr.properties.length; i < len; i += 1) {
      +                  property = expr.properties[i];
      +                  if (property.kind !== 'init') {
      +                      throwError({}, Messages.InvalidLHSInAssignment);
      +                  }
      +                  reinterpretAsAssignmentBindingPattern(property.value);
      +              }
      +          } else if (expr.type === Syntax.ArrayExpression) {
      +              expr.type = Syntax.ArrayPattern;
      +              for (i = 0, len = expr.elements.length; i < len; i += 1) {
      +                  element = expr.elements[i];
      +                  if (element) {
      +                      reinterpretAsAssignmentBindingPattern(element);
      +                  }
      +              }
      +          } else if (expr.type === Syntax.Identifier) {
      +              if (isRestrictedWord(expr.name)) {
      +                  throwError({}, Messages.InvalidLHSInAssignment);
      +              }
      +          } else {
      +              if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) {
      +                  throwError({}, Messages.InvalidLHSInAssignment);
      +              }
      +          }
      +      }
      +  
      +      function reinterpretAsCoverFormalsList(expr) {
      +          var i, len, param, paramSet;
      +          assert(expr.type === Syntax.SequenceExpression);
      +  
      +          paramSet = {};
      +  
      +          for (i = 0, len = expr.expressions.length; i < len; i += 1) {
      +              param = expr.expressions[i];
      +              if (param.type !== Syntax.Identifier) {
      +                  return null;
      +              }
      +              if (isRestrictedWord(param.name)) {
      +                  throwError({}, Messages.StrictParamName);
      +              }
      +              if (Object.prototype.hasOwnProperty.call(paramSet, param.name)) {
      +                  throwError({}, Messages.StrictParamDupe);
      +              }
      +              paramSet[param.name] = true;
      +          }
      +          return expr.expressions;
      +      }
      +  
      +      function parseArrowFunctionExpression(param) {
      +          var previousStrict, previousYieldAllowed, body;
      +  
      +          expect('=>');
      +  
      +          previousStrict = strict;
      +          previousYieldAllowed = yieldAllowed;
      +          strict = true;
      +          yieldAllowed = false;
      +          body = parseConciseBody();
      +          strict = previousStrict;
      +          yieldAllowed = previousYieldAllowed;
      +  
      +          return {
      +              type: Syntax.ArrowFunctionExpression,
      +              id: null,
      +              params: param,
      +              body: body
      +          };
      +      }
      +  
      +      function parseAssignmentExpression() {
      +          var expr, token, oldParenthesizedCount, coverFormalsList;
      +  
      +          if (matchKeyword('yield')) {
      +              return parseYieldExpression();
      +          }
      +  
      +          oldParenthesizedCount = state.parenthesizedCount;
      +  
      +          if (match('(')) {
      +              token = lookahead2();
      +              if (token.type === Token.Punctuator && token.value === ')') {
      +                  lex();
      +                  lex();
      +                  if (!match('=>')) {
      +                      throwUnexpected(lex());
      +                  }
      +                  return parseArrowFunctionExpression([]);
      +              }
      +          }
      +  
      +          expr = parseConditionalExpression();
      +  
      +          if (match('=>')) {
      +              if (expr.type === Syntax.Identifier) {
      +                  if (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1)) {
      +                      if (isRestrictedWord(expr.name)) {
      +                          throwError({}, Messages.StrictParamName);
      +                      }
      +                      return parseArrowFunctionExpression([ expr ]);
      +                  }
      +              } else if (expr.type === Syntax.SequenceExpression) {
      +                  if (state.parenthesizedCount === (oldParenthesizedCount + 1)) {
      +                      coverFormalsList = reinterpretAsCoverFormalsList(expr);
      +                      if (coverFormalsList) {
      +                          return parseArrowFunctionExpression(coverFormalsList);
      +                      }
      +                  }
      +              }
      +          }
      +  
      +          if (matchAssign()) {
      +              // 11.13.1
      +              if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
      +                  throwError({}, Messages.StrictLHSAssignment);
      +              }
      +  
      +              // ES.next draf 11.13 Runtime Semantics step 1
      +              if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) {
      +                  reinterpretAsAssignmentBindingPattern(expr);
      +              } else if (!isLeftHandSide(expr)) {
      +                  throwError({}, Messages.InvalidLHSInAssignment);
      +              }
      +  
      +              expr = {
      +                  type: Syntax.AssignmentExpression,
      +                  operator: lex().value,
      +                  left: expr,
      +                  right: parseAssignmentExpression()
      +              };
      +          }
      +  
      +          return expr;
      +      }
      +  
      +      // 11.14 Comma Operator
      +  
      +      function parseExpression() {
      +          var expr = parseAssignmentExpression();
      +  
      +          if (match(',')) {
      +              expr = {
      +                  type: Syntax.SequenceExpression,
      +                  expressions: [ expr ]
      +              };
      +  
      +              while (index < length) {
      +                  if (!match(',')) {
      +                      break;
      +                  }
      +                  lex();
      +                  expr.expressions.push(parseAssignmentExpression());
      +              }
      +  
      +          }
      +          return expr;
      +      }
      +  
      +      // 12.1 Block
      +  
      +      function parseStatementList() {
      +          var list = [],
      +              statement;
      +  
      +          while (index < length) {
      +              if (match('}')) {
      +                  break;
      +              }
      +              statement = parseSourceElement();
      +              if (typeof statement === 'undefined') {
      +                  break;
      +              }
      +              list.push(statement);
      +          }
      +  
      +          return list;
      +      }
      +  
      +      function parseBlock() {
      +          var block;
      +  
      +          expect('{');
      +  
      +          block = parseStatementList();
      +  
      +          expect('}');
      +  
      +          return {
      +              type: Syntax.BlockStatement,
      +              body: block
      +          };
      +      }
      +  
      +      // 12.2 Variable Statement
      +  
      +      function parseVariableIdentifier() {
      +          var token = lex();
      +  
      +          if (token.type !== Token.Identifier) {
      +              throwUnexpected(token);
      +          }
      +  
      +          return {
      +              type: Syntax.Identifier,
      +              name: token.value
      +          };
      +      }
      +  
      +      function parseVariableDeclaration(kind) {
      +          var id = parseVariableIdentifier(),
      +              init = null;
      +  
      +          // 12.2.1
      +          if (strict && isRestrictedWord(id.name)) {
      +              throwErrorTolerant({}, Messages.StrictVarName);
      +          }
      +  
      +          if (kind === 'const') {
      +              expect('=');
      +              init = parseAssignmentExpression();
      +          } else if (match('=')) {
      +              lex();
      +              init = parseAssignmentExpression();
      +          }
      +  
      +          return {
      +              type: Syntax.VariableDeclarator,
      +              id: id,
      +              init: init
      +          };
      +      }
      +  
      +      function parseVariableDeclarationList(kind) {
      +          var list = [];
      +  
      +          while (index < length) {
      +              list.push(parseVariableDeclaration(kind));
      +              if (!match(',')) {
      +                  break;
      +              }
      +              lex();
      +          }
      +  
      +          return list;
      +      }
      +  
      +      function parseVariableStatement() {
      +          var declarations;
      +  
      +          expectKeyword('var');
      +  
      +          declarations = parseVariableDeclarationList();
      +  
      +          consumeSemicolon();
      +  
      +          return {
      +              type: Syntax.VariableDeclaration,
      +              declarations: declarations,
      +              kind: 'var'
      +          };
      +      }
      +  
      +      // kind may be `const` or `let`
      +      // Both are experimental and not in the specification yet.
      +      // see http://wiki.ecmascript.org/doku.php?id=harmony:const
      +      // and http://wiki.ecmascript.org/doku.php?id=harmony:let
      +      function parseConstLetDeclaration(kind) {
      +          var declarations;
      +  
      +          expectKeyword(kind);
      +  
      +          declarations = parseVariableDeclarationList(kind);
      +  
      +          consumeSemicolon();
      +  
      +          return {
      +              type: Syntax.VariableDeclaration,
      +              declarations: declarations,
      +              kind: kind
      +          };
      +      }
      +  
      +      // http://wiki.ecmascript.org/doku.php?id=harmony:modules
      +  
      +      function parsePath() {
      +          var result, id;
      +  
      +          result = {
      +              type: Syntax.Path,
      +              body: []
      +          };
      +  
      +          while (true) {
      +              id = parseVariableIdentifier();
      +              result.body.push(id);
      +              if (!match('.')) {
      +                  break;
      +              }
      +              lex();
      +          }
      +  
      +          return result;
      +      }
      +  
      +      function parseGlob() {
      +          expect('*');
      +          return {
      +              type: Syntax.Glob
      +          };
      +      }
      +  
      +      function parseModuleDeclaration() {
      +          var id, token, declaration;
      +  
      +          token = lex();
      +          if (token.value !== 'module') {
      +              throwUnexpected(token);
      +          }
      +  
      +          id = parseVariableIdentifier();
      +  
      +          if (match('{')) {
      +              return {
      +                  type: Syntax.ModuleDeclaration,
      +                  id: id,
      +                  body: parseModuleBlock()
      +              };
      +          }
      +  
      +          expect('=');
      +  
      +          token = lookahead();
      +          if (token.type === Token.StringLiteral) {
      +              declaration = {
      +                  type: Syntax.ModuleDeclaration,
      +                  id: id,
      +                  from: parsePrimaryExpression()
      +              };
      +          } else {
      +              declaration = {
      +                  type: Syntax.ModuleDeclaration,
      +                  id: id,
      +                  from: parsePath()
      +              };
      +          }
      +  
      +          consumeSemicolon();
      +  
      +          return declaration;
      +      }
      +  
      +      function parseExportSpecifierSetProperty() {
      +          var specifier;
      +  
      +          specifier = {
      +              type: Syntax.ExportSpecifier,
      +              id: parseVariableIdentifier(),
      +              from: null
      +          };
      +  
      +          if (match(':')) {
      +              lex();
      +              specifier.from = parsePath();
      +          }
      +  
      +          return specifier;
      +      }
      +  
      +      function parseExportSpecifier() {
      +          var specifier, specifiers;
      +  
      +          if (match('{')) {
      +              lex();
      +              specifiers = [];
      +  
      +              do {
      +                  specifiers.push(parseExportSpecifierSetProperty());
      +              } while (match(',') && lex());
      +  
      +              expect('}');
      +  
      +              return {
      +                  type: Syntax.ExportSpecifierSet,
      +                  specifiers: specifiers
      +              };
      +          }
      +  
      +          if (match('*')) {
      +              specifier = {
      +                  type: Syntax.ExportSpecifier,
      +                  id: parseGlob(),
      +                  from: null
      +              };
      +  
      +              if (matchContextualKeyword('from')) {
      +                  lex();
      +                  specifier.from = parsePath();
      +              }
      +          } else {
      +              specifier = {
      +                  type: Syntax.ExportSpecifier,
      +                  id: parseVariableIdentifier(),
      +                  from: null
      +              };
      +          }
      +          return specifier;
      +      }
      +  
      +      function parseExportDeclaration() {
      +          var token, specifiers;
      +  
      +          expectKeyword('export');
      +  
      +          token = lookahead();
      +  
      +          if (token.type === Token.Keyword || (token.type === Token.Identifier && token.value === 'module')) {
      +              switch (token.value) {
      +              case 'function':
      +                  return {
      +                      type: Syntax.ExportDeclaration,
      +                      declaration: parseFunctionDeclaration()
      +                  };
      +              case 'module':
      +                  return {
      +                      type: Syntax.ExportDeclaration,
      +                      declaration: parseModuleDeclaration()
      +                  };
      +              case 'let':
      +              case 'const':
      +                  return {
      +                      type: Syntax.ExportDeclaration,
      +                      declaration: parseConstLetDeclaration(token.value)
      +                  };
      +              case 'var':
      +                  return {
      +                      type: Syntax.ExportDeclaration,
      +                      declaration: parseStatement()
      +                  };
      +              }
      +              throwUnexpected(lex());
      +          }
      +  
      +          specifiers = [ parseExportSpecifier() ];
      +          if (match(',')) {
      +              while (index < length) {
      +                  if (!match(',')) {
      +                      break;
      +                  }
      +                  lex();
      +                  specifiers.push(parseExportSpecifier());
      +              }
      +          }
      +  
      +          consumeSemicolon();
      +  
      +          return {
      +              type: Syntax.ExportDeclaration,
      +              specifiers: specifiers
      +          };
      +      }
      +  
      +      function parseImportDeclaration() {
      +          var specifiers, from;
      +  
      +          expectKeyword('import');
      +  
      +          if (match('*')) {
      +              specifiers = [parseGlob()];
      +          } else if (match('{')) {
      +              lex();
      +              specifiers = [];
      +  
      +              do {
      +                  specifiers.push(parseImportSpecifier());
      +              } while (match(',') && lex());
      +  
      +              expect('}');
      +          } else {
      +              specifiers = [parseVariableIdentifier()];
      +          }
      +  
      +          if (!matchContextualKeyword('from')) {
      +              throwError({}, Messages.NoFromAfterImport);
      +          }
      +  
      +          lex();
      +  
      +          if (lookahead().type === Token.StringLiteral) {
      +              from = parsePrimaryExpression();
      +          } else {
      +              from = parsePath();
      +          }
      +  
      +          consumeSemicolon();
      +  
      +          return {
      +              type: Syntax.ImportDeclaration,
      +              specifiers: specifiers,
      +              from: from
      +          };
      +      }
      +  
      +      function parseImportSpecifier() {
      +          var specifier;
      +  
      +          specifier = {
      +              type: Syntax.ImportSpecifier,
      +              id: parseVariableIdentifier(),
      +              from: null
      +          };
      +  
      +          if (match(':')) {
      +              lex();
      +              specifier.from = parsePath();
      +          }
      +  
      +          return specifier;
      +      }
      +  
      +      // 12.3 Empty Statement
      +  
      +      function parseEmptyStatement() {
      +          expect(';');
      +  
      +          return {
      +              type: Syntax.EmptyStatement
      +          };
      +      }
      +  
      +      // 12.4 Expression Statement
      +  
      +      function parseExpressionStatement() {
      +          var expr = parseExpression();
      +  
      +          consumeSemicolon();
      +  
      +          return {
      +              type: Syntax.ExpressionStatement,
      +              expression: expr
      +          };
      +      }
      +  
      +      // 12.5 If statement
      +  
      +      function parseIfStatement() {
      +          var test, consequent, alternate;
      +  
      +          expectKeyword('if');
      +  
      +          expect('(');
      +  
      +          test = parseExpression();
      +  
      +          expect(')');
      +  
      +          consequent = parseStatement();
      +  
      +          if (matchKeyword('else')) {
      +              lex();
      +              alternate = parseStatement();
      +          } else {
      +              alternate = null;
      +          }
      +  
      +          return {
      +              type: Syntax.IfStatement,
      +              test: test,
      +              consequent: consequent,
      +              alternate: alternate
      +          };
      +      }
      +  
      +      // 12.6 Iteration Statements
      +  
      +      function parseDoWhileStatement() {
      +          var body, test, oldInIteration;
      +  
      +          expectKeyword('do');
      +  
      +          oldInIteration = state.inIteration;
      +          state.inIteration = true;
      +  
      +          body = parseStatement();
      +  
      +          state.inIteration = oldInIteration;
      +  
      +          expectKeyword('while');
      +  
      +          expect('(');
      +  
      +          test = parseExpression();
      +  
      +          expect(')');
      +  
      +          if (match(';')) {
      +              lex();
      +          }
      +  
      +          return {
      +              type: Syntax.DoWhileStatement,
      +              body: body,
      +              test: test
      +          };
      +      }
      +  
      +      function parseWhileStatement() {
      +          var test, body, oldInIteration;
      +  
      +          expectKeyword('while');
      +  
      +          expect('(');
      +  
      +          test = parseExpression();
      +  
      +          expect(')');
      +  
      +          oldInIteration = state.inIteration;
      +          state.inIteration = true;
      +  
      +          body = parseStatement();
      +  
      +          state.inIteration = oldInIteration;
      +  
      +          return {
      +              type: Syntax.WhileStatement,
      +              test: test,
      +              body: body
      +          };
      +      }
      +  
      +      function parseForVariableDeclaration() {
      +          var token = lex();
      +  
      +          return {
      +              type: Syntax.VariableDeclaration,
      +              declarations: parseVariableDeclarationList(),
      +              kind: token.value
      +          };
      +      }
      +  
      +      function parseForStatement() {
      +          var init, test, update, left, right, body, operator, oldInIteration;
      +  
      +          init = test = update = null;
      +  
      +          expectKeyword('for');
      +  
      +          expect('(');
      +  
      +          if (match(';')) {
      +              lex();
      +          } else {
      +              if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) {
      +                  state.allowIn = false;
      +                  init = parseForVariableDeclaration();
      +                  state.allowIn = true;
      +  
      +                  if (init.declarations.length === 1) {
      +                      if (matchKeyword('in') || matchContextualKeyword('of')) {
      +                          operator = lookahead();
      +                          if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) {
      +                              lex();
      +                              left = init;
      +                              right = parseExpression();
      +                              init = null;
      +                          }
      +                      }
      +                  }
      +              } else {
      +                  state.allowIn = false;
      +                  init = parseExpression();
      +                  state.allowIn = true;
      +  
      +                  if (matchContextualKeyword('of')) {
      +                      operator = lex();
      +                      left = init;
      +                      right = parseExpression();
      +                      init = null;
      +                  } else if (matchKeyword('in')) {
      +                      // LeftHandSideExpression
      +                      if (!isAssignableLeftHandSide(init)) {
      +                          throwError({}, Messages.InvalidLHSInForIn);
      +                      }
      +                      operator = lex();
      +                      left = init;
      +                      right = parseExpression();
      +                      init = null;
      +                  }
      +              }
      +  
      +              if (typeof left === 'undefined') {
      +                  expect(';');
      +              }
      +          }
      +  
      +          if (typeof left === 'undefined') {
      +  
      +              if (!match(';')) {
      +                  test = parseExpression();
      +              }
      +              expect(';');
      +  
      +              if (!match(')')) {
      +                  update = parseExpression();
      +              }
      +          }
      +  
      +          expect(')');
      +  
      +          oldInIteration = state.inIteration;
      +          state.inIteration = true;
      +  
      +          body = parseStatement();
      +  
      +          state.inIteration = oldInIteration;
      +  
      +          if (typeof left === 'undefined') {
      +              return {
      +                  type: Syntax.ForStatement,
      +                  init: init,
      +                  test: test,
      +                  update: update,
      +                  body: body
      +              };
      +          }
      +  
      +          if (operator.value === 'in') {
      +              return {
      +                  type: Syntax.ForInStatement,
      +                  left: left,
      +                  right: right,
      +                  body: body,
      +                  each: false
      +              };
      +          } else {
      +              return {
      +                  type: Syntax.ForOfStatement,
      +                  left: left,
      +                  right: right,
      +                  body: body
      +              };
      +          }
      +      }
      +  
      +      // 12.7 The continue statement
      +  
      +      function parseContinueStatement() {
      +          var token, label = null;
      +  
      +          expectKeyword('continue');
      +  
      +          // Optimize the most common form: 'continue;'.
      +          if (source[index] === ';') {
      +              lex();
      +  
      +              if (!state.inIteration) {
      +                  throwError({}, Messages.IllegalContinue);
      +              }
      +  
      +              return {
      +                  type: Syntax.ContinueStatement,
      +                  label: null
      +              };
      +          }
      +  
      +          if (peekLineTerminator()) {
      +              if (!state.inIteration) {
      +                  throwError({}, Messages.IllegalContinue);
      +              }
      +  
      +              return {
      +                  type: Syntax.ContinueStatement,
      +                  label: null
      +              };
      +          }
      +  
      +          token = lookahead();
      +          if (token.type === Token.Identifier) {
      +              label = parseVariableIdentifier();
      +  
      +              if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) {
      +                  throwError({}, Messages.UnknownLabel, label.name);
      +              }
      +          }
      +  
      +          consumeSemicolon();
      +  
      +          if (label === null && !state.inIteration) {
      +              throwError({}, Messages.IllegalContinue);
      +          }
      +  
      +          return {
      +              type: Syntax.ContinueStatement,
      +              label: label
      +          };
      +      }
      +  
      +      // 12.8 The break statement
      +  
      +      function parseBreakStatement() {
      +          var token, label = null;
      +  
      +          expectKeyword('break');
      +  
      +          // Optimize the most common form: 'break;'.
      +          if (source[index] === ';') {
      +              lex();
      +  
      +              if (!(state.inIteration || state.inSwitch)) {
      +                  throwError({}, Messages.IllegalBreak);
      +              }
      +  
      +              return {
      +                  type: Syntax.BreakStatement,
      +                  label: null
      +              };
      +          }
      +  
      +          if (peekLineTerminator()) {
      +              if (!(state.inIteration || state.inSwitch)) {
      +                  throwError({}, Messages.IllegalBreak);
      +              }
      +  
      +              return {
      +                  type: Syntax.BreakStatement,
      +                  label: null
      +              };
      +          }
      +  
      +          token = lookahead();
      +          if (token.type === Token.Identifier) {
      +              label = parseVariableIdentifier();
      +  
      +              if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) {
      +                  throwError({}, Messages.UnknownLabel, label.name);
      +              }
      +          }
      +  
      +          consumeSemicolon();
      +  
      +          if (label === null && !(state.inIteration || state.inSwitch)) {
      +              throwError({}, Messages.IllegalBreak);
      +          }
      +  
      +          return {
      +              type: Syntax.BreakStatement,
      +              label: label
      +          };
      +      }
      +  
      +      // 12.9 The return statement
      +  
      +      function parseReturnStatement() {
      +          var token, argument = null;
      +  
      +          expectKeyword('return');
      +  
      +          if (!state.inFunctionBody) {
      +              throwErrorTolerant({}, Messages.IllegalReturn);
      +          }
      +  
      +          // 'return' followed by a space and an identifier is very common.
      +          if (source[index] === ' ') {
      +              if (isIdentifierStart(source[index + 1])) {
      +                  argument = parseExpression();
      +                  consumeSemicolon();
      +                  return {
      +                      type: Syntax.ReturnStatement,
      +                      argument: argument
      +                  };
      +              }
      +          }
      +  
      +          if (peekLineTerminator()) {
      +              return {
      +                  type: Syntax.ReturnStatement,
      +                  argument: null
      +              };
      +          }
      +  
      +          if (!match(';')) {
      +              token = lookahead();
      +              if (!match('}') && token.type !== Token.EOF) {
      +                  argument = parseExpression();
      +              }
      +          }
      +  
      +          consumeSemicolon();
      +  
      +          return {
      +              type: Syntax.ReturnStatement,
      +              argument: argument
      +          };
      +      }
      +  
      +      // 12.10 The with statement
      +  
      +      function parseWithStatement() {
      +          var object, body;
      +  
      +          if (strict) {
      +              throwErrorTolerant({}, Messages.StrictModeWith);
      +          }
      +  
      +          expectKeyword('with');
      +  
      +          expect('(');
      +  
      +          object = parseExpression();
      +  
      +          expect(')');
      +  
      +          body = parseStatement();
      +  
      +          return {
      +              type: Syntax.WithStatement,
      +              object: object,
      +              body: body
      +          };
      +      }
      +  
      +      // 12.10 The swith statement
      +  
      +      function parseSwitchCase() {
      +          var test,
      +              consequent = [],
      +              statement;
      +  
      +          if (matchKeyword('default')) {
      +              lex();
      +              test = null;
      +          } else {
      +              expectKeyword('case');
      +              test = parseExpression();
      +          }
      +          expect(':');
      +  
      +          while (index < length) {
      +              if (match('}') || matchKeyword('default') || matchKeyword('case')) {
      +                  break;
      +              }
      +              statement = parseSourceElement();
      +              if (typeof statement === 'undefined') {
      +                  break;
      +              }
      +              consequent.push(statement);
      +          }
      +  
      +          return {
      +              type: Syntax.SwitchCase,
      +              test: test,
      +              consequent: consequent
      +          };
      +      }
      +  
      +      function parseSwitchStatement() {
      +          var discriminant, cases, clause, oldInSwitch, defaultFound;
      +  
      +          expectKeyword('switch');
      +  
      +          expect('(');
      +  
      +          discriminant = parseExpression();
      +  
      +          expect(')');
      +  
      +          expect('{');
      +  
      +          if (match('}')) {
      +              lex();
      +              return {
      +                  type: Syntax.SwitchStatement,
      +                  discriminant: discriminant
      +              };
      +          }
      +  
      +          cases = [];
      +  
      +          oldInSwitch = state.inSwitch;
      +          state.inSwitch = true;
      +          defaultFound = false;
      +  
      +          while (index < length) {
      +              if (match('}')) {
      +                  break;
      +              }
      +              clause = parseSwitchCase();
      +              if (clause.test === null) {
      +                  if (defaultFound) {
      +                      throwError({}, Messages.MultipleDefaultsInSwitch);
      +                  }
      +                  defaultFound = true;
      +              }
      +              cases.push(clause);
      +          }
      +  
      +          state.inSwitch = oldInSwitch;
      +  
      +          expect('}');
      +  
      +          return {
      +              type: Syntax.SwitchStatement,
      +              discriminant: discriminant,
      +              cases: cases
      +          };
      +      }
      +  
      +      // 12.13 The throw statement
      +  
      +      function parseThrowStatement() {
      +          var argument;
      +  
      +          expectKeyword('throw');
      +  
      +          if (peekLineTerminator()) {
      +              throwError({}, Messages.NewlineAfterThrow);
      +          }
      +  
      +          argument = parseExpression();
      +  
      +          consumeSemicolon();
      +  
      +          return {
      +              type: Syntax.ThrowStatement,
      +              argument: argument
      +          };
      +      }
      +  
      +      // 12.14 The try statement
      +  
      +      function parseCatchClause() {
      +          var param;
      +  
      +          expectKeyword('catch');
      +  
      +          expect('(');
      +          if (!match(')')) {
      +              param = parseExpression();
      +              // 12.14.1
      +              if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) {
      +                  throwErrorTolerant({}, Messages.StrictCatchVariable);
      +              }
      +          }
      +          expect(')');
      +  
      +          return {
      +              type: Syntax.CatchClause,
      +              param: param,
      +              guard: null,
      +              body: parseBlock()
      +          };
      +      }
      +  
      +      function parseTryStatement() {
      +          var block, handlers = [], finalizer = null;
      +  
      +          expectKeyword('try');
      +  
      +          block = parseBlock();
      +  
      +          if (matchKeyword('catch')) {
      +              handlers.push(parseCatchClause());
      +          }
      +  
      +          if (matchKeyword('finally')) {
      +              lex();
      +              finalizer = parseBlock();
      +          }
      +  
      +          if (handlers.length === 0 && !finalizer) {
      +              throwError({}, Messages.NoCatchOrFinally);
      +          }
      +  
      +          return {
      +              type: Syntax.TryStatement,
      +              block: block,
      +              handlers: handlers,
      +              finalizer: finalizer
      +          };
      +      }
      +  
      +      // 12.15 The debugger statement
      +  
      +      function parseDebuggerStatement() {
      +          expectKeyword('debugger');
      +  
      +          consumeSemicolon();
      +  
      +          return {
      +              type: Syntax.DebuggerStatement
      +          };
      +      }
      +  
      +      // 12 Statements
      +  
      +      function parseStatement() {
      +          var token = lookahead(),
      +              expr,
      +              labeledBody;
      +  
      +          if (token.type === Token.EOF) {
      +              throwUnexpected(token);
      +          }
      +  
      +          if (token.type === Token.Punctuator) {
      +              switch (token.value) {
      +              case ';':
      +                  return parseEmptyStatement();
      +              case '{':
      +                  return parseBlock();
      +              case '(':
      +                  return parseExpressionStatement();
      +              default:
      +                  break;
      +              }
      +          }
      +  
      +          if (token.type === Token.Keyword) {
      +              switch (token.value) {
      +              case 'break':
      +                  return parseBreakStatement();
      +              case 'continue':
      +                  return parseContinueStatement();
      +              case 'debugger':
      +                  return parseDebuggerStatement();
      +              case 'do':
      +                  return parseDoWhileStatement();
      +              case 'for':
      +                  return parseForStatement();
      +              case 'function':
      +                  return parseFunctionDeclaration();
      +              case 'class':
      +                  return parseClassDeclaration();
      +              case 'if':
      +                  return parseIfStatement();
      +              case 'return':
      +                  return parseReturnStatement();
      +              case 'switch':
      +                  return parseSwitchStatement();
      +              case 'throw':
      +                  return parseThrowStatement();
      +              case 'try':
      +                  return parseTryStatement();
      +              case 'var':
      +                  return parseVariableStatement();
      +              case 'while':
      +                  return parseWhileStatement();
      +              case 'with':
      +                  return parseWithStatement();
      +              default:
      +                  break;
      +              }
      +          }
      +  
      +          expr = parseExpression();
      +  
      +          // 12.12 Labelled Statements
      +          if ((expr.type === Syntax.Identifier) && match(':')) {
      +              lex();
      +  
      +              if (Object.prototype.hasOwnProperty.call(state.labelSet, expr.name)) {
      +                  throwError({}, Messages.Redeclaration, 'Label', expr.name);
      +              }
      +  
      +              state.labelSet[expr.name] = true;
      +              labeledBody = parseStatement();
      +              delete state.labelSet[expr.name];
      +  
      +              return {
      +                  type: Syntax.LabeledStatement,
      +                  label: expr,
      +                  body: labeledBody
      +              };
      +          }
      +  
      +          consumeSemicolon();
      +  
      +          return {
      +              type: Syntax.ExpressionStatement,
      +              expression: expr
      +          };
      +      }
      +  
      +      // 13 Function Definition
      +  
      +      function parseConciseBody() {
      +          if (match('{')) {
      +              return parseFunctionSourceElements();
      +          } else {
      +              return parseAssignmentExpression();
      +          }
      +      }
      +  
      +      function parseFunctionSourceElements() {
      +          var sourceElement, sourceElements = [], token, directive, firstRestricted,
      +              oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount;
      +  
      +          expect('{');
      +  
      +          while (index < length) {
      +              token = lookahead();
      +              if (token.type !== Token.StringLiteral) {
      +                  break;
      +              }
      +  
      +              sourceElement = parseSourceElement();
      +              sourceElements.push(sourceElement);
      +              if (sourceElement.expression.type !== Syntax.Literal) {
      +                  // this is not directive
      +                  break;
      +              }
      +              directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
      +              if (directive === 'use strict') {
      +                  strict = true;
      +                  if (firstRestricted) {
      +                      throwError(firstRestricted, Messages.StrictOctalLiteral);
      +                  }
      +              } else {
      +                  if (!firstRestricted && token.octal) {
      +                      firstRestricted = token;
      +                  }
      +              }
      +          }
      +  
      +          oldLabelSet = state.labelSet;
      +          oldInIteration = state.inIteration;
      +          oldInSwitch = state.inSwitch;
      +          oldInFunctionBody = state.inFunctionBody;
      +          oldParenthesizedCount = state.parenthesizedCount;
      +  
      +          state.labelSet = {};
      +          state.inIteration = false;
      +          state.inSwitch = false;
      +          state.inFunctionBody = true;
      +          state.parenthesizedCount = 0;
      +  
      +          while (index < length) {
      +              if (match('}')) {
      +                  break;
      +              }
      +              sourceElement = parseSourceElement();
      +              if (typeof sourceElement === 'undefined') {
      +                  break;
      +              }
      +              sourceElements.push(sourceElement);
      +          }
      +  
      +          expect('}');
      +  
      +          state.labelSet = oldLabelSet;
      +          state.inIteration = oldInIteration;
      +          state.inSwitch = oldInSwitch;
      +          state.inFunctionBody = oldInFunctionBody;
      +          state.parenthesizedCount = oldParenthesizedCount;
      +  
      +          return {
      +              type: Syntax.BlockStatement,
      +              body: sourceElements
      +          };
      +      }
      +  
      +      function parseFunctionDeclaration() {
      +          var id, param, params = [], body, token, firstRestricted, message, previousStrict, previousYieldAllowed, paramSet, generator;
      +  
      +          expectKeyword('function');
      +  
      +          generator = false;
      +          if (match('*')) {
      +              lex();
      +              generator = true;
      +          }
      +  
      +          token = lookahead();
      +  
      +          id = parseVariableIdentifier();
      +          if (strict) {
      +              if (isRestrictedWord(token.value)) {
      +                  throwError(token, Messages.StrictFunctionName);
      +              }
      +          } else {
      +              if (isRestrictedWord(token.value)) {
      +                  firstRestricted = token;
      +                  message = Messages.StrictFunctionName;
      +              } else if (isStrictModeReservedWord(token.value)) {
      +                  firstRestricted = token;
      +                  message = Messages.StrictReservedWord;
      +              }
      +          }
      +  
      +          expect('(');
      +  
      +          if (!match(')')) {
      +              paramSet = {};
      +              while (index < length) {
      +                  token = lookahead();
      +                  param = parseVariableIdentifier();
      +                  if (strict) {
      +                      if (isRestrictedWord(token.value)) {
      +                          throwError(token, Messages.StrictParamName);
      +                      }
      +                      if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
      +                          throwError(token, Messages.StrictParamDupe);
      +                      }
      +                  } else if (!firstRestricted) {
      +                      if (isRestrictedWord(token.value)) {
      +                          firstRestricted = token;
      +                          message = Messages.StrictParamName;
      +                      } else if (isStrictModeReservedWord(token.value)) {
      +                          firstRestricted = token;
      +                          message = Messages.StrictReservedWord;
      +                      } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
      +                          firstRestricted = token;
      +                          message = Messages.StrictParamDupe;
      +                      }
      +                  }
      +                  params.push(param);
      +                  paramSet[param.name] = true;
      +                  if (match(')')) {
      +                      break;
      +                  }
      +                  expect(',');
      +              }
      +          }
      +  
      +          expect(')');
      +  
      +          previousStrict = strict;
      +          previousYieldAllowed = yieldAllowed;
      +          yieldAllowed = generator;
      +          body = parseFunctionSourceElements();
      +          if (strict && firstRestricted) {
      +              throwError(firstRestricted, message);
      +          }
      +          if (yieldAllowed && !yieldFound) {
      +              throwError({}, Messages.NoYieldInGenerator);
      +          }
      +          strict = previousStrict;
      +          yieldAllowed = previousYieldAllowed;
      +  
      +          return {
      +              type: Syntax.FunctionDeclaration,
      +              id: id,
      +              params: params,
      +              body: body,
      +              generator: generator
      +          };
      +      }
      +  
      +      function parseFunctionExpression() {
      +          var token, id = null, firstRestricted, message, param, params = [], body, previousStrict, previousYieldAllowed, paramSet, generator;
      +  
      +          expectKeyword('function');
      +  
      +          generator = false;
      +  
      +          if (match('*')) {
      +              lex();
      +              generator = true;
      +          }
      +  
      +          if (!match('(')) {
      +              token = lookahead();
      +              id = parseVariableIdentifier();
      +              if (strict) {
      +                  if (isRestrictedWord(token.value)) {
      +                      throwError(token, Messages.StrictFunctionName);
      +                  }
      +              } else {
      +                  if (isRestrictedWord(token.value)) {
      +                      firstRestricted = token;
      +                      message = Messages.StrictFunctionName;
      +                  } else if (isStrictModeReservedWord(token.value)) {
      +                      firstRestricted = token;
      +                      message = Messages.StrictReservedWord;
      +                  }
      +              }
      +          }
      +  
      +          expect('(');
      +  
      +          if (!match(')')) {
      +              paramSet = {};
      +              while (index < length) {
      +                  token = lookahead();
      +                  param = parseVariableIdentifier();
      +                  if (strict) {
      +                      if (isRestrictedWord(token.value)) {
      +                          throwError(token, Messages.StrictParamName);
      +                      }
      +                      if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
      +                          throwError(token, Messages.StrictParamDupe);
      +                      }
      +                  } else if (!firstRestricted) {
      +                      if (isRestrictedWord(token.value)) {
      +                          firstRestricted = token;
      +                          message = Messages.StrictParamName;
      +                      } else if (isStrictModeReservedWord(token.value)) {
      +                          firstRestricted = token;
      +                          message = Messages.StrictReservedWord;
      +                      } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
      +                          firstRestricted = token;
      +                          message = Messages.StrictParamDupe;
      +                      }
      +                  }
      +                  params.push(param);
      +                  paramSet[param.name] = true;
      +                  if (match(')')) {
      +                      break;
      +                  }
      +                  expect(',');
      +              }
      +          }
      +  
      +          expect(')');
      +  
      +          previousStrict = strict;
      +          previousYieldAllowed = yieldAllowed;
      +          yieldAllowed = generator;
      +          body = parseFunctionSourceElements();
      +          if (strict && firstRestricted) {
      +              throwError(firstRestricted, message);
      +          }
      +          if (yieldAllowed && !yieldFound) {
      +              throwError({}, Messages.NoYieldInGenerator);
      +          }
      +          strict = previousStrict;
      +          yieldAllowed = previousYieldAllowed;
      +  
      +  
      +          return {
      +              type: Syntax.FunctionExpression,
      +              id: id,
      +              params: params,
      +              body: body,
      +              generator: generator
      +          };
      +      }
      +  
      +      function parseYieldExpression() {
      +          var delegate, expr, previousYieldAllowed;
      +  
      +          expectKeyword('yield');
      +  
      +          if (!yieldAllowed) {
      +              throwErrorTolerant({}, Messages.IllegalYield);
      +          }
      +  
      +          delegate = false;
      +          if (match('*')) {
      +              lex();
      +              delegate = true;
      +          }
      +  
      +          // It is a Syntax Error if any AssignmentExpression Contains YieldExpression.
      +          previousYieldAllowed = yieldAllowed;
      +          yieldAllowed = false;
      +          expr = parseAssignmentExpression();
      +          yieldAllowed = previousYieldAllowed;
      +          yieldFound = true;
      +  
      +          return {
      +              type: Syntax.YieldExpression,
      +              argument: expr,
      +              delegate: delegate
      +          };
      +      }
      +  
      +      // 14 Classes
      +  
      +      function parseMethodDefinition() {
      +          var token, key, param;
      +  
      +          if (match('*')) {
      +              lex();
      +              return {
      +                  type: Syntax.MethodDefinition,
      +                  key: parseObjectPropertyKey(),
      +                  value: parsePropertyMethodFunction({ generator: true }),
      +                  kind: ''
      +              };
      +          }
      +  
      +          token = lookahead();
      +          key = parseObjectPropertyKey();
      +  
      +          if (token.value === 'get' && !match('(')) {
      +              key = parseObjectPropertyKey();
      +              expect('(');
      +              expect(')');
      +              return {
      +                  type: Syntax.MethodDefinition,
      +                  key: key,
      +                  value: parsePropertyFunction([], { generator: false }),
      +                  kind: 'get'
      +              };
      +          } else if (token.value === 'set' && !match('(')) {
      +              key = parseObjectPropertyKey();
      +              expect('(');
      +              token = lookahead();
      +              param = [ parseVariableIdentifier() ];
      +              expect(')');
      +              return {
      +                  type: Syntax.MethodDefinition,
      +                  key: key,
      +                  value: parsePropertyFunction(param, { generator: false, name: token }),
      +                  kind: 'set'
      +              };
      +          } else {
      +              return {
      +                  type: Syntax.MethodDefinition,
      +                  key: key,
      +                  value: parsePropertyMethodFunction({ generator: false }),
      +                  kind: ''
      +              };
      +          }
      +      }
      +  
      +      function parseClassElement() {
      +          if (match(';')) {
      +              lex();
      +              return;
      +          } else {
      +              return parseMethodDefinition();
      +          }
      +      }
      +  
      +      function parseClassBody() {
      +          var classElement, classElements = [];
      +  
      +          expect('{');
      +  
      +          while (index < length) {
      +              if (match('}')) {
      +                  break;
      +              }
      +              classElement = parseClassElement();
      +              if (typeof classElement !== 'undefined') {
      +                  classElements.push(classElement);
      +              }
      +          }
      +  
      +          expect('}');
      +  
      +          return {
      +              type: Syntax.ClassBody,
      +              body: classElements
      +          };
      +      }
      +  
      +      function parseClassExpression() {
      +          var id, body, previousYieldAllowed, superClass;
      +  
      +          expectKeyword('class');
      +  
      +          if (!matchKeyword('extends') && !match('{')) {
      +              id = parseVariableIdentifier();
      +          }
      +  
      +          if (matchKeyword('extends')) {
      +              expectKeyword('extends');
      +              previousYieldAllowed = yieldAllowed;
      +              yieldAllowed = false;
      +              superClass = parseAssignmentExpression();
      +              yieldAllowed = previousYieldAllowed;
      +          }
      +  
      +          body = parseClassBody();
      +          return {
      +              id: id,
      +              type: Syntax.ClassExpression,
      +              body: body,
      +              superClass: superClass
      +          };
      +      }
      +  
      +      function parseClassDeclaration() {
      +          var token, id, body, previousYieldAllowed, superClass;
      +  
      +          expectKeyword('class');
      +  
      +          token = lookahead();
      +          id = parseVariableIdentifier();
      +  
      +          if (matchKeyword('extends')) {
      +              expectKeyword('extends');
      +              previousYieldAllowed = yieldAllowed;
      +              yieldAllowed = false;
      +              superClass = parseAssignmentExpression();
      +              yieldAllowed = previousYieldAllowed;
      +          }
      +  
      +          body = parseClassBody();
      +          return {
      +              id: id,
      +              type: Syntax.ClassDeclaration,
      +              body: body,
      +              superClass: superClass
      +          };
      +      }
      +  
      +      // 15 Program
      +  
      +      function parseSourceElement() {
      +          var token = lookahead();
      +  
      +          if (token.type === Token.Keyword) {
      +              switch (token.value) {
      +              case 'const':
      +              case 'let':
      +                  return parseConstLetDeclaration(token.value);
      +              case 'function':
      +                  return parseFunctionDeclaration();
      +              default:
      +                  return parseStatement();
      +              }
      +          }
      +  
      +          if (token.type !== Token.EOF) {
      +              return parseStatement();
      +          }
      +      }
      +  
      +      function parseProgramElement() {
      +          var token = lookahead(), lineNumber;
      +  
      +          if (token.type === Token.Keyword) {
      +              switch (token.value) {
      +              case 'export':
      +                  return parseExportDeclaration();
      +              case 'import':
      +                  return parseImportDeclaration();
      +              }
      +          }
      +  
      +          if (token.value === 'module' && token.type === Token.Identifier) {
      +              lineNumber = token.lineNumber;
      +              token = lookahead2();
      +              if (token.type === Token.Identifier && token.lineNumber === lineNumber) {
      +                  return parseModuleDeclaration();
      +              }
      +          }
      +  
      +          return parseSourceElement();
      +      }
      +  
      +      function parseProgramElements() {
      +          var sourceElement, sourceElements = [], token, directive, firstRestricted;
      +  
      +          while (index < length) {
      +              token = lookahead();
      +              if (token.type !== Token.StringLiteral) {
      +                  break;
      +              }
      +  
      +              sourceElement = parseProgramElement();
      +              sourceElements.push(sourceElement);
      +              if (sourceElement.expression.type !== Syntax.Literal) {
      +                  // this is not directive
      +                  break;
      +              }
      +              directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
      +              if (directive === 'use strict') {
      +                  strict = true;
      +                  if (firstRestricted) {
      +                      throwError(firstRestricted, Messages.StrictOctalLiteral);
      +                  }
      +              } else {
      +                  if (!firstRestricted && token.octal) {
      +                      firstRestricted = token;
      +                  }
      +              }
      +          }
      +  
      +          while (index < length) {
      +              sourceElement = parseProgramElement();
      +              if (typeof sourceElement === 'undefined') {
      +                  break;
      +              }
      +              sourceElements.push(sourceElement);
      +          }
      +          return sourceElements;
      +      }
      +  
      +      function parseModuleElement() {
      +          return parseProgramElement();
      +      }
      +  
      +      function parseModuleElements() {
      +          var list = [],
      +              statement;
      +  
      +          while (index < length) {
      +              if (match('}')) {
      +                  break;
      +              }
      +              statement = parseModuleElement();
      +              if (typeof statement === 'undefined') {
      +                  break;
      +              }
      +              list.push(statement);
      +          }
      +  
      +          return list;
      +      }
      +  
      +      function parseModuleBlock() {
      +          var block;
      +  
      +          expect('{');
      +  
      +          block = parseModuleElements();
      +  
      +          expect('}');
      +  
      +          return {
      +              type: Syntax.BlockStatement,
      +              body: block
      +          };
      +      }
      +  
      +      function parseProgram() {
      +          var program;
      +          strict = false;
      +          yieldAllowed = false;
      +          yieldFound = false;
      +          program = {
      +              type: Syntax.Program,
      +              body: parseProgramElements()
      +          };
      +          return program;
      +      }
      +  
      +      // The following functions are needed only when the option to preserve
      +      // the comments is active.
      +  
      +      function addComment(type, value, start, end, loc) {
      +          assert(typeof start === 'number', 'Comment must have valid position');
      +  
      +          // Because the way the actual token is scanned, often the comments
      +          // (if any) are skipped twice during the lexical analysis.
      +          // Thus, we need to skip adding a comment if the comment array already
      +          // handled it.
      +          if (extra.comments.length > 0) {
      +              if (extra.comments[extra.comments.length - 1].range[1] > start) {
      +                  return;
      +              }
      +          }
      +  
      +          extra.comments.push({
      +              type: type,
      +              value: value,
      +              range: [start, end],
      +              loc: loc
      +          });
      +      }
      +  
      +      function scanComment() {
      +          var comment, ch, loc, start, blockComment, lineComment;
      +  
      +          comment = '';
      +          blockComment = false;
      +          lineComment = false;
      +  
      +          while (index < length) {
      +              ch = source[index];
      +  
      +              if (lineComment) {
      +                  ch = nextChar();
      +                  if (isLineTerminator(ch)) {
      +                      loc.end = {
      +                          line: lineNumber,
      +                          column: index - lineStart - 1
      +                      };
      +                      lineComment = false;
      +                      addComment('Line', comment, start, index - 1, loc);
      +                      if (ch === '\r' && source[index] === '\n') {
      +                          ++index;
      +                      }
      +                      ++lineNumber;
      +                      lineStart = index;
      +                      comment = '';
      +                  } else if (index >= length) {
      +                      lineComment = false;
      +                      comment += ch;
      +                      loc.end = {
      +                          line: lineNumber,
      +                          column: length - lineStart
      +                      };
      +                      addComment('Line', comment, start, length, loc);
      +                  } else {
      +                      comment += ch;
      +                  }
      +              } else if (blockComment) {
      +                  if (isLineTerminator(ch)) {
      +                      if (ch === '\r' && source[index + 1] === '\n') {
      +                          ++index;
      +                          comment += '\r\n';
      +                      } else {
      +                          comment += ch;
      +                      }
      +                      ++lineNumber;
      +                      ++index;
      +                      lineStart = index;
      +                      if (index >= length) {
      +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                      }
      +                  } else {
      +                      ch = nextChar();
      +                      if (index >= length) {
      +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                      }
      +                      comment += ch;
      +                      if (ch === '*') {
      +                          ch = source[index];
      +                          if (ch === '/') {
      +                              comment = comment.substr(0, comment.length - 1);
      +                              blockComment = false;
      +                              ++index;
      +                              loc.end = {
      +                                  line: lineNumber,
      +                                  column: index - lineStart
      +                              };
      +                              addComment('Block', comment, start, index, loc);
      +                              comment = '';
      +                          }
      +                      }
      +                  }
      +              } else if (ch === '/') {
      +                  ch = source[index + 1];
      +                  if (ch === '/') {
      +                      loc = {
      +                          start: {
      +                              line: lineNumber,
      +                              column: index - lineStart
      +                          }
      +                      };
      +                      start = index;
      +                      index += 2;
      +                      lineComment = true;
      +                      if (index >= length) {
      +                          loc.end = {
      +                              line: lineNumber,
      +                              column: index - lineStart
      +                          };
      +                          lineComment = false;
      +                          addComment('Line', comment, start, index, loc);
      +                      }
      +                  } else if (ch === '*') {
      +                      start = index;
      +                      index += 2;
      +                      blockComment = true;
      +                      loc = {
      +                          start: {
      +                              line: lineNumber,
      +                              column: index - lineStart - 2
      +                          }
      +                      };
      +                      if (index >= length) {
      +                          throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
      +                      }
      +                  } else {
      +                      break;
      +                  }
      +              } else if (isWhiteSpace(ch)) {
      +                  ++index;
      +              } else if (isLineTerminator(ch)) {
      +                  ++index;
      +                  if (ch ===  '\r' && source[index] === '\n') {
      +                      ++index;
      +                  }
      +                  ++lineNumber;
      +                  lineStart = index;
      +              } else {
      +                  break;
      +              }
      +          }
      +      }
      +  
      +      function filterCommentLocation() {
      +          var i, entry, comment, comments = [];
      +  
      +          for (i = 0; i < extra.comments.length; ++i) {
      +              entry = extra.comments[i];
      +              comment = {
      +                  type: entry.type,
      +                  value: entry.value
      +              };
      +              if (extra.range) {
      +                  comment.range = entry.range;
      +              }
      +              if (extra.loc) {
      +                  comment.loc = entry.loc;
      +              }
      +              comments.push(comment);
      +          }
      +  
      +          extra.comments = comments;
      +      }
      +  
      +      function collectToken() {
      +          var start, loc, token, range, value;
      +  
      +          skipComment();
      +          start = index;
      +          loc = {
      +              start: {
      +                  line: lineNumber,
      +                  column: index - lineStart
      +              }
      +          };
      +  
      +          token = extra.advance();
      +          loc.end = {
      +              line: lineNumber,
      +              column: index - lineStart
      +          };
      +  
      +          if (token.type !== Token.EOF) {
      +              range = [token.range[0], token.range[1]];
      +              value = sliceSource(token.range[0], token.range[1]);
      +              extra.tokens.push({
      +                  type: TokenName[token.type],
      +                  value: value,
      +                  range: range,
      +                  loc: loc
      +              });
      +          }
      +  
      +          return token;
      +      }
      +  
      +      function collectRegex() {
      +          var pos, loc, regex, token;
      +  
      +          skipComment();
      +  
      +          pos = index;
      +          loc = {
      +              start: {
      +                  line: lineNumber,
      +                  column: index - lineStart
      +              }
      +          };
      +  
      +          regex = extra.scanRegExp();
      +          loc.end = {
      +              line: lineNumber,
      +              column: index - lineStart
      +          };
      +  
      +          // Pop the previous token, which is likely '/' or '/='
      +          if (extra.tokens.length > 0) {
      +              token = extra.tokens[extra.tokens.length - 1];
      +              if (token.range[0] === pos && token.type === 'Punctuator') {
      +                  if (token.value === '/' || token.value === '/=') {
      +                      extra.tokens.pop();
      +                  }
      +              }
      +          }
      +  
      +          extra.tokens.push({
      +              type: 'RegularExpression',
      +              value: regex.literal,
      +              range: [pos, index],
      +              loc: loc
      +          });
      +  
      +          return regex;
      +      }
      +  
      +      function filterTokenLocation() {
      +          var i, entry, token, tokens = [];
      +  
      +          for (i = 0; i < extra.tokens.length; ++i) {
      +              entry = extra.tokens[i];
      +              token = {
      +                  type: entry.type,
      +                  value: entry.value
      +              };
      +              if (extra.range) {
      +                  token.range = entry.range;
      +              }
      +              if (extra.loc) {
      +                  token.loc = entry.loc;
      +              }
      +              tokens.push(token);
      +          }
      +  
      +          extra.tokens = tokens;
      +      }
      +  
      +      function createLiteral(token) {
      +          return {
      +              type: Syntax.Literal,
      +              value: token.value
      +          };
      +      }
      +  
      +      function createRawLiteral(token) {
      +          return {
      +              type: Syntax.Literal,
      +              value: token.value,
      +              raw: sliceSource(token.range[0], token.range[1])
      +          };
      +      }
      +  
      +      function wrapTrackingFunction(range, loc) {
      +  
      +          return function (parseFunction) {
      +  
      +              function isBinary(node) {
      +                  return node.type === Syntax.LogicalExpression ||
      +                      node.type === Syntax.BinaryExpression;
      +              }
      +  
      +              function visit(node) {
      +                  if (isBinary(node.left)) {
      +                      visit(node.left);
      +                  }
      +                  if (isBinary(node.right)) {
      +                      visit(node.right);
      +                  }
      +  
      +                  if (range && typeof node.range === 'undefined') {
      +                      node.range = [node.left.range[0], node.right.range[1]];
      +                  }
      +                  if (loc && typeof node.loc === 'undefined') {
      +                      node.loc = {
      +                          start: node.left.loc.start,
      +                          end: node.right.loc.end
      +                      };
      +                  }
      +              }
      +  
      +              return function () {
      +                  var node, rangeInfo, locInfo;
      +  
      +                  skipComment();
      +                  rangeInfo = [index, 0];
      +                  locInfo = {
      +                      start: {
      +                          line: lineNumber,
      +                          column: index - lineStart
      +                      }
      +                  };
      +  
      +                  node = parseFunction.apply(null, arguments);
      +                  if (typeof node !== 'undefined') {
      +  
      +                      if (range) {
      +                          rangeInfo[1] = index;
      +                          node.range = rangeInfo;
      +                      }
      +  
      +                      if (loc) {
      +                          locInfo.end = {
      +                              line: lineNumber,
      +                              column: index - lineStart
      +                          };
      +                          node.loc = locInfo;
      +                      }
      +  
      +                      if (isBinary(node)) {
      +                          visit(node);
      +                      }
      +  
      +                      if (node.type === Syntax.MemberExpression) {
      +                          if (typeof node.object.range !== 'undefined') {
      +                              node.range[0] = node.object.range[0];
      +                          }
      +                          if (typeof node.object.loc !== 'undefined') {
      +                              node.loc.start = node.object.loc.start;
      +                          }
      +                      }
      +  
      +                      if (node.type === Syntax.CallExpression) {
      +                          if (typeof node.callee.range !== 'undefined') {
      +                              node.range[0] = node.callee.range[0];
      +                          }
      +                          if (typeof node.callee.loc !== 'undefined') {
      +                              node.loc.start = node.callee.loc.start;
      +                          }
      +                      }
      +                      return node;
      +                  }
      +              };
      +  
      +          };
      +      }
      +  
      +      function patch() {
      +  
      +          var wrapTracking;
      +  
      +          if (extra.comments) {
      +              extra.skipComment = skipComment;
      +              skipComment = scanComment;
      +          }
      +  
      +          if (extra.raw) {
      +              extra.createLiteral = createLiteral;
      +              createLiteral = createRawLiteral;
      +          }
      +  
      +          if (extra.range || extra.loc) {
      +  
      +              wrapTracking = wrapTrackingFunction(extra.range, extra.loc);
      +  
      +              extra.parseAdditiveExpression = parseAdditiveExpression;
      +              extra.parseAssignmentExpression = parseAssignmentExpression;
      +              extra.parseBitwiseANDExpression = parseBitwiseANDExpression;
      +              extra.parseBitwiseORExpression = parseBitwiseORExpression;
      +              extra.parseBitwiseXORExpression = parseBitwiseXORExpression;
      +              extra.parseBlock = parseBlock;
      +              extra.parseFunctionSourceElements = parseFunctionSourceElements;
      +              extra.parseCallMember = parseCallMember;
      +              extra.parseCatchClause = parseCatchClause;
      +              extra.parseComputedMember = parseComputedMember;
      +              extra.parseConditionalExpression = parseConditionalExpression;
      +              extra.parseConstLetDeclaration = parseConstLetDeclaration;
      +              extra.parseEqualityExpression = parseEqualityExpression;
      +              extra.parseExportDeclaration = parseExportDeclaration;
      +              extra.parseExportSpecifier = parseExportSpecifier;
      +              extra.parseExportSpecifierSetProperty = parseExportSpecifierSetProperty;
      +              extra.parseExpression = parseExpression;
      +              extra.parseForVariableDeclaration = parseForVariableDeclaration;
      +              extra.parseFunctionDeclaration = parseFunctionDeclaration;
      +              extra.parseFunctionExpression = parseFunctionExpression;
      +              extra.parseGlob = parseGlob;
      +              extra.parseImportDeclaration = parseImportDeclaration;
      +              extra.parseImportSpecifier = parseImportSpecifier;
      +              extra.parseLogicalANDExpression = parseLogicalANDExpression;
      +              extra.parseLogicalORExpression = parseLogicalORExpression;
      +              extra.parseMultiplicativeExpression = parseMultiplicativeExpression;
      +              extra.parseModuleDeclaration = parseModuleDeclaration;
      +              extra.parseModuleBlock = parseModuleBlock;
      +              extra.parseNewExpression = parseNewExpression;
      +              extra.parseNonComputedMember = parseNonComputedMember;
      +              extra.parseNonComputedProperty = parseNonComputedProperty;
      +              extra.parseObjectProperty = parseObjectProperty;
      +              extra.parseObjectPropertyKey = parseObjectPropertyKey;
      +              extra.parsePath = parsePath;
      +              extra.parsePostfixExpression = parsePostfixExpression;
      +              extra.parsePrimaryExpression = parsePrimaryExpression;
      +              extra.parseProgram = parseProgram;
      +              extra.parsePropertyFunction = parsePropertyFunction;
      +              extra.parseRelationalExpression = parseRelationalExpression;
      +              extra.parseStatement = parseStatement;
      +              extra.parseShiftExpression = parseShiftExpression;
      +              extra.parseSwitchCase = parseSwitchCase;
      +              extra.parseUnaryExpression = parseUnaryExpression;
      +              extra.parseVariableDeclaration = parseVariableDeclaration;
      +              extra.parseVariableIdentifier = parseVariableIdentifier;
      +              extra.parseMethodDefinition = parseMethodDefinition;
      +              extra.parseClassDeclaration = parseClassDeclaration;
      +              extra.parseClassExpression = parseClassExpression;
      +              extra.parseClassBody = parseClassBody;
      +  
      +              parseAdditiveExpression = wrapTracking(extra.parseAdditiveExpression);
      +              parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression);
      +              parseBitwiseANDExpression = wrapTracking(extra.parseBitwiseANDExpression);
      +              parseBitwiseORExpression = wrapTracking(extra.parseBitwiseORExpression);
      +              parseBitwiseXORExpression = wrapTracking(extra.parseBitwiseXORExpression);
      +              parseBlock = wrapTracking(extra.parseBlock);
      +              parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements);
      +              parseCallMember = wrapTracking(extra.parseCallMember);
      +              parseCatchClause = wrapTracking(extra.parseCatchClause);
      +              parseComputedMember = wrapTracking(extra.parseComputedMember);
      +              parseConditionalExpression = wrapTracking(extra.parseConditionalExpression);
      +              parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration);
      +              parseExportDeclaration = wrapTracking(parseExportDeclaration);
      +              parseExportSpecifier = wrapTracking(parseExportSpecifier);
      +              parseExportSpecifierSetProperty = wrapTracking(parseExportSpecifierSetProperty);
      +              parseEqualityExpression = wrapTracking(extra.parseEqualityExpression);
      +              parseExpression = wrapTracking(extra.parseExpression);
      +              parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration);
      +              parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration);
      +              parseFunctionExpression = wrapTracking(extra.parseFunctionExpression);
      +              parseGlob = wrapTracking(extra.parseGlob);
      +              parseImportDeclaration = wrapTracking(extra.parseImportDeclaration);
      +              parseImportSpecifier = wrapTracking(extra.parseImportSpecifier);
      +              parseLogicalANDExpression = wrapTracking(extra.parseLogicalANDExpression);
      +              parseLogicalORExpression = wrapTracking(extra.parseLogicalORExpression);
      +              parseMultiplicativeExpression = wrapTracking(extra.parseMultiplicativeExpression);
      +              parseModuleDeclaration = wrapTracking(extra.parseModuleDeclaration);
      +              parseModuleBlock = wrapTracking(extra.parseModuleBlock);
      +              parseNewExpression = wrapTracking(extra.parseNewExpression);
      +              parseNonComputedMember = wrapTracking(extra.parseNonComputedMember);
      +              parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty);
      +              parseObjectProperty = wrapTracking(extra.parseObjectProperty);
      +              parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey);
      +              parsePath = wrapTracking(extra.parsePath);
      +              parsePostfixExpression = wrapTracking(extra.parsePostfixExpression);
      +              parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression);
      +              parseProgram = wrapTracking(extra.parseProgram);
      +              parsePropertyFunction = wrapTracking(extra.parsePropertyFunction);
      +              parseRelationalExpression = wrapTracking(extra.parseRelationalExpression);
      +              parseStatement = wrapTracking(extra.parseStatement);
      +              parseShiftExpression = wrapTracking(extra.parseShiftExpression);
      +              parseSwitchCase = wrapTracking(extra.parseSwitchCase);
      +              parseUnaryExpression = wrapTracking(extra.parseUnaryExpression);
      +              parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration);
      +              parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier);
      +              parseMethodDefinition = wrapTracking(extra.parseMethodDefinition);
      +              parseClassDeclaration = wrapTracking(extra.parseClassDeclaration);
      +              parseClassExpression = wrapTracking(extra.parseClassExpression);
      +              parseClassBody = wrapTracking(extra.parseClassBody);
      +          }
      +  
      +          if (typeof extra.tokens !== 'undefined') {
      +              extra.advance = advance;
      +              extra.scanRegExp = scanRegExp;
      +  
      +              advance = collectToken;
      +              scanRegExp = collectRegex;
      +          }
      +      }
      +  
      +      function unpatch() {
      +          if (typeof extra.skipComment === 'function') {
      +              skipComment = extra.skipComment;
      +          }
      +  
      +          if (extra.raw) {
      +              createLiteral = extra.createLiteral;
      +          }
      +  
      +          if (extra.range || extra.loc) {
      +              parseAdditiveExpression = extra.parseAdditiveExpression;
      +              parseAssignmentExpression = extra.parseAssignmentExpression;
      +              parseBitwiseANDExpression = extra.parseBitwiseANDExpression;
      +              parseBitwiseORExpression = extra.parseBitwiseORExpression;
      +              parseBitwiseXORExpression = extra.parseBitwiseXORExpression;
      +              parseBlock = extra.parseBlock;
      +              parseFunctionSourceElements = extra.parseFunctionSourceElements;
      +              parseCallMember = extra.parseCallMember;
      +              parseCatchClause = extra.parseCatchClause;
      +              parseComputedMember = extra.parseComputedMember;
      +              parseConditionalExpression = extra.parseConditionalExpression;
      +              parseConstLetDeclaration = extra.parseConstLetDeclaration;
      +              parseEqualityExpression = extra.parseEqualityExpression;
      +              parseExportDeclaration = extra.parseExportDeclaration;
      +              parseExportSpecifier = extra.parseExportSpecifier;
      +              parseExportSpecifierSetProperty = extra.parseExportSpecifierSetProperty;
      +              parseExpression = extra.parseExpression;
      +              parseForVariableDeclaration = extra.parseForVariableDeclaration;
      +              parseFunctionDeclaration = extra.parseFunctionDeclaration;
      +              parseFunctionExpression = extra.parseFunctionExpression;
      +              parseGlob = extra.parseGlob;
      +              parseImportDeclaration = extra.parseImportDeclaration;
      +              parseImportSpecifier = extra.parseImportSpecifier;
      +              parseLogicalANDExpression = extra.parseLogicalANDExpression;
      +              parseLogicalORExpression = extra.parseLogicalORExpression;
      +              parseMultiplicativeExpression = extra.parseMultiplicativeExpression;
      +              parseModuleDeclaration = extra.parseModuleDeclaration;
      +              parseModuleBlock = extra.parseModuleBlock;
      +              parseNewExpression = extra.parseNewExpression;
      +              parseNonComputedMember = extra.parseNonComputedMember;
      +              parseNonComputedProperty = extra.parseNonComputedProperty;
      +              parseObjectProperty = extra.parseObjectProperty;
      +              parseObjectPropertyKey = extra.parseObjectPropertyKey;
      +              parsePath = extra.parsePath;
      +              parsePostfixExpression = extra.parsePostfixExpression;
      +              parsePrimaryExpression = extra.parsePrimaryExpression;
      +              parseProgram = extra.parseProgram;
      +              parsePropertyFunction = extra.parsePropertyFunction;
      +              parseRelationalExpression = extra.parseRelationalExpression;
      +              parseStatement = extra.parseStatement;
      +              parseShiftExpression = extra.parseShiftExpression;
      +              parseSwitchCase = extra.parseSwitchCase;
      +              parseUnaryExpression = extra.parseUnaryExpression;
      +              parseVariableDeclaration = extra.parseVariableDeclaration;
      +              parseVariableIdentifier = extra.parseVariableIdentifier;
      +              parseMethodDefinition = extra.parseMethodDefinition;
      +              parseClassDeclaration = extra.parseClassDeclaration;
      +              parseClassExpression = extra.parseClassExpression;
      +              parseClassBody = extra.parseClassBody;
      +          }
      +  
      +          if (typeof extra.scanRegExp === 'function') {
      +              advance = extra.advance;
      +              scanRegExp = extra.scanRegExp;
      +          }
      +      }
      +  
      +      function stringToArray(str) {
      +          var length = str.length,
      +              result = [],
      +              i;
      +          for (i = 0; i < length; ++i) {
      +              result[i] = str.charAt(i);
      +          }
      +          return result;
      +      }
      +  
      +      function parse(code, options) {
      +          var program, toString;
      +  
      +          toString = String;
      +          if (typeof code !== 'string' && !(code instanceof String)) {
      +              code = toString(code);
      +          }
      +  
      +          source = code;
      +          index = 0;
      +          lineNumber = (source.length > 0) ? 1 : 0;
      +          lineStart = 0;
      +          length = source.length;
      +          buffer = null;
      +          state = {
      +              allowIn: true,
      +              labelSet: {},
      +              parenthesizedCount: 0,
      +              lastParenthesized: null,
      +              inFunctionBody: false,
      +              inIteration: false,
      +              inSwitch: false
      +          };
      +  
      +          extra = {};
      +          if (typeof options !== 'undefined') {
      +              extra.range = (typeof options.range === 'boolean') && options.range;
      +              extra.loc = (typeof options.loc === 'boolean') && options.loc;
      +              extra.raw = (typeof options.raw === 'boolean') && options.raw;
      +              if (typeof options.tokens === 'boolean' && options.tokens) {
      +                  extra.tokens = [];
      +              }
      +              if (typeof options.comment === 'boolean' && options.comment) {
      +                  extra.comments = [];
      +              }
      +              if (typeof options.tolerant === 'boolean' && options.tolerant) {
      +                  extra.errors = [];
      +              }
      +          }
      +  
      +          if (length > 0) {
      +              if (typeof source[0] === 'undefined') {
      +                  // Try first to convert to a string. This is good as fast path
      +                  // for old IE which understands string indexing for string
      +                  // literals only and not for string object.
      +                  if (code instanceof String) {
      +                      source = code.valueOf();
      +                  }
      +  
      +                  // Force accessing the characters via an array.
      +                  if (typeof source[0] === 'undefined') {
      +                      source = stringToArray(code);
      +                  }
      +              }
      +          }
      +  
      +          patch();
      +          try {
      +              program = parseProgram();
      +              if (typeof extra.comments !== 'undefined') {
      +                  filterCommentLocation();
      +                  program.comments = extra.comments;
      +              }
      +              if (typeof extra.tokens !== 'undefined') {
      +                  filterTokenLocation();
      +                  program.tokens = extra.tokens;
      +              }
      +              if (typeof extra.errors !== 'undefined') {
      +                  program.errors = extra.errors;
      +              }
      +          } catch (e) {
      +              throw e;
      +          } finally {
      +              unpatch();
      +              extra = {};
      +          }
      +  
      +          return program;
      +      }
      +  
      +      // Sync with package.json.
      +      exports.version = '1.0.0-dev-harmony';
      +  
      +      exports.parse = parse;
      +  
      +      // Deep copy.
      +      exports.Syntax = (function () {
      +          var name, types = {};
      +  
      +          if (typeof Object.create === 'function') {
      +              types = Object.create(null);
      +          }
      +  
      +          for (name in Syntax) {
      +              if (Syntax.hasOwnProperty(name)) {
      +                  types[name] = Syntax[name];
      +              }
      +          }
      +  
      +          if (typeof Object.freeze === 'function') {
      +              Object.freeze(types);
      +          }
      +  
      +          return types;
      +      }());
      +  
      +  }));
      +  /* vim: set sw=4 ts=4 et tw=80 : */
      + +
      + + diff --git a/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/index.html b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/index.html new file mode 100644 index 000000000..ec2af9c5a --- /dev/null +++ b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/index.html @@ -0,0 +1,37 @@ + + + + +Esprima: Unit Tests + + + + + + + +
      + + + +

      Unit Tests ensures the correct implementation

      +

      Esprima version .

      +

      Please wait...

      +
      + +
      + + + diff --git a/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/module.html b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/module.html new file mode 100644 index 000000000..7173a30cc --- /dev/null +++ b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/module.html @@ -0,0 +1,36 @@ + + + + +Esprima: Module Loading Test + + + + +
      + + + +

      Module Loading works also with web browsers

      + +

      The following tests are to ensure that Esprima can be loaded using AMD (Asynchronous Module Definition) loader such as RequireJS.

      +

      +
      + +
      + + + + diff --git a/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/module.js b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/module.js new file mode 100644 index 000000000..bba84c740 --- /dev/null +++ b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/module.js @@ -0,0 +1,129 @@ +/*jslint browser:true plusplus:true */ +/*global require:true */ +function runTests() { + 'use strict'; + + function setText(el, str) { + if (typeof el.innerText === 'string') { + el.innerText = str; + } else { + el.textContent = str; + } + } + + function reportSuccess(code) { + var report, e; + report = document.getElementById('report'); + e = document.createElement('pre'); + e.setAttribute('class', 'code'); + setText(e, code); + report.appendChild(e); + } + + function reportFailure(code, expected, actual) { + var report, e; + + report = document.getElementById('report'); + + e = document.createElement('pre'); + e.setAttribute('class', 'code'); + setText(e, code); + report.appendChild(e); + + e = document.createElement('p'); + setText(e, 'Expected type: ' + expected); + report.appendChild(e); + + e = document.createElement('p'); + setText(e, 'Actual type: ' + actual); + report.appendChild(e); + } + + + require(['../esprima'], function (ESParser) { + var tick, total, failures, obj, variable, variables, i, entry, entries; + + // We check only the type of some members of ESParser. + variables = { + 'version': 'string', + 'parse': 'function', + 'Syntax': 'object', + 'Syntax.AssignmentExpression': 'string', + 'Syntax.ArrayExpression': 'string', + 'Syntax.BlockStatement': 'string', + 'Syntax.BinaryExpression': 'string', + 'Syntax.BreakStatement': 'string', + 'Syntax.CallExpression': 'string', + 'Syntax.CatchClause': 'string', + 'Syntax.ConditionalExpression': 'string', + 'Syntax.ContinueStatement': 'string', + 'Syntax.DoWhileStatement': 'string', + 'Syntax.DebuggerStatement': 'string', + 'Syntax.EmptyStatement': 'string', + 'Syntax.ExpressionStatement': 'string', + 'Syntax.ForStatement': 'string', + 'Syntax.ForInStatement': 'string', + 'Syntax.FunctionDeclaration': 'string', + 'Syntax.FunctionExpression': 'string', + 'Syntax.Identifier': 'string', + 'Syntax.IfStatement': 'string', + 'Syntax.Literal': 'string', + 'Syntax.LabeledStatement': 'string', + 'Syntax.LogicalExpression': 'string', + 'Syntax.MemberExpression': 'string', + 'Syntax.NewExpression': 'string', + 'Syntax.ObjectExpression': 'string', + 'Syntax.Program': 'string', + 'Syntax.Property': 'string', + 'Syntax.ReturnStatement': 'string', + 'Syntax.SequenceExpression': 'string', + 'Syntax.SwitchStatement': 'string', + 'Syntax.SwitchCase': 'string', + 'Syntax.ThisExpression': 'string', + 'Syntax.ThrowStatement': 'string', + 'Syntax.TryStatement': 'string', + 'Syntax.UnaryExpression': 'string', + 'Syntax.UpdateExpression': 'string', + 'Syntax.VariableDeclaration': 'string', + 'Syntax.VariableDeclarator': 'string', + 'Syntax.WhileStatement': 'string', + 'Syntax.WithStatement': 'string' + }; + + total = failures = 0; + tick = new Date(); + + for (variable in variables) { + if (variables.hasOwnProperty(variable)) { + entries = variable.split('.'); + obj = ESParser; + for (i = 0; i < entries.length; ++i) { + entry = entries[i]; + if (typeof obj[entry] !== 'undefined') { + obj = obj[entry]; + } else { + obj = undefined; + break; + } + } + total++; + if (typeof obj === variables[variable]) { + reportSuccess(variable); + } else { + failures++; + reportFailure(variable, variables[variable], typeof obj); + } + } + } + + tick = (new Date()) - tick; + + if (failures > 0) { + setText(document.getElementById('status'), total + ' tests. ' + + 'Failures: ' + failures + '. ' + tick + ' ms'); + } else { + setText(document.getElementById('status'), total + ' tests. ' + + 'No failure. ' + tick + ' ms'); + } + }); +} diff --git a/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/reflect.js b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/reflect.js new file mode 100644 index 000000000..ffbeb5371 --- /dev/null +++ b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/reflect.js @@ -0,0 +1,422 @@ +// This is modified from Mozilla Reflect.parse test suite (the file is located +// at js/src/tests/js1_8_5/extensions/reflect-parse.js in the source tree). +// +// Some notable changes: +// * Removed unsupported features (destructuring, let, comprehensions...). +// * Removed tests for E4X (ECMAScript for XML). +// * Removed everything related to builder. +// * Enclosed every 'Pattern' construct with a scope. +// * Tweaked some expected tree to remove generator field. +// * Removed the test for bug 632030 and bug 632024. + +/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* + * Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/licenses/publicdomain/ + */ + +(function (exports) { + +function testReflect(Reflect, Pattern) { + +function program(elts) { return Pattern({ type: "Program", body: elts }) } +function exprStmt(expr) { return Pattern({ type: "ExpressionStatement", expression: expr }) } +function throwStmt(expr) { return Pattern({ type: "ThrowStatement", argument: expr }) } +function returnStmt(expr) { return Pattern({ type: "ReturnStatement", argument: expr }) } +function yieldExpr(expr) { return Pattern({ type: "YieldExpression", argument: expr }) } +function lit(val) { return Pattern({ type: "Literal", value: val }) } +var thisExpr = Pattern({ type: "ThisExpression" }); +function funDecl(id, params, body) { return Pattern({ type: "FunctionDeclaration", + id: id, + params: params, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }) } +function genFunDecl(id, params, body) { return Pattern({ type: "FunctionDeclaration", + id: id, + params: params, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }) } +function declarator(id, init) { return Pattern({ type: "VariableDeclarator", id: id, init: init }) } +function varDecl(decls) { return Pattern({ type: "VariableDeclaration", declarations: decls, kind: "var" }) } +function letDecl(decls) { return Pattern({ type: "VariableDeclaration", declarations: decls, kind: "let" }) } +function constDecl(decls) { return Pattern({ type: "VariableDeclaration", declarations: decls, kind: "const" }) } +function ident(name) { return Pattern({ type: "Identifier", name: name }) } +function dotExpr(obj, id) { return Pattern({ type: "MemberExpression", computed: false, object: obj, property: id }) } +function memExpr(obj, id) { return Pattern({ type: "MemberExpression", computed: true, object: obj, property: id }) } +function forStmt(init, test, update, body) { return Pattern({ type: "ForStatement", init: init, test: test, update: update, body: body }) } +function forInStmt(lhs, rhs, body) { return Pattern({ type: "ForInStatement", left: lhs, right: rhs, body: body, each: false }) } +function forEachInStmt(lhs, rhs, body) { return Pattern({ type: "ForInStatement", left: lhs, right: rhs, body: body, each: true }) } +function breakStmt(lab) { return Pattern({ type: "BreakStatement", label: lab }) } +function continueStmt(lab) { return Pattern({ type: "ContinueStatement", label: lab }) } +function blockStmt(body) { return Pattern({ type: "BlockStatement", body: body }) } +var emptyStmt = Pattern({ type: "EmptyStatement" }); +function ifStmt(test, cons, alt) { return Pattern({ type: "IfStatement", test: test, alternate: alt, consequent: cons }) } +function labStmt(lab, stmt) { return Pattern({ type: "LabeledStatement", label: lab, body: stmt }) } +function withStmt(obj, stmt) { return Pattern({ type: "WithStatement", object: obj, body: stmt }) } +function whileStmt(test, stmt) { return Pattern({ type: "WhileStatement", test: test, body: stmt }) } +function doStmt(stmt, test) { return Pattern({ type: "DoWhileStatement", test: test, body: stmt }) } +function switchStmt(disc, cases) { return Pattern({ type: "SwitchStatement", discriminant: disc, cases: cases }) } +function caseClause(test, stmts) { return Pattern({ type: "SwitchCase", test: test, consequent: stmts }) } +function defaultClause(stmts) { return Pattern({ type: "SwitchCase", test: null, consequent: stmts }) } +function catchClause(id, guard, body) { if (guard) { return Pattern({ type: "GuardedCatchClause", param: id, guard: guard, body: body }) } else { return Pattern({ type: "CatchClause", param: id, body: body }) } } +function tryStmt(body, guarded, catches, fin) { return Pattern({ type: "TryStatement", block: body, guardedHandlers: guarded, handlers: catches, finalizer: fin }) } +function letStmt(head, body) { return Pattern({ type: "LetStatement", head: head, body: body }) } +function funExpr(id, args, body, gen) { return Pattern({ type: "FunctionExpression", + id: id, + params: args, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }) } +function genFunExpr(id, args, body) { return Pattern({ type: "FunctionExpression", + id: id, + params: args, + defaults: [], + body: body, + rest: null, + generator: false, + expression: false + }) } + +function unExpr(op, arg) { return Pattern({ type: "UnaryExpression", operator: op, argument: arg }) } +function binExpr(op, left, right) { return Pattern({ type: "BinaryExpression", operator: op, left: left, right: right }) } +function aExpr(op, left, right) { return Pattern({ type: "AssignmentExpression", operator: op, left: left, right: right }) } +function updExpr(op, arg, prefix) { return Pattern({ type: "UpdateExpression", operator: op, argument: arg, prefix: prefix }) } +function logExpr(op, left, right) { return Pattern({ type: "LogicalExpression", operator: op, left: left, right: right }) } + +function condExpr(test, cons, alt) { return Pattern({ type: "ConditionalExpression", test: test, consequent: cons, alternate: alt }) } +function seqExpr(exprs) { return Pattern({ type: "SequenceExpression", expressions: exprs }) } +function newExpr(callee, args) { return Pattern({ type: "NewExpression", callee: callee, arguments: args }) } +function callExpr(callee, args) { return Pattern({ type: "CallExpression", callee: callee, arguments: args }) } +function arrExpr(elts) { return Pattern({ type: "ArrayExpression", elements: elts }) } +function objExpr(elts) { return Pattern({ type: "ObjectExpression", properties: elts }) } +function objProp(key, value, kind) { return Pattern({ type: "Property", key: key, value: value, kind: kind }) } + +function arrPatt(elts) { return Pattern({ type: "ArrayPattern", elements: elts }) } +function objPatt(elts) { return Pattern({ type: "ObjectPattern", properties: elts }) } + +function localSrc(src) { return "(function(){ " + src + " })" } +function localPatt(patt) { return program([exprStmt(funExpr(null, [], blockStmt([patt])))]) } +function blockSrc(src) { return "(function(){ { " + src + " } })" } +function blockPatt(patt) { return program([exprStmt(funExpr(null, [], blockStmt([blockStmt([patt])])))]) } + +function assertBlockStmt(src, patt) { + blockPatt(patt).assert(Reflect.parse(blockSrc(src))); +} + +function assertBlockExpr(src, patt) { + assertBlockStmt(src, exprStmt(patt)); +} + +function assertBlockDecl(src, patt, builder) { + blockPatt(patt).assert(Reflect.parse(blockSrc(src), {builder: builder})); +} + +function assertLocalStmt(src, patt) { + localPatt(patt).assert(Reflect.parse(localSrc(src))); +} + +function assertLocalExpr(src, patt) { + assertLocalStmt(src, exprStmt(patt)); +} + +function assertLocalDecl(src, patt) { + localPatt(patt).assert(Reflect.parse(localSrc(src))); +} + +function assertGlobalStmt(src, patt, builder) { + program([patt]).assert(Reflect.parse(src, {builder: builder})); +} + +function assertGlobalExpr(src, patt, builder) { + program([exprStmt(patt)]).assert(Reflect.parse(src, {builder: builder})); + //assertStmt(src, exprStmt(patt)); +} + +function assertGlobalDecl(src, patt) { + program([patt]).assert(Reflect.parse(src)); +} + +function assertProg(src, patt) { + program(patt).assert(Reflect.parse(src)); +} + +function assertStmt(src, patt) { + assertLocalStmt(src, patt); + assertGlobalStmt(src, patt); + assertBlockStmt(src, patt); +} + +function assertExpr(src, patt) { + assertLocalExpr(src, patt); + assertGlobalExpr(src, patt); + assertBlockExpr(src, patt); +} + +function assertDecl(src, patt) { + assertLocalDecl(src, patt); + assertGlobalDecl(src, patt); + assertBlockDecl(src, patt); +} + +function assertError(src, errorType) { + try { + Reflect.parse(src); + } catch (e) { + return; + } + throw new Error("expected " + errorType.name + " for " + uneval(src)); +} + + +// general tests + +// NB: These are useful but for now jit-test doesn't do I/O reliably. + +//program(_).assert(Reflect.parse(snarf('data/flapjax.txt'))); +//program(_).assert(Reflect.parse(snarf('data/jquery-1.4.2.txt'))); +//program(_).assert(Reflect.parse(snarf('data/prototype.js'))); +//program(_).assert(Reflect.parse(snarf('data/dojo.js.uncompressed.js'))); +//program(_).assert(Reflect.parse(snarf('data/mootools-1.2.4-core-nc.js'))); + + +// declarations + +assertDecl("var x = 1, y = 2, z = 3", + varDecl([declarator(ident("x"), lit(1)), + declarator(ident("y"), lit(2)), + declarator(ident("z"), lit(3))])); +assertDecl("var x, y, z", + varDecl([declarator(ident("x"), null), + declarator(ident("y"), null), + declarator(ident("z"), null)])); +assertDecl("function foo() { }", + funDecl(ident("foo"), [], blockStmt([]))); +assertDecl("function foo() { return 42 }", + funDecl(ident("foo"), [], blockStmt([returnStmt(lit(42))]))); + + +// Bug 591437: rebound args have their defs turned into uses +assertDecl("function f(a) { function a() { } }", + funDecl(ident("f"), [ident("a")], blockStmt([funDecl(ident("a"), [], blockStmt([]))]))); +assertDecl("function f(a,b,c) { function b() { } }", + funDecl(ident("f"), [ident("a"),ident("b"),ident("c")], blockStmt([funDecl(ident("b"), [], blockStmt([]))]))); + +// expressions + +assertExpr("true", lit(true)); +assertExpr("false", lit(false)); +assertExpr("42", lit(42)); +assertExpr("(/asdf/)", lit(/asdf/)); +assertExpr("this", thisExpr); +assertExpr("foo", ident("foo")); +assertExpr("foo.bar", dotExpr(ident("foo"), ident("bar"))); +assertExpr("foo[bar]", memExpr(ident("foo"), ident("bar"))); +assertExpr("(function(){})", funExpr(null, [], blockStmt([]))); +assertExpr("(function f() {})", funExpr(ident("f"), [], blockStmt([]))); +assertExpr("(function f(x,y,z) {})", funExpr(ident("f"), [ident("x"),ident("y"),ident("z")], blockStmt([]))); +assertExpr("(++x)", updExpr("++", ident("x"), true)); +assertExpr("(x++)", updExpr("++", ident("x"), false)); +assertExpr("(+x)", unExpr("+", ident("x"))); +assertExpr("(-x)", unExpr("-", ident("x"))); +assertExpr("(!x)", unExpr("!", ident("x"))); +assertExpr("(~x)", unExpr("~", ident("x"))); +assertExpr("(delete x)", unExpr("delete", ident("x"))); +assertExpr("(typeof x)", unExpr("typeof", ident("x"))); +assertExpr("(void x)", unExpr("void", ident("x"))); +assertExpr("(x == y)", binExpr("==", ident("x"), ident("y"))); +assertExpr("(x != y)", binExpr("!=", ident("x"), ident("y"))); +assertExpr("(x === y)", binExpr("===", ident("x"), ident("y"))); +assertExpr("(x !== y)", binExpr("!==", ident("x"), ident("y"))); +assertExpr("(x < y)", binExpr("<", ident("x"), ident("y"))); +assertExpr("(x <= y)", binExpr("<=", ident("x"), ident("y"))); +assertExpr("(x > y)", binExpr(">", ident("x"), ident("y"))); +assertExpr("(x >= y)", binExpr(">=", ident("x"), ident("y"))); +assertExpr("(x << y)", binExpr("<<", ident("x"), ident("y"))); +assertExpr("(x >> y)", binExpr(">>", ident("x"), ident("y"))); +assertExpr("(x >>> y)", binExpr(">>>", ident("x"), ident("y"))); +assertExpr("(x + y)", binExpr("+", ident("x"), ident("y"))); +assertExpr("(w + x + y + z)", binExpr("+", binExpr("+", binExpr("+", ident("w"), ident("x")), ident("y")), ident("z"))); +assertExpr("(x - y)", binExpr("-", ident("x"), ident("y"))); +assertExpr("(w - x - y - z)", binExpr("-", binExpr("-", binExpr("-", ident("w"), ident("x")), ident("y")), ident("z"))); +assertExpr("(x * y)", binExpr("*", ident("x"), ident("y"))); +assertExpr("(x / y)", binExpr("/", ident("x"), ident("y"))); +assertExpr("(x % y)", binExpr("%", ident("x"), ident("y"))); +assertExpr("(x | y)", binExpr("|", ident("x"), ident("y"))); +assertExpr("(x ^ y)", binExpr("^", ident("x"), ident("y"))); +assertExpr("(x & y)", binExpr("&", ident("x"), ident("y"))); +assertExpr("(x in y)", binExpr("in", ident("x"), ident("y"))); +assertExpr("(x instanceof y)", binExpr("instanceof", ident("x"), ident("y"))); +assertExpr("(x = y)", aExpr("=", ident("x"), ident("y"))); +assertExpr("(x += y)", aExpr("+=", ident("x"), ident("y"))); +assertExpr("(x -= y)", aExpr("-=", ident("x"), ident("y"))); +assertExpr("(x *= y)", aExpr("*=", ident("x"), ident("y"))); +assertExpr("(x /= y)", aExpr("/=", ident("x"), ident("y"))); +assertExpr("(x %= y)", aExpr("%=", ident("x"), ident("y"))); +assertExpr("(x <<= y)", aExpr("<<=", ident("x"), ident("y"))); +assertExpr("(x >>= y)", aExpr(">>=", ident("x"), ident("y"))); +assertExpr("(x >>>= y)", aExpr(">>>=", ident("x"), ident("y"))); +assertExpr("(x |= y)", aExpr("|=", ident("x"), ident("y"))); +assertExpr("(x ^= y)", aExpr("^=", ident("x"), ident("y"))); +assertExpr("(x &= y)", aExpr("&=", ident("x"), ident("y"))); +assertExpr("(x || y)", logExpr("||", ident("x"), ident("y"))); +assertExpr("(x && y)", logExpr("&&", ident("x"), ident("y"))); +assertExpr("(w || x || y || z)", logExpr("||", logExpr("||", logExpr("||", ident("w"), ident("x")), ident("y")), ident("z"))) +assertExpr("(x ? y : z)", condExpr(ident("x"), ident("y"), ident("z"))); +assertExpr("(x,y)", seqExpr([ident("x"),ident("y")])) +assertExpr("(x,y,z)", seqExpr([ident("x"),ident("y"),ident("z")])) +assertExpr("(a,b,c,d,e,f,g)", seqExpr([ident("a"),ident("b"),ident("c"),ident("d"),ident("e"),ident("f"),ident("g")])); +assertExpr("(new Object)", newExpr(ident("Object"), [])); +assertExpr("(new Object())", newExpr(ident("Object"), [])); +assertExpr("(new Object(42))", newExpr(ident("Object"), [lit(42)])); +assertExpr("(new Object(1,2,3))", newExpr(ident("Object"), [lit(1),lit(2),lit(3)])); +assertExpr("(String())", callExpr(ident("String"), [])); +assertExpr("(String(42))", callExpr(ident("String"), [lit(42)])); +assertExpr("(String(1,2,3))", callExpr(ident("String"), [lit(1),lit(2),lit(3)])); +assertExpr("[]", arrExpr([])); +assertExpr("[1]", arrExpr([lit(1)])); +assertExpr("[1,2]", arrExpr([lit(1),lit(2)])); +assertExpr("[1,2,3]", arrExpr([lit(1),lit(2),lit(3)])); +assertExpr("[1,,2,3]", arrExpr([lit(1),,lit(2),lit(3)])); +assertExpr("[1,,,2,3]", arrExpr([lit(1),,,lit(2),lit(3)])); +assertExpr("[1,,,2,,3]", arrExpr([lit(1),,,lit(2),,lit(3)])); +assertExpr("[1,,,2,,,3]", arrExpr([lit(1),,,lit(2),,,lit(3)])); +assertExpr("[,1,2,3]", arrExpr([,lit(1),lit(2),lit(3)])); +assertExpr("[,,1,2,3]", arrExpr([,,lit(1),lit(2),lit(3)])); +assertExpr("[,,,1,2,3]", arrExpr([,,,lit(1),lit(2),lit(3)])); +assertExpr("[,,,1,2,3,]", arrExpr([,,,lit(1),lit(2),lit(3)])); +assertExpr("[,,,1,2,3,,]", arrExpr([,,,lit(1),lit(2),lit(3),undefined])); +assertExpr("[,,,1,2,3,,,]", arrExpr([,,,lit(1),lit(2),lit(3),undefined,undefined])); +assertExpr("[,,,,,]", arrExpr([undefined,undefined,undefined,undefined,undefined])); +assertExpr("({})", objExpr([])); +assertExpr("({x:1})", objExpr([objProp(ident("x"), lit(1), "init")])); +assertExpr("({x:1, y:2})", objExpr([objProp(ident("x"), lit(1), "init"), + objProp(ident("y"), lit(2), "init")])); +assertExpr("({x:1, y:2, z:3})", objExpr([objProp(ident("x"), lit(1), "init"), + objProp(ident("y"), lit(2), "init"), + objProp(ident("z"), lit(3), "init") ])); +assertExpr("({x:1, 'y':2, z:3})", objExpr([objProp(ident("x"), lit(1), "init"), + objProp(lit("y"), lit(2), "init"), + objProp(ident("z"), lit(3), "init") ])); +assertExpr("({'x':1, 'y':2, z:3})", objExpr([objProp(lit("x"), lit(1), "init"), + objProp(lit("y"), lit(2), "init"), + objProp(ident("z"), lit(3), "init") ])); +assertExpr("({'x':1, 'y':2, 3:3})", objExpr([objProp(lit("x"), lit(1), "init"), + objProp(lit("y"), lit(2), "init"), + objProp(lit(3), lit(3), "init") ])); + +// Bug 571617: eliminate constant-folding +assertExpr("2 + 3", binExpr("+", lit(2), lit(3))); + +// Bug 632026: constant-folding +assertExpr("typeof(0?0:a)", unExpr("typeof", condExpr(lit(0), lit(0), ident("a")))); + +// Bug 632056: constant-folding +program([exprStmt(ident("f")), + ifStmt(lit(1), + funDecl(ident("f"), [], blockStmt([])), + null)]).assert(Reflect.parse("f; if (1) function f(){}")); + +// statements + +assertStmt("throw 42", throwStmt(lit(42))); +assertStmt("for (;;) break", forStmt(null, null, null, breakStmt(null))); +assertStmt("for (x; y; z) break", forStmt(ident("x"), ident("y"), ident("z"), breakStmt(null))); +assertStmt("for (var x; y; z) break", forStmt(varDecl([declarator(ident("x"), null)]), ident("y"), ident("z"), breakStmt(null))); +assertStmt("for (var x = 42; y; z) break", forStmt(varDecl([declarator(ident("x"), lit(42))]), ident("y"), ident("z"), breakStmt(null))); +assertStmt("for (x; ; z) break", forStmt(ident("x"), null, ident("z"), breakStmt(null))); +assertStmt("for (var x; ; z) break", forStmt(varDecl([declarator(ident("x"), null)]), null, ident("z"), breakStmt(null))); +assertStmt("for (var x = 42; ; z) break", forStmt(varDecl([declarator(ident("x"), lit(42))]), null, ident("z"), breakStmt(null))); +assertStmt("for (x; y; ) break", forStmt(ident("x"), ident("y"), null, breakStmt(null))); +assertStmt("for (var x; y; ) break", forStmt(varDecl([declarator(ident("x"), null)]), ident("y"), null, breakStmt(null))); +assertStmt("for (var x = 42; y; ) break", forStmt(varDecl([declarator(ident("x"),lit(42))]), ident("y"), null, breakStmt(null))); +assertStmt("for (var x in y) break", forInStmt(varDecl([declarator(ident("x"),null)]), ident("y"), breakStmt(null))); +assertStmt("for (x in y) break", forInStmt(ident("x"), ident("y"), breakStmt(null))); +assertStmt("{ }", blockStmt([])); +assertStmt("{ throw 1; throw 2; throw 3; }", blockStmt([ throwStmt(lit(1)), throwStmt(lit(2)), throwStmt(lit(3))])); +assertStmt(";", emptyStmt); +assertStmt("if (foo) throw 42;", ifStmt(ident("foo"), throwStmt(lit(42)), null)); +assertStmt("if (foo) throw 42; else true;", ifStmt(ident("foo"), throwStmt(lit(42)), exprStmt(lit(true)))); +assertStmt("if (foo) { throw 1; throw 2; throw 3; }", + ifStmt(ident("foo"), + blockStmt([throwStmt(lit(1)), throwStmt(lit(2)), throwStmt(lit(3))]), + null)); +assertStmt("if (foo) { throw 1; throw 2; throw 3; } else true;", + ifStmt(ident("foo"), + blockStmt([throwStmt(lit(1)), throwStmt(lit(2)), throwStmt(lit(3))]), + exprStmt(lit(true)))); +assertStmt("foo: for(;;) break foo;", labStmt(ident("foo"), forStmt(null, null, null, breakStmt(ident("foo"))))); +assertStmt("foo: for(;;) continue foo;", labStmt(ident("foo"), forStmt(null, null, null, continueStmt(ident("foo"))))); +assertStmt("with (obj) { }", withStmt(ident("obj"), blockStmt([]))); +assertStmt("with (obj) { obj; }", withStmt(ident("obj"), blockStmt([exprStmt(ident("obj"))]))); +assertStmt("while (foo) { }", whileStmt(ident("foo"), blockStmt([]))); +assertStmt("while (foo) { foo; }", whileStmt(ident("foo"), blockStmt([exprStmt(ident("foo"))]))); +assertStmt("do { } while (foo);", doStmt(blockStmt([]), ident("foo"))); +assertStmt("do { foo; } while (foo)", doStmt(blockStmt([exprStmt(ident("foo"))]), ident("foo"))); +assertStmt("switch (foo) { case 1: 1; break; case 2: 2; break; default: 3; }", + switchStmt(ident("foo"), + [ caseClause(lit(1), [ exprStmt(lit(1)), breakStmt(null) ]), + caseClause(lit(2), [ exprStmt(lit(2)), breakStmt(null) ]), + defaultClause([ exprStmt(lit(3)) ]) ])); +assertStmt("switch (foo) { case 1: 1; break; case 2: 2; break; default: 3; case 42: 42; }", + switchStmt(ident("foo"), + [ caseClause(lit(1), [ exprStmt(lit(1)), breakStmt(null) ]), + caseClause(lit(2), [ exprStmt(lit(2)), breakStmt(null) ]), + defaultClause([ exprStmt(lit(3)) ]), + caseClause(lit(42), [ exprStmt(lit(42)) ]) ])); +assertStmt("try { } catch (e) { }", + tryStmt(blockStmt([]), + [], + [ catchClause(ident("e"), null, blockStmt([])) ], + null)); +assertStmt("try { } catch (e) { } finally { }", + tryStmt(blockStmt([]), + [], + [ catchClause(ident("e"), null, blockStmt([])) ], + blockStmt([]))); +assertStmt("try { } finally { }", + tryStmt(blockStmt([]), + [], + [], + blockStmt([]))); + +// redeclarations (TOK_NAME nodes with lexdef) + +assertStmt("function f() { function g() { } function g() { } }", + funDecl(ident("f"), [], blockStmt([funDecl(ident("g"), [], blockStmt([])), + funDecl(ident("g"), [], blockStmt([]))]))); + +assertStmt("function f() { function g() { } function g() { return 42 } }", + funDecl(ident("f"), [], blockStmt([funDecl(ident("g"), [], blockStmt([])), + funDecl(ident("g"), [], blockStmt([returnStmt(lit(42))]))]))); + +assertStmt("function f() { var x = 42; var x = 43; }", + funDecl(ident("f"), [], blockStmt([varDecl([declarator(ident("x"),lit(42))]), + varDecl([declarator(ident("x"),lit(43))])]))); + +// getters and setters + + assertExpr("({ get x() { return 42 } })", + objExpr([ objProp(ident("x"), + funExpr(null, [], blockStmt([returnStmt(lit(42))])), + "get" ) ])); + assertExpr("({ set x(v) { return 42 } })", + objExpr([ objProp(ident("x"), + funExpr(null, [ident("v")], blockStmt([returnStmt(lit(42))])), + "set" ) ])); + +} + +exports.testReflect = testReflect; + +}(typeof exports === 'undefined' ? this : exports)); diff --git a/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/run.js b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/run.js new file mode 100644 index 000000000..32ca3faa4 --- /dev/null +++ b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/run.js @@ -0,0 +1,66 @@ +/* + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Ariya Hidayat + + 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. + + 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 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. +*/ + +/*jslint node:true */ + +(function () { + 'use strict'; + + var child = require('child_process'), + nodejs = '"' + process.execPath + '"', + ret = 0, + suites, + index; + + suites = [ + 'runner', + 'compat' + ]; + + function nextTest() { + var suite = suites[index]; + + if (index < suites.length) { + child.exec(nodejs + ' ./test/' + suite + '.js', function (err, stdout, stderr) { + if (stdout) { + process.stdout.write(suite + ': ' + stdout); + } + if (stderr) { + process.stderr.write(suite + ': ' + stderr); + } + if (err) { + ret = err.code; + } + index += 1; + nextTest(); + }); + } else { + process.exit(ret); + } + } + + index = 0; + nextTest(); +}()); diff --git a/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/runner.js b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/runner.js new file mode 100644 index 000000000..c1a3fc9bf --- /dev/null +++ b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/runner.js @@ -0,0 +1,387 @@ +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2011 Ariya Hidayat + Copyright (C) 2011 Yusuke Suzuki + Copyright (C) 2011 Arpad Borsos + + 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. + + 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 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. +*/ + +/*jslint browser:true node:true */ +/*global esprima:true, testFixture:true */ + +var runTests; + +// Special handling for regular expression literal since we need to +// convert it to a string literal, otherwise it will be decoded +// as object "{}" and the regular expression would be lost. +function adjustRegexLiteral(key, value) { + 'use strict'; + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } + return value; +} + +function NotMatchingError(expected, actual) { + 'use strict'; + Error.call(this, 'Expected '); + this.expected = expected; + this.actual = actual; +} +NotMatchingError.prototype = new Error(); + +function errorToObject(e) { + 'use strict'; + var msg = e.toString(); + + // Opera 9.64 produces an non-standard string in toString(). + if (msg.substr(0, 6) !== 'Error:') { + if (typeof e.message === 'string') { + msg = 'Error: ' + e.message; + } + } + + return { + index: e.index, + lineNumber: e.lineNumber, + column: e.column, + message: msg + }; +} + +function testParse(esprima, code, syntax) { + 'use strict'; + var expected, tree, actual, options, StringObject, i, len, err; + + // alias, so that JSLint does not complain. + StringObject = String; + + options = { + comment: (typeof syntax.comments !== 'undefined'), + range: true, + loc: true, + tokens: (typeof syntax.tokens !== 'undefined'), + raw: true, + tolerant: (typeof syntax.errors !== 'undefined') + }; + + if (typeof syntax.tokens !== 'undefined') { + if (syntax.tokens.length > 0) { + options.range = (typeof syntax.tokens[0].range !== 'undefined'); + options.loc = (typeof syntax.tokens[0].loc !== 'undefined'); + } + } + + if (typeof syntax.comments !== 'undefined') { + if (syntax.comments.length > 0) { + options.range = (typeof syntax.comments[0].range !== 'undefined'); + options.loc = (typeof syntax.comments[0].loc !== 'undefined'); + } + } + + expected = JSON.stringify(syntax, null, 4); + try { + tree = esprima.parse(code, options); + tree = (options.comment || options.tokens || options.tolerant) ? tree : tree.body[0]; + + if (options.tolerant) { + for (i = 0, len = tree.errors.length; i < len; i += 1) { + tree.errors[i] = errorToObject(tree.errors[i]); + } + } + + actual = JSON.stringify(tree, adjustRegexLiteral, 4); + + // Only to ensure that there is no error when using string object. + esprima.parse(new StringObject(code), options); + + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } + + function filter(key, value) { + if (key === 'value' && value instanceof RegExp) { + value = value.toString(); + } + return (key === 'loc' || key === 'range') ? undefined : value; + } + + if (options.tolerant) { + return; + } + + + // Check again without any location info. + options.range = false; + options.loc = false; + expected = JSON.stringify(syntax, filter, 4); + try { + tree = esprima.parse(code, options); + tree = (options.comment || options.tokens) ? tree : tree.body[0]; + + if (options.tolerant) { + for (i = 0, len = tree.errors.length; i < len; i += 1) { + tree.errors[i] = errorToObject(tree.errors[i]); + } + } + + actual = JSON.stringify(tree, filter, 4); + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } +} + +function testError(esprima, code, exception) { + 'use strict'; + var i, options, expected, actual, handleInvalidRegexFlag; + + // Different parsing options should give the same error. + options = [ + {}, + { comment: true }, + { raw: true }, + { raw: true, comment: true } + ]; + + // If handleInvalidRegexFlag is true, an invalid flag in a regular expression + // will throw an exception. In some old version V8, this is not the case + // and hence handleInvalidRegexFlag is false. + handleInvalidRegexFlag = false; + try { + 'test'.match(new RegExp('[a-z]', 'x')); + } catch (e) { + handleInvalidRegexFlag = true; + } + + expected = JSON.stringify(exception); + + for (i = 0; i < options.length; i += 1) { + + try { + esprima.parse(code, options[i]); + } catch (e) { + actual = JSON.stringify(errorToObject(e)); + } + + if (expected !== actual) { + + // Compensate for old V8 which does not handle invalid flag. + if (exception.message.indexOf('Invalid regular expression') > 0) { + if (typeof actual === 'undefined' && !handleInvalidRegexFlag) { + return; + } + } + + throw new NotMatchingError(expected, actual); + } + + } +} + +function testAPI(esprima, code, result) { + 'use strict'; + var expected, res, actual; + + expected = JSON.stringify(result.result, null, 4); + try { + if (typeof result.property !== 'undefined') { + res = esprima[result.property]; + } else { + res = esprima[result.call].apply(esprima, result.args); + } + actual = JSON.stringify(res, adjustRegexLiteral, 4); + } catch (e) { + throw new NotMatchingError(expected, e.toString()); + } + if (expected !== actual) { + throw new NotMatchingError(expected, actual); + } +} + +function runTest(esprima, code, result) { + 'use strict'; + if (result.hasOwnProperty('lineNumber')) { + testError(esprima, code, result); + } else if (result.hasOwnProperty('result')) { + testAPI(esprima, code, result); + } else { + testParse(esprima, code, result); + } +} + +if (typeof window !== 'undefined') { + // Run all tests in a browser environment. + runTests = function () { + 'use strict'; + var total = 0, + failures = 0, + category, + fixture, + source, + tick, + expected, + index, + len; + + function setText(el, str) { + if (typeof el.innerText === 'string') { + el.innerText = str; + } else { + el.textContent = str; + } + } + + function startCategory(category) { + var report, e; + report = document.getElementById('report'); + e = document.createElement('h4'); + setText(e, category); + report.appendChild(e); + } + + function reportSuccess(code) { + var report, e; + report = document.getElementById('report'); + e = document.createElement('pre'); + e.setAttribute('class', 'code'); + setText(e, code); + report.appendChild(e); + } + + function reportFailure(code, expected, actual) { + var report, e; + + report = document.getElementById('report'); + + e = document.createElement('p'); + setText(e, 'Code:'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'code'); + setText(e, code); + report.appendChild(e); + + e = document.createElement('p'); + setText(e, 'Expected'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'expected'); + setText(e, expected); + report.appendChild(e); + + e = document.createElement('p'); + setText(e, 'Actual'); + report.appendChild(e); + + e = document.createElement('pre'); + e.setAttribute('class', 'actual'); + setText(e, actual); + report.appendChild(e); + } + + setText(document.getElementById('version'), esprima.version); + + tick = new Date(); + for (category in testFixture) { + if (testFixture.hasOwnProperty(category)) { + startCategory(category); + fixture = testFixture[category]; + for (source in fixture) { + if (fixture.hasOwnProperty(source)) { + expected = fixture[source]; + total += 1; + try { + runTest(esprima, source, expected); + reportSuccess(source, JSON.stringify(expected, null, 4)); + } catch (e) { + failures += 1; + reportFailure(source, e.expected, e.actual); + } + } + } + } + } + tick = (new Date()) - tick; + + if (failures > 0) { + setText(document.getElementById('status'), total + ' tests. ' + + 'Failures: ' + failures + '. ' + tick + ' ms'); + } else { + setText(document.getElementById('status'), total + ' tests. ' + + 'No failure. ' + tick + ' ms'); + } + }; +} else { + (function () { + 'use strict'; + + var esprima = require('../esprima'), + vm = require('vm'), + fs = require('fs'), + total = 0, + failures = [], + tick = new Date(), + expected, + header; + + vm.runInThisContext(fs.readFileSync(__dirname + '/test.js', 'utf-8')); + + Object.keys(testFixture).forEach(function (category) { + Object.keys(testFixture[category]).forEach(function (source) { + total += 1; + expected = testFixture[category][source]; + try { + runTest(esprima, source, expected); + } catch (e) { + e.source = source; + failures.push(e); + } + }); + }); + tick = (new Date()) - tick; + + header = total + ' tests. ' + failures.length + ' failures. ' + + tick + ' ms'; + if (failures.length) { + console.error(header); + failures.forEach(function (failure) { + console.error(failure.source + ': Expected\n ' + + failure.expected.split('\n').join('\n ') + + '\nto match\n ' + failure.actual); + }); + } else { + console.log(header); + } + process.exit(failures.length === 0 ? 0 : 1); + }()); +} diff --git a/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/test.js b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/test.js new file mode 100644 index 000000000..780af55aa --- /dev/null +++ b/node/node_modules/grunt/node_modules/js-yaml/node_modules/esprima/test/test.js @@ -0,0 +1,19764 @@ +/* + Copyright (C) 2012 Ariya Hidayat + Copyright (C) 2012 Joost-Wim Boekesteijn + Copyright (C) 2012 Yusuke Suzuki + Copyright (C) 2012 Arpad Borsos + Copyright (C) 2011 Ariya Hidayat + Copyright (C) 2011 Yusuke Suzuki + Copyright (C) 2011 Arpad Borsos + + 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. + + 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 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. +*/ + +var testFixture = { + + 'Primary Expression': { + + 'this\n': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'ThisExpression', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 0 } + } + }], + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 0 } + }, + tokens: [{ + type: 'Keyword', + value: 'this', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }] + }, + + 'null\n': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: null, + raw: 'null', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 0 } + } + }], + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 0 } + }, + tokens: [{ + type: 'Null', + value: 'null', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }] + }, + + '\n 42\n\n': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }, + range: [5, 9], + loc: { + start: { line: 2, column: 4 }, + end: { line: 4, column: 0 } + } + }], + range: [5, 9], + loc: { + start: { line: 2, column: 4 }, + end: { line: 4, column: 0 } + }, + tokens: [{ + type: 'Numeric', + value: '42', + range: [5, 7], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }] + }, + + '(1 + 2 ) * 3': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Literal', + value: 1, + raw: '1', + range: [1, 2], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'Literal', + value: 2, + raw: '2', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [1, 6], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 6 } + } + }, + right: { + type: 'Literal', + value: 3, + raw: '3', + range: [11, 12], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + } + + }, + + 'Grouping Operator': { + + '(1) + (2 ) + 3': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Literal', + value: 1, + raw: '1', + range: [1, 2], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'Literal', + value: 2, + raw: '2', + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + right: { + type: 'Literal', + value: 3, + raw: '3', + range: [14, 15], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + + '4 + 5 << (6)': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '<<', + left: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Literal', + value: 4, + raw: '4', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 5, + raw: '5', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Literal', + value: 6, + raw: '6', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + } + + }, + + 'Array Initializer': { + + 'x = []': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }], + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + }, + tokens: [{ + type: 'Identifier', + value: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, { + type: 'Punctuator', + value: '=', + range: [2, 3], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Punctuator', + value: '[', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: ']', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }] + }, + + 'x = [ ]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x = [ 42 ]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [{ + type: 'Literal', + value: 42, + raw: '42', + range: [6, 8], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 8 } + } + }], + range: [4, 10], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 10 } + } + }, + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + + 'x = [ 42, ]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [{ + type: 'Literal', + value: 42, + raw: '42', + range: [6, 8], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 8 } + } + }], + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'x = [ ,, 42 ]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [ + null, + null, + { + type: 'Literal', + value: 42, + raw: '42', + range: [9, 11], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 11 } + } + }], + range: [4, 13], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + 'x = [ 1, 2, 3, ]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [{ + type: 'Literal', + value: 1, + raw: '1', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'Literal', + value: 2, + raw: '2', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, { + type: 'Literal', + value: 3, + raw: '3', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }], + range: [4, 16], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + 'x = [ 1, 2,, 3, ]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ArrayExpression', + elements: [{ + type: 'Literal', + value: 1, + raw: '1', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'Literal', + value: 2, + raw: '2', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, null, { + type: 'Literal', + value: 3, + raw: '3', + range: [13, 14], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 14 } + } + }], + range: [4, 17], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + + '日本語 = []': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: '日本語', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [6, 8], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + 'T\u203F = []': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'T\u203F', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'T\u200C = []': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'T\u200C', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'T\u200D = []': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'T\u200D', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + '\u2163\u2161 = []': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: '\u2163\u2161', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + '\u2163\u2161\u200A=\u2009[]': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: '\u2163\u2161', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + } + + }, + + 'Object Initializer': { + + 'x = {}': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [], + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x = { }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x = { answer: 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'answer', + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [14, 16], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 16 } + } + }, + kind: 'init', + range: [6, 16], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 16 } + } + }], + range: [4, 18], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 18 } + } + }, + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }, + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }, + + 'x = { if: 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'if', + range: [6, 8], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 8 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + kind: 'init', + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }], + range: [4, 14], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + 'x = { true: 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'true', + range: [6, 10], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 10 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [12, 14], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 14 } + } + }, + kind: 'init', + range: [6, 14], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 14 } + } + }], + range: [4, 16], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + 'x = { false: 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'false', + range: [6, 11], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 11 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [13, 15], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 15 } + } + }, + kind: 'init', + range: [6, 15], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 15 } + } + }], + range: [4, 17], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + + 'x = { null: 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'null', + range: [6, 10], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 10 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [12, 14], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 14 } + } + }, + kind: 'init', + range: [6, 14], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 14 } + } + }], + range: [4, 16], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + 'x = { "answer": 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Literal', + value: 'answer', + raw: '"answer"', + range: [6, 14], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 14 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [16, 18], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 18 } + } + }, + kind: 'init', + range: [6, 18], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 18 } + } + }], + range: [4, 20], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 20 } + } + }, + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + + 'x = { x: 1, x: 2 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [ + { + type: 'Property', + key: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + value: { + type: 'Literal', + value: 1, + raw: '1', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + kind: 'init', + range: [6, 10], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 10 } + } + }, + { + type: 'Property', + key: { + type: 'Identifier', + name: 'x', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }, + value: { + type: 'Literal', + value: 2, + raw: '2', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }, + kind: 'init', + range: [12, 16], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 16 } + } + } + ], + range: [4, 18], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 18 } + } + }, + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }, + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }, + + 'x = { get width() { return m_width } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'width', + range: [10, 15], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 15 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ReturnStatement', + argument: { + type: 'Identifier', + name: 'm_width', + range: [27, 34], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 34 } + } + }, + range: [20, 35], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 35 } + } + }], + range: [18, 36], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 36 } + } + }, + rest: null, + generator: false, + expression: false, + range: [18, 36], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 36 } + } + }, + kind: 'get', + range: [6, 36], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 36 } + } + }], + range: [4, 38], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 38 } + } + }, + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + }, + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + }, + + 'x = { get undef() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'undef', + range: [10, 15], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 15 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [18, 20], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 20 } + } + }, + rest: null, + generator: false, + expression: false, + range: [18, 20], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 20 } + } + }, + kind: 'get', + range: [6, 20], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 20 } + } + }], + range: [4, 22], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + + 'x = { get if() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'if', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + kind: 'get', + range: [6, 17], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 17 } + } + }], + range: [4, 19], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 19 } + } + }, + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + } + }, + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + } + }, + + 'x = { get true() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'true', + range: [10, 14], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 14 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [17, 19], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 19 } + } + }, + rest: null, + generator: false, + expression: false, + range: [17, 19], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 19 } + } + }, + kind: 'get', + range: [6, 19], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 19 } + } + }], + range: [4, 21], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + + 'x = { get false() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'false', + range: [10, 15], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 15 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [18, 20], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 20 } + } + }, + rest: null, + generator: false, + expression: false, + range: [18, 20], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 20 } + } + }, + kind: 'get', + range: [6, 20], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 20 } + } + }], + range: [4, 22], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + + 'x = { get null() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'null', + range: [10, 14], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 14 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [17, 19], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 19 } + } + }, + rest: null, + generator: false, + expression: false, + range: [17, 19], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 19 } + } + }, + kind: 'get', + range: [6, 19], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 19 } + } + }], + range: [4, 21], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + + 'x = { get "undef"() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Literal', + value: 'undef', + raw: '"undef"', + range: [10, 17], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 17 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [20, 22], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 22 } + } + }, + rest: null, + generator: false, + expression: false, + range: [20, 22], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 22 } + } + }, + kind: 'get', + range: [6, 22], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 22 } + } + }], + range: [4, 24], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 24 } + } + }, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + + 'x = { get 10() {} }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Literal', + value: 10, + raw: '10', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + kind: 'get', + range: [6, 17], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 17 } + } + }], + range: [4, 19], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 19 } + } + }, + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + } + }, + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + } + }, + + 'x = { set width(w) { m_width = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'width', + range: [10, 15], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 15 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_width', + range: [21, 28], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 28 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [31, 32], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 32 } + } + }, + range: [21, 32], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 32 } + } + }, + range: [21, 33], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 33 } + } + }], + range: [19, 34], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [19, 34], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 34 } + } + }, + kind: 'set', + range: [6, 34], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 34 } + } + }], + range: [4, 36], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + + 'x = { set if(w) { m_if = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'if', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [13, 14], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 14 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_if', + range: [18, 22], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 22 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [25, 26], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 26 } + } + }, + range: [18, 26], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 26 } + } + }, + range: [18, 27], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 27 } + } + }], + range: [16, 28], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 28 } + } + }, + rest: null, + generator: false, + expression: false, + range: [16, 28], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 28 } + } + }, + kind: 'set', + range: [6, 28], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 28 } + } + }], + range: [4, 30], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 30 } + } + }, + range: [0, 30], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 30 } + } + }, + range: [0, 30], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 30 } + } + }, + + 'x = { set true(w) { m_true = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'true', + range: [10, 14], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 14 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_true', + range: [20, 26], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 26 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [29, 30], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 30 } + } + }, + range: [20, 30], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 30 } + } + }, + range: [20, 31], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 31 } + } + }], + range: [18, 32], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 32 } + } + }, + rest: null, + generator: false, + expression: false, + range: [18, 32], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 32 } + } + }, + kind: 'set', + range: [6, 32], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 32 } + } + }], + range: [4, 34], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 34 } + } + }, + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + + 'x = { set false(w) { m_false = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'false', + range: [10, 15], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 15 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_false', + range: [21, 28], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 28 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [31, 32], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 32 } + } + }, + range: [21, 32], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 32 } + } + }, + range: [21, 33], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 33 } + } + }], + range: [19, 34], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [19, 34], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 34 } + } + }, + kind: 'set', + range: [6, 34], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 34 } + } + }], + range: [4, 36], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + + 'x = { set null(w) { m_null = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'null', + range: [10, 14], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 14 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_null', + range: [20, 26], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 26 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [29, 30], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 30 } + } + }, + range: [20, 30], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 30 } + } + }, + range: [20, 31], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 31 } + } + }], + range: [18, 32], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 32 } + } + }, + rest: null, + generator: false, + expression: false, + range: [18, 32], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 32 } + } + }, + kind: 'set', + range: [6, 32], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 32 } + } + }], + range: [4, 34], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 34 } + } + }, + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + + 'x = { set "null"(w) { m_null = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Literal', + value: 'null', + raw: '"null"', + range: [10, 16], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 16 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [17, 18], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 18 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_null', + range: [22, 28], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 28 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [31, 32], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 32 } + } + }, + range: [22, 32], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 32 } + } + }, + range: [22, 33], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 33 } + } + }], + range: [20, 34], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [20, 34], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 34 } + } + }, + kind: 'set', + range: [6, 34], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 34 } + } + }], + range: [4, 36], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + + 'x = { set 10(w) { m_null = w } }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Literal', + value: 10, + raw: '10', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'w', + range: [13, 14], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 14 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'm_null', + range: [18, 24], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 24 } + } + }, + right: { + type: 'Identifier', + name: 'w', + range: [27, 28], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 28 } + } + }, + range: [18, 28], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 28 } + } + }, + range: [18, 29], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 29 } + } + }], + range: [16, 30], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 30 } + } + }, + rest: null, + generator: false, + expression: false, + range: [16, 30], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 30 } + } + }, + kind: 'set', + range: [6, 30], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 30 } + } + }], + range: [4, 32], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 32 } + } + }, + range: [0, 32], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 32 } + } + }, + range: [0, 32], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 32 } + } + }, + + 'x = { get: 42 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'get', + range: [6, 9], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 9 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [11, 13], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 13 } + } + }, + kind: 'init', + range: [6, 13], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 13 } + } + }], + range: [4, 15], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + + 'x = { set: 43 }': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'set', + range: [6, 9], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 9 } + } + }, + value: { + type: 'Literal', + value: 43, + raw: '43', + range: [11, 13], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 13 } + } + }, + kind: 'init', + range: [6, 13], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 13 } + } + }], + range: [4, 15], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + } + + }, + + 'Comments': { + + '/* block comment */ 42': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [20, 22], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 22 } + } + }, + range: [20, 22], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 22 } + } + }, + + '42 /*The*/ /*Answer*/': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }], + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + }, + comments: [{ + type: 'Block', + value: 'The', + range: [3, 10], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 10 } + } + }, { + type: 'Block', + value: 'Answer', + range: [11, 21], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 21 } + } + }] + }, + + '42 /*the*/ /*answer*/': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [0, 2] + }, + range: [0, 21] + }], + range: [0, 21], + comments: [{ + type: 'Block', + value: 'the', + range: [3, 10] + }, { + type: 'Block', + value: 'answer', + range: [11, 21] + }] + }, + + '/* multiline\ncomment\nshould\nbe\nignored */ 42': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [42, 44], + loc: { + start: { line: 5, column: 11 }, + end: { line: 5, column: 13 } + } + }, + range: [42, 44], + loc: { + start: { line: 5, column: 11 }, + end: { line: 5, column: 13 } + } + }, + + '/*a\r\nb*/ 42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [9, 11], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }, + range: [9, 11], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }], + range: [9, 11], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + }, + comments: [{ + type: 'Block', + value: 'a\r\nb', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 3 } + } + }] + }, + + '/*a\rb*/ 42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [8, 10], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }, + range: [8, 10], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }], + range: [8, 10], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + }, + comments: [{ + type: 'Block', + value: 'a\rb', + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 3 } + } + }] + }, + + '/*a\nb*/ 42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [8, 10], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }, + range: [8, 10], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }], + range: [8, 10], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + }, + comments: [{ + type: 'Block', + value: 'a\nb', + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 3 } + } + }] + }, + + '/*a\nc*/ 42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }, + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + } + }], + loc: { + start: { line: 2, column: 4 }, + end: { line: 2, column: 6 } + }, + comments: [{ + type: 'Block', + value: 'a\nc', + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 3 } + } + }] + }, + + '// line comment\n42': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [16, 18], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }, + range: [16, 18], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }, + + '42 // line comment': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }], + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + }, + comments: [{ + type: 'Line', + value: ' line comment', + range: [3, 18], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 18 } + } + }] + }, + + '// Hello, world!\n42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [17, 19], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }, + range: [17, 19], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }], + range: [17, 19], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + }, + comments: [{ + type: 'Line', + value: ' Hello, world!', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }] + }, + + '// Hello, world!\n': { + type: 'Program', + body: [], + range: [17, 17], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 0 } + }, + comments: [{ + type: 'Line', + value: ' Hello, world!', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }] + }, + + '// Hallo, world!\n': { + type: 'Program', + body: [], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 0 } + }, + comments: [{ + type: 'Line', + value: ' Hallo, world!', + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }] + }, + + '//\n42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [3, 5], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }, + range: [3, 5], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }], + range: [3, 5], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + }, + comments: [{ + type: 'Line', + value: '', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }] + }, + + '//': { + type: 'Program', + body: [], + range: [2, 2], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 2 } + }, + comments: [{ + type: 'Line', + value: '', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }] + }, + + '// ': { + type: 'Program', + body: [], + range: [3, 3], + comments: [{ + type: 'Line', + value: ' ', + range: [0, 3] + }] + }, + + '/**/42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }], + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + }, + comments: [{ + type: 'Block', + value: '', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }] + }, + + '// Hello, world!\n\n// Another hello\n42': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [37, 39], + loc: { + start: { line: 4, column: 0 }, + end: { line: 4, column: 2 } + } + }, + range: [37, 39], + loc: { + start: { line: 4, column: 0 }, + end: { line: 4, column: 2 } + } + }], + range: [37, 39], + loc: { + start: { line: 4, column: 0 }, + end: { line: 4, column: 2 } + }, + comments: [{ + type: 'Line', + value: ' Hello, world!', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, { + type: 'Line', + value: ' Another hello', + range: [18, 36], + loc: { + start: { line: 3, column: 0 }, + end: { line: 3, column: 18 } + } + }] + }, + + 'if (x) { // Some comment\ndoThat(); }': { + type: 'Program', + body: [{ + type: 'IfStatement', + test: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + consequent: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'doThat', + range: [25, 31], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }, + 'arguments': [], + range: [25, 33], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 8 } + } + }, + range: [25, 34], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 9 } + } + }], + range: [7, 36], + loc: { + start: { line: 1, column: 7 }, + end: { line: 2, column: 11 } + } + }, + alternate: null, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 11 } + } + }], + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 11 } + }, + comments: [{ + type: 'Line', + value: ' Some comment', + range: [9, 24], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 24 } + } + }] + }, + + 'switch (answer) { case 42: /* perfect */ bingo() }': { + type: 'Program', + body: [{ + type: 'SwitchStatement', + discriminant: { + type: 'Identifier', + name: 'answer', + range: [8, 14], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 14 } + } + }, + cases: [{ + type: 'SwitchCase', + test: { + type: 'Literal', + value: 42, + raw: '42', + range: [23, 25], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 25 } + } + }, + consequent: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'bingo', + range: [41, 46], + loc: { + start: { line: 1, column: 41 }, + end: { line: 1, column: 46 } + } + }, + 'arguments': [], + range: [41, 48], + loc: { + start: { line: 1, column: 41 }, + end: { line: 1, column: 48 } + } + }, + range: [41, 49], + loc: { + start: { line: 1, column: 41 }, + end: { line: 1, column: 49 } + } + }], + range: [18, 49], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 49 } + } + }], + range: [0, 50], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 50 } + } + }], + range: [0, 50], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 50 } + }, + comments: [{ + type: 'Block', + value: ' perfect ', + range: [27, 40], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 40 } + } + }] + } + + }, + + 'Numeric Literals': { + + '0': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0, + raw: '0', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + + '42': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42, + raw: '42', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + + '3': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 3, + raw: '3', + range: [0, 1] + }, + range: [0, 1] + }], + range: [0, 1], + tokens: [{ + type: 'Numeric', + value: '3', + range: [0, 1] + }] + }, + + '5': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 5, + raw: '5', + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + }, + tokens: [{ + type: 'Numeric', + value: '5', + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }] + }, + + '.14': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0.14, + raw: '.14', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + '3.14159': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 3.14159, + raw: '3.14159', + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + '6.02214179e+23': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 6.02214179e+23, + raw: '6.02214179e+23', + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + '1.492417830e-10': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 1.49241783e-10, + raw: '1.492417830e-10', + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + + '0x0': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0, + raw: '0x0', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + '0e+100': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0, + raw: '0e+100', + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + '0xabc': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0xabc, + raw: '0xabc', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + '0xdef': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0xdef, + raw: '0xdef', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + '0X1A': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0x1A, + raw: '0X1A', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + + '0x10': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0x10, + raw: '0x10', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + + '0x100': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0x100, + raw: '0x100', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + '0X04': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 0X04, + raw: '0X04', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + + '02': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 2, + raw: '02', + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + + '012': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 10, + raw: '012', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + '0012': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 10, + raw: '0012', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + } + + }, + + 'String Literals': { + + '"Hello"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello', + raw: '"Hello"', + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + '"\\n\\r\\t\\v\\b\\f\\\\\\\'\\"\\0"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: '\n\r\t\v\b\f\\\'"\x00', + raw: '"\\n\\r\\t\\v\\b\\f\\\\\\\'\\"\\0"', + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + + '"\\u0061"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'a', + raw: '"\\u0061"', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + '"\\x61"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'a', + raw: '"\\x61"', + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + '"\\u00"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'u00', + raw: '"\\u00"', + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + '"\\xt"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'xt', + raw: '"\\xt"', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + '"Hello\\nworld"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\nworld', + raw: '"Hello\\nworld"', + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + '"Hello\\\nworld"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Helloworld', + raw: '"Hello\\\nworld"', + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 14 } + } + }, + + '"Hello\\02World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\u0002World', + raw: '"Hello\\02World"', + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + + '"Hello\\012World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\u000AWorld', + raw: '"Hello\\012World"', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '"Hello\\122World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\122World', + raw: '"Hello\\122World"', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '"Hello\\0122World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\u000A2World', + raw: '"Hello\\0122World"', + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + + '"Hello\\312World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\u00CAWorld', + raw: '"Hello\\312World"', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '"Hello\\412World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\412World', + raw: '"Hello\\412World"', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '"Hello\\812World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello812World', + raw: '"Hello\\812World"', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '"Hello\\712World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\712World', + raw: '"Hello\\712World"', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '"Hello\\0World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\u0000World', + raw: '"Hello\\0World"', + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + '"Hello\\\r\nworld"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Helloworld', + raw: '"Hello\\\r\nworld"', + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 15 } + } + }, + + '"Hello\\1World"': { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'Hello\u0001World', + raw: '"Hello\\1World"', + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + } + }, + + 'Regular Expression Literals': { + + 'var x = /[a-z]/i': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/[a-z]/i', + raw: '/[a-z]/i', + range: [8, 16], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 16 } + } + }, + range: [4, 16], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 16 } + } + }], + kind: 'var', + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }], + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/[a-z]/i', + range: [8, 16], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 16 } + } + }] + }, + + 'var x = /[x-z]/i': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5] + }, + init: { + type: 'Literal', + value: '/[x-z]/i', + raw: '/[x-z]/i', + range: [8, 16] + }, + range: [4, 16] + }], + kind: 'var', + range: [0, 16] + }], + range: [0, 16], + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3] + }, { + type: 'Identifier', + value: 'x', + range: [4, 5] + }, { + type: 'Punctuator', + value: '=', + range: [6, 7] + }, { + type: 'RegularExpression', + value: '/[x-z]/i', + range: [8, 16] + }] + }, + + 'var x = /[a-c]/i': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/[a-c]/i', + raw: '/[a-c]/i', + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 16 } + } + }, + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 16 } + } + }], + kind: 'var', + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/[a-c]/i', + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 16 } + } + }] + }, + + 'var x = /[P QR]/i': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/[P QR]/i', + raw: '/[P QR]/i', + range: [8, 17], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 17 } + } + }, + range: [4, 17], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 17 } + } + }], + kind: 'var', + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }], + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/[P QR]/i', + range: [8, 17], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 17 } + } + }] + }, + + 'var x = /foo\\/bar/': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/foo\\/bar/', + raw: '/foo\\/bar/', + range: [8, 18], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 18 } + } + }, + range: [4, 18], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 18 } + } + }], + kind: 'var', + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }], + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/foo\\/bar/', + range: [8, 18], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 18 } + } + }] + }, + + 'var x = /=([^=\\s])+/g': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/=([^=\\s])+/g', + raw: '/=([^=\\s])+/g', + range: [8, 21], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 21 } + } + }, + range: [4, 21], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 21 } + } + }], + kind: 'var', + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }], + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/=([^=\\s])+/g', + range: [8, 21], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 21 } + } + }] + }, + + 'var x = /[P QR]/\\u0067': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/[P QR]/g', + raw: '/[P QR]/\\u0067', + range: [8, 22], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 22 } + } + }, + range: [4, 22], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 22 } + } + }], + kind: 'var', + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }], + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/[P QR]/\\u0067', + range: [8, 22], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 22 } + } + }] + }, + + 'var x = /[P QR]/\\g': { + type: 'Program', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: '/[P QR]/g', + raw: '/[P QR]/\\g', + range: [8, 18], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 18 } + } + }, + range: [4, 18], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 18 } + } + }], + kind: 'var', + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }], + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + }, + tokens: [{ + type: 'Keyword', + value: 'var', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, { + type: 'Identifier', + value: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'Punctuator', + value: '=', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, { + type: 'RegularExpression', + value: '/[P QR]/\\g', + range: [8, 18], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 18 } + } + }] + } + + }, + + 'Left-Hand-Side Expression': { + + 'new Button': { + type: 'ExpressionStatement', + expression: { + type: 'NewExpression', + callee: { + type: 'Identifier', + name: 'Button', + range: [4, 10], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 10 } + } + }, + 'arguments': [], + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + + 'new Button()': { + type: 'ExpressionStatement', + expression: { + type: 'NewExpression', + callee: { + type: 'Identifier', + name: 'Button', + range: [4, 10], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 10 } + } + }, + 'arguments': [], + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + + 'new new foo': { + type: 'ExpressionStatement', + expression: { + type: 'NewExpression', + callee: { + type: 'NewExpression', + callee: { + type: 'Identifier', + name: 'foo', + range: [8, 11], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 11 } + } + }, + 'arguments': [], + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + 'arguments': [], + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'new new foo()': { + type: 'ExpressionStatement', + expression: { + type: 'NewExpression', + callee: { + type: 'NewExpression', + callee: { + type: 'Identifier', + name: 'foo', + range: [8, 11], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 11 } + } + }, + 'arguments': [], + range: [4, 13], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 13 } + } + }, + 'arguments': [], + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + 'new foo().bar()': { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + computed: false, + object: { + type: 'NewExpression', + callee: { + type: 'Identifier', + name: 'foo', + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + 'arguments': [], + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + property: { + type: 'Identifier', + name: 'bar', + range: [10, 13], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + 'arguments': [], + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + range: [0, 15], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 15 } + } + }, + + 'new foo[bar]': { + type: 'ExpressionStatement', + expression: { + type: 'NewExpression', + callee: { + type: 'MemberExpression', + computed: true, + object: { + type: 'Identifier', + name: 'foo', + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + property: { + type: 'Identifier', + name: 'bar', + range: [8, 11], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 11 } + } + }, + range: [4, 12], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 12 } + } + }, + 'arguments': [], + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + + 'new foo.bar()': { + type: 'ExpressionStatement', + expression: { + type: 'NewExpression', + callee: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'foo', + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + property: { + type: 'Identifier', + name: 'bar', + range: [8, 11], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 11 } + } + }, + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + 'arguments': [], + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + '( new foo).bar()': { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + computed: false, + object: { + type: 'NewExpression', + callee: { + type: 'Identifier', + name: 'foo', + range: [6, 9], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 9 } + } + }, + 'arguments': [], + range: [2, 9], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 9 } + } + }, + property: { + type: 'Identifier', + name: 'bar', + range: [11, 14], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + 'arguments': [], + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + 'foo(bar, baz)': { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'foo', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'bar', + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, { + type: 'Identifier', + name: 'baz', + range: [9, 12], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 12 } + } + }], + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + '( foo )()': { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'foo', + range: [5, 8], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 8 } + } + }, + 'arguments': [], + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + 'universe.milkyway': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'milkyway', + range: [9, 17], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + + 'universe.milkyway.solarsystem': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'milkyway', + range: [9, 17], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + property: { + type: 'Identifier', + name: 'solarsystem', + range: [18, 29], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 29 } + } + }, + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + + 'universe.milkyway.solarsystem.Earth': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'MemberExpression', + computed: false, + object: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'milkyway', + range: [9, 17], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + property: { + type: 'Identifier', + name: 'solarsystem', + range: [18, 29], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 29 } + } + }, + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + property: { + type: 'Identifier', + name: 'Earth', + range: [30, 35], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 35 } + } + }, + range: [0, 35], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 35 } + } + }, + range: [0, 35], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 35 } + } + }, + + 'universe[galaxyName, otherUselessName]': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: true, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'SequenceExpression', + expressions: [{ + type: 'Identifier', + name: 'galaxyName', + range: [9, 19], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 19 } + } + }, { + type: 'Identifier', + name: 'otherUselessName', + range: [21, 37], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 37 } + } + }], + range: [9, 37], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 37 } + } + }, + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + }, + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + }, + + 'universe[galaxyName]': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: true, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'galaxyName', + range: [9, 19], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 19 } + } + }, + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + + 'universe[42].galaxies': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'MemberExpression', + computed: true, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Literal', + value: 42, + raw: '42', + range: [9, 11], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + property: { + type: 'Identifier', + name: 'galaxies', + range: [13, 21], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + + 'universe(42).galaxies': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + 'arguments': [{ + type: 'Literal', + value: 42, + raw: '42', + range: [9, 11], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 11 } + } + }], + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + property: { + type: 'Identifier', + name: 'galaxies', + range: [13, 21], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + + 'universe(42).galaxies(14, 3, 77).milkyway': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + computed: false, + object: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + 'arguments': [{ + type: 'Literal', + value: 42, + raw: '42', + range: [9, 11], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 11 } + } + }], + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + property: { + type: 'Identifier', + name: 'galaxies', + range: [13, 21], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + 'arguments': [{ + type: 'Literal', + value: 14, + raw: '14', + range: [22, 24], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 24 } + } + }, { + type: 'Literal', + value: 3, + raw: '3', + range: [26, 27], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 27 } + } + }, { + type: 'Literal', + value: 77, + raw: '77', + range: [29, 31], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 31 } + } + }], + range: [0, 32], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 32 } + } + }, + property: { + type: 'Identifier', + name: 'milkyway', + range: [33, 41], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 41 } + } + }, + range: [0, 41], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 41 } + } + }, + range: [0, 41], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 41 } + } + }, + + 'earth.asia.Indonesia.prepareForElection(2014)': { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'MemberExpression', + computed: false, + object: { + type: 'MemberExpression', + computed: false, + object: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'earth', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + property: { + type: 'Identifier', + name: 'asia', + range: [6, 10], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 10 } + } + }, + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + property: { + type: 'Identifier', + name: 'Indonesia', + range: [11, 20], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 20 } + } + }, + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + property: { + type: 'Identifier', + name: 'prepareForElection', + range: [21, 39], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 39 } + } + }, + range: [0, 39], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 39 } + } + }, + 'arguments': [{ + type: 'Literal', + value: 2014, + raw: '2014', + range: [40, 44], + loc: { + start: { line: 1, column: 40 }, + end: { line: 1, column: 44 } + } + }], + range: [0, 45], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 45 } + } + }, + range: [0, 45], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 45 } + } + }, + + 'universe.if': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'if', + range: [9, 11], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'universe.true': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'true', + range: [9, 13], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + 'universe.false': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'false', + range: [9, 14], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + 'universe.null': { + type: 'ExpressionStatement', + expression: { + type: 'MemberExpression', + computed: false, + object: { + type: 'Identifier', + name: 'universe', + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + property: { + type: 'Identifier', + name: 'null', + range: [9, 13], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + } + + }, + + 'Postfix Expressions': { + + 'x++': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + prefix: false, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + 'x--': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + prefix: false, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + 'eval++': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'eval', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + prefix: false, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'eval--': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'eval', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + prefix: false, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'arguments++': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'arguments', + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + prefix: false, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'arguments--': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'arguments', + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + prefix: false, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + } + + }, + + 'Unary Operators': { + + '++x': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'x', + range: [2, 3], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 3 } + } + }, + prefix: true, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + '--x': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'x', + range: [2, 3], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 3 } + } + }, + prefix: true, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + '++eval': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'eval', + range: [2, 6], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 6 } + } + }, + prefix: true, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + '--eval': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'eval', + range: [2, 6], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 6 } + } + }, + prefix: true, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + '++arguments': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'arguments', + range: [2, 11], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 11 } + } + }, + prefix: true, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + '--arguments': { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'arguments', + range: [2, 11], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 11 } + } + }, + prefix: true, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + '+x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: '+', + argument: { + type: 'Identifier', + name: 'x', + range: [1, 2], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + + '-x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: '-', + argument: { + type: 'Identifier', + name: 'x', + range: [1, 2], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + + '~x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: '~', + argument: { + type: 'Identifier', + name: 'x', + range: [1, 2], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + + '!x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: '!', + argument: { + type: 'Identifier', + name: 'x', + range: [1, 2], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + }, + + 'void x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: 'void', + argument: { + type: 'Identifier', + name: 'x', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'delete x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: 'delete', + argument: { + type: 'Identifier', + name: 'x', + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + 'typeof x': { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: 'typeof', + argument: { + type: 'Identifier', + name: 'x', + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + } + + }, + + 'Multiplicative Operators': { + + 'x * y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x / y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '/', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x % y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '%', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + } + + }, + + 'Additive Operators': { + + 'x + y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x - y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '-', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + } + + }, + + 'Bitwise Shift Operator': { + + 'x << y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '<<', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x >> y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '>>', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x >>> y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '>>>', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + } + + }, + + 'Relational Operators': { + + 'x < y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x > y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '>', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x <= y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '<=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x >= y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '>=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x in y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: 'in', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x instanceof y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: 'instanceof', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [13, 14], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + 'x < y < z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + } + + }, + + 'Equality Operators': { + + 'x == y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '==', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x != y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '!=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x === y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '===', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x !== y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '!==', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + } + + }, + + 'Binary Bitwise Operators': { + + 'x & y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '&', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x ^ y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '^', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'x | y': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '|', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + } + + }, + + 'Binary Expressions': { + + 'x + y + z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x - y + z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'BinaryExpression', + operator: '-', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x + y - z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '-', + left: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x - y - z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '-', + left: { + type: 'BinaryExpression', + operator: '-', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x + y * z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x + y / z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '+', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'BinaryExpression', + operator: '/', + left: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x - y % z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '-', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'BinaryExpression', + operator: '%', + left: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x * y * z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x * y / z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '/', + left: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x * y % z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '%', + left: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x % y * z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'BinaryExpression', + operator: '%', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x << y << z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '<<', + left: { + type: 'BinaryExpression', + operator: '<<', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'x | y | z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '|', + left: { + type: 'BinaryExpression', + operator: '|', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x & y & z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '&', + left: { + type: 'BinaryExpression', + operator: '&', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x ^ y ^ z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '^', + left: { + type: 'BinaryExpression', + operator: '^', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x & y | z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '|', + left: { + type: 'BinaryExpression', + operator: '&', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x | y ^ z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '|', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'BinaryExpression', + operator: '^', + left: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x | y & z': { + type: 'ExpressionStatement', + expression: { + type: 'BinaryExpression', + operator: '|', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'BinaryExpression', + operator: '&', + left: { + type: 'Identifier', + name: 'y', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + } + + }, + + 'Binary Logical Operators': { + + 'x || y': { + type: 'ExpressionStatement', + expression: { + type: 'LogicalExpression', + operator: '||', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x && y': { + type: 'ExpressionStatement', + expression: { + type: 'LogicalExpression', + operator: '&&', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'x || y || z': { + type: 'ExpressionStatement', + expression: { + type: 'LogicalExpression', + operator: '||', + left: { + type: 'LogicalExpression', + operator: '||', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'x && y && z': { + type: 'ExpressionStatement', + expression: { + type: 'LogicalExpression', + operator: '&&', + left: { + type: 'LogicalExpression', + operator: '&&', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'x || y && z': { + type: 'ExpressionStatement', + expression: { + type: 'LogicalExpression', + operator: '||', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'LogicalExpression', + operator: '&&', + left: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + range: [5, 11], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'x || y ^ z': { + type: 'ExpressionStatement', + expression: { + type: 'LogicalExpression', + operator: '||', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'BinaryExpression', + operator: '^', + left: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + right: { + type: 'Identifier', + name: 'z', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + range: [5, 10], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 10 } + } + }, + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + } + + }, + + 'Conditional Operator': { + + 'y ? 1 : 2': { + type: 'ExpressionStatement', + expression: { + type: 'ConditionalExpression', + test: { + type: 'Identifier', + name: 'y', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + consequent: { + type: 'Literal', + value: 1, + raw: '1', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + alternate: { + type: 'Literal', + value: 2, + raw: '2', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x && y ? 1 : 2': { + type: 'ExpressionStatement', + expression: { + type: 'ConditionalExpression', + test: { + type: 'LogicalExpression', + operator: '&&', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + consequent: { + type: 'Literal', + value: 1, + raw: '1', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + alternate: { + type: 'Literal', + value: 2, + raw: '2', + range: [13, 14], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + } + + }, + + 'Assignment Operators': { + + 'x = 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'eval = 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'eval', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [7, 9], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'arguments = 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'arguments', + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [12, 14], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + 'x *= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '*=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x /= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '/=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x %= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '%=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x += 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '+=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x -= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '-=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x <<= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '<<=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [6, 8], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + 'x >>= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '>>=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [6, 8], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + 'x >>>= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '>>>=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [7, 9], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'x &= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '&=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x ^= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '^=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + 'x |= 42': { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '|=', + left: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [5, 7], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + } + + }, + + 'Block': { + + '{ foo }': { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'foo', + range: [2, 5], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 5 } + } + }, + range: [2, 6], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 6 } + } + }], + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + '{ doThis(); doThat(); }': { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'doThis', + range: [2, 8], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 8 } + } + }, + 'arguments': [], + range: [2, 10], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 10 } + } + }, + range: [2, 11], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 11 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'doThat', + range: [12, 18], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 18 } + } + }, + 'arguments': [], + range: [12, 20], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 20 } + } + }, + range: [12, 21], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 21 } + } + }], + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + } + }, + + '{}': { + type: 'BlockStatement', + body: [], + range: [0, 2], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 2 } + } + } + + }, + + 'Variable Statement': { + + 'var x': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: null, + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }], + kind: 'var', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + 'var x, y;': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: null, + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'y', + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }, + init: null, + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }], + kind: 'var', + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'var x = 42': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [8, 10], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 10 } + } + }, + range: [4, 10], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 10 } + } + }], + kind: 'var', + range: [0, 10], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 10 } + } + }, + + 'var eval = 42, arguments = 42': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'eval', + range: [4, 8], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 8 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [11, 13], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 13 } + } + }, + range: [4, 13], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'arguments', + range: [15, 24], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 24 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [27, 29], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 29 } + } + }, + range: [15, 29], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 29 } + } + }], + kind: 'var', + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + + 'var x = 14, y = 3, z = 1977': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: { + type: 'Literal', + value: 14, + raw: '14', + range: [8, 10], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 10 } + } + }, + range: [4, 10], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 10 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'y', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }, + init: { + type: 'Literal', + value: 3, + raw: '3', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }, + range: [12, 17], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 17 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'z', + range: [19, 20], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 20 } + } + }, + init: { + type: 'Literal', + value: 1977, + raw: '1977', + range: [23, 27], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 27 } + } + }, + range: [19, 27], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 27 } + } + }], + kind: 'var', + range: [0, 27], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 27 } + } + }, + + 'var implements, interface, package': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'implements', + range: [4, 14], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 14 } + } + }, + init: null, + range: [4, 14], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 14 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'interface', + range: [16, 25], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 25 } + } + }, + init: null, + range: [16, 25], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 25 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'package', + range: [27, 34], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 34 } + } + }, + init: null, + range: [27, 34], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 34 } + } + }], + kind: 'var', + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + + 'var private, protected, public, static': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'private', + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + init: null, + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'protected', + range: [13, 22], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 22 } + } + }, + init: null, + range: [13, 22], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 22 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'public', + range: [24, 30], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 30 } + } + }, + init: null, + range: [24, 30], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 30 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'static', + range: [32, 38], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 38 } + } + }, + init: null, + range: [32, 38], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 38 } + } + }], + kind: 'var', + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + } + + }, + + 'Let Statement': { + + 'let x': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: null, + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }], + kind: 'let', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + + '{ let x }': { + type: 'BlockStatement', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + init: null, + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }], + kind: 'let', + range: [2, 8], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 8 } + } + }], + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + '{ let x = 42 }': { + type: 'BlockStatement', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }], + kind: 'let', + range: [2, 13], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 13 } + } + }], + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + }, + + '{ let x = 14, y = 3, z = 1977 }': { + type: 'BlockStatement', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + init: { + type: 'Literal', + value: 14, + raw: '14', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'y', + range: [14, 15], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 15 } + } + }, + init: { + type: 'Literal', + value: 3, + raw: '3', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + range: [14, 19], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 19 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'z', + range: [21, 22], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 22 } + } + }, + init: { + type: 'Literal', + value: 1977, + raw: '1977', + range: [25, 29], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 29 } + } + }, + range: [21, 29], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 29 } + } + }], + kind: 'let', + range: [2, 30], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 30 } + } + }], + range: [0, 31], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 31 } + } + } + + }, + + 'Const Statement': { + + 'const x = 42': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }], + kind: 'const', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + + '{ const x = 42 }': { + type: 'BlockStatement', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [12, 14], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 14 } + } + }, + range: [8, 14], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 14 } + } + }], + kind: 'const', + range: [2, 15], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 15 } + } + }], + range: [0, 16], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 16 } + } + }, + + '{ const x = 14, y = 3, z = 1977 }': { + type: 'BlockStatement', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + init: { + type: 'Literal', + value: 14, + raw: '14', + range: [12, 14], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 14 } + } + }, + range: [8, 14], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 14 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'y', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }, + init: { + type: 'Literal', + value: 3, + raw: '3', + range: [20, 21], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 21 } + } + }, + range: [16, 21], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 21 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'z', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }, + init: { + type: 'Literal', + value: 1977, + raw: '1977', + range: [27, 31], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 31 } + } + }, + range: [23, 31], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 31 } + } + }], + kind: 'const', + range: [2, 32], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 32 } + } + }], + range: [0, 33], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 33 } + } + } + + }, + + 'Empty Statement': { + + ';': { + type: 'EmptyStatement', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + } + + }, + + 'Expression Statement': { + + 'x': { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, + + 'x, y': { + type: 'ExpressionStatement', + expression: { + type: 'SequenceExpression', + expressions: [{ + type: 'Identifier', + name: 'x', + range: [0, 1], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 1 } + } + }, { + type: 'Identifier', + name: 'y', + range: [3, 4], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 4 } + } + }], + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + + '\\u0061': { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'a', + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }, + + 'a\\u0061': { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'aa', + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 7], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 7 } + } + }, + + '\\ua': { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'ua', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + + 'a\\u': { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'au', + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + }, + range: [0, 3], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 3 } + } + } + + }, + + 'If Statement': { + + 'if (morning) goodMorning()': { + type: 'IfStatement', + test: { + type: 'Identifier', + name: 'morning', + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + consequent: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'goodMorning', + range: [13, 24], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 24 } + } + }, + 'arguments': [], + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + }, + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + }, + alternate: null, + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + } + }, + + 'if (morning) (function(){})': { + type: 'IfStatement', + test: { + type: 'Identifier', + name: 'morning', + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + consequent: { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [24, 26], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 26 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 26], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 26 } + } + }, + range: [13, 27], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 27 } + } + }, + alternate: null, + range: [0, 27], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 27 } + } + }, + + 'if (morning) var x = 0;': { + type: 'IfStatement', + test: { + type: 'Identifier', + name: 'morning', + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + consequent: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [17, 18], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 18 } + } + }, + init: { + type: 'Literal', + value: 0, + raw: '0', + range: [21, 22], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 22 } + } + }, + range: [17, 22], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 22 } + } + }], + kind: 'var', + range: [13, 23], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 23 } + } + }, + alternate: null, + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + } + }, + + 'if (morning) function a(){}': { + type: 'IfStatement', + test: { + type: 'Identifier', + name: 'morning', + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + consequent: { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'a', + range: [22, 23], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 23 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [25, 27], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 27 } + } + }, + rest: null, + generator: false, + expression: false, + range: [13, 27], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 27 } + } + }, + alternate: null, + range: [0, 27], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 27 } + } + }, + + 'if (morning) goodMorning(); else goodDay()': { + type: 'IfStatement', + test: { + type: 'Identifier', + name: 'morning', + range: [4, 11], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 11 } + } + }, + consequent: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'goodMorning', + range: [13, 24], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 24 } + } + }, + 'arguments': [], + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + }, + range: [13, 27], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 27 } + } + }, + alternate: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'goodDay', + range: [33, 40], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 40 } + } + }, + 'arguments': [], + range: [33, 42], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 42 } + } + }, + range: [33, 42], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 42 } + } + }, + range: [0, 42], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 42 } + } + } + + }, + + 'Iteration Statements': { + + 'do keep(); while (true)': { + type: 'DoWhileStatement', + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'keep', + range: [3, 7], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 7 } + } + }, + 'arguments': [], + range: [3, 9], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 9 } + } + }, + range: [3, 10], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 10 } + } + }, + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [18, 22], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + } + }, + + 'do keep(); while (true);': { + type: 'DoWhileStatement', + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'keep', + range: [3, 7], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 7 } + } + }, + 'arguments': [], + range: [3, 9], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 9 } + } + }, + range: [3, 10], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 10 } + } + }, + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [18, 22], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + + 'do { x++; y--; } while (x < 10)': { + type: 'DoWhileStatement', + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'x', + range: [5, 6], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 6 } + } + }, + prefix: false, + range: [5, 8], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 8 } + } + }, + range: [5, 9], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 9 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'y', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + prefix: false, + range: [10, 13], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 13 } + } + }, + range: [10, 14], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 14 } + } + }], + range: [3, 16], + loc: { + start: { line: 1, column: 3 }, + end: { line: 1, column: 16 } + } + }, + test: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + right: { + type: 'Literal', + value: 10, + raw: '10', + range: [28, 30], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 30 } + } + }, + range: [24, 30], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 30 } + } + }, + range: [0, 31], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 31 } + } + }, + + '{ do { } while (false) false }': { + type: 'BlockStatement', + body: [{ + type: 'DoWhileStatement', + body: { + type: 'BlockStatement', + body: [], + range: [5, 8], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 8 } + } + }, + test: { + type: 'Literal', + value: false, + raw: 'false', + range: [16, 21], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 21 } + } + }, + range: [2, 22], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 22 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: false, + raw: 'false', + range: [23, 28], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 28 } + } + }, + range: [23, 29], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 29 } + } + }], + range: [0, 30], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 30 } + } + }, + + 'while (true) doSomething()': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'doSomething', + range: [13, 24], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 24 } + } + }, + 'arguments': [], + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + }, + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + }, + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + } + }, + + 'while (x < 10) { x++; y--; }': { + type: 'WhileStatement', + test: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }, + right: { + type: 'Literal', + value: 10, + raw: '10', + range: [11, 13], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 13 } + } + }, + range: [7, 13], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 13 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'x', + range: [17, 18], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 18 } + } + }, + prefix: false, + range: [17, 20], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 20 } + } + }, + range: [17, 21], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 21 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'y', + range: [22, 23], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 23 } + } + }, + prefix: false, + range: [22, 25], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 25 } + } + }, + range: [22, 26], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 26 } + } + }], + range: [15, 28], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 28 } + } + }, + range: [0, 28], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 28 } + } + }, + + 'for(;;);': { + type: 'ForStatement', + init: null, + test: null, + update: null, + body: { + type: 'EmptyStatement', + range: [7, 8], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 8 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + 'for(;;){}': { + type: 'ForStatement', + init: null, + test: null, + update: null, + body: { + type: 'BlockStatement', + body: [], + range: [7, 9], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + }, + + 'for(x = 0;;);': { + type: 'ForStatement', + init: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Literal', + value: 0, + raw: '0', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + test: null, + update: null, + body: { + type: 'EmptyStatement', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + 'for(var x = 0;;);': { + type: 'ForStatement', + init: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + init: { + type: 'Literal', + value: 0, + raw: '0', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }, + range: [8, 13], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 13 } + } + }], + kind: 'var', + range: [4, 13], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 13 } + } + }, + test: null, + update: null, + body: { + type: 'EmptyStatement', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + + 'for(let x = 0;;);': { + type: 'ForStatement', + init: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + init: { + type: 'Literal', + value: 0, + raw: '0', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }, + range: [8, 13], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 13 } + } + }], + kind: 'let', + range: [4, 13], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 13 } + } + }, + test: null, + update: null, + body: { + type: 'EmptyStatement', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }, + range: [0, 17], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 17 } + } + }, + + 'for(var x = 0, y = 1;;);': { + type: 'ForStatement', + init: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + init: { + type: 'Literal', + value: 0, + raw: '0', + range: [12, 13], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 13 } + } + }, + range: [8, 13], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'y', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }, + init: { + type: 'Literal', + value: 1, + raw: '1', + range: [19, 20], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 20 } + } + }, + range: [15, 20], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 20 } + } + }], + kind: 'var', + range: [4, 20], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 20 } + } + }, + test: null, + update: null, + body: { + type: 'EmptyStatement', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + + 'for(x = 0; x < 42;);': { + type: 'ForStatement', + init: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Literal', + value: 0, + raw: '0', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + test: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [11, 12], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 12 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + range: [11, 17], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 17 } + } + }, + update: null, + body: { + type: 'EmptyStatement', + range: [19, 20], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 20 } + } + }, + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + + 'for(x = 0; x < 42; x++);': { + type: 'ForStatement', + init: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Literal', + value: 0, + raw: '0', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + test: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [11, 12], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 12 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + range: [11, 17], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 17 } + } + }, + update: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'x', + range: [19, 20], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 20 } + } + }, + prefix: false, + range: [19, 22], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 22 } + } + }, + body: { + type: 'EmptyStatement', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + + 'for(x = 0; x < 42; x++) process(x);': { + type: 'ForStatement', + init: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Literal', + value: 0, + raw: '0', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + test: { + type: 'BinaryExpression', + operator: '<', + left: { + type: 'Identifier', + name: 'x', + range: [11, 12], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 12 } + } + }, + right: { + type: 'Literal', + value: 42, + raw: '42', + range: [15, 17], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 17 } + } + }, + range: [11, 17], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 17 } + } + }, + update: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'x', + range: [19, 20], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 20 } + } + }, + prefix: false, + range: [19, 22], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 22 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [24, 31], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 31 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [32, 33], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 33 } + } + }], + range: [24, 34], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 34 } + } + }, + range: [24, 35], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 35 } + } + }, + range: [0, 35], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 35 } + } + }, + + 'for(x in list) process(x);': { + type: 'ForInStatement', + left: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + right: { + type: 'Identifier', + name: 'list', + range: [9, 13], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 13 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [15, 22], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 22 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }], + range: [15, 25], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 25 } + } + }, + range: [15, 26], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 26 } + } + }, + each: false, + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + } + }, + + 'for (var x in list) process(x);': { + type: 'ForInStatement', + left: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + init: null, + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }], + kind: 'var', + range: [5, 10], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 10 } + } + }, + right: { + type: 'Identifier', + name: 'list', + range: [14, 18], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 18 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [20, 27], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 27 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [28, 29], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 29 } + } + }], + range: [20, 30], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 30 } + } + }, + range: [20, 31], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 31 } + } + }, + each: false, + range: [0, 31], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 31 } + } + }, + + 'for (var x = 42 in list) process(x);': { + type: 'ForInStatement', + left: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [13, 15], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 15 } + } + }, + range: [9, 15], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 15 } + } + }], + kind: 'var', + range: [5, 15], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 15 } + } + }, + right: { + type: 'Identifier', + name: 'list', + range: [19, 23], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 23 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [25, 32], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 32 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [33, 34], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 34 } + } + }], + range: [25, 35], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 35 } + } + }, + range: [25, 36], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 36 } + } + }, + each: false, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + + 'for (let x in list) process(x);': { + type: 'ForInStatement', + left: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + init: null, + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }], + kind: 'let', + range: [5, 10], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 10 } + } + }, + right: { + type: 'Identifier', + name: 'list', + range: [14, 18], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 18 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [20, 27], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 27 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [28, 29], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 29 } + } + }], + range: [20, 30], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 30 } + } + }, + range: [20, 31], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 31 } + } + }, + each: false, + range: [0, 31], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 31 } + } + }, + + 'for (let x = 42 in list) process(x);': { + type: 'ForInStatement', + left: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + init: { + type: 'Literal', + value: 42, + raw: '42', + range: [13, 15], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 15 } + } + }, + range: [9, 15], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 15 } + } + }], + kind: 'let', + range: [5, 15], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 15 } + } + }, + right: { + type: 'Identifier', + name: 'list', + range: [19, 23], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 23 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [25, 32], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 32 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [33, 34], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 34 } + } + }], + range: [25, 35], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 35 } + } + }, + range: [25, 36], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 36 } + } + }, + each: false, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + + 'for (var i = function() { return 10 in [] } in list) process(x);': { + type: 'ForInStatement', + left: { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'i', + range: [9, 10], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 10 } + } + }, + init: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ReturnStatement', + argument: { + type: 'BinaryExpression', + operator: 'in', + left: { + type: 'Literal', + value: 10, + raw: '10', + range: [33, 35], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 35 } + } + }, + right: { + type: 'ArrayExpression', + elements: [], + range: [39, 41], + loc: { + start: { line: 1, column: 39 }, + end: { line: 1, column: 41 } + } + }, + range: [33, 41], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 41 } + } + }, + range: [26, 42], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 42 } + } + }], + range: [24, 43], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 43 } + } + }, + rest: null, + generator: false, + expression: false, + range: [13, 43], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 43 } + } + }, + range: [9, 43], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 43 } + } + }], + kind: 'var', + range: [5, 43], + loc: { + start: { line: 1, column: 5 }, + end: { line: 1, column: 43 } + } + }, + right: { + type: 'Identifier', + name: 'list', + range: [47, 51], + loc: { + start: { line: 1, column: 47 }, + end: { line: 1, column: 51 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'process', + range: [53, 60], + loc: { + start: { line: 1, column: 53 }, + end: { line: 1, column: 60 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'x', + range: [61, 62], + loc: { + start: { line: 1, column: 61 }, + end: { line: 1, column: 62 } + } + }], + range: [53, 63], + loc: { + start: { line: 1, column: 53 }, + end: { line: 1, column: 63 } + } + }, + range: [53, 64], + loc: { + start: { line: 1, column: 53 }, + end: { line: 1, column: 64 } + } + }, + each: false, + range: [0, 64], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 64 } + } + } + + }, + + 'continue statement': { + + 'while (true) { continue; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'ContinueStatement', + label: null, + range: [15, 24], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 24 } + } + } + ], + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + }, + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + } + }, + + 'while (true) { continue }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'ContinueStatement', + label: null, + range: [15, 24], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 24 } + } + } + ], + range: [13, 25], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 25 } + } + }, + range: [0, 25], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 25 } + } + }, + + 'done: while (true) { continue done }': { + type: 'LabeledStatement', + label: { + type: 'Identifier', + name: 'done', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + body: { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [13, 17], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 17 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'ContinueStatement', + label: { + type: 'Identifier', + name: 'done', + range: [30, 34], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 34 } + } + }, + range: [21, 35], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 35 } + } + } + ], + range: [19, 36], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 36 } + } + }, + range: [6, 36], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + } + }, + + 'done: while (true) { continue done; }': { + type: 'LabeledStatement', + label: { + type: 'Identifier', + name: 'done', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + body: { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [13, 17], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 17 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'ContinueStatement', + label: { + type: 'Identifier', + name: 'done', + range: [30, 34], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 34 } + } + }, + range: [21, 35], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 35 } + } + } + ], + range: [19, 37], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 37 } + } + }, + range: [6, 37], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 37 } + } + }, + range: [0, 37], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 37 } + } + } + + }, + + 'break statement': { + + 'while (true) { break }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'BreakStatement', + label: null, + range: [15, 21], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 21 } + } + } + ], + range: [13, 22], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + + 'done: while (true) { break done }': { + type: 'LabeledStatement', + label: { + type: 'Identifier', + name: 'done', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + body: { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [13, 17], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 17 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'BreakStatement', + label: { + type: 'Identifier', + name: 'done', + range: [27, 31], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 31 } + } + }, + range: [21, 32], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 32 } + } + } + ], + range: [19, 33], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 33 } + } + }, + range: [6, 33], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 33 } + } + }, + range: [0, 33], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 33 } + } + }, + + 'done: while (true) { break done; }': { + type: 'LabeledStatement', + label: { + type: 'Identifier', + name: 'done', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + body: { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [13, 17], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 17 } + } + }, + body: { + type: 'BlockStatement', + body: [ + { + type: 'BreakStatement', + label: { + type: 'Identifier', + name: 'done', + range: [27, 31], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 31 } + } + }, + range: [21, 32], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 32 } + } + } + ], + range: [19, 34], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 34 } + } + }, + range: [6, 34], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 34 } + } + }, + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + } + + }, + + 'return statement': { + + '(function(){ return })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: null, + range: [13, 20], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 20 } + } + } + ], + range: [11, 21], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 21 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 21], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 21 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + }, + + '(function(){ return; })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: null, + range: [13, 20], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 20 } + } + } + ], + range: [11, 22], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 22 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 22], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + } + }, + + '(function(){ return x; })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: { + type: 'Identifier', + name: 'x', + range: [20, 21], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 21 } + } + }, + range: [13, 22], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 22 } + } + } + ], + range: [11, 24], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 24 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 24], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 24 } + } + }, + range: [0, 25], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 25 } + } + }, + + '(function(){ return x * y })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'x', + range: [20, 21], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 21 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + range: [20, 25], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 25 } + } + }, + range: [13, 26], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 26 } + } + } + ], + range: [11, 27], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 27 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 27], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 27 } + } + }, + range: [0, 28], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 28 } + } + } + }, + + 'with statement': { + + 'with (x) foo = bar': { + type: 'WithStatement', + object: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'foo', + range: [9, 12], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 12 } + } + }, + right: { + type: 'Identifier', + name: 'bar', + range: [15, 18], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 18 } + } + }, + range: [9, 18], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 18 } + } + }, + range: [9, 18], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 18 } + } + }, + range: [0, 18], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 18 } + } + }, + + 'with (x) foo = bar;': { + type: 'WithStatement', + object: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + body: { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'foo', + range: [9, 12], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 12 } + } + }, + right: { + type: 'Identifier', + name: 'bar', + range: [15, 18], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 18 } + } + }, + range: [9, 18], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 18 } + } + }, + range: [9, 19], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 19 } + } + }, + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + } + }, + + 'with (x) { foo = bar }': { + type: 'WithStatement', + object: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'foo', + range: [11, 14], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 14 } + } + }, + right: { + type: 'Identifier', + name: 'bar', + range: [17, 20], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 20 } + } + }, + range: [11, 20], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 20 } + } + }, + range: [11, 21], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 21 } + } + }], + range: [9, 22], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 22 } + } + }, + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + } + } + + }, + + 'switch statement': { + + 'switch (x) {}': { + type: 'SwitchStatement', + discriminant: { + type: 'Identifier', + name: 'x', + range: [8, 9], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 9 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, + + 'switch (answer) { case 42: hi(); break; }': { + type: 'SwitchStatement', + discriminant: { + type: 'Identifier', + name: 'answer', + range: [8, 14], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 14 } + } + }, + cases: [{ + type: 'SwitchCase', + test: { + type: 'Literal', + value: 42, + raw: '42', + range: [23, 25], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 25 } + } + }, + consequent: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'hi', + range: [27, 29], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 29 } + } + }, + 'arguments': [], + range: [27, 31], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 31 } + } + }, + range: [27, 32], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 32 } + } + }, { + type: 'BreakStatement', + label: null, + range: [33, 39], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 39 } + } + }], + range: [18, 39], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 39 } + } + }], + range: [0, 41], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 41 } + } + }, + + 'switch (answer) { case 42: hi(); break; default: break }': { + type: 'SwitchStatement', + discriminant: { + type: 'Identifier', + name: 'answer', + range: [8, 14], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 14 } + } + }, + cases: [{ + type: 'SwitchCase', + test: { + type: 'Literal', + value: 42, + raw: '42', + range: [23, 25], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 25 } + } + }, + consequent: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'hi', + range: [27, 29], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 29 } + } + }, + 'arguments': [], + range: [27, 31], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 31 } + } + }, + range: [27, 32], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 32 } + } + }, { + type: 'BreakStatement', + label: null, + range: [33, 39], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 39 } + } + }], + range: [18, 39], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 39 } + } + }, { + type: 'SwitchCase', + test: null, + consequent: [{ + type: 'BreakStatement', + label: null, + range: [49, 55], + loc: { + start: { line: 1, column: 49 }, + end: { line: 1, column: 55 } + } + }], + range: [40, 55], + loc: { + start: { line: 1, column: 40 }, + end: { line: 1, column: 55 } + } + }], + range: [0, 56], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 56 } + } + } + + }, + + 'Labelled Statements': { + + 'start: for (;;) break start': { + type: 'LabeledStatement', + label: { + type: 'Identifier', + name: 'start', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + body: { + type: 'ForStatement', + init: null, + test: null, + update: null, + body: { + type: 'BreakStatement', + label: { + type: 'Identifier', + name: 'start', + range: [22, 27], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 27 } + } + }, + range: [16, 27], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 27 } + } + }, + range: [7, 27], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 27 } + } + }, + range: [0, 27], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 27 } + } + }, + + 'start: while (true) break start': { + type: 'LabeledStatement', + label: { + type: 'Identifier', + name: 'start', + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, + body: { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [14, 18], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 18 } + } + }, + body: { + type: 'BreakStatement', + label: { + type: 'Identifier', + name: 'start', + range: [26, 31], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 31 } + } + }, + range: [20, 31], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 31 } + } + }, + range: [7, 31], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 31 } + } + }, + range: [0, 31], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 31 } + } + } + + }, + + 'throw statement': { + + 'throw x;': { + type: 'ThrowStatement', + argument: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + range: [0, 8], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 8 } + } + }, + + 'throw x * y': { + type: 'ThrowStatement', + argument: { + type: 'BinaryExpression', + operator: '*', + left: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + right: { + type: 'Identifier', + name: 'y', + range: [10, 11], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 11 } + } + }, + range: [6, 11], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 11 } + } + }, + range: [0, 11], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 11 } + } + }, + + 'throw { message: "Error" }': { + type: 'ThrowStatement', + argument: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'message', + range: [8, 15], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 15 } + } + }, + value: { + type: 'Literal', + value: 'Error', + raw: '"Error"', + range: [17, 24], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 24 } + } + }, + kind: 'init', + range: [8, 24], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 24 } + } + }], + range: [6, 26], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 26 } + } + }, + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + } + } + + }, + + 'try statement': { + + 'try { } catch (e) { }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'e', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }, + body: { + type: 'BlockStatement', + body: [], + range: [18, 21], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 21 } + } + }, + range: [8, 21], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 21 } + } + }], + finalizer: null, + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + } + }, + + 'try { } catch (eval) { }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'eval', + range: [15, 19], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 19 } + } + }, + body: { + type: 'BlockStatement', + body: [], + range: [21, 24], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 24 } + } + }, + range: [8, 24], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 24 } + } + }], + finalizer: null, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + + 'try { } catch (arguments) { }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'arguments', + range: [15, 24], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 24 } + } + }, + body: { + type: 'BlockStatement', + body: [], + range: [26, 29], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 29 } + } + }, + range: [8, 29], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 29 } + } + }], + finalizer: null, + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + + 'try { } catch (e) { say(e) }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'e', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'say', + range: [20, 23], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 23 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'e', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }], + range: [20, 26], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 26 } + } + }, + range: [20, 27], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 27 } + } + }], + range: [18, 28], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 28 } + } + }, + range: [8, 28], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 28 } + } + }], + finalizer: null, + range: [0, 28], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 28 } + } + }, + + 'try { } finally { cleanup(stuff) }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [4, 7], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 7 } + } + }, + guardedHandlers: [], + handlers: [], + finalizer: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'cleanup', + range: [18, 25], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 25 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'stuff', + range: [26, 31], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 31 } + } + }], + range: [18, 32], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 32 } + } + }, + range: [18, 33], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 33 } + } + }], + range: [16, 34], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 34 } + } + }, + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + + 'try { doThat(); } catch (e) { say(e) }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'doThat', + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }, + 'arguments': [], + range: [6, 14], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 14 } + } + }, + range: [6, 15], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 15 } + } + }], + range: [4, 17], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 17 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'e', + range: [25, 26], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 26 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'say', + range: [30, 33], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 33 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'e', + range: [34, 35], + loc: { + start: { line: 1, column: 34 }, + end: { line: 1, column: 35 } + } + }], + range: [30, 36], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 36 } + } + }, + range: [30, 37], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 37 } + } + }], + range: [28, 38], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 38 } + } + }, + range: [18, 38], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 38 } + } + }], + finalizer: null, + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + }, + + 'try { doThat(); } catch (e) { say(e) } finally { cleanup(stuff) }': { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'doThat', + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }, + 'arguments': [], + range: [6, 14], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 14 } + } + }, + range: [6, 15], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 15 } + } + }], + range: [4, 17], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 17 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'e', + range: [25, 26], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 26 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'say', + range: [30, 33], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 33 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'e', + range: [34, 35], + loc: { + start: { line: 1, column: 34 }, + end: { line: 1, column: 35 } + } + }], + range: [30, 36], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 36 } + } + }, + range: [30, 37], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 37 } + } + }], + range: [28, 38], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 38 } + } + }, + range: [18, 38], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 38 } + } + }], + finalizer: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'cleanup', + range: [49, 56], + loc: { + start: { line: 1, column: 49 }, + end: { line: 1, column: 56 } + } + }, + 'arguments': [{ + type: 'Identifier', + name: 'stuff', + range: [57, 62], + loc: { + start: { line: 1, column: 57 }, + end: { line: 1, column: 62 } + } + }], + range: [49, 63], + loc: { + start: { line: 1, column: 49 }, + end: { line: 1, column: 63 } + } + }, + range: [49, 64], + loc: { + start: { line: 1, column: 49 }, + end: { line: 1, column: 64 } + } + }], + range: [47, 65], + loc: { + start: { line: 1, column: 47 }, + end: { line: 1, column: 65 } + } + }, + range: [0, 65], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 65 } + } + } + + }, + + 'debugger statement': { + + 'debugger;': { + type: 'DebuggerStatement', + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 9 } + } + } + + }, + + 'Function Definition': { + + 'function hello() { sayHi(); }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'hello', + range: [9, 14], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 14 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'sayHi', + range: [19, 24], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 24 } + } + }, + 'arguments': [], + range: [19, 26], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 26 } + } + }, + range: [19, 27], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 27 } + } + }], + range: [17, 29], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 29 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + + 'function eval() { }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'eval', + range: [9, 13], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 13 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [16, 19], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 19 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + } + }, + + 'function arguments() { }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'arguments', + range: [9, 18], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 18 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [21, 24], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 24 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + } + }, + + 'function test(t, t) { }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'test', + range: [9, 13], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 13 } + } + }, + params: [{ + type: 'Identifier', + name: 't', + range: [14, 15], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 15 } + } + }, { + type: 'Identifier', + name: 't', + range: [17, 18], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 18 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [20, 23], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 23 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + } + }, + + '(function test(t, t) { })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'test', + range: [10, 14], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 14 } + } + }, + params: [{ + type: 'Identifier', + name: 't', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }, { + type: 'Identifier', + name: 't', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [21, 24], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 24 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 24], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 24 } + } + }, + range: [0, 25], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 25 } + } + }, + + 'function eval() { function inner() { "use strict" } }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'eval', + range: [9, 13], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 13 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'inner', + range: [27, 32], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 32 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '\"use strict\"', + range: [37, 49], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 49 } + } + }, + range: [37, 50], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 50 } + } + }], + range: [35, 51], + loc: { + start: { line: 1, column: 35 }, + end: { line: 1, column: 51 } + } + }, + rest: null, + generator: false, + expression: false, + range: [18, 51], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 51 } + } + }], + range: [16, 53], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 53 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 53], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 53 } + } + }, + + 'function hello(a) { sayHi(); }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'hello', + range: [9, 14], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 14 } + } + }, + params: [{ + type: 'Identifier', + name: 'a', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'sayHi', + range: [20, 25], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 25 } + } + }, + 'arguments': [], + range: [20, 27], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 27 } + } + }, + range: [20, 28], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 28 } + } + }], + range: [18, 30], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 30 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 30], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 30 } + } + }, + + 'function hello(a, b) { sayHi(); }': { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'hello', + range: [9, 14], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 14 } + } + }, + params: [{ + type: 'Identifier', + name: 'a', + range: [15, 16], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 16 } + } + }, { + type: 'Identifier', + name: 'b', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'sayHi', + range: [23, 28], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 28 } + } + }, + 'arguments': [], + range: [23, 30], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 30 } + } + }, + range: [23, 31], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 31 } + } + }], + range: [21, 33], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 33 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 33], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 33 } + } + }, + + 'var hi = function() { sayHi() };': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'hi', + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + init: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'sayHi', + range: [22, 27], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 27 } + } + }, + 'arguments': [], + range: [22, 29], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 29 } + } + }, + range: [22, 30], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 30 } + } + }], + range: [20, 31], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 31 } + } + }, + rest: null, + generator: false, + expression: false, + range: [9, 31], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 31 } + } + }, + range: [4, 31], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 31 } + } + }], + kind: 'var', + range: [0, 32], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 32 } + } + }, + + 'var hi = function eval() { };': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'hi', + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + init: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'eval', + range: [18, 22], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 22 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [25, 28], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 28 } + } + }, + rest: null, + generator: false, + expression: false, + range: [9, 28], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 28 } + } + }, + range: [4, 28], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 28 } + } + }], + kind: 'var', + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 29 } + } + }, + + 'var hi = function arguments() { };': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'hi', + range: [4, 6], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 6 } + } + }, + init: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'arguments', + range: [18, 27], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 27 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [30, 33], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 33 } + } + }, + rest: null, + generator: false, + expression: false, + range: [9, 33], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 33 } + } + }, + range: [4, 33], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 33 } + } + }], + kind: 'var', + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + } + }, + + 'var hello = function hi() { sayHi() };': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'hello', + range: [4, 9], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 9 } + } + }, + init: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'hi', + range: [21, 23], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 23 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'Identifier', + name: 'sayHi', + range: [28, 33], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 33 } + } + }, + 'arguments': [], + range: [28, 35], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 35 } + } + }, + range: [28, 36], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 36 } + } + }], + range: [26, 37], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 37 } + } + }, + rest: null, + generator: false, + expression: false, + range: [12, 37], + loc: { + start: { line: 1, column: 12 }, + end: { line: 1, column: 37 } + } + }, + range: [4, 37], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 37 } + } + }], + kind: 'var', + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + } + }, + + '(function(){})': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [11, 13], + loc: { + start: { line: 1, column: 11 }, + end: { line: 1, column: 13 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 13], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 13 } + } + }, + range: [0, 14], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 14 } + } + } + + }, + + 'Automatic semicolon insertion': { + + '{ x\n++y }': { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'x', + range: [2, 3], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 3 } + } + }, + range: [2, 4], + loc: { + start: { line: 1, column: 2 }, + end: { line: 2, column: 0 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'y', + range: [6, 7], + loc: { + start: { line: 2, column: 2 }, + end: { line: 2, column: 3 } + } + }, + prefix: true, + range: [4, 7], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 3 } + } + }, + range: [4, 8], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 4 } + } + }], + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 5 } + } + }, + + '{ x\n--y }': { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'x', + range: [2, 3], + loc: { + start: { line: 1, column: 2 }, + end: { line: 1, column: 3 } + } + }, + range: [2, 4], + loc: { + start: { line: 1, column: 2 }, + end: { line: 2, column: 0 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'y', + range: [6, 7], + loc: { + start: { line: 2, column: 2 }, + end: { line: 2, column: 3 } + } + }, + prefix: true, + range: [4, 7], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 3 } + } + }, + range: [4, 8], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 4 } + } + }], + range: [0, 9], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 5 } + } + }, + + 'var x /* comment */;': { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }, + init: null, + range: [4, 5], + loc: { + start: { line: 1, column: 4 }, + end: { line: 1, column: 5 } + } + }], + kind: 'var', + range: [0, 20], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 20 } + } + }, + + '{ var x = 14, y = 3\nz; }': { + type: 'BlockStatement', + body: [{ + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [6, 7], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 7 } + } + }, + init: { + type: 'Literal', + value: 14, + raw: '14', + range: [10, 12], + loc: { + start: { line: 1, column: 10 }, + end: { line: 1, column: 12 } + } + }, + range: [6, 12], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 12 } + } + }, { + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'y', + range: [14, 15], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 15 } + } + }, + init: { + type: 'Literal', + value: 3, + raw: '3', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + range: [14, 19], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 19 } + } + }], + kind: 'var', + range: [2, 20], + loc: { + start: { line: 1, column: 2 }, + end: { line: 2, column: 0 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'z', + range: [20, 21], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 1 } + } + }, + range: [20, 22], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + }], + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 4 } + } + }, + + 'while (true) { continue\nthere; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ContinueStatement', + label: null, + range: [15, 23], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 23 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'there', + range: [24, 29], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 5 } + } + }, + range: [24, 30], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }], + range: [13, 32], + loc: { + start: { line: 1, column: 13 }, + end: { line: 2, column: 8 } + } + }, + range: [0, 32], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 8 } + } + }, + + 'while (true) { continue // Comment\nthere; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ContinueStatement', + label: null, + range: [15, 23], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 23 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'there', + range: [35, 40], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 5 } + } + }, + range: [35, 41], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }], + range: [13, 43], + loc: { + start: { line: 1, column: 13 }, + end: { line: 2, column: 8 } + } + }, + range: [0, 43], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 8 } + } + }, + + 'while (true) { continue /* Multiline\nComment */there; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'ContinueStatement', + label: null, + range: [15, 23], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 23 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'there', + range: [47, 52], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 15 } + } + }, + range: [47, 53], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 16 } + } + }], + range: [13, 55], + loc: { + start: { line: 1, column: 13 }, + end: { line: 2, column: 18 } + } + }, + range: [0, 55], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 18 } + } + }, + + 'while (true) { break\nthere; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'BreakStatement', + label: null, + range: [15, 20], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 20 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'there', + range: [21, 26], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 5 } + } + }, + range: [21, 27], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }], + range: [13, 29], + loc: { + start: { line: 1, column: 13 }, + end: { line: 2, column: 8 } + } + }, + range: [0, 29], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 8 } + } + }, + + 'while (true) { break // Comment\nthere; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'BreakStatement', + label: null, + range: [15, 20], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 20 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'there', + range: [32, 37], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 5 } + } + }, + range: [32, 38], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }], + range: [13, 40], + loc: { + start: { line: 1, column: 13 }, + end: { line: 2, column: 8 } + } + }, + range: [0, 40], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 8 } + } + }, + + 'while (true) { break /* Multiline\nComment */there; }': { + type: 'WhileStatement', + test: { + type: 'Literal', + value: true, + raw: 'true', + range: [7, 11], + loc: { + start: { line: 1, column: 7 }, + end: { line: 1, column: 11 } + } + }, + body: { + type: 'BlockStatement', + body: [{ + type: 'BreakStatement', + label: null, + range: [15, 20], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 20 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'there', + range: [44, 49], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 15 } + } + }, + range: [44, 50], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 16 } + } + }], + range: [13, 52], + loc: { + start: { line: 1, column: 13 }, + end: { line: 2, column: 18 } + } + }, + range: [0, 52], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 18 } + } + }, + + '(function(){ return\nx; })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: null, + range: [13, 19], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 19 } + } + }, + { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'x', + range: [20, 21], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 1 } + } + }, + range: [20, 22], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + } + ], + range: [11, 24], + loc: { + start: { line: 1, column: 11 }, + end: { line: 2, column: 4 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 24], + loc: { + start: { line: 1, column: 1 }, + end: { line: 2, column: 4 } + } + }, + range: [0, 25], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 5 } + } + }, + + '(function(){ return // Comment\nx; })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: null, + range: [13, 19], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 19 } + } + }, + { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'x', + range: [31, 32], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 1 } + } + }, + range: [31, 33], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 2 } + } + } + ], + range: [11, 35], + loc: { + start: { line: 1, column: 11 }, + end: { line: 2, column: 4 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 35], + loc: { + start: { line: 1, column: 1 }, + end: { line: 2, column: 4 } + } + }, + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 5 } + } + }, + + '(function(){ return/* Multiline\nComment */x; })': { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [ + { + type: 'ReturnStatement', + argument: null, + range: [13, 19], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 19 } + } + }, + { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'x', + range: [42, 43], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 11 } + } + }, + range: [42, 44], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 12 } + } + } + ], + range: [11, 46], + loc: { + start: { line: 1, column: 11 }, + end: { line: 2, column: 14 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 46], + loc: { + start: { line: 1, column: 1 }, + end: { line: 2, column: 14 } + } + }, + range: [0, 47], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 15 } + } + }, + + '{ throw error\nerror; }': { + type: 'BlockStatement', + body: [{ + type: 'ThrowStatement', + argument: { + type: 'Identifier', + name: 'error', + range: [8, 13], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 13 } + } + }, + range: [2, 14], + loc: { + start: { line: 1, column: 2 }, + end: { line: 2, column: 0 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'error', + range: [14, 19], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 5 } + } + }, + range: [14, 20], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }], + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 8 } + } + }, + + '{ throw error// Comment\nerror; }': { + type: 'BlockStatement', + body: [{ + type: 'ThrowStatement', + argument: { + type: 'Identifier', + name: 'error', + range: [8, 13], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 13 } + } + }, + range: [2, 24], + loc: { + start: { line: 1, column: 2 }, + end: { line: 2, column: 0 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'error', + range: [24, 29], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 5 } + } + }, + range: [24, 30], + loc: { + start: { line: 2, column: 0 }, + end: { line: 2, column: 6 } + } + }], + range: [0, 32], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 8 } + } + }, + + '{ throw error/* Multiline\nComment */error; }': { + type: 'BlockStatement', + body: [{ + type: 'ThrowStatement', + argument: { + type: 'Identifier', + name: 'error', + range: [8, 13], + loc: { + start: { line: 1, column: 8 }, + end: { line: 1, column: 13 } + } + }, + range: [2, 36], + loc: { + start: { line: 1, column: 2 }, + end: { line: 2, column: 10 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'error', + range: [36, 41], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 15 } + } + }, + range: [36, 42], + loc: { + start: { line: 2, column: 10 }, + end: { line: 2, column: 16 } + } + }], + range: [0, 44], + loc: { + start: { line: 1, column: 0 }, + end: { line: 2, column: 18 } + } + } + + }, + + 'Source elements': { + + '': { + type: 'Program', + body: [], + range: [0, 0], + loc: { + start: { line: 0, column: 0 }, + end: { line: 0, column: 0 } + }, + tokens: [] + } + }, + + 'Invalid syntax': { + + '{': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected end of input' + }, + + '}': { + index: 0, + lineNumber: 1, + column: 1, + message: 'Error: Line 1: Unexpected token }' + }, + + '3ea': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3in []': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3e': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3e+': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3e-': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3x': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3x0': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '0x': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '09': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '018': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '01a': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '3in[]': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '0x3in[]': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '"Hello\nWorld"': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'x\\': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'x\\u005c': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'x\\u002a': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'var x = /(s/g': { + index: 13, + lineNumber: 1, + column: 14, + message: 'Error: Line 1: Invalid regular expression' + }, + + '/': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Invalid regular expression: missing /' + }, + + '/test': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Invalid regular expression: missing /' + }, + + 'var x = /[a-z]/\\ux': { + index: 18, + lineNumber: 1, + column: 19, + message: 'Error: Line 1: Invalid regular expression' + }, + + '3 = 4': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + 'func() = 4': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '(1 + 1) = 10': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '1++': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '1--': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '++1': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '--1': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + 'for((1 + 1) in list) process(x);': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Invalid left-hand side in for-in' + }, + + '[': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected end of input' + }, + + '[,': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected end of input' + }, + + '1 + {': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Unexpected end of input' + }, + + '1 + { t:t ': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Unexpected end of input' + }, + + '1 + { t:t,': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'var x = /\n/': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Invalid regular expression: missing /' + }, + + 'var x = "\n': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'var if = 42': { + index: 4, + lineNumber: 1, + column: 5, + message: 'Error: Line 1: Unexpected token if' + }, + + 'i + 2 = 42': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '+i = 42': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Invalid left-hand side in assignment' + }, + + '1 + (': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Unexpected end of input' + }, + + '\n\n\n{': { + index: 4, + lineNumber: 4, + column: 2, + message: 'Error: Line 4: Unexpected end of input' + }, + + '\n/* Some multiline\ncomment */\n)': { + index: 30, + lineNumber: 4, + column: 1, + message: 'Error: Line 4: Unexpected token )' + }, + + '{ set 1 }': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Unexpected number' + }, + + '{ get 2 }': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Unexpected number' + }, + + '({ set: s(if) { } })': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Unexpected token if' + }, + + '({ set s(.) { } })': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token .' + }, + + '({ set: s() { } })': { + index: 12, + lineNumber: 1, + column: 13, + message: 'Error: Line 1: Unexpected token {' + }, + + '({ set: s(a, b) { } })': { + index: 16, + lineNumber: 1, + column: 17, + message: 'Error: Line 1: Unexpected token {' + }, + + '({ get: g(d) { } })': { + index: 13, + lineNumber: 1, + column: 14, + message: 'Error: Line 1: Unexpected token {' + }, + + '({ get i() { }, i: 42 })': { + index: 21, + lineNumber: 1, + column: 22, + message: 'Error: Line 1: Object literal may not have data and accessor property with the same name' + }, + + '({ i: 42, get i() { } })': { + index: 21, + lineNumber: 1, + column: 22, + message: 'Error: Line 1: Object literal may not have data and accessor property with the same name' + }, + + '({ set i(x) { }, i: 42 })': { + index: 22, + lineNumber: 1, + column: 23, + message: 'Error: Line 1: Object literal may not have data and accessor property with the same name' + }, + + '({ i: 42, set i(x) { } })': { + index: 22, + lineNumber: 1, + column: 23, + message: 'Error: Line 1: Object literal may not have data and accessor property with the same name' + }, + + '({ get i() { }, get i() { } })': { + index: 27, + lineNumber: 1, + column: 28, + message: 'Error: Line 1: Object literal may not have multiple get/set accessors with the same name' + }, + + '({ set i(x) { }, set i(x) { } })': { + index: 29, + lineNumber: 1, + column: 30, + message: 'Error: Line 1: Object literal may not have multiple get/set accessors with the same name' + }, + + 'function t(if) { }': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Unexpected token if' + }, + + 'function t(true) { }': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Unexpected token true' + }, + + 'function t(false) { }': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Unexpected token false' + }, + + 'function t(null) { }': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Unexpected token null' + }, + + 'function null() { }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token null' + }, + + 'function true() { }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token true' + }, + + 'function false() { }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token false' + }, + + 'function if() { }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token if' + }, + + 'a b;': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected identifier' + }, + + 'if.a;': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token .' + }, + + 'a if;': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token if' + }, + + 'a class;': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected reserved word' + }, + + 'break\n': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Illegal break statement' + }, + + 'break 1;': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Unexpected number' + }, + + 'continue\n': { + index: 8, + lineNumber: 1, + column: 9, + message: 'Error: Line 1: Illegal continue statement' + }, + + 'continue 2;': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected number' + }, + + 'throw': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'throw;': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Unexpected token ;' + }, + + 'throw\n': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Illegal newline after throw' + }, + + 'for (var i, i2 in {});': { + index: 15, + lineNumber: 1, + column: 16, + message: 'Error: Line 1: Unexpected token in' + }, + + 'for ((i in {}));': { + index: 14, + lineNumber: 1, + column: 15, + message: 'Error: Line 1: Unexpected token )' + }, + + 'for (i + 1 in {});': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Invalid left-hand side in for-in' + }, + + 'for (+i in {});': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Invalid left-hand side in for-in' + }, + + 'if(false)': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'if(false) doThis(); else': { + index: 24, + lineNumber: 1, + column: 25, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'do': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'while(false)': { + index: 12, + lineNumber: 1, + column: 13, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'for(;;)': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'with(x)': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected end of input' + }, + + 'try { }': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Missing catch or finally after try' + }, + + '\u203F = 10': { + index: 0, + lineNumber: 1, + column: 1, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'const x = 12, y;': { + index: 15, + lineNumber: 1, + column: 16, + message: 'Error: Line 1: Unexpected token ;' + }, + + 'const x, y = 12;': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected token ,' + }, + + 'const x;': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected token ;' + }, + + 'if(true) let a = 1;': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token let' + }, + + 'if(true) const a = 1;': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token const' + }, + + 'switch (c) { default: default: }': { + index: 30, + lineNumber: 1, + column: 31, + message: 'Error: Line 1: More than one default clause in switch statement' + }, + + 'new X()."s"': { + index: 8, + lineNumber: 1, + column: 9, + message: 'Error: Line 1: Unexpected string' + }, + + '/*': { + index: 2, + lineNumber: 1, + column: 3, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '/*\n\n\n': { + index: 5, + lineNumber: 4, + column: 1, + message: 'Error: Line 4: Unexpected token ILLEGAL' + }, + + '/**': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '/*\n\n*': { + index: 5, + lineNumber: 3, + column: 2, + message: 'Error: Line 3: Unexpected token ILLEGAL' + }, + + '/*hello': { + index: 7, + lineNumber: 1, + column: 8, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '/*hello *': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '\n]': { + index: 1, + lineNumber: 2, + column: 1, + message: 'Error: Line 2: Unexpected token ]' + }, + + '\r]': { + index: 1, + lineNumber: 2, + column: 1, + message: 'Error: Line 2: Unexpected token ]' + }, + + '\r\n]': { + index: 2, + lineNumber: 2, + column: 1, + message: 'Error: Line 2: Unexpected token ]' + }, + + '\n\r]': { + index: 2, + lineNumber: 3, + column: 1, + message: 'Error: Line 3: Unexpected token ]' + }, + + '//\r\n]': { + index: 4, + lineNumber: 2, + column: 1, + message: 'Error: Line 2: Unexpected token ]' + }, + + '//\n\r]': { + index: 4, + lineNumber: 3, + column: 1, + message: 'Error: Line 3: Unexpected token ]' + }, + + '/a\\\n/': { + index: 4, + lineNumber: 1, + column: 5, + message: 'Error: Line 1: Invalid regular expression: missing /' + }, + + '//\r \n]': { + index: 5, + lineNumber: 3, + column: 1, + message: 'Error: Line 3: Unexpected token ]' + }, + + '/*\r\n*/]': { + index: 6, + lineNumber: 2, + column: 3, + message: 'Error: Line 2: Unexpected token ]' + }, + + '/*\n\r*/]': { + index: 6, + lineNumber: 3, + column: 3, + message: 'Error: Line 3: Unexpected token ]' + }, + + '/*\r \n*/]': { + index: 7, + lineNumber: 3, + column: 3, + message: 'Error: Line 3: Unexpected token ]' + }, + + '\\\\': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '\\u005c': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + + '\\x': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '\\u0000': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '\u200C = []': { + index: 0, + lineNumber: 1, + column: 1, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '\u200D = []': { + index: 0, + lineNumber: 1, + column: 1, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '"\\': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + '"\\u': { + index: 3, + lineNumber: 1, + column: 4, + message: 'Error: Line 1: Unexpected token ILLEGAL' + }, + + 'return': { + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Illegal return statement' + }, + + 'break': { + index: 5, + lineNumber: 1, + column: 6, + message: 'Error: Line 1: Illegal break statement' + }, + + 'continue': { + index: 8, + lineNumber: 1, + column: 9, + message: 'Error: Line 1: Illegal continue statement' + }, + + 'switch (x) { default: continue; }': { + index: 31, + lineNumber: 1, + column: 32, + message: 'Error: Line 1: Illegal continue statement' + }, + + 'do { x } *': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Unexpected token *' + }, + + 'while (true) { break x; }': { + index: 22, + lineNumber: 1, + column: 23, + message: 'Error: Line 1: Undefined label \'x\'' + }, + + 'while (true) { continue x; }': { + index: 25, + lineNumber: 1, + column: 26, + message: 'Error: Line 1: Undefined label \'x\'' + }, + + 'x: while (true) { (function () { break x; }); }': { + index: 40, + lineNumber: 1, + column: 41, + message: 'Error: Line 1: Undefined label \'x\'' + }, + + 'x: while (true) { (function () { continue x; }); }': { + index: 43, + lineNumber: 1, + column: 44, + message: 'Error: Line 1: Undefined label \'x\'' + }, + + 'x: while (true) { (function () { break; }); }': { + index: 39, + lineNumber: 1, + column: 40, + message: 'Error: Line 1: Illegal break statement' + }, + + 'x: while (true) { (function () { continue; }); }': { + index: 42, + lineNumber: 1, + column: 43, + message: 'Error: Line 1: Illegal continue statement' + }, + + 'x: while (true) { x: while (true) { } }': { + index: 20, + lineNumber: 1, + column: 21, + message: 'Error: Line 1: Label \'x\' has already been declared' + }, + + '(function () { \'use strict\'; delete i; }())': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Delete of an unqualified identifier in strict mode.' + }, + + '(function () { \'use strict\'; with (i); }())': { + index: 28, + lineNumber: 1, + column: 29, + message: 'Error: Line 1: Strict mode code may not include a with statement' + }, + + 'function hello() {\'use strict\'; ({ i: 42, i: 42 }) }': { + index: 47, + lineNumber: 1, + column: 48, + message: 'Error: Line 1: Duplicate data property in object literal not allowed in strict mode' + }, + + 'function hello() {\'use strict\'; ({ hasOwnProperty: 42, hasOwnProperty: 42 }) }': { + index: 73, + lineNumber: 1, + column: 74, + message: 'Error: Line 1: Duplicate data property in object literal not allowed in strict mode' + }, + + 'function hello() {\'use strict\'; var eval = 10; }': { + index: 40, + lineNumber: 1, + column: 41, + message: 'Error: Line 1: Variable name may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; var arguments = 10; }': { + index: 45, + lineNumber: 1, + column: 46, + message: 'Error: Line 1: Variable name may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; try { } catch (eval) { } }': { + index: 51, + lineNumber: 1, + column: 52, + message: 'Error: Line 1: Catch variable may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; try { } catch (arguments) { } }': { + index: 56, + lineNumber: 1, + column: 57, + message: 'Error: Line 1: Catch variable may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; eval = 10; }': { + index: 32, + lineNumber: 1, + column: 33, + message: 'Error: Line 1: Assignment to eval or arguments is not allowed in strict mode' + }, + + 'function hello() {\'use strict\'; arguments = 10; }': { + index: 32, + lineNumber: 1, + column: 33, + message: 'Error: Line 1: Assignment to eval or arguments is not allowed in strict mode' + }, + + 'function hello() {\'use strict\'; ++eval; }': { + index: 38, + lineNumber: 1, + column: 39, + message: 'Error: Line 1: Prefix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; --eval; }': { + index: 38, + lineNumber: 1, + column: 39, + message: 'Error: Line 1: Prefix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; ++arguments; }': { + index: 43, + lineNumber: 1, + column: 44, + message: 'Error: Line 1: Prefix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; --arguments; }': { + index: 43, + lineNumber: 1, + column: 44, + message: 'Error: Line 1: Prefix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; eval++; }': { + index: 36, + lineNumber: 1, + column: 37, + message: 'Error: Line 1: Postfix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; eval--; }': { + index: 36, + lineNumber: 1, + column: 37, + message: 'Error: Line 1: Postfix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; arguments++; }': { + index: 41, + lineNumber: 1, + column: 42, + message: 'Error: Line 1: Postfix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; arguments--; }': { + index: 41, + lineNumber: 1, + column: 42, + message: 'Error: Line 1: Postfix increment/decrement may not have eval or arguments operand in strict mode' + }, + + 'function hello() {\'use strict\'; function eval() { } }': { + index: 41, + lineNumber: 1, + column: 42, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; function arguments() { } }': { + index: 41, + lineNumber: 1, + column: 42, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + 'function eval() {\'use strict\'; }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + 'function arguments() {\'use strict\'; }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; (function eval() { }()) }': { + index: 42, + lineNumber: 1, + column: 43, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; (function arguments() { }()) }': { + index: 42, + lineNumber: 1, + column: 43, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + '(function eval() {\'use strict\'; })()': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + '(function arguments() {\'use strict\'; })()': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + 'function hello() {\'use strict\'; ({ s: function eval() { } }); }': { + index: 47, + lineNumber: 1, + column: 48, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }, + + '(function package() {\'use strict\'; })()': { + index: 10, + lineNumber: 1, + column: 11, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() {\'use strict\'; ({ i: 10, set s(eval) { } }); }': { + index: 48, + lineNumber: 1, + column: 49, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function hello() {\'use strict\'; ({ set s(eval) { } }); }': { + index: 41, + lineNumber: 1, + column: 42, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function hello() {\'use strict\'; ({ s: function s(eval) { } }); }': { + index: 49, + lineNumber: 1, + column: 50, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function hello(eval) {\'use strict\';}': { + index: 15, + lineNumber: 1, + column: 16, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function hello(arguments) {\'use strict\';}': { + index: 15, + lineNumber: 1, + column: 16, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function hello() { \'use strict\'; function inner(eval) {} }': { + index: 48, + lineNumber: 1, + column: 49, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function hello() { \'use strict\'; function inner(arguments) {} }': { + index: 48, + lineNumber: 1, + column: 49, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + ' "\\1"; \'use strict\';': { + index: 1, + lineNumber: 1, + column: 2, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { \'use strict\'; "\\1"; }': { + index: 33, + lineNumber: 1, + column: 34, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { \'use strict\'; 021; }': { + index: 33, + lineNumber: 1, + column: 34, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { \'use strict\'; ({ "\\1": 42 }); }': { + index: 36, + lineNumber: 1, + column: 37, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { \'use strict\'; ({ 021: 42 }); }': { + index: 36, + lineNumber: 1, + column: 37, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { "octal directive\\1"; "use strict"; }': { + index: 19, + lineNumber: 1, + column: 20, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { "octal directive\\1"; "octal directive\\2"; "use strict"; }': { + index: 19, + lineNumber: 1, + column: 20, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { "use strict"; function inner() { "octal directive\\1"; } }': { + index: 52, + lineNumber: 1, + column: 53, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }, + + 'function hello() { "use strict"; var implements; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var interface; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var package; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var private; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var protected; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var public; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var static; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var yield; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello() { "use strict"; var let; }': { + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function hello(static) { "use strict"; }': { + index: 15, + lineNumber: 1, + column: 16, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function static() { "use strict"; }': { + index: 9, + lineNumber: 1, + column: 10, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'var yield': { + index: 4, + lineNumber: 1, + column: 5, + message: 'Error: Line 1: Unexpected token yield' + }, + + 'var let': { + index: 4, + lineNumber: 1, + column: 5, + message: 'Error: Line 1: Unexpected token let' + }, + + '"use strict"; function static() { }': { + index: 23, + lineNumber: 1, + column: 24, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function a(t, t) { "use strict"; }': { + index: 14, + lineNumber: 1, + column: 15, + message: 'Error: Line 1: Strict mode function may not have duplicate parameter names' + }, + + 'function a(eval) { "use strict"; }': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + 'function a(package) { "use strict"; }': { + index: 11, + lineNumber: 1, + column: 12, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }, + + 'function a() { "use strict"; function b(t, t) { }; }': { + index: 43, + lineNumber: 1, + column: 44, + message: 'Error: Line 1: Strict mode function may not have duplicate parameter names' + }, + + '(function a(t, t) { "use strict"; })': { + index: 15, + lineNumber: 1, + column: 16, + message: 'Error: Line 1: Strict mode function may not have duplicate parameter names' + }, + + 'function a() { "use strict"; (function b(t, t) { }); }': { + index: 44, + lineNumber: 1, + column: 45, + message: 'Error: Line 1: Strict mode function may not have duplicate parameter names' + }, + + '(function a(eval) { "use strict"; })': { + index: 12, + lineNumber: 1, + column: 13, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }, + + '(function a(package) { "use strict"; })': { + index: 12, + lineNumber: 1, + column: 13, + message: 'Error: Line 1: Use of future reserved word in strict mode' + } + + }, + + 'API': { + 'parse()': { + call: 'parse', + args: [], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'undefined' + } + }] + } + }, + + 'parse(null)': { + call: 'parse', + args: [null], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: null + } + }] + } + }, + + 'parse(42)': { + call: 'parse', + args: [42], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42 + } + }] + } + }, + + 'parse(true)': { + call: 'parse', + args: [true], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: true + } + }] + } + }, + + 'parse(undefined)': { + call: 'parse', + args: [void 0], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'undefined' + } + }] + } + }, + + 'parse(new String("test"))': { + call: 'parse', + args: [new String('test')], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Identifier', + name: 'test' + } + }] + } + }, + + 'parse(new Number(42))': { + call: 'parse', + args: [new Number(42)], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 42 + } + }] + } + }, + + 'parse(new Boolean(true))': { + call: 'parse', + args: [new Boolean(true)], + result: { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: true + } + }] + } + }, + + 'Syntax': { + property: 'Syntax', + result: { + AssignmentExpression: 'AssignmentExpression', + ArrayExpression: 'ArrayExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + Program: 'Program', + Property: 'Property', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SwitchStatement: 'SwitchStatement', + SwitchCase: 'SwitchCase', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement' + } + } + + }, + + 'Tolerant parse': { + 'return': { + type: 'Program', + body: [{ + type: 'ReturnStatement', + 'argument': null, + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + } + }], + range: [0, 6], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 6 } + }, + errors: [{ + index: 6, + lineNumber: 1, + column: 7, + message: 'Error: Line 1: Illegal return statement' + }] + }, + + '(function () { \'use strict\'; with (i); }())': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '\'use strict\'', + range: [15, 27], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 27 } + } + }, + range: [15, 28], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 28 } + } + }, { + type: 'WithStatement', + object: { + type: 'Identifier', + name: 'i', + range: [35, 36], + loc: { + start: { line: 1, column: 35 }, + end: { line: 1, column: 36 } + } + }, + body: { + type: 'EmptyStatement', + range: [37, 38], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 38 } + } + }, + range: [29, 38], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 38 } + } + }], + range: [13, 40], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 40 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 40], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 40 } + } + }, + 'arguments': [], + range: [1, 42], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 42 } + } + }, + range: [0, 43], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 43 } + } + }], + range: [0, 43], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 43 } + }, + errors: [{ + index: 29, + lineNumber: 1, + column: 30, + message: 'Error: Line 1: Strict mode code may not include a with statement' + }] + }, + + '(function () { \'use strict\'; 021 }())': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'CallExpression', + callee: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '\'use strict\'', + range: [15, 27], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 27 } + } + }, + range: [15, 28], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 28 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 17, + raw: "021", + range: [29, 32], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 32 } + } + }, + range: [29, 33], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 33 } + } + }], + range: [13, 34], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [1, 34], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 34 } + } + }, + 'arguments': [], + range: [1, 36], + loc: { + start: { line: 1, column: 1 }, + end: { line: 1, column: 36 } + } + }, + range: [0, 37], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 37 } + } + }], + range: [0, 37], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 37 } + }, + errors: [{ + index: 29, + lineNumber: 1, + column: 30, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }] + }, + + '"use strict"; delete x': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UnaryExpression', + operator: 'delete', + argument: { + type: 'Identifier', + name: 'x', + range: [21, 22], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 22 } + } + }, + range: [14, 22], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 22 } + } + }, + range: [14, 22], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 22 } + } + }], + range: [0, 22], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 22 } + }, + errors: [{ + index: 22, + lineNumber: 1, + column: 23, + message: 'Error: Line 1: Delete of an unqualified identifier in strict mode.' + }] + }, + + '"use strict"; try {} catch (eval) {}': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [18, 20], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 20 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'eval', + range: [28, 32], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 32 } + } + }, + body: { + type: 'BlockStatement', + body: [], + range: [34, 36], + loc: { + start: { line: 1, column: 34 }, + end: { line: 1, column: 36 } + } + }, + range: [21, 36], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 36 } + } + }], + finalizer: null, + range: [14, 36], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 36 } + } + }], + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + }, + errors: [{ + index: 32, + lineNumber: 1, + column: 33, + message: 'Error: Line 1: Catch variable may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; try {} catch (arguments) {}': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'TryStatement', + block: { + type: 'BlockStatement', + body: [], + range: [18, 20], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 20 } + } + }, + guardedHandlers: [], + handlers: [{ + type: 'CatchClause', + param: { + type: 'Identifier', + name: 'arguments', + range: [28, 37], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 37 } + } + }, + body: { + type: 'BlockStatement', + body: [], + range: [39, 41], + loc: { + start: { line: 1, column: 39 }, + end: { line: 1, column: 41 } + } + }, + range: [21, 41], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 41 } + } + }], + finalizer: null, + range: [14, 41], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 41 } + } + }], + range: [0, 41], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 41 } + }, + errors: [{ + index: 37, + lineNumber: 1, + column: 38, + message: 'Error: Line 1: Catch variable may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; var eval;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'eval', + range: [18, 22], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 22 } + } + }, + init: null, + range: [18, 22], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 22 } + } + }], + kind: 'var', + range: [14, 23], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 23 } + } + }], + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + }, + errors: [{ + index: 22, + lineNumber: 1, + column: 23, + message: 'Error: Line 1: Variable name may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; var arguments;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'arguments', + range: [18, 27], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 27 } + } + }, + init: null, + range: [18, 27], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 27 } + } + }], + kind: 'var', + range: [14, 28], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 28 } + } + }], + range: [0, 28], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 28 } + }, + errors: [{ + index: 27, + lineNumber: 1, + column: 28, + message: 'Error: Line 1: Variable name may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; eval = 0;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'eval', + range: [14, 18], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 18 } + } + }, + right: { + type: 'Literal', + value: 0, + raw: '0', + range: [21, 22], + loc: { + start: { line: 1, column: 21 }, + end: { line: 1, column: 22 } + } + }, + range: [14, 22], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 22 } + } + }, + range: [14, 23], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 23 } + } + }], + range: [0, 23], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 23 } + }, + errors: [{ + index: 14, + lineNumber: 1, + column: 15, + message: 'Error: Line 1: Assignment to eval or arguments is not allowed in strict mode' + }] + }, + + '"use strict"; eval++;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'eval', + range: [14, 18], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 18 } + } + }, + prefix: false, + range: [14, 20], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 20 } + } + }, + range: [14, 21], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 21 } + } + }], + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + }, + errors: [{ + index: 18, + lineNumber: 1, + column: 19, + message: 'Error: Line 1: Postfix increment/decrement may not have eval or arguments operand in strict mode' + }] + }, + + '"use strict"; --eval;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'eval', + range: [16, 20], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 20 } + } + }, + prefix: true, + range: [14, 20], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 20 } + } + }, + range: [14, 21], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 21 } + } + }], + range: [0, 21], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 21 } + }, + errors: [{ + index: 20, + lineNumber: 1, + column: 21, + message: 'Error: Line 1: Prefix increment/decrement may not have eval or arguments operand in strict mode' + }] + }, + + '"use strict"; arguments = 0;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'arguments', + range: [14, 23], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 23 } + } + }, + right: { + type: 'Literal', + value: 0, + raw: '0', + range: [26, 27], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 27 } + } + }, + range: [14, 27], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 27 } + } + }, + range: [14, 28], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 28 } + } + }], + range: [0, 28], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 28 } + }, + errors: [{ + index: 14, + lineNumber: 1, + column: 15, + message: 'Error: Line 1: Assignment to eval or arguments is not allowed in strict mode' + }] + }, + + '"use strict"; arguments--;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '--', + argument: { + type: 'Identifier', + name: 'arguments', + range: [14, 23], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 23 } + } + }, + prefix: false, + range: [14, 25], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 25 } + } + }, + range: [14, 26], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 26 } + } + }], + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + }, + errors: [{ + index: 23, + lineNumber: 1, + column: 24, + message: 'Error: Line 1: Postfix increment/decrement may not have eval or arguments operand in strict mode' + }] + }, + + '"use strict"; ++arguments;': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'UpdateExpression', + operator: '++', + argument: { + type: 'Identifier', + name: 'arguments', + range: [16, 25], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 25 } + } + }, + prefix: true, + range: [14, 25], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 25 } + } + }, + range: [14, 26], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 26 } + } + }], + range: [0, 26], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 26 } + }, + errors: [{ + index: 25, + lineNumber: 1, + column: 26, + message: 'Error: Line 1: Prefix increment/decrement may not have eval or arguments operand in strict mode' + }] + }, + + + '"use strict";x={y:1,y:1}': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [13, 14], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 14 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'y', + range: [16, 17], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 17 } + } + }, + value: { + type: 'Literal', + value: 1, + raw: '1', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + kind: 'init', + range: [16, 19], + loc: { + start: { line: 1, column: 16 }, + end: { line: 1, column: 19 } + } + }, { + type: 'Property', + key: { + type: 'Identifier', + name: 'y', + range: [20, 21], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 21 } + } + }, + value: { + type: 'Literal', + value: 1, + raw: '1', + range: [22, 23], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 23 } + } + }, + kind: 'init', + range: [20, 23], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 23 } + } + }], + range: [15, 24], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 24 } + } + }, + range: [13, 24], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 24 } + } + }, + range: [13, 24], + loc: { + start: { line: 1, column: 13 }, + end: { line: 1, column: 24 } + } + }], + range: [0, 24], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 24 } + }, + errors: [{ + index: 23, + lineNumber: 1, + column: 24, + message: 'Error: Line 1: Duplicate data property in object literal not allowed in strict mode' + }] + }, + + '"use strict"; function eval() {};': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'eval', + range: [23, 27], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 27 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [30, 32], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 32 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 32], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 32 } + } + }, { + type: 'EmptyStatement', + range: [32, 33], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 33 } + } + }], + range: [0, 33], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 33 } + }, + errors: [{ + index: 23, + lineNumber: 1, + column: 24, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; function arguments() {};': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'arguments', + range: [23, 32], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 32 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [35, 37], + loc: { + start: { line: 1, column: 35 }, + end: { line: 1, column: 37 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 37], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 37 } + } + }, { + type: 'EmptyStatement', + range: [37, 38], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 38 } + } + }], + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + }, + errors: [{ + index: 23, + lineNumber: 1, + column: 24, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; function interface() {};': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'interface', + range: [23, 32], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 32 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [35, 37], + loc: { + start: { line: 1, column: 35 }, + end: { line: 1, column: 37 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 37], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 37 } + } + }, { + type: 'EmptyStatement', + range: [37, 38], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 38 } + } + }], + range: [0, 38], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 38 } + }, + errors: [{ + index: 23, + lineNumber: 1, + column: 24, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }] + }, + + '"use strict"; (function eval() {});': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'eval', + range: [24, 28], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 28 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [31, 33], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 33 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 33], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 33 } + } + }, + range: [14, 35], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 35 } + } + }], + range: [0, 35], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 35 } + }, + errors: [{ + index: 24, + lineNumber: 1, + column: 25, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; (function arguments() {});': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'arguments', + range: [24, 33], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 33 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [36, 38], + loc: { + start: { line: 1, column: 36 }, + end: { line: 1, column: 38 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 38], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 38 } + } + }, + range: [14, 40], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 40 } + } + }], + range: [0, 40], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 40 } + }, + errors: [{ + index: 24, + lineNumber: 1, + column: 25, + message: 'Error: Line 1: Function name may not be eval or arguments in strict mode' + }] + }, + + '"use strict"; (function interface() {});': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'interface', + range: [24, 33], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 33 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [36, 38], + loc: { + start: { line: 1, column: 36 }, + end: { line: 1, column: 38 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 38], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 38 } + } + }, + range: [14, 40], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 40 } + } + }], + range: [0, 40], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 40 } + }, + errors: [{ + index: 24, + lineNumber: 1, + column: 25, + message: 'Error: Line 1: Use of future reserved word in strict mode' + }] + }, + + '"use strict"; function f(eval) {};': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'f', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }, + params: [{ + type: 'Identifier', + name: 'eval', + range: [25, 29], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 29 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [31, 33], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 33 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 33], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 33 } + } + }, { + type: 'EmptyStatement', + range: [33, 34], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 34 } + } + }], + range: [0, 34], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 34 } + }, + errors: [{ + index: 25, + lineNumber: 1, + column: 26, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }] + }, + + '"use strict"; function f(arguments) {};': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'f', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }, + params: [{ + type: 'Identifier', + name: 'arguments', + range: [25, 34], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 34 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [36, 38], + loc: { + start: { line: 1, column: 36 }, + end: { line: 1, column: 38 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 38], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 38 } + } + }, { + type: 'EmptyStatement', + range: [38, 39], + loc: { + start: { line: 1, column: 38 }, + end: { line: 1, column: 39 } + } + }], + range: [0, 39], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 39 } + }, + errors: [{ + index: 25, + lineNumber: 1, + column: 26, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }] + }, + + '"use strict"; function f(foo, foo) {};': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'f', + range: [23, 24], + loc: { + start: { line: 1, column: 23 }, + end: { line: 1, column: 24 } + } + }, + params: [{ + type: 'Identifier', + name: 'foo', + range: [25, 28], + loc: { + start: { line: 1, column: 25 }, + end: { line: 1, column: 28 } + } + }, { + type: 'Identifier', + name: 'foo', + range: [31, 34], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 34 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [36, 38], + loc: { + start: { line: 1, column: 36 }, + end: { line: 1, column: 38 } + } + }, + rest: null, + generator: false, + expression: false, + range: [14, 38], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 38 } + } + }, { + type: 'EmptyStatement', + range: [38, 39], + loc: { + start: { line: 1, column: 38 }, + end: { line: 1, column: 39 } + } + }], + range: [0, 39], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 39 } + }, + errors: [{ + index: 31, + lineNumber: 1, + column: 32, + message: 'Error: Line 1: Strict mode function may not have duplicate parameter names' + }] + }, + + '"use strict"; (function f(eval) {});': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'f', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + params: [{ + type: 'Identifier', + name: 'eval', + range: [26, 30], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 30 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [32, 34], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 34], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 34 } + } + }, + range: [14, 36], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 36 } + } + }], + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + }, + errors: [{ + index: 26, + lineNumber: 1, + column: 27, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }] + }, + + + '"use strict"; (function f(arguments) {});': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'f', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + params: [{ + type: 'Identifier', + name: 'arguments', + range: [26, 35], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 35 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [37, 39], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 39 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 39], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 39 } + } + }, + range: [14, 41], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 41 } + } + }], + range: [0, 41], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 41 } + }, + errors: [{ + index: 26, + lineNumber: 1, + column: 27, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }] + }, + + '"use strict"; (function f(foo, foo) {});': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'FunctionExpression', + id: { + type: 'Identifier', + name: 'f', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + params: [{ + type: 'Identifier', + name: 'foo', + range: [26, 29], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 29 } + } + }, { + type: 'Identifier', + name: 'foo', + range: [32, 35], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 35 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [37, 39], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 39 } + } + }, + rest: null, + generator: false, + expression: false, + range: [15, 39], + loc: { + start: { line: 1, column: 15 }, + end: { line: 1, column: 39 } + } + }, + range: [14, 41], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 41 } + } + }], + range: [0, 41], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 41 } + }, + errors: [{ + index: 32, + lineNumber: 1, + column: 33, + message: 'Error: Line 1: Strict mode function may not have duplicate parameter names' + }] + }, + + '"use strict"; x = { set f(eval) {} }' : { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'AssignmentExpression', + operator: '=', + left: { + type: 'Identifier', + name: 'x', + range: [14, 15], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 15 } + } + }, + right: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'f', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + value : { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'eval', + range: [26, 30], + loc: { + start: { line: 1, column: 26 }, + end: { line: 1, column: 30 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [32, 34], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [32, 34], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 34 } + } + }, + kind: 'set', + range: [20, 34], + loc: { + start: { line: 1, column: 20 }, + end: { line: 1, column: 34 } + } + }], + range: [18, 36], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 36 } + } + }, + range: [14, 36], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 36 } + } + }, + range: [14, 36], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 36 } + } + }], + range: [0, 36], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 36 } + }, + errors: [{ + index: 26, + lineNumber: 1, + column: 27, + message: 'Error: Line 1: Parameter name eval or arguments is not allowed in strict mode' + }] + }, + + 'function hello() { "octal directive\\1"; "use strict"; }': { + type: 'Program', + body: [{ + type: 'FunctionDeclaration', + id: { + type: 'Identifier', + name: 'hello', + range: [9, 14], + loc: { + start: { line: 1, column: 9 }, + end: { line: 1, column: 14 } + } + }, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'octal directive\u0001', + raw: '"octal directive\\1"', + range: [19, 38], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 38 } + } + }, + range: [19, 39], + loc: { + start: { line: 1, column: 19 }, + end: { line: 1, column: 39 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [40, 52], + loc: { + start: { line: 1, column: 40 }, + end: { line: 1, column: 52 } + } + }, + range: [40, 53], + loc: { + start: { line: 1, column: 40 }, + end: { line: 1, column: 53 } + } + }], + range: [17, 55], + loc: { + start: { line: 1, column: 17 }, + end: { line: 1, column: 55 } + } + }, + rest: null, + generator: false, + expression: false, + range: [0, 55], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 55 } + } + }], + range: [0, 55], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 55 } + }, + errors: [{ + index: 19, + lineNumber: 1, + column: 20, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }] + }, + + '"\\1"; \'use strict\';': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: '\u0001', + raw: '"\\1"', + range: [0, 4], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 4 } + } + }, + range: [0, 5], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 5 } + } + }, { + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '\'use strict\'', + range: [6, 18], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 18 } + } + }, + range: [6, 19], + loc: { + start: { line: 1, column: 6 }, + end: { line: 1, column: 19 } + } + }], + range: [0, 19], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 19 } + }, + errors: [{ + index: 0, + lineNumber: 1, + column: 1, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }] + }, + + '"use strict"; var x = { 014: 3}': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + init: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Literal', + value: 12, + raw: '014', + range: [24, 27], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 27 } + } + }, + value: { + type: 'Literal', + value: 3, + raw: '3', + range: [29, 30], + loc: { + start: { line: 1, column: 29 }, + end: { line: 1, column: 30 } + } + }, + kind: 'init', + range: [24, 30], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 30 } + } + }], + range: [22, 31], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 31 } + } + }, + range: [18, 31], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 31 } + } + }], + kind: 'var', + range: [14, 31], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 31 } + } + }], + range: [0, 31], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 31 } + }, + errors: [{ + index: 24, + lineNumber: 1, + column: 25, + message: 'Error: Line 1: Octal literals are not allowed in strict mode.' + }] + }, + + '"use strict"; var x = { get i() {}, get i() {} }': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + init: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'i', + range: [28, 29], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 29 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [32, 34], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 34 } + } + }, + rest: null, + generator: false, + expression: false, + range: [32, 34], + loc: { + start: { line: 1, column: 32 }, + end: { line: 1, column: 34 } + } + }, + kind: 'get', + range: [24, 34], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 34 } + } + }, { + type: 'Property', + key: { + type: 'Identifier', + name: 'i', + range: [40, 41], + loc: { + start: { line: 1, column: 40 }, + end: { line: 1, column: 41 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [44, 46], + loc: { + start: { line: 1, column: 44 }, + end: { line: 1, column: 46 } + } + }, + rest: null, + generator: false, + expression: false, + range: [44, 46], + loc: { + start: { line: 1, column: 44 }, + end: { line: 1, column: 46 } + } + }, + kind: 'get', + range: [36, 46], + loc: { + start: { line: 1, column: 36 }, + end: { line: 1, column: 46 } + } + }], + range: [22, 48], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 48 } + } + }, + range: [18, 48], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 48 } + } + }], + kind: 'var', + range: [14, 48], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 48 } + } + }], + range: [0, 48], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 48 } + }, + errors: [{ + index: 46, + lineNumber: 1, + column: 47, + message: 'Error: Line 1: Object literal may not have multiple get/set accessors with the same name' + }] + }, + + '"use strict"; var x = { i: 42, get i() {} }': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + init: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'i', + range: [24, 25], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 25 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [27, 29], + loc: { + start: { line: 1, column: 27 }, + end: { line: 1, column: 29 } + } + }, + kind: 'init', + range: [24, 29], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 29 } + } + }, { + type: 'Property', + key: { + type: 'Identifier', + name: 'i', + range: [35, 36], + loc: { + start: { line: 1, column: 35 }, + end: { line: 1, column: 36 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [39, 41], + loc: { + start: { line: 1, column: 39 }, + end: { line: 1, column: 41 } + } + }, + rest: null, + generator: false, + expression: false, + range: [39, 41], + loc: { + start: { line: 1, column: 39 }, + end: { line: 1, column: 41 } + } + }, + kind: 'get', + range: [31, 41], + loc: { + start: { line: 1, column: 31 }, + end: { line: 1, column: 41 } + } + }], + range: [22, 43], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 43 } + } + }, + range: [18, 43], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 43 } + } + }], + kind: 'var', + range: [14, 43], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 43 } + } + }], + range: [0, 43], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 43 } + }, + errors: [{ + index: 41, + lineNumber: 1, + column: 42, + message: 'Error: Line 1: Object literal may not have data and accessor property with the same name' + }] + }, + + '"use strict"; var x = { set i(x) {}, i: 42 }': { + type: 'Program', + body: [{ + type: 'ExpressionStatement', + expression: { + type: 'Literal', + value: 'use strict', + raw: '"use strict"', + range: [0, 12], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 12 } + } + }, + range: [0, 13], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 13 } + } + }, { + type: 'VariableDeclaration', + declarations: [{ + type: 'VariableDeclarator', + id: { + type: 'Identifier', + name: 'x', + range: [18, 19], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 19 } + } + }, + init: { + type: 'ObjectExpression', + properties: [{ + type: 'Property', + key: { + type: 'Identifier', + name: 'i', + range: [28, 29], + loc: { + start: { line: 1, column: 28 }, + end: { line: 1, column: 29 } + } + }, + value: { + type: 'FunctionExpression', + id: null, + params: [{ + type: 'Identifier', + name: 'x', + range: [30, 31], + loc: { + start: { line: 1, column: 30 }, + end: { line: 1, column: 31 } + } + }], + defaults: [], + body: { + type: 'BlockStatement', + body: [], + range: [33, 35], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 35 } + } + }, + rest: null, + generator: false, + expression: false, + range: [33, 35], + loc: { + start: { line: 1, column: 33 }, + end: { line: 1, column: 35 } + } + }, + kind: 'set', + range: [24, 35], + loc: { + start: { line: 1, column: 24 }, + end: { line: 1, column: 35 } + } + }, { + type: 'Property', + key: { + type: 'Identifier', + name: 'i', + range: [37, 38], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 38 } + } + }, + value: { + type: 'Literal', + value: 42, + raw: '42', + range: [40, 42], + loc: { + start: { line: 1, column: 40 }, + end: { line: 1, column: 42 } + } + }, + kind: 'init', + range: [37, 42], + loc: { + start: { line: 1, column: 37 }, + end: { line: 1, column: 42 } + } + }], + range: [22, 44], + loc: { + start: { line: 1, column: 22 }, + end: { line: 1, column: 44 } + } + }, + range: [18, 44], + loc: { + start: { line: 1, column: 18 }, + end: { line: 1, column: 44 } + } + }], + kind: 'var', + range: [14, 44], + loc: { + start: { line: 1, column: 14 }, + end: { line: 1, column: 44 } + } + }], + range: [0, 44], + loc: { + start: { line: 1, column: 0 }, + end: { line: 1, column: 44 } + }, + errors: [{ + index: 42, + lineNumber: 1, + column: 43, + message: 'Error: Line 1: Object literal may not have data and accessor property with the same name' + }] + + + } + + + } +}; + diff --git a/node/node_modules/grunt/node_modules/js-yaml/package.json b/node/node_modules/grunt/node_modules/js-yaml/package.json new file mode 100644 index 000000000..2244b99c4 --- /dev/null +++ b/node/node_modules/grunt/node_modules/js-yaml/package.json @@ -0,0 +1,60 @@ +{ + "name": "js-yaml", + "version": "2.0.5", + "description": "YAML 1.2 parser and serializer", + "keywords": [ + "yaml", + "parser", + "serializer", + "pyyaml" + ], + "homepage": "https://github.com/nodeca/js-yaml", + "author": { + "name": "Dervus Grim", + "email": "dervus@lavabit.com" + }, + "contributors": [ + { + "name": "Aleksey V Zapparov", + "email": "ixti@member.fsf.org", + "url": "http://www.ixti.net/" + }, + { + "name": "Martin Grenfell", + "email": "martin.grenfell@gmail.com", + "url": "http://got-ravings.blogspot.com" + } + ], + "bugs": { + "url": "https://github.com/nodeca/js-yaml/issues" + }, + "license": { + "type": "MIT", + "url": "https://github.com/nodeca/js-yaml/blob/master/LICENSE" + }, + "repository": { + "type": "git", + "url": "git://github.com/nodeca/js-yaml.git" + }, + "main": "./index.js", + "bin": { + "js-yaml": "bin/js-yaml.js" + }, + "scripts": { + "test": "make test" + }, + "dependencies": { + "argparse": "~ 0.1.11", + "esprima": "~ 1.0.2" + }, + "devDependencies": { + "mocha": "*" + }, + "engines": { + "node": ">= 0.6.0" + }, + "readme": "JS-YAML - YAML 1.2 parser and serializer for JavaScript\n=======================================================\n\n[![Build Status](https://secure.travis-ci.org/nodeca/js-yaml.png)](http://travis-ci.org/nodeca/js-yaml)\n\n[Online Demo](http://nodeca.github.com/js-yaml/)\n\n\nThis is an implementation of [YAML](http://yaml.org/), a human friendly data\nserialization language. Started as [PyYAML](http://pyyaml.org/) port, it was\ncompletely rewritten from scratch. Now it's very fast, and supports 1.2 spec.\n\n\nBreaking changes in 1.x.x -> 2.0.x\n----------------------------------\n\nIf your have not used __custom__ tags or loader classes - no changes needed. Just\nupgrade library and enjoy high parse speed.\n\nIn other case, you should rewrite your tag constructors and custom loader\nclasses, to conform new schema-based API. See\n[examples](https://github.com/nodeca/js-yaml/tree/master/examples) and\n[wiki](https://github.com/nodeca/js-yaml/wiki) for details.\nNote, that parser internals were completely rewritten.\n\n\nInstallation\n------------\n\n### YAML module for node.js\n\n```\nnpm install js-yaml\n```\n\n\n### CLI executable\n\nIf you want to inspect your YAML files from CLI, install js-yaml globally:\n\n```\nnpm install js-yaml -g\n```\n\n#### Usage\n\n```\nusage: js-yaml [-h] [-v] [-c] [-j] [-t] file\n\nPositional arguments:\n file File with YAML document(s)\n\nOptional arguments:\n -h, --help Show this help message and exit.\n -v, --version Show program's version number and exit.\n -c, --compact Display errors in compact mode\n -j, --to-json Output a non-funky boring JSON\n -t, --trace Show stack trace on error\n```\n\n\n### Bundled YAML library for browsers\n\n``` html\n\n\n```\n\nBrowser support was done mostly for online demo. If you find any errors - feel\nfree to send pull requests with fixes. Also note, that IE and other old browsers\nneeds [es5-shims](https://github.com/kriskowal/es5-shim) to operate.\n\n\nAPI\n---\n\nHere we cover the most 'useful' methods. If you need advanced details (creating\nyour own tags), see [wiki](https://github.com/nodeca/js-yaml/wiki) and\n[examples](https://github.com/nodeca/js-yaml/tree/master/examples) for more\ninfo.\n\nIn node.js JS-YAML automatically registers handlers for `.yml` and `.yaml`\nfiles. You can load them just with `require`. That's mostly equivalent to\ncalling `load()` on fetched content of a file. Just with one string!\n\n``` javascript\nrequire('js-yaml');\n\n// Get document, or throw exception on error\ntry {\n var doc = require('/home/ixti/example.yml');\n console.log(doc);\n} catch (e) {\n console.log(e);\n}\n```\n\n\n### load (string [ , options ])\n\nParses `string` as single YAML document. Returns a JavaScript object or throws\n`YAMLException` on error.\n\nNOTE: This function **does not** understands multi-document sources, it throws\nexception on those.\n\noptions:\n\n- `filename` _(default: null)_ - string to be used as a file path in\n error/warning messages.\n- `strict` _(default - false)_ makes the loader to throw errors instead of\n warnings.\n- `schema` _(default: `DEFAULT_SCHEMA`)_ - specifies a schema to use.\n\n\n### loadAll (string, iterator [ , options ])\n\nSame as `load()`, but understands multi-document sources and apply `iterator` to\neach document.\n\n``` javascript\nvar yaml = require('js-yaml');\n\nyaml.loadAll(data, function (doc) {\n console.log(doc);\n});\n```\n\n\n### safeLoad (string [ , options ])\n\nSame as `load()` but uses `SAFE_SCHEMA` by default - only recommended tags of\nYAML specification (no JavaScript-specific tags, e.g. `!!js/regexp`).\n\n\n### safeLoadAll (string, iterator [ , options ])\n\nSame as `loadAll()` but uses `SAFE_SCHEMA` by default - only recommended tags of\nYAML specification (no JavaScript-specific tags, e.g. `!!js/regexp`).\n\n\n### dump (object [ , options ])\n\nSerializes `object` as YAML document.\n\noptions:\n\n- `indent` _(default: 2)_ - indentation width to use (in spaces).\n- `flowLevel` (default: -1) - specifies level of nesting, when to switch from\n block to flow style for collections. -1 means block style everwhere\n- `styles` - \"tag\" => \"style\" map. Each tag may have own set of styles.\n- `schema` _(default: `DEFAULT_SCHEMA`)_ specifies a schema to use.\n\nstyles:\n\n``` none\n!!null\n \"canonical\" => \"~\"\n\n!!int\n \"binary\" => \"0b1\", \"0b101010\", \"0b1110001111010\"\n \"octal\" => \"01\", \"052\", \"016172\"\n \"decimal\" => \"1\", \"42\", \"7290\"\n \"hexadecimal\" => \"0x1\", \"0x2A\", \"0x1C7A\"\n\n!!null, !!bool, !!float\n \"lowercase\" => \"null\", \"true\", \"false\", \".nan\", '.inf'\n \"uppercase\" => \"NULL\", \"TRUE\", \"FALSE\", \".NAN\", '.INF'\n \"camelcase\" => \"Null\", \"True\", \"False\", \".NaN\", '.Inf'\n```\n\nBy default, !!int uses `decimal`, and !!null, !!bool, !!float use `lowercase`.\n\n\n### safeDump (object [ , options ])\n\nSame as `dump()` but uses `SAFE_SCHEMA` by default - only recommended tags of\nYAML specification (no JavaScript-specific tags, e.g. `!!js/regexp`).\n\n\nSupported YAML types\n--------------------\n\nThe list of standard YAML tags and corresponding JavaScipt types. See also\n[YAML tag discussion](http://pyyaml.org/wiki/YAMLTagDiscussion) and\n[YAML types repository](http://yaml.org/type/).\n\n```\n!!null '' # null\n!!bool 'yes' # bool\n!!int '3...' # number\n!!float '3.14...' # number\n!!binary '...base64...' # buffer\n!!timestamp 'YYYY-...' # date\n!!omap [ ... ] # array of key-value pairs\n!!pairs [ ... ] # array or array pairs\n!!set { ... } # array of objects with given keys and null values\n!!str '...' # string\n!!seq [ ... ] # array\n!!map { ... } # object\n```\n\n**JavaScript-specific tags**\n\n```\n!!js/regexp /pattern/gim # RegExp\n!!js/undefined '' # Undefined\n!!js/function 'function () {...}' # Function\n```\n\n\n\n\n## Caveats\n\nNote, that you use arrays or objects as key in JS-YAML. JS do not allows objects\nor array as keys, and stringifies (by calling .toString method) them at the\nmoment of adding them.\n\n``` yaml\n---\n? [ foo, bar ]\n: - baz\n? { foo: bar }\n: - baz\n - baz\n```\n\n``` javascript\n{ \"foo,bar\": [\"baz\"], \"[object Object]\": [\"baz\", \"baz\"] }\n```\n\nAlso, reading of properties on implicit block mapping keys is not supported yet.\nSo, the following YAML document cannot be loaded.\n\n``` yaml\n&anchor foo:\n foo: bar\n *anchor: duplicate key\n baz: bat\n *anchor: duplicate key\n```\n\n## License\n\nView the [LICENSE](https://github.com/nodeca/js-yaml/blob/master/LICENSE) file\n(MIT).\n", + "readmeFilename": "README.md", + "_id": "js-yaml@2.0.5", + "_from": "js-yaml@~2.0.2" +} diff --git a/node/node_modules/grunt/node_modules/jshint/LICENSE b/node/node_modules/grunt/node_modules/jshint/LICENSE deleted file mode 100644 index 0b310fe7c..000000000 --- a/node/node_modules/grunt/node_modules/jshint/LICENSE +++ /dev/null @@ -1,4 +0,0 @@ -** Licensed Under ** - - The MIT License - http://www.opensource.org/licenses/mit-license.php diff --git a/node/node_modules/grunt/node_modules/jshint/README.md b/node/node_modules/grunt/node_modules/jshint/README.md deleted file mode 100644 index ac1ee12eb..000000000 --- a/node/node_modules/grunt/node_modules/jshint/README.md +++ /dev/null @@ -1,91 +0,0 @@ -# node-jshint - -A command line interface and npm package for jshint. - -## Install - -To use jshint from any location (for npm v1.x) you need to install using the global (-g) flag. - - npm install -g jshint - -## Usage - - jshint -h - -You can also require JSHint itself as a module. - - var jshint = require('jshint'); - -Note: If you are using npm v1.x be sure to install jshint locally (without the -g flag) or link it globally. - -## Text Editor Plugins - -* [gedit-node-jshint](https://github.com/niftylettuce/gedit-node-jshint) - Simply use CTRL+J in gedit to run JSHint using `node-jshint`. -* [vim syntastic](https://github.com/scrooloose/syntastic) - Run node-jshint at each file save. -* [sublime-jshint](https://github.com/uipoet/sublime-jshint) - `F7` or `command-B` on any .js file. `F4` next error line,column. `shift-F4` previous error line,column. - -## Custom Reporters - -Specify a custom reporter module (see example/reporter.js). - - --reporter path/to/reporter.js - -Use a jslint compatible xml reporter. - - --jslint-reporter - -Show additional non-error data generated by jshint (unused globals etc). - - --show-non-errors - -## Configuration Options - -**Note:** This behavior described below is very different from versions prior to `0.6`. - -The CLI uses the default options that come with JSHint. - -Only one extra option is unique to node-jshint: `globals` -allows you to define an object of globals that get ignored for every file. -To see an example you can look at how whitelisted globals are defined -in the [jshint code](https://github.com/jshint/jshint/blob/c047ea1b01097fcc220fcd1a55c41f67ae2e6e81/jshint.js#L556) - -To have your own configuration apply, there are several methods you can use: - -### Specify Manually - -Setting the `--config=/path/to/your/config` command line option to specify your own configuration file outside of the directory tree for your project. - -### Within your Project's Directory Tree - -When the CLI is called, and a configuration file isn't specified already, `node-jshint` will attempt to locate one for you starting in `pwd`. (or "present working directory") If this does not yield a `.jshintrc` file, it will move one level up (`..`) the directory tree all the way up to the filesystem root. If a file is found, it stops immediately and uses that set of configuration. - -This setup allows you to set up **one** configuration file for your entire project. (place it in the root folder) As long as you run `jshint` from anywhere within your project directory tree, the same configuration file will be used. - -### Home Directory - -If all the methods above do not yield a `.jshintrc` to use, the last place that will be checked is your user's `$HOME` directory. - -## File Extensions - -Default extension for files is ".js". If you want to use JSHint with other file extensions (.json), you need to pass this extra extension as an option : - - --extra-ext .json - -## Ignoring Files and Directories - -If there is a .jshintignore file in your project's directory tree, (also provided you run `jshint` from within your project's directory) then any directories or files specified will be skipped over. (behaves just like a `.gitignore` file) - -**Note:** Pattern matching uses minimatch, with the nocase [option](https://github.com/isaacs/minimatch). When there is no match, it performs a left side match (when no forward slashes present and path is a directory). - -## Installing dependencies for development - - ./configure - -## Build Commands - - jake -T - -## Project Guidelines - -* All tests are passing. -* No (new) JSHint errors are introduced. diff --git a/node/node_modules/grunt/node_modules/jshint/bin/hint b/node/node_modules/grunt/node_modules/jshint/bin/hint deleted file mode 100755 index 2b11eece4..000000000 --- a/node/node_modules/grunt/node_modules/jshint/bin/hint +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -require('./../lib/cli').interpret(process.argv); diff --git a/node/node_modules/grunt/node_modules/jshint/lib/cli.js b/node/node_modules/grunt/node_modules/jshint/lib/cli.js deleted file mode 100644 index 14d6ed4e0..000000000 --- a/node/node_modules/grunt/node_modules/jshint/lib/cli.js +++ /dev/null @@ -1,159 +0,0 @@ -var fs = require('fs'), - path = require('path'), - cli = require('cli').enable('glob', 'help'), - hint = require('./hint'); - -function existsSync() { - var obj = fs.existsSync ? fs : path; - return obj.existsSync.apply(obj, arguments); -} - -function _removeJsComments(str) { - str = str || ''; - - // replace everything between "/* */" in a non-greedy way - // The English version of the regex is: - // match '/*' - // then match 0 or more instances of any character (including newlines) - // except for instances of '*/' - // then match '*/' - str = str.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\//g, ''); - - str = str.replace(/\/\/[^\n\r]*/g, ''); //everything after "//" - return str; -} - -function _loadAndParseConfig(filePath) { - return filePath && existsSync(filePath) ? - JSON.parse(_removeJsComments(fs.readFileSync(filePath, "utf-8"))) : {}; -} - -/** - * This function searches for a file with a specified name, it starts - * with the dir passed, and traverses up the filesystem until it either - * finds the file, or hits the root - * - * @param {String} name Filename to search for (.jshintrc, .jshintignore) - * @param {String} dir Defaults to process.cwd() - */ -function _searchFile(name, dir) { - dir = dir || process.cwd(); - - var filename = path.normalize(path.join(dir, name)), - parent = path.resolve(dir, ".."); - - if (existsSync(filename)) { - return filename; - } - - return dir === parent ? null : _searchFile(name, parent); -} - -function _findConfig() { - var name = ".jshintrc", - projectConfig = _searchFile(name), - homeConfig = path.normalize(path.join(process.env.HOME, name)); - - if (projectConfig) { - return projectConfig; - } - - // if no project config, check $HOME - if (existsSync(homeConfig)) { - return homeConfig; - } - - return false; -} - -function _print(results) { - function exit() { - process.exit(results.length > 0 ? 1 : 0); - } - - // avoid stdout cutoff in node 0.4.x, also supports 0.5.x - // see https://github.com/joyent/node/issues/1669 - try { - if (!process.stdout.flush()) { - process.stdout.once("drain", exit); - } else { - exit(); - } - } catch (e) { - exit(); - } -} - -module.exports = { - interpret: function (args) { - var config, reporter, options, - customConfig, customReporter, - ignoreFile, ignores, extraExtensionList; - - cli.setArgv(args); - cli.options = {}; - options = cli.parse({ - 'version': ['v', 'display package version', 'boolean', false], - 'config': ['config', 'custom config file', 'string', false], - 'reporter': ['reporter', 'custom reporter', 'string', undefined], - 'jslint-reporter': ['jslint-reporter', 'use a jslint compatible xml reporter'], - 'checkstyle-reporter': ['checkstyle-reporter', 'use a CheckStyle compatible xml reporter'], - 'show-non-errors': ['show-non-errors', 'show additional data generated by jshint'], - 'extra-ext': ['extra-ext', 'comma-separated list of file extensions to use (.js is default)', 'string', ''] - }); - - customConfig = options.config; - customReporter = options.reporter ? path.resolve(process.cwd(), options.reporter) : null; - extraExtensionList = options["extra-ext"]; - - if (options.version) { - cli.setApp(path.resolve(__dirname + "/../package.json")); - process.stdout.write(cli.version + "\n"); - return; - } - - if (options.help || !cli.args.length) { - cli.getUsage(); - process.exit(); - return; - } - - if (options['jslint-reporter']) { - customReporter = "./reporters/jslint_xml.js"; - } - - if (options['checkstyle-reporter']) { - customReporter = "./reporters/checkstyle.js"; - } - - if (options['show-non-errors']) { - customReporter = "./reporters/non_error.js"; - } - - config = _loadAndParseConfig(customConfig ? customConfig : _findConfig()); - - if (customReporter) { - try { - reporter = require(customReporter).reporter; - } catch (r) { - process.stdout.write("Error opening reporter file: " + customReporter); - process.stdout.write(r + "\n"); - process.exit(1); - } - } - - ignoreFile = _searchFile(".jshintignore"); - - if (ignoreFile) { - ignores = fs.readFileSync(ignoreFile, "utf8").split("\n") - .filter(function (line) { - return !!line.trim(); - }) - .map(function (line) { - return path.resolve(path.dirname(ignoreFile), line.trim()); - }); - } - - _print(hint.hint(cli.args, config, reporter, ignores, extraExtensionList)); - } -}; diff --git a/node/node_modules/grunt/node_modules/jshint/lib/hint.js b/node/node_modules/grunt/node_modules/jshint/lib/hint.js deleted file mode 100644 index 0ecbbe873..000000000 --- a/node/node_modules/grunt/node_modules/jshint/lib/hint.js +++ /dev/null @@ -1,125 +0,0 @@ -var fs = require('fs'), - minimatch = require('minimatch'), - path = require('path'), - jshint = require('./../packages/jshint/jshint.js'), - _reporter = require('./reporters/default').reporter, - _cache = { - directories: {} - }; - -function _lint(file, results, config, data) { - var buffer, - globals, - lintdata; - - // config may be a pointer, but we modify it below, which changes it the next time it is used. - config = !config ? {} : Object.keys(config).reduce(function (obj, key) { - obj[key] = config[key]; - return obj; - }, {}); - - try { - buffer = fs.readFileSync(file, 'utf-8'); - } catch (e) { - process.stdout.write("Error: Cant open: " + file); - process.stdout.write(e + '\n'); - } - - // Remove potential Unicode Byte Order Mark. - buffer = buffer.replace(/^\uFEFF/, ''); - - // remove custom node-jshint option - if (config.globals) { - globals = config.globals; - delete config.globals; - } - - if (!jshint.JSHINT(buffer, config, globals)) { - jshint.JSHINT.errors.forEach(function (error) { - if (error) { - results.push({file: file, error: error}); - } - }); - } - - lintdata = jshint.JSHINT.data(); - - if (lintdata) { - lintdata.file = file; - data.push(lintdata); - } -} - -function isDirectory(aPath) { - var isDir; - - try { - if (_cache.directories.hasOwnProperty(aPath)) { - isDir = _cache.directories[aPath]; - } else { - isDir = fs.statSync(aPath).isDirectory(); - _cache.directories[aPath] = isDir; - } - } catch (e) { - isDir = false; - } - - return isDir; -} - - -function _shouldIgnore(somePath, ignore) { - function isIgnored(p) { - var fnmatch = minimatch(somePath, p, {nocase: true}), - absmatch = path.resolve(somePath) === p, - lsmatch = isDirectory(p) && p.match(/^[^\/]*\/?$/) && - somePath.match(new RegExp("^" + p + ".*")); - - return !!(fnmatch || lsmatch || absmatch); - } - - return ignore.some(function (ignorePath) { - return isIgnored(ignorePath); - }); -} - -function _collect(filePath, files, ignore, regExtension) { - if (ignore && _shouldIgnore(filePath, ignore)) { - return; - } - if (fs.statSync(filePath).isDirectory()) { - fs.readdirSync(filePath).forEach(function (item) { - _collect(path.join(filePath, item), files, ignore, regExtension); - }); - } else if (filePath.match(regExtension)) { - files.push(filePath); - } -} - -module.exports = { - hint: function (targets, config, reporter, ignore, extraExtensionList) { - var files = [], - results = [], - data = [], - regExtension; - - extraExtensionList = extraExtensionList || ""; - regExtension = new RegExp('\\.(js' + (extraExtensionList === "" ? "" : "|" + extraExtensionList.replace(/,/g, "|").replace(/[\. ]/g, "")) + ")$"); - - targets.forEach(function (target) { - _collect(target, files, ignore, regExtension); - }); - - files.forEach(function (file) { - _lint(file, results, config, data); - }); - - _cache = { - directories: {} - }; - - (reporter || _reporter)(results, data); - - return results; - } -}; diff --git a/node/node_modules/grunt/node_modules/jshint/lib/reporters/checkstyle.js b/node/node_modules/grunt/node_modules/jshint/lib/reporters/checkstyle.js deleted file mode 100644 index 0b2f6e10a..000000000 --- a/node/node_modules/grunt/node_modules/jshint/lib/reporters/checkstyle.js +++ /dev/null @@ -1,107 +0,0 @@ -// Author: Boy Baukema -// http://github.com/relaxnow -module.exports = -{ - reporter: function (results, data) - { - "use strict"; - - var files = {}, - out = [], - pairs = { - "&": "&", - '"': """, - "'": "'", - "<": "<", - ">": ">" - }, - file, fileName, i, issue, globals, unuseds; - - function encode(s) { - for (var r in pairs) { - if (typeof(s) !== "undefined") { - s = s.replace(new RegExp(r, "g"), pairs[r]); - } - } - return s || ""; - } - - results.forEach(function (result) { - // Register the file - result.file = result.file.replace(/^\.\//, ''); - if (!files[result.file]) { - files[result.file] = []; - } - - // Add the error - files[result.file].push({ - severity: 'error', - line: result.error.line, - column: result.error.character, - message: result.error.reason, - source: result.error.raw - }); - }); - - data.forEach(function (result) { - file = data.file; - globals = result.implieds; - unuseds = result.unused; - - // Register the file - result.file = result.file.replace(/^\.\//, ''); - if (!files[result.file]) { - files[result.file] = []; - } - - if (globals) { - globals.forEach(function (global) { - files[result.file].push({ - severity: 'warning', - line: global.line, - column: 0, - message: "Implied global '" + global.name + "'", - source: 'jshint.implied-globals' - }); - }); - } - if (unuseds) { - unuseds.forEach(function (unused) { - files[result.file].push({ - severity: 'warning', - line: unused.line, - column: 0, - message: "Unused variable: '" + unused.name + "'", - source: 'jshint.implied-unuseds' - }); - }); - } - }); - - out.push(""); - out.push(""); - - for (fileName in files) { - if (files.hasOwnProperty(fileName)) { - out.push("\t"); - for (i = 0; i < files[fileName].length; i++) { - issue = files[fileName][i]; - out.push( - "\t\t" - ); - } - out.push("\t"); - } - } - - out.push(""); - - process.stdout.write(out.join("\n") + "\n"); - } -}; diff --git a/node/node_modules/grunt/node_modules/jshint/lib/reporters/default.js b/node/node_modules/grunt/node_modules/jshint/lib/reporters/default.js deleted file mode 100644 index 90805d831..000000000 --- a/node/node_modules/grunt/node_modules/jshint/lib/reporters/default.js +++ /dev/null @@ -1,18 +0,0 @@ -module.exports = { - reporter: function (results) { - var len = results.length, - str = '', - file, error; - - results.forEach(function (result) { - file = result.file; - error = result.error; - str += file + ': line ' + error.line + ', col ' + - error.character + ', ' + error.reason + '\n'; - }); - - if (str) { - process.stdout.write(str + "\n" + len + ' error' + ((len === 1) ? '' : 's') + "\n"); - } - } -}; diff --git a/node/node_modules/grunt/node_modules/jshint/lib/reporters/jslint_xml.js b/node/node_modules/grunt/node_modules/jshint/lib/reporters/jslint_xml.js deleted file mode 100644 index eca232763..000000000 --- a/node/node_modules/grunt/node_modules/jshint/lib/reporters/jslint_xml.js +++ /dev/null @@ -1,54 +0,0 @@ -// Author: Vasili Sviridov -// http://github.com/vsviridov -module.exports = -{ - reporter: function (results) - { - "use strict"; - - var files = {}, - out = [], - pairs = { - "&": "&", - '"': """, - "'": "'", - "<": "<", - ">": ">" - }, - file, i, issue; - - function encode(s) { - for (var r in pairs) { - if (typeof(s) !== "undefined") { - s = s.replace(new RegExp(r, "g"), pairs[r]); - } - } - return s || ""; - } - - - results.forEach(function (result) { - result.file = result.file.replace(/^\.\//, ''); - if (!files[result.file]) { - files[result.file] = []; - } - files[result.file].push(result.error); - }); - - out.push(""); - out.push(""); - - for (file in files) { - out.push("\t"); - for (i = 0; i < files[file].length; i++) { - issue = files[file][i]; - out.push("\t\t"); - } - out.push("\t"); - } - - out.push(""); - - process.stdout.write(out.join("\n") + "\n"); - } -}; diff --git a/node/node_modules/grunt/node_modules/jshint/lib/reporters/non_error.js b/node/node_modules/grunt/node_modules/jshint/lib/reporters/non_error.js deleted file mode 100644 index 6b1f8c477..000000000 --- a/node/node_modules/grunt/node_modules/jshint/lib/reporters/non_error.js +++ /dev/null @@ -1,45 +0,0 @@ -/*jshint node: true */ -module.exports = -{ - reporter: function (results, data) { - var len = results.length, - str = '', - file, error, globals, unuseds; - - results.forEach(function (result) { - file = result.file; - error = result.error; - str += file + ': line ' + error.line + ', col ' + - error.character + ', ' + error.reason + '\n'; - }); - - str += len > 0 ? ("\n" + len + ' error' + ((len === 1) ? '' : 's')) : ""; - - data.forEach(function (data) { - file = data.file; - globals = data.implieds; - unuseds = data.unused; - - if (globals || unuseds) { - str += '\n\n' + file + ' :\n'; - } - - if (globals) { - str += '\tImplied globals:\n'; - globals.forEach(function (global) { - str += '\t\t' + global.name + ': ' + global.line + '\n'; - }); - } - if (unuseds) { - str += '\tUnused Variables:\n\t\t'; - unuseds.forEach(function (unused) { - str += unused.name + '(' + unused.line + '), '; - }); - } - }); - - if (str) { - process.stdout.write(str + "\n"); - } - } -}; diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/README.md b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/README.md deleted file mode 100644 index 0fe30d4fb..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/README.md +++ /dev/null @@ -1,196 +0,0 @@ -**cli is a toolkit for rapidly building command line apps - it includes:** - -- Full featured opts/args parser -- Plugin support for adding common options and switches -- Helper methods for working with input/output and spawning child processes -- Output colored/styled messages, [progress bars](https://github.com/chriso/cli/blob/master/examples/progress.js) or [spinners](https://github.com/chriso/cli/blob/master/examples/spinner.js) -- Command [auto-completion](https://github.com/chriso/cli/blob/master/examples/command.js) and [glob support](https://github.com/chriso/cli/blob/master/examples/glob.js) - -Install using `npm install cli` or just bundle [cli.js](https://github.com/chriso/cli/raw/master/cli-min.js) with your app. - -## Example apps - -### sort.js - -```javascript -#!/usr/bin/env node -require('cli').withStdinLines(function(lines, newline) { - this.output(lines.sort().join(newline)); -}); -``` - -Try it out - -```bash -$ ./sort.js < input.txt -``` - -Let's add support for an `-n` switch to use a numeric sort, and a `-r` switch to reverse output - only 5 extra lines of code (!) - -```javascript -var cli = require('cli'), options = cli.parse(); - -cli.withStdinLines(function(lines, newline) { - lines.sort(!options.n ? null : function(a, b) { - return parseInt(a) > parseInt(b); - }); - if (options.r) lines.reverse(); - this.output(lines.join(newline)); -}); -``` - -### static.js - -Let's create a static file server with daemon support to see the opts parser + plugins in use - note: this requires `npm install creationix daemon` - -```javascript -var cli = require('cli').enable('daemon', 'status'); //Enable 2 plugins - -cli.parse({ - log: ['l', 'Enable logging'], - port: ['p', 'Listen on this port', 'number', 8080], - serve: [false, 'Serve static files from PATH', 'path', './public'] -}); - -cli.main(function(args, options) { - var server, middleware = []; - - if (options.log) { - this.debug('Enabling logging'); - middleware.push(require('creationix/log')()); - } - - this.debug('Serving files from ' + options.serve); - middleware.push(require('creationix/static')('/', options.serve, 'index.html')); - - server = this.createServer(middleware).listen(options.port); - - this.ok('Listening on port ' + options.port); -}); -``` - -To output usage information - -```bash -$ ./static.js --help -``` - -To create a daemon that serves files from */tmp*, run - -```bash -$ ./static.js -ld --serve=/tmp -``` - -For more examples, see [./examples](https://github.com/chriso/cli/tree/master/examples) - -## Helper methods - -cli has methods that collect stdin (newline is autodetected as \n or \r\n) - -```javascript -cli.withStdin(callback); //callback receives stdin as a string -cli.withStdinLines(callback); //callback receives stdin split into an array of lines (lines, newline) -``` - -cli also has a lower level method for working with input line by line (see [./examples/cat.js](https://github.com/chriso/cli/blob/master/examples/cat.js) for an example). - -```javascript -cli.withInput(file, function (line, newline, eof) { - if (!eof) { - this.output(line + newline); - } -}); -``` - -*Note: `file` can be omitted if you want to work with stdin* - -To output a progress bar, call - -```javascript -cli.progress(progress); //Where 0 <= progress <= 1 -``` - -To spawn a child process, use - -```javascript -cli.exec(cmd, callback); //callback receives the output of the process (split into lines) -``` - -cli also comes bundled with kof's [node-natives](https://github.com/kof/node-natives) (access with cli.native) and creationix' [stack](https://github.com/creationix/stack) (access with cli.createServer) - -## Plugins - -Plugins are a way of adding common opts and can be enabled using - -```javascript -cli.enable(plugin1, [plugin2, ...]); //To disable, use the equivalent disable() method -``` - -**help** - *enabled by default* - -Adds `-h,--help` to output auto-generated usage information - -**version** - -Adds `-v,--version` to output version information for the app. cli will attempt to locate and parse a nearby *package.json* - -To set your own app name and version, use `cli.setApp(app_name, version)` - -**status** - -Adds options to show/hide the stylized status messages that are output to the console when using one of these methods - -```javascript -cli.debug(msg); //Only shown when using --debug -cli.error(msg); -cli.fatal(msg); //Exits the process after outputting msg -cli.info(msg); -cli.ok(msg); -``` - -`-k,--no-color` will omit ANSI color escapes from the output - -**glob** - *requires* `npm install glob` - -Enables glob matching of arguments - -**daemon** - *requires* `npm install daemon` - -Adds `-d,--daemon ARG` for daemonizing the process and controlling the resulting daemon - -`ARG` can be either start (default), stop, restart, pid (outputs the daemon's pid if it's running), or log (output the daemon's stdout+stderr) - -**timeout** - -Adds `-t,--timeout N` to exit the process after N seconds with an error - -**catchall** - -Adds `-c,--catch` to catch and output uncaughtExceptions and resume execution - -*Note: Plugins are automatically disabled if an option or switch of the same name is already defined* - -## LICENSE - -(MIT license) - -Copyright (c) 2010 Chris O'Hara - -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/node_modules/grunt/node_modules/jshint/node_modules/cli/cli.js b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/cli.js deleted file mode 100644 index 91fa4db74..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/cli.js +++ /dev/null @@ -1,1125 +0,0 @@ -/** - * Copyright (c) 2010 Chris O'Hara - * - * 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. - */ - - //Note: cli includes kof/node-natives and creationix/stack. I couldn't find - //license information for either - contact me if you want your license added - -var cli = exports, - argv, curr_opt, curr_val, full_opt, is_long, - short_tags = [], opt_list, parsed = {}, - usage, argv_parsed, command_list, commands, - daemon, daemon_arg, no_color, show_debug; - -cli.app = null; -cli.version = null; -cli.argv = []; -cli.argc = 0; - -cli.options = {}; -cli.args = []; -cli.command; - -cli.width = 70; -cli.option_width = 25; - -/** - * Bind kof's node-natives (https://github.com/kof/node-natives) to `cli.native` - * - * Rather than requiring node natives (e.g. var fs = require('fs')), all - * native modules can be accessed like `cli.native.fs` - */ -cli.native = {}; -var define_native = function (module) { - Object.defineProperty(cli.native, module, { - enumerable: true, - configurable: true, - get: function() { - delete cli.native[module]; - return cli.native[module] = require(module); - } - }); -}; -var natives = process.binding('natives'); -for (var module in natives) { - define_native(module); -} - -cli.output = cli.native.util.print; -cli.exit = process.exit; - -/** - * Define plugins. Plugins can be enabled and disabled by calling: - * - * `cli.enable(plugin1, [plugin2, ...])` - * `cli.disable(plugin1, [plugin2, ...])` - * - * Methods are chainable - `cli.enable(plugin).disable(plugin2)`. - * - * The 'help' plugin is enabled by default. - */ -var enable = { - help: true, //Adds -h, --help - version: false, //Adds -v,--version => gets version by parsing a nearby package.json - daemon: false, //Adds -d,--daemon [ARG] => (see cli.daemon() below) - status: false, //Adds -k,--no-color & --debug => display plain status messages /display debug messages - timeout: false, //Adds -t,--timeout N => timeout the process after N seconds - catchall: false, //Adds -c,--catch => catch and output uncaughtExceptions - glob: false //Adds glob matching => use cli.glob(arg) -} -cli.enable = function (/*plugins*/) { - Array.prototype.slice.call(arguments).forEach(function (plugin) { - switch (plugin) { - case 'daemon': - try { - daemon = require('daemon'); - if (typeof daemon.daemonize !== 'function') { - throw 'Invalid module'; - } - } catch (e) { - cli.fatal('daemon.node not installed. Please run `npm install daemon`'); - } - break; - case 'catchall': - process.on('uncaughtException', function (err) { - cli.error('Uncaught exception: ' + (err.msg || err)); - }); - break; - case 'help': case 'version': case 'status': - case 'autocomplete': case 'timeout': - //Just add switches. - break; - case 'glob': - cli.glob = require('glob'); - break; - default: - cli.fatal('Unknown plugin "' + plugin + '"'); - break; - } - enable[plugin] = true; - }); - return cli; -} -cli.disable = function (/*plugins*/) { - Array.prototype.slice.call(arguments).forEach(function (plugin) { - if (enable[plugin]) { - enable[plugin] = false; - } - }); - return cli; -} - -/** - * Sets argv (default is process.argv). - * - * @param {Array|String} argv - * @param {Boolean} keep_arg0 (optional - default is false) - * @api public - */ -cli.setArgv = function (arr, keep_arg0) { - if (typeof arr == 'string') { - arr = arr.split(' '); - } else { - arr = arr.slice(); - } - cli.app = arr.shift(); - //Strip off argv[0] if it's a node binary - if (!keep_arg0 && ('node' === cli.native.path.basename(cli.app) - || process.execPath === cli.app)) { - cli.app = arr.shift(); - } - cli.app = cli.native.path.basename(cli.app); - argv_parsed = false; - cli.args = cli.argv = argv = arr; - cli.argc = argv.length; -}; -cli.setArgv(process.argv); - -/** - * Returns the next opt, or false if no opts are found. - * - * @return {String} opt - * @api public - */ -cli.next = function () { - if (!argv_parsed) { - cli.args = []; - argv_parsed = true; - } - - curr_val = null; - - //If we're currently in a group of short opts (e.g. -abc), return the next opt - if (short_tags.length) { - curr_opt = short_tags.shift(); - full_opt = '-' + curr_opt; - return curr_opt; - } - - if (!argv.length) { - return false; - } - - curr_opt = argv.shift(); - - //If an escape sequence is found (- or --), subsequent opts are ignored - if (curr_opt === '-' || curr_opt === '--') { - while (argv.length) { - cli.args.push(argv.shift()); - } - return false; - } - - //If the next element in argv isn't an opt, add it to the list of args - if (curr_opt[0] !== '-') { - cli.args.push(curr_opt); - return cli.next(); - } else { - //Check if the opt is short/long - is_long = curr_opt[1] === '-'; - curr_opt = curr_opt.substr(is_long ? 2 : 1); - } - - //Accept grouped short opts, e.g. -abc => -a -b -c - if (!is_long && curr_opt.length > 1) { - short_tags = curr_opt.split(''); - return cli.next(); - } - - var eq, len; - - //Check if the long opt is in the form --option=VALUE - if (is_long && (eq = curr_opt.indexOf('=')) >= 0) { - curr_val = curr_opt.substr(eq + 1); - curr_opt = curr_opt.substr(0, eq); - len = curr_val.length; - //Allow values to be quoted - if ((curr_val[0] === '"' && curr_val[len - 1] === '"') || - (curr_val[0] === "'" && curr_val[len - 1] === "'")) - { - curr_val = curr_val.substr(1, len-2); - } - if (curr_val.match(/^[0-9]+$/)) { - curr_val = parseInt(curr_val, 10); - } - } - - //Save the opt representation for later - full_opt = (is_long ? '--' : '-') + curr_opt; - - return curr_opt; -}; - -/** - * Parses command line opts. - * - * `opts` must be an object with opts defined like: - * long_tag: [short_tag, description, value_type, default_value]; - * - * `commands` is an optional array or object for apps that are of the form - * my_app [OPTIONS] [ARGS] - * The command list is output with usage information + there is bundled - * support for auto-completion, etc. - * - * See README.md for more information. - * - * @param {Object} opts - * @param {Object} commands (optional) - * @return {Object} opts (parsed) - * @api public - */ -cli.parse = function (opts, command_def) { - var default_val, i, parsed = cli.options, seen, - catch_all = !opts; - opt_list = opts || {}; - commands = command_def; - command_list = commands || []; - if (commands && !Array.isArray(commands)) { - command_list = Object.keys(commands); - } - while (o = cli.next()) { - seen = false; - for (opt in opt_list) { - if (!(opt_list[opt] instanceof Array)) { - continue; - } - if (!opt_list[opt][0]) { - opt_list[opt][0] = opt; - } - if (o === opt || o === opt_list[opt][0]) { - seen = true; - if (opt_list[opt].length === 2) { - parsed[opt] = true; - break; - } - default_val = null; - if (opt_list[opt].length === 4) { - default_val = opt_list[opt][3]; - } - if (opt_list[opt][2] instanceof Array) { - for (i = 0, l = opt_list[opt][2].length; i < l; i++) { - if (typeof opt_list[opt][2][i] === 'number') { - opt_list[opt][2][i] += ''; - } - } - parsed[opt] = cli.getArrayValue(opt_list[opt][2], is_long ? null : default_val); - break; - } - if (opt_list[opt][2].toLowerCase) { - opt_list[opt][2] = opt_list[opt][2].toLowerCase(); - } - switch (opt_list[opt][2]) { - case 'string': case 1: case true: - parsed[opt] = cli.getValue(default_val); - break; - case 'int': case 'number': case 'num': - case 'time': case 'seconds': case 'secs': case 'minutes': case 'mins': - case 'x': case 'n': - parsed[opt] = cli.getInt(default_val); - break; - case 'float': case 'decimal': - parsed[opt] = cli.getFloat(default_val); - break; - case 'path': case 'file': case 'directory': case 'dir': - parsed[opt] = cli.getPath(default_val, opt_list[opt][2]); - break; - case 'email': - parsed[opt] = cli.getEmail(default_val); - break; - case 'url': case 'uri': case 'domain': case 'host': - parsed[opt] = cli.getUrl(default_val, opt_list[opt][2]); - break; - case 'ip': - parsed[opt] = cli.getIp(default_val); - break; - case 'bool': case 'boolean': case 'on': - parsed[opt] = true; - break; - case 'false': case 'off': case false: case 0: - parsed[opt] = false; - break; - default: - cli.fatal('Unknown opt type "' + opt_list[opt][2] + '"'); - } - break; - } - } - if (process.env.NODE_DISABLE_COLORS) { - no_color = true; - } - if (!seen) { - if (enable.help && (o === 'h' || o === 'help')) { - cli.getUsage(); - process.exit(); - } else if (enable.version && (o === 'v' || o === 'version')) { - if (cli.version == null) { - cli.parsePackageJson(); - } - console.error(cli.app + ' v' + cli.version); - process.exit(); - } else if (enable.daemon && (o === 'd' || o === 'daemon')) { - daemon_arg = cli.getArrayValue(['start','stop','restart','pid','log'], is_long ? null : 'start'); - continue; - } else if (enable.catchall && (o === 'c' || o === 'catch')) { - continue; - } else if (enable.status && (o === 'k' || o === 'no-color' || o === 'debug')) { - no_color = (o === 'k' || o === 'no-color'); - show_debug = o === 'debug'; - continue; - } else if (enable.timeout && (o === 't' || o === 'timeout')) { - var secs = cli.getInt(); - setTimeout(function () { - cli.fatal('Process timed out after ' + secs + 's'); - }, secs * 1000); - continue; - } else if (catch_all) { - parsed[o] = curr_val || true; - continue; - } - cli.fatal('Unknown option ' + full_opt); - } - } - //Fill the remaining options with their default value or null - for (opt in opt_list) { - default_val = opt_list[opt].length === 4 ? opt_list[opt][3] : null; - if (!(opt_list[opt] instanceof Array)) { - parsed[opt] = opt_list[opt]; - continue; - } else if (typeof parsed[opt] === 'undefined') { - parsed[opt] = default_val; - } - } - if (command_list.length) { - if (cli.args.length === 0) { - if (enable.help) { - cli.getUsage(); - } else { - cli.fatal('A command is required (' + command_list.join(', ') + ').'); - } - process.exit(1); - } else { - cli.command = cli.autocompleteCommand(cli.args.shift()); - } - } - cli.argc = cli.args.length; - return parsed; -}; - -/** - * Helper method for matching a command from the command list. - * - * @param {String} command - * @return {String} full_command - * @api public - */ -cli.autocompleteCommand = function (command) { - var list; - if (!(command_list instanceof Array)) { - list = Object.keys(command_list); - } else { - list = command_list; - } - var i, j = 0, c = command.length, tmp_list; - if (list.length === 0 || list.indexOf(command) !== -1) { - return command; - } - for (i = 0; i < c; i++) { - tmp_list = []; - l = list.length; - if (l <= 1) break; - for (j = 0; j < l; j++) - if (list[j].length >= i && list[j][i] === command[i]) - tmp_list.push(list[j]); - list = tmp_list; - } - l = list.length; - if (l === 1) { - return list[0]; - } else if (l === 0) { - cli.fatal('Unknown command "' + command + '"' + (enable.help ? '. Please see --help for more information' : '')); - } else { - list.sort(); - cli.fatal('The command "' + command + '" is ambiguous and could mean "' + list.join('", "') + '"'); - } -}; - -/** - * Adds methods to output styled status messages to stderr. - * - * Added methods are cli.info(msg), cli.error(msg), cli.ok(msg), and - * cli.debug(msg). - * - * To control status messages, use the 'status' plugin - * 1) debug() messages are hidden by default. Display them with - * the --debug opt. - * 2) to hide all status messages, use the -s or --silent opt. - * - * @api private - */ -cli.status = function (msg, type) { - var pre; - switch (type) { - case 'info': - pre = no_color ? 'INFO:' : '\x1B[33mINFO\x1B[0m:'; - break; - case 'debug': - pre = no_color ? 'DEBUG:' : '\x1B[36mDEBUG\x1B[0m:'; - break; - case 'error': - case 'fatal': - pre = no_color ? 'ERROR:' : '\x1B[31mERROR\x1B[0m:'; - break; - case 'ok': - pre = no_color ? 'OK:' : '\x1B[32mOK\x1B[0m:'; - break; - } - msg = pre + ' ' + msg; - if (type === 'fatal') { - console.error(msg); - process.exit(1); - } - if (enable.status && !show_debug && type === 'debug') { - return; - } - console.error(msg); -}; -['info','error','ok','debug','fatal'].forEach(function (type) { - cli[type] = function (msg) { - cli.status(msg, type); - }; -}); - -/** - * Sets the app name and version. - * - * Usage: - * setApp('myapp', '0.1.0'); - * setApp('./package.json'); //Pull name/version from package.json - * - * @param {String} name - * @return cli (for chaining) - * @api public - */ -cli.setApp = function (name, version) { - if (name.indexOf('package.json') !== -1) { - cli.parsePackageJson(name); - } else { - cli.app = name; - cli.version = version; - } - return cli; -}; - -/** - * Parses the version number from package.json. If no path is specified, cli - * will attempt to locate a package.json in ./, ../ or ../../ - * - * @param {String} path (optional) - * @api public - */ -cli.parsePackageJson = function (path) { - var parse_packagejson = function (path) { - var packagejson = JSON.parse(cli.native.fs.readFileSync(path, 'utf8')); - cli.version = packagejson.version; - cli.app = packagejson.name; - }; - var try_all = function (arr, func, err) { - for (var i = 0, l = arr.length; i < l; i++) { - try { - func(arr[i]); - return; - } catch (e) { - if (i === l-1) { - cli.fatal(err); - } - } - } - }; - try { - if (path) { - return parse_packagejson(path); - } - try_all([ - __dirname + '/package.json', - __dirname + '/../package.json', - __dirname + '/../../package.json' - ], parse_packagejson); - } catch (e) { - cli.fatal('Could not detect ' + cli.app + ' version'); - } -}; - -/** - * Sets the usage string - default is `app [OPTIONS] [ARGS]`. - * - * @param {String} u - * @return cli (for chaining) - * @api public - */ -cli.setUsage = function (u) { - usage = u; - return cli; -}; - -var pad = function (str, len) { - if (typeof len === 'undefined') { - len = str; - str = ''; - } - if (str.length < len) { - len -= str.length; - while (len--) str += ' '; - } - return str; -}; - -/** - * Automatically build usage information from the opts list. If the help - * plugin is enabled (default), this info is displayed with -h, --help. - * - * @api public - */ -cli.getUsage = function () { - var short, desc, optional, line, seen_opts = [], - switch_pad = cli.option_width; - - var trunc_desc = function (pref, desc, len) { - var pref_len = pref.length, - desc_len = cli.width - pref_len, - truncated = ''; - if (desc.length <= desc_len) { - return desc; - } - var desc_words = (desc+'').split(' '), chars = 0, word; - while (desc_words.length) { - truncated += (word = desc_words.shift()) + ' '; - chars += word.length; - if (desc_words.length && chars + desc_words[0].length > desc_len) { - truncated += '\n' + pad(pref_len); - chars = 0; - } - } - return truncated; - }; - - usage = usage || cli.app + ' [OPTIONS]' + (command_list.length ? ' ' : '') + ' [ARGS]'; - if (no_color) { - console.error('Usage:\n ' + usage); - console.error('Options: '); - } else { - console.error('\x1b[1mUsage\x1b[0m:\n ' + usage); - console.error('\n\x1b[1mOptions\x1b[0m: '); - } - for (opt in opt_list) { - - if (opt.length === 1) { - long = opt_list[opt][0]; - short = opt; - } else { - long = opt; - short = opt_list[opt][0]; - } - - //Parse opt_list - desc = opt_list[opt][1].trim(); - type = opt_list[opt].length >= 3 ? opt_list[opt][2] : null; - optional = opt_list[opt].length === 4 ? opt_list[opt][3] : null; - - //Build usage line - if (short === long) { - if (short.length === 1) { - line = ' -' + short; - } else { - line = ' --' + long; - } - } else { - line = ' -' + short + ', --' + long; - } - line += ' '; - - if (type) { - if (type instanceof Array) { - desc += '. VALUE must be either [' + type.join('|') + ']'; - type = 'VALUE'; - } - if (type === true || type === 1) { - type = long.toUpperCase(); - } - type = type.toUpperCase(); - if (type === 'FLOAT' || type === 'INT') { - type = 'NUMBER'; - } - line += optional ? '[' + type + ']' : type; - } - line = pad(line, switch_pad); - line += trunc_desc(line, desc); - line += optional ? ' (Default is ' + optional + ')' : ''; - console.error(line.replace('%s', '%\0s')); - - seen_opts.push(short); - seen_opts.push(long); - } - if (enable.timeout && seen_opts.indexOf('t') === -1 && seen_opts.indexOf('timeout') === -1) { - console.error(pad(' -t, --timeout N', switch_pad) + 'Exit if the process takes longer than N seconds'); - } - if (enable.status) { - if (seen_opts.indexOf('k') === -1 && seen_opts.indexOf('no-color') === -1) { - console.error(pad(' -k, --no-color', switch_pad) + 'Omit color from output'); - } - if (seen_opts.indexOf('debug') === -1) { - console.error(pad(' --debug', switch_pad) + 'Show debug information'); - } - } - if (enable.catchall && seen_opts.indexOf('c') === -1 && seen_opts.indexOf('catch') === -1) { - console.error(pad(' -c, --catch', switch_pad) + 'Catch unanticipated errors'); - } - if (enable.daemon && seen_opts.indexOf('d') === -1 && seen_opts.indexOf('daemon') === -1) { - console.error(pad(' -d, --daemon [ARG]', switch_pad) + 'Daemonize the process. Control the daemon using [start, stop, restart, log, pid]'); - } - if (enable.version && seen_opts.indexOf('v') === -1 && seen_opts.indexOf('version') === -1) { - console.error(pad(' -v, --version', switch_pad) + 'Display the current version'); - } - if (enable.help && seen_opts.indexOf('h') === -1 && seen_opts.indexOf('help') === -1) { - console.error(pad(' -h, --help', switch_pad) + 'Display help and usage details'); - } - if (command_list.length) { - console.error('\n\x1b[1mCommands\x1b[0m: '); - if (!Array.isArray(commands)) { - for (var c in commands) { - line = ' ' + pad(c, switch_pad - 2); - line += trunc_desc(line, commands[c]); - console.error(line); - } - } else { - command_list.sort(); - console.error(' ' + trunc_desc(' ', command_list.join(', '))); - } - } - process.exit(); -}; - -/** - * Generates an error message when an opt is incorrectly used. - * - * @param {String} expects (e.g. 'a value') - * @param {String} type (e.g. 'VALUE') - * @api public - */ -cli.getOptError = function (expects, type) { - var err = full_opt + ' expects ' + expects - + '. Use `' + cli.app + ' ' + full_opt + (is_long ? '=' : ' ') + type + '`'; - return err; -}; - -/** - * Gets the next opt value and validates it with an optional validation - * function. If validation fails or no value can be obtained, this method - * will return the default value (if specified) or exit with err_msg. - * - * @param {String} default_val - * @param {Function} validate_func - * @param {String} err_msg - * @api public - */ -cli.getValue = function (default_val, validate_func, err_msg) { - err_msg = err_msg || cli.getOptError('a value', 'VALUE'); - - var value; - - try { - if (curr_val) { - if (validate_func) { - curr_val = validate_func(curr_val); - } - return curr_val; - } - - //Grouped short opts aren't allowed to have values - if (short_tags.length) { - throw 'Short tags'; - } - - //If there's no args left or the next arg is an opt, return the - //default value (if specified) - otherwise fail - if (!argv.length || argv[0][0] === '-') { - throw 'No value'; - } - - value = argv.shift(); - - if (value.match(/^[0-9]+$/)) { - value = parseInt(value, 10); - } - - //Run the value through a validation/transformation function if specified - if (validate_func) { - value = validate_func(value); - } - } catch (e) { - - //The value didn't pass the validation/transformation. Unshift the value and - //return the default value (if specified) - if (value) { - argv.unshift(value); - } - return default_val != null ? default_val : cli.fatal(err_msg); - } - return value; -}; - -cli.getInt = function (default_val) { - return cli.getValue(default_val, function (value) { - if (typeof value === 'number') return value; - if (!value.match(/^(?:-?(?:0|[1-9][0-9]*))$/)) { - throw 'Invalid int'; - } - return parseInt(value); - }, cli.getOptError('a number', 'NUMBER')); -} - -cli.getFloat = function (default_val) { - return cli.getValue(default_val, function (value) { - if (!value.match(/^(?:-?(?:0|[1-9][0-9]*))?(?:\.[0-9]*)?$/)) { - throw 'Invalid float'; - } - return parseFloat(value, 10); - }, cli.getOptError('a number', 'NUMBER')); -} - -cli.getUrl = function (default_val, identifier) { - identifier = identifier || 'url'; - return cli.getValue(default_val, function (value) { - if (!value.match(/^(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?:\w+:\w+@)?((?:(?:[-\w\d{1-3}]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|edu|co\.uk|ac\.uk|it|fr|tv|museum|asia|local|travel|[a-z]{2})?)|((\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)(\.(\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)){3}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$ |\/.,*:;=]|%[a-f\d]{2})*)?$/i)) { - throw 'Invalid URL'; - } - return value; - }, cli.getOptError('a ' + identifier, identifier.toUpperCase())); -} - -cli.getEmail = function (default_val) { - return cli.getValue(default_val, function (value) { - if (!value.match(/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/)) { - throw 'Invalid email'; - } - return value; - }, cli.getOptError('an email', 'EMAIL')); -} - -cli.getIp = function (default_val) { - return cli.getValue(default_val, function (value) { - if (!value.match(/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/)) { - throw 'Invalid IP'; - } - return value; - }, cli.getOptError('an IP', 'IP')); -} - -cli.getPath = function (default_val, identifier) { - identifier = identifier || 'path'; - return cli.getValue(default_val, function (value) { - if (value.match(/[?*:;{}]/)) { - throw 'Invalid path'; - } - return value; - }, cli.getOptError('a ' + identifier, identifier.toUpperCase())); -} - -cli.getArrayValue = function (arr, default_val) { - return cli.getValue(default_val, function (value) { - if (arr.indexOf(value) === -1) { - throw 'Unexpected value'; - } - return value; - }, cli.getOptError('either [' + arr.join('|') + ']', 'VALUE')); -} - -/** - * Gets all data from STDIN (with optional encoding) and sends it to callback. - * - * @param {String} encoding (optional - default is 'utf8') - * @param {Function} callback - * @api public - */ -cli.withStdin = function (encoding, callback) { - if (typeof encoding === 'function') { - callback = encoding; - encoding = 'utf8'; - } - var stream = process.openStdin(), data = ''; - stream.setEncoding(encoding); - stream.on('data', function (chunk) { - data += chunk; - }); - stream.on('end', function () { - callback.apply(cli, [data]); - }); -}; - -/** - * Gets all data from STDIN, splits the data into lines and sends it - * to callback (callback isn't called until all of STDIN is read. To - * process each line as it's received, see the method below - * - * @param {Function} callback - * @api public - */ -cli.withStdinLines = function (callback) { - cli.withStdin(function (data) { - var sep = data.indexOf('\r\n') !== -1 ? '\r\n' : '\n'; - callback.apply(cli, [data.split(sep), sep]); - }); -}; - -/** - * Asynchronously reads a file line by line. When a line is received, - * callback is called with (line, sep) - when EOF is reached, callback - * receives (null, null, true) - * - * @param {String} file (optional - default is 'stdin') - * @param {String} encoding (optional - default is 'utf8') - * @param {Function} callback (line, sep, eof) - * @api public - */ -cli.withInput = function (file, encoding, callback) { - if (typeof encoding === 'function') { - callback = encoding; - encoding = 'utf8'; - } else if (typeof file === 'function') { - callback = file; - encoding = 'utf8'; - file = 'stdin'; - } - if (file === 'stdin') { - file = process.openStdin(); - } else { - try { - file = cli.native.fs.createReadStream(file); - file.on('error', cli.fatal); - } catch (e) { - return cli.fatal(e); - } - } - file.setEncoding(encoding); - var lines = [], data = '', eof, sep; - file.on('data', function (chunk) { - if (eof) return; - data += chunk; - if (!sep) { - if (data.indexOf('\r\n') !== -1) { - sep = '\r\n'; - } else if (data.indexOf('\n') !== -1) { - sep = '\n'; - } else { - last_line = data; - return; - } - } - lines = data.split(sep); - data = eof ? null : lines.pop(); - while (lines.length) { - callback.apply(cli, [lines.shift(), sep, false]); - } - }); - file.on('end', function () { - eof = true; - if (data.length) { - callback.apply(cli, [data, sep || '', false]); - } - callback.apply(cli, [null, null, true]); - }); -}; - -/** - * A method for creating and controlling a daemon. - * - * `arg` can be: - * start = daemonizes the process - * stop = stops the daemon if it is running - * restart = alias for stop -> start - * pid = outputs the daemon's PID if it is running - * log = outputs the daemon's log file (stdout + stderr) - * - * @param {String} arg (Optional - default is 'start') - * @param {Function} callback - * @api public - */ -cli.daemon = function (arg, callback) { - if (typeof daemon === 'undefined') { - cli.fatal('Daemon is not initialized'); - } - - if (typeof arg === 'function') { - callback = arg; - arg = 'start'; - } - - var lock_file = '/tmp/' + cli.app + '.pid', - log_file = '/tmp/' + cli.app + '.log'; - - var start = function () { - daemon.daemonize(log_file, lock_file, function (err) { - if (err) return cli.error('Error starting daemon: ' + err); - callback(); - }); - }; - - var stop = function () { - try { - cli.native.fs.readFileSync(lock_file); - } catch (e) { - return cli.error('Daemon is not running'); - }; - daemon.kill(lock_file, function (err, pid) { - if (err && err.errno === 3) { - return cli.error('Daemon is not running'); - } else if (err) { - return cli.error('Error stopping daemon: ' + err.errno); - } - cli.ok('Successfully stopped daemon with pid: ' + pid); - }); - }; - - switch(arg) { - case 'stop': - stop(); - break; - case 'restart': - daemon.stop(lock_file, function () { - start(); - }); - break; - case 'log': - try { - cli.native.fs.createReadStream(log_file, {encoding: 'utf8'}).pipe(process.stdout); - } catch (e) { - return cli.error('No daemon log file'); - }; - break; - case 'pid': - try { - var pid = cli.native.fs.readFileSync(lock_file, 'utf8'); - cli.native.fs.statSync('/proc/' + pid); - cli.info(pid); - } catch (e) { - return cli.error('Daemon is not running'); - }; - break; - default: - start(); - break; - } -} - -/** - * The main entry method. Calling cli.main() is only necessary in - * scripts that have daemon support enabled. `callback` receives (args, options) - * - * @param {Function} callback - * @api public - */ -cli.main = function (callback) { - var after = function () { - callback.apply(cli, [cli.args, cli.options]); - }; - if (enable.daemon && daemon_arg) { - cli.daemon(daemon_arg, after); - } else { - after(); - } -} - -/** - * Bind creationix's stack (https://github.com/creationix/stack). - * - * Create a simple middleware stack by calling: - * - * cli.createServer(middleware).listen(port); - * - * @return {Server} server - * @api public - */ -cli.createServer = function(/*layers*/) { - var defaultStackErrorHandler = function (req, res, err) { - if (err) { - console.error(err.stack); - res.writeHead(500, {"Content-Type": "text/plain"}); - return res.end(err.stack + "\n"); - } - res.writeHead(404, {"Content-Type": "text/plain"}); - res.end("Not Found\n"); - }; - var handle = error = defaultStackErrorHandler, - layers = Array.prototype.slice.call(arguments); - - //Allow createServer(a,b,c) and createServer([a,b,c]) - if (layers.length && layers[0] instanceof Array) { - layers = layers[0]; - } - layers.reverse().forEach(function (layer) { - var child = handle; - handle = function (req, res) { - try { - layer(req, res, function (err) { - if (err) return error(req, res, err); - child(req, res); - }); - } catch (err) { - error(req, res, err); - } - }; - }); - return cli.native.http.createServer(handle); -}; - -/** - * A wrapper for child_process.exec(). - * - * If the child_process exits successfully, `callback` receives an array of - * stdout lines. The current process exits if the child process has an error - * and `errback` isn't defined. - * - * @param {String} cmd - * @param {Function} callback (optional) - * @param {Function} errback (optional) - * @api public - */ -cli.exec = function (cmd, callback, errback) { - cli.native.child_process.exec(cmd, function (err, stdout, stderr) { - err = err || stderr; - if (err) { - if (errback) { - return errback(err); - } - return cli.fatal('exec() failed\n' + err); - } - if (callback) { - callback(stdout.split('\n')); - } - }); -}; - -/** - * Helper method for outputting a progress bar to the console. - * - * @param {Number} progress (0 <= progress <= 1) - * @api public - */ -var last_progress_call, progress_len = 74; -cli.progress = function (progress) { - if (progress < 0 || progress > 1 || isNaN(progress)) return; - var now = (new Date()).getTime(); - if (last_progress_call && (now - last_progress_call) < 100 && progress !== 1) { - return; //Throttle progress calls - } - last_progress_call = now; - - - var barLength = Math.floor(progress_len * progress), - str = ''; - if (barLength == 0 && progress > 0) { - barLength = 1; - } - for (var i = 1; i <= progress_len; i++) { - str += i <= barLength ? '#' : ' '; - } - cli.native.util.print('[' + str + '] ' + Math.floor(progress * 100) + '%' + (progress === 1 ? '\n' : '\u000D')); -}; - -/** - * Helper method for outputting a spinner to the console. - * - * @param {String|Boolean} prefix (optional) - * @api public - */ -var spinnerInterval; -cli.spinner = function (prefix, end) { - if (end) { - cli.native.util.print('\u000D' + prefix); - return clearInterval(spinnerInterval); - } - prefix = prefix + ' ' || ''; - var spinner = ['-','\\','|','/'], i = 0, l = spinner.length; - spinnerInterval = setInterval(function () { - cli.native.util.print('\u000D' + prefix + spinner[i++]); - if (i == l) i = 0; - }, 200); -}; diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/cat.js b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/cat.js deleted file mode 100755 index 14c4e79c4..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/cat.js +++ /dev/null @@ -1,17 +0,0 @@ -#!/usr/bin/env node - -var cli = require('cli'); - -var output_file = function (file) { - cli.withInput(file, function (line, sep, eof) { - if (!eof) { - cli.output(line + sep); - } else if (cli.args.length) { - output_file(cli.args.shift()); - } - }); -}; - -if (cli.args.length) { - output_file(cli.args.shift()); -} \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/command.js b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/command.js deleted file mode 100755 index 2f04491e7..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/command.js +++ /dev/null @@ -1,16 +0,0 @@ -#!/usr/bin/env node - -var cli = require('cli'); - -//The second (optional) argument of cli.parse() is a command list -//Type `./command.js --help` for usage info - -//cli enables auto-completion of commands (similiar to npm), e.g. all of -//the following are equivalent and result in "Command is: install": -// $ ./command.js install -// $ ./command.js inst -// $ ./command.js i - -cli.parse(null, ['install', 'test', 'edit', 'remove', 'uninstall', 'ls']); - -console.log('Command is: ' + cli.command); diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/echo.js b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/echo.js deleted file mode 100755 index dac9ccaf1..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/echo.js +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env node - -/* All of the following commands are equivalent and write `foo\tbar foo` to out.txt - $ ./echo.js -n -e --output=out.txt "foo\tbar" "foo" - $ ./echo.js --newline --escape --output "out.txt" "foo\tbar" "foo" - $ ./echo.js -ne --output=out.txt "foo\tbar" "foo" - $ ./echo.js -en --output="out.txt" "foo\tbar" "foo" -*/ - -var cli = require('cli'); - -cli.parse({ - newline: ['n', 'Do not output the trailing newline'], - escape: ['e', 'Enable interpretation of backslash escapes'], - separator: ['s', 'Separate arguments using this value', 'string', ' '], - output: [false, 'Write to FILE rather than the console', 'file'] -}); - -cli.main(function (args, options) { - var output = '', i, j, l, output_stream; - - if (this.argc) { - if (options.escape) { - var replace = {'\\n':'\n','\\r':'\r','\\t':'\t','\\e':'\e','\\v':'\v','\\f':'\f','\\c':'\c','\\b':'\b','\\a':'\a','\\\\':'\\'}; - var escape = function (str) { - string += ''; - for (j in replace) { - string = string.replace(i, replace[i]); - } - return string; - } - for (i = 0, l = this.argc; i < l; i++) { - args[i] = escape(args[i]); - } - options.separator = escape(options.separator); - } - output += args.join(options.separator); - } - - if (!options.newline) { - output += '\n'; - } - - try { - if (options.output) { - output_stream = this.native.fs.createWriteStream(options.output) - } else { - output_stream = process.stdout; - } - output_stream.write(output); - } catch (e) { - this.fatal('Could not write to output stream'); - } -}); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/glob.js b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/glob.js deleted file mode 100755 index 12585c01f..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/glob.js +++ /dev/null @@ -1,6 +0,0 @@ -#!/usr/bin/env node - -var cli = require('cli').enable('glob'); - -//Running `./glob.js *.js` will output a list of .js files in this directory -console.log(cli.args); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/long_desc.js b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/long_desc.js deleted file mode 100755 index 63632f4bb..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/long_desc.js +++ /dev/null @@ -1,20 +0,0 @@ -#!/usr/bin/env node - -var cli = require('../'); - -//You can (optionally) boost the width of output with: -//cli.width = 120; - -//You can also adjust the width of the options/command definitions -//cli.option_width = 25; - -var long_desc = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s ' - + 'standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make' - + ' a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, ' - + 'remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing ' - + 'Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions' - + ' of Lorem Ipsum.'; - -cli.parse({ - foo: ['f', long_desc] -}); diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/progress.js b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/progress.js deleted file mode 100755 index 300c67405..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/progress.js +++ /dev/null @@ -1,11 +0,0 @@ -#!/usr/bin/env node - -var cli = require('cli'); - -var i = 0, interval = setInterval(function () { - cli.progress(++i / 100); - if (i === 100) { - clearInterval(interval); - cli.ok('Finished!'); - } -}, 50); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/sort.js b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/sort.js deleted file mode 100755 index 5d223133f..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/sort.js +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env node - -var cli = require('cli'); - -var options = cli.parse({ - numeric: ['n', 'Compare using a numeric sort'], - reverse: ['r', 'Reverse the results'] -}); - -cli.withStdinLines(function (lines, newline) { - lines.sort(!options.numeric ? null : function (a, b) { - return parseInt(a) > parseInt(b); - }); - if (options.reverse) { - lines.reverse(); - } - this.output(lines.join(newline)); -}); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/spinner.js b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/spinner.js deleted file mode 100755 index 61000013a..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/spinner.js +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env node - -var cli = require('cli'); - -cli.spinner('Working..'); - -setTimeout(function () { - cli.spinner('Working.. done!', true); //End the spinner -}, 3000); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/static.coffee b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/static.coffee deleted file mode 100755 index cbf3b16e1..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/static.coffee +++ /dev/null @@ -1,27 +0,0 @@ -#!/usr/bin/env coffee - -cli = require 'cli' - -cli.enable('daemon','status') - .setUsage('static.coffee [OPTIONS]') - -cli.parse { - log: ['l', 'Enable logging'] - port: ['p', 'Listen on this port', 'number', 8080] - serve: [false, 'Serve static files from PATH', 'path', './public'] -} - -middleware = [] - -cli.main (args, options) -> - - if options.log - @debug 'Enabling logging' - middleware.push require('creationix/log')() - - @debug 'Serving files from ' + options.serve - middleware.push require('creationix/static')('/', options.serve, 'index.html') - - server = @createServer(middleware).listen options.port - - @ok 'Listening on port ' + options.port \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/static.js b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/static.js deleted file mode 100755 index eb6fd2481..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/examples/static.js +++ /dev/null @@ -1,25 +0,0 @@ -#!/usr/bin/env node - -var cli = require('cli').enable('status', 'daemon'); - -cli.parse({ - log: ['l', 'Enable logging'], - port: ['p', 'Listen on this port', 'number', 8080], - serve: [false, 'Serve static files from PATH', 'path', './public'] -}); - -cli.main(function (args, options) { - var server, middleware = []; - - if (options.log) { - this.debug('Enabling logging'); - middleware.push(require('creationix/log')()); - } - - this.debug('Serving files from ' + options.serve); - middleware.push(require('creationix/static')('/', options.serve, 'index.html')); - - server = this.createServer(middleware).listen(options.port); - - this.ok('Listening on port ' + options.port); -}); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/index.js b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/index.js deleted file mode 100644 index 3966bd737..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./cli'); diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/package.json b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/package.json deleted file mode 100644 index 03f91c912..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/graceful-fs/package.json +++ /dev/null @@ -1,48 +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": "1.2.1", - "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", - "readme": "# graceful-fs\n\ngraceful-fs functions as a drop-in replacement for the fs module,\nmaking various improvements.\n\nThe improvements are meant to normalize behavior across different\nplatforms and environments, and to make filesystem access more\nresilient to errors.\n\n## Improvements over fs module\n\ngraceful-fs:\n\n* keeps track of how many file descriptors are open, and by default\n limits this to 1024. Any further requests to open a file are put in a\n queue until new slots become available. If 1024 turns out to be too\n much, it decreases the limit further.\n* fixes `lchmod` for Node versions prior to 0.6.2.\n* implements `fs.lutimes` if possible. Otherwise it becomes a noop.\n* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or\n `lchown` if the user isn't root.\n* makes `lchmod` and `lchown` become noops, if not available.\n* retries reading a file if `read` results in EAGAIN error.\n\nOn Windows, it retries renaming a file for up to one second if `EACCESS`\nor `EPERM` error occurs, likely because antivirus software has locked\nthe directory.\n\n## Configuration\n\nThe maximum number of open file descriptors that graceful-fs manages may\nbe adjusted by setting `fs.MAX_OPEN` to a different number. The default\nis 1024.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/node-graceful-fs/issues" - }, - "_id": "graceful-fs@1.2.1", - "_from": "graceful-fs@~1.2.0" -} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/inherits/package.json b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/inherits/package.json deleted file mode 100644 index aae88dbbf..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/inherits/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "inherits", - "description": "A tiny simple way to do classic inheritance in js", - "version": "1.0.0", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented" - ], - "main": "./inherits.js", - "repository": { - "type": "git", - "url": "https://github.com/isaacs/inherits" - }, - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "readme": "A dead simple way to do inheritance in JS.\n\n var inherits = require(\"inherits\")\n\n function Animal () {\n this.alive = true\n }\n Animal.prototype.say = function (what) {\n console.log(what)\n }\n\n inherits(Dog, Animal)\n function Dog () {\n Dog.super.apply(this)\n }\n Dog.prototype.sniff = function () {\n this.say(\"sniff sniff\")\n }\n Dog.prototype.bark = function () {\n this.say(\"woof woof\")\n }\n\n inherits(Chihuahua, Dog)\n function Chihuahua () {\n Chihuahua.super.apply(this)\n }\n Chihuahua.prototype.bark = function () {\n this.say(\"yip yip\")\n }\n\n // also works\n function Cat () {\n Cat.super.apply(this)\n }\n Cat.prototype.hiss = function () {\n this.say(\"CHSKKSS!!\")\n }\n inherits(Cat, Animal, {\n meow: function () { this.say(\"miao miao\") }\n })\n Cat.prototype.purr = function () {\n this.say(\"purr purr\")\n }\n\n\n var c = new Chihuahua\n assert(c instanceof Chihuahua)\n assert(c instanceof Dog)\n assert(c instanceof Animal)\n\nThe actual function is laughably small. 10-lines small.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/inherits/issues" - }, - "_id": "inherits@1.0.0", - "_from": "inherits@1", - "scripts": {} -} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json deleted file mode 100644 index 73920bf2a..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "lru-cache", - "description": "A cache object that deletes the least-recently-used items.", - "version": "2.3.0", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me" - }, - "scripts": { - "test": "tap test --gc" - }, - "main": "lib/lru-cache.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/node-lru-cache.git" - }, - "devDependencies": { - "tap": "", - "weak": "" - }, - "license": { - "type": "MIT", - "url": "http://github.com/isaacs/node-lru-cache/raw/master/LICENSE" - }, - "contributors": [ - { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me" - }, - { - "name": "Carlos Brito Lage", - "email": "carlos@carloslage.net" - }, - { - "name": "Marko Mikulicic", - "email": "marko.mikulicic@isti.cnr.it" - }, - { - "name": "Trent Mick", - "email": "trentm@gmail.com" - }, - { - "name": "Kevin O'Hara", - "email": "kevinohara80@gmail.com" - }, - { - "name": "Marco Rogers", - "email": "marco.rogers@gmail.com" - }, - { - "name": "Jesse Dailey", - "email": "jesse.dailey@gmail.com" - } - ], - "readme": "# lru cache\n\nA cache object that deletes the least-recently-used items.\n\n## Usage:\n\n```javascript\nvar LRU = require(\"lru-cache\")\n , options = { max: 500\n , length: function (n) { return n * 2 }\n , dispose: function (key, n) { n.close() }\n , maxAge: 1000 * 60 * 60 }\n , cache = LRU(options)\n , otherCache = LRU(50) // sets just the max size\n\ncache.set(\"key\", \"value\")\ncache.get(\"key\") // \"value\"\n\ncache.reset() // empty the cache\n```\n\nIf you put more stuff in it, then items will fall out.\n\nIf you try to put an oversized thing in it, then it'll fall out right\naway.\n\n## Options\n\n* `max` The maximum size of the cache, checked by applying the length\n function to all values in the cache. Not setting this is kind of\n silly, since that's the whole purpose of this lib, but it defaults\n to `Infinity`.\n* `maxAge` Maximum age in ms. Items are not pro-actively pruned out\n as they age, but if you try to get an item that is too old, it'll\n drop it and return undefined instead of giving it to you.\n* `length` Function that is used to calculate the length of stored\n items. If you're storing strings or buffers, then you probably want\n to do something like `function(n){return n.length}`. The default is\n `function(n){return 1}`, which is fine if you want to store `n`\n like-sized things.\n* `dispose` Function that is called on items when they are dropped\n from the cache. This can be handy if you want to close file\n descriptors or do other cleanup tasks when items are no longer\n accessible. Called with `key, value`. It's called *before*\n actually removing the item from the internal cache, so if you want\n to immediately put it back in, you'll have to do that in a\n `nextTick` or `setTimeout` callback or it won't do anything.\n* `stale` By default, if you set a `maxAge`, it'll only actually pull\n stale items out of the cache when you `get(key)`. (That is, it's\n not pre-emptively doing a `setTimeout` or anything.) If you set\n `stale:true`, it'll return the stale value before deleting it. If\n you don't set this, then it'll return `undefined` when you try to\n get a stale entry, as if it had already been deleted.\n\n## API\n\n* `set(key, value)`\n* `get(key) => value`\n\n Both of these will update the \"recently used\"-ness of the key.\n They do what you think.\n\n* `peek(key)`\n\n Returns the key value (or `undefined` if not found) without\n updating the \"recently used\"-ness of the key.\n\n (If you find yourself using this a lot, you *might* be using the\n wrong sort of data structure, but there are some use cases where\n it's handy.)\n\n* `del(key)`\n\n Deletes a key out of the cache.\n\n* `reset()`\n\n Clear the cache entirely, throwing away all values.\n\n* `has(key)`\n\n Check if a key is in the cache, without updating the recent-ness\n or deleting it for being stale.\n\n* `forEach(function(value,key,cache), [thisp])`\n\n Just like `Array.prototype.forEach`. Iterates over all the keys\n in the cache, in order of recent-ness. (Ie, more recently used\n items are iterated over first.)\n\n* `keys()`\n\n Return an array of the keys in the cache.\n\n* `values()`\n\n Return an array of the values in the cache.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/node-lru-cache/issues" - }, - "_id": "lru-cache@2.3.0", - "_from": "lru-cache@2" -} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json deleted file mode 100644 index ec8e2eb3e..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "sigmund", - "version": "1.0.0", - "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" - }, - "keywords": [ - "object", - "signature", - "key", - "data", - "psychoanalysis" - ], - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "BSD", - "readme": "# sigmund\n\nQuick and dirty signatures for Objects.\n\nThis is like a much faster `deepEquals` comparison, which returns a\nstring key suitable for caches and the like.\n\n## Usage\n\n```javascript\nfunction doSomething (someObj) {\n var key = sigmund(someObj, maxDepth) // max depth defaults to 10\n var cached = cache.get(key)\n if (cached) return cached)\n\n var result = expensiveCalculation(someObj)\n cache.set(key, result)\n return result\n}\n```\n\nThe resulting key will be as unique and reproducible as calling\n`JSON.stringify` or `util.inspect` on the object, but is much faster.\nIn order to achieve this speed, some differences are glossed over.\nFor example, the object `{0:'foo'}` will be treated identically to the\narray `['foo']`.\n\nAlso, just as there is no way to summon the soul from the scribblings\nof a cocain-addled psychoanalyst, there is no way to revive the object\nfrom the signature string that sigmund gives you. In fact, it's\nbarely even readable.\n\nAs with `sys.inspect` and `JSON.stringify`, larger objects will\nproduce larger signature strings.\n\nBecause sigmund is a bit less strict than the more thorough\nalternatives, the strings will be shorter, and also there is a\nslightly higher chance for collisions. For example, these objects\nhave the same signature:\n\n var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]}\n var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']}\n\nLike a good Freudian, sigmund is most effective when you already have\nsome understanding of what you're looking for. It can help you help\nyourself, but you must be willing to do some work as well.\n\nCycles are handled, and cyclical objects are silently omitted (though\nthe key is included in the signature output.)\n\nThe second argument is the maximum depth, which defaults to 10,\nbecause that is the maximum object traversal depth covered by most\ninsurance carriers.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/sigmund/issues" - }, - "_id": "sigmund@1.0.0", - "_from": "sigmund@~1.0.0" -} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/package.json b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/package.json deleted file mode 100644 index a34740535..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/node_modules/minimatch/package.json +++ /dev/null @@ -1,39 +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.12", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/minimatch.git" - }, - "main": "minimatch.js", - "scripts": { - "test": "tap test" - }, - "engines": { - "node": "*" - }, - "dependencies": { - "lru-cache": "2", - "sigmund": "~1.0.0" - }, - "devDependencies": { - "tap": "" - }, - "license": { - "type": "MIT", - "url": "http://github.com/isaacs/minimatch/raw/master/LICENSE" - }, - "readme": "# minimatch\n\nA minimal matching utility.\n\n[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch)\n\n\nThis is the matching library used internally by npm.\n\nEventually, it will replace the C binding in node-glob.\n\nIt works by converting glob expressions into JavaScript `RegExp`\nobjects.\n\n## Usage\n\n```javascript\nvar minimatch = require(\"minimatch\")\n\nminimatch(\"bar.foo\", \"*.foo\") // true!\nminimatch(\"bar.foo\", \"*.bar\") // false!\n```\n\n## Features\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\n### Comparisons to other fnmatch/glob implementations\n\nWhile strict compliance with the existing standards is a worthwhile\ngoal, some discrepancies exist between minimatch 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. **Note that this is different from the way that `**` is\nhandled by ruby's `Dir` class.**\n\nIf an escaped pattern has no matches, and the `nonull` flag is set,\nthen minimatch.match returns the pattern as-provided, rather than\ninterpreting the character escapes. For example,\n`minimatch.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\n## Minimatch Class\n\nCreate a minimatch object by instanting the `minimatch.Minimatch` class.\n\n```javascript\nvar Minimatch = require(\"minimatch\").Minimatch\nvar mm = new Minimatch(pattern, options)\n```\n\n### Properties\n\n* `pattern` The original pattern the minimatch object represents.\n* `options` The options supplied to the constructor.\n* `set` A 2-dimensional array of regexp or string expressions.\n Each row in the\n array corresponds to a brace-expanded pattern. Each item in the row\n corresponds to a single path-part. For example, the pattern\n `{a,b/c}/d` would expand to a set of patterns like:\n\n [ [ a, d ]\n , [ b, c, d ] ]\n\n If a portion of the pattern doesn't have any \"magic\" in it\n (that is, it's something like `\"foo\"` rather than `fo*o?`), then it\n will be left as a string rather than converted to a regular\n expression.\n\n* `regexp` Created by the `makeRe` method. A single regular expression\n expressing the entire pattern. This is useful in cases where you wish\n to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.\n* `negate` True if the pattern is negated.\n* `comment` True if the pattern is a comment.\n* `empty` True if the pattern is `\"\"`.\n\n### Methods\n\n* `makeRe` Generate the `regexp` member if necessary, and return it.\n Will return `false` if the pattern is invalid.\n* `match(fname)` Return true if the filename matches the pattern, or\n false otherwise.\n* `matchOne(fileArray, patternArray, partial)` Take a `/`-split\n filename, and match it against a single row in the `regExpSet`. This\n method is mainly for internal use, but is exposed so that it can be\n used by a glob-walker that needs to avoid excessive filesystem calls.\n\nAll other methods are internal, and will be called as necessary.\n\n## Functions\n\nThe top-level exported function has a `cache` property, which is an LRU\ncache set to store 100 items. So, calling these methods repeatedly\nwith the same pattern and options will use the same Minimatch object,\nsaving the cost of parsing it multiple times.\n\n### minimatch(path, pattern, options)\n\nMain export. Tests a path against the pattern using the options.\n\n```javascript\nvar isJS = minimatch(file, \"*.js\", { matchBase: true })\n```\n\n### minimatch.filter(pattern, options)\n\nReturns a function that tests its\nsupplied argument, suitable for use with `Array.filter`. Example:\n\n```javascript\nvar javascripts = fileList.filter(minimatch.filter(\"*.js\", {matchBase: true}))\n```\n\n### minimatch.match(list, pattern, options)\n\nMatch against the list of\nfiles, in the style of fnmatch or glob. If nothing is matched, and\noptions.nonull is set, then return a list containing the pattern itself.\n\n```javascript\nvar javascripts = minimatch.match(fileList, \"*.js\", {matchBase: true}))\n```\n\n### minimatch.makeRe(pattern, options)\n\nMake a regular expression object from the pattern.\n\n## Options\n\nAll options are `false` by default.\n\n### debug\n\nDump a ton of stuff to stderr.\n\n### nobrace\n\nDo not expand `{a,b}` and `{1..3}` brace sets.\n\n### noglobstar\n\nDisable `**` matching against multiple folder names.\n\n### dot\n\nAllow patterns to match filenames starting with a period, even if\nthe pattern does not explicitly have a period in that spot.\n\nNote that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`\nis set.\n\n### noext\n\nDisable \"extglob\" style patterns like `+(a|b)`.\n\n### nocase\n\nPerform a case-insensitive match.\n\n### nonull\n\nWhen a match is not found by `minimatch.match`, return a list containing\nthe pattern itself. When set, an empty list is returned if there are\nno matches.\n\n### matchBase\n\nIf set, then patterns without slashes will be matched\nagainst the basename of the path if it contains slashes. For example,\n`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.\n\n### nocomment\n\nSuppress the behavior of treating `#` at the start of a pattern as a\ncomment.\n\n### nonegate\n\nSuppress the behavior of treating a leading `!` character as negation.\n\n### flipNegate\n\nReturns from negate expressions the same as if they were not negated.\n(Ie, true on a hit, false on a miss.)\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/minimatch/issues" - }, - "_id": "minimatch@0.2.12", - "_from": "minimatch@~0.2.11" -} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/package.json b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/package.json deleted file mode 100644 index 03a589168..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/node_modules/glob/package.json +++ /dev/null @@ -1,39 +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.1", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/node-glob.git" - }, - "main": "glob.js", - "engines": { - "node": "*" - }, - "dependencies": { - "minimatch": "~0.2.11", - "graceful-fs": "~1.2.0", - "inherits": "1" - }, - "devDependencies": { - "tap": "~0.4.0", - "mkdirp": "0", - "rimraf": "1" - }, - "scripts": { - "test": "tap test/*.js" - }, - "license": "BSD", - "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", - "bugs": { - "url": "https://github.com/isaacs/node-glob/issues" - }, - "_id": "glob@3.2.1", - "_from": "glob@>= 3.1.4" -} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/package.json b/node/node_modules/grunt/node_modules/jshint/node_modules/cli/package.json deleted file mode 100755 index 9bec11a41..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/cli/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "cli", - "description": "A tool for rapidly building command line apps", - "version": "0.4.3", - "homepage": "http://github.com/chriso/cli", - "keywords": [ - "cli", - "command line", - "opts", - "parseopt", - "opt", - "args", - "console", - "argsparse", - "optparse", - "daemon", - "autocomplete", - "command", - "autocompletion" - ], - "author": { - "name": "Chris O'Hara", - "email": "cohara87@gmail.com" - }, - "main": "cli.js", - "bugs": { - "url": "http://github.com/chriso/cli/issues" - }, - "repository": { - "type": "git", - "url": "http://github.com/chriso/cli.git" - }, - "dependencies": { - "glob": ">= 3.1.4" - }, - "contributors": [ - { - "name": "Douglas Meyer" - } - ], - "engines": { - "node": ">=0.2.5" - }, - "licenses": [ - { - "type": "MIT" - } - ], - "readme": "**cli is a toolkit for rapidly building command line apps - it includes:**\n\n- Full featured opts/args parser\n- Plugin support for adding common options and switches\n- Helper methods for working with input/output and spawning child processes\n- Output colored/styled messages, [progress bars](https://github.com/chriso/cli/blob/master/examples/progress.js) or [spinners](https://github.com/chriso/cli/blob/master/examples/spinner.js)\n- Command [auto-completion](https://github.com/chriso/cli/blob/master/examples/command.js) and [glob support](https://github.com/chriso/cli/blob/master/examples/glob.js)\n\nInstall using `npm install cli` or just bundle [cli.js](https://github.com/chriso/cli/raw/master/cli-min.js) with your app.\n\n## Example apps\n\n### sort.js\n\n```javascript\n#!/usr/bin/env node\nrequire('cli').withStdinLines(function(lines, newline) {\n this.output(lines.sort().join(newline));\n});\n```\n\nTry it out\n\n```bash\n$ ./sort.js < input.txt\n```\n\nLet's add support for an `-n` switch to use a numeric sort, and a `-r` switch to reverse output - only 5 extra lines of code (!)\n\n```javascript\nvar cli = require('cli'), options = cli.parse();\n\ncli.withStdinLines(function(lines, newline) {\n lines.sort(!options.n ? null : function(a, b) {\n return parseInt(a) > parseInt(b);\n });\n if (options.r) lines.reverse();\n this.output(lines.join(newline));\n});\n```\n\n### static.js\n\nLet's create a static file server with daemon support to see the opts parser + plugins in use - note: this requires `npm install creationix daemon`\n\n```javascript\nvar cli = require('cli').enable('daemon', 'status'); //Enable 2 plugins\n\ncli.parse({\n log: ['l', 'Enable logging'],\n port: ['p', 'Listen on this port', 'number', 8080],\n serve: [false, 'Serve static files from PATH', 'path', './public']\n});\n\ncli.main(function(args, options) {\n var server, middleware = [];\n\n if (options.log) {\n this.debug('Enabling logging');\n middleware.push(require('creationix/log')());\n }\n\n this.debug('Serving files from ' + options.serve);\n middleware.push(require('creationix/static')('/', options.serve, 'index.html'));\n\n server = this.createServer(middleware).listen(options.port);\n\n this.ok('Listening on port ' + options.port);\n});\n```\n\nTo output usage information\n\n```bash\n$ ./static.js --help\n```\n\nTo create a daemon that serves files from */tmp*, run\n\n```bash\n$ ./static.js -ld --serve=/tmp\n```\n\nFor more examples, see [./examples](https://github.com/chriso/cli/tree/master/examples)\n\n## Helper methods\n\ncli has methods that collect stdin (newline is autodetected as \\n or \\r\\n)\n\n```javascript\ncli.withStdin(callback); //callback receives stdin as a string\ncli.withStdinLines(callback); //callback receives stdin split into an array of lines (lines, newline)\n```\n\ncli also has a lower level method for working with input line by line (see [./examples/cat.js](https://github.com/chriso/cli/blob/master/examples/cat.js) for an example). \n\n```javascript\ncli.withInput(file, function (line, newline, eof) {\n if (!eof) {\n this.output(line + newline);\n }\n});\n```\n\n*Note: `file` can be omitted if you want to work with stdin*\n\nTo output a progress bar, call\n\n```javascript\ncli.progress(progress); //Where 0 <= progress <= 1\n```\n\nTo spawn a child process, use\n\n```javascript\ncli.exec(cmd, callback); //callback receives the output of the process (split into lines)\n```\n\ncli also comes bundled with kof's [node-natives](https://github.com/kof/node-natives) (access with cli.native) and creationix' [stack](https://github.com/creationix/stack) (access with cli.createServer)\n\n## Plugins\n\nPlugins are a way of adding common opts and can be enabled using \n\n```javascript\ncli.enable(plugin1, [plugin2, ...]); //To disable, use the equivalent disable() method\n```\n\n**help** - *enabled by default*\n\nAdds `-h,--help` to output auto-generated usage information\n\n**version**\n\nAdds `-v,--version` to output version information for the app. cli will attempt to locate and parse a nearby *package.json*\n\nTo set your own app name and version, use `cli.setApp(app_name, version)`\n\n**status**\n\nAdds options to show/hide the stylized status messages that are output to the console when using one of these methods\n\n```javascript\ncli.debug(msg); //Only shown when using --debug\ncli.error(msg);\ncli.fatal(msg); //Exits the process after outputting msg\ncli.info(msg);\ncli.ok(msg);\n```\n\n`-k,--no-color` will omit ANSI color escapes from the output\n\n**glob** - *requires* `npm install glob`\n\nEnables glob matching of arguments\n\n**daemon** - *requires* `npm install daemon`\n\nAdds `-d,--daemon ARG` for daemonizing the process and controlling the resulting daemon\n\n`ARG` can be either start (default), stop, restart, pid (outputs the daemon's pid if it's running), or log (output the daemon's stdout+stderr)\n\n**timeout**\n\nAdds `-t,--timeout N` to exit the process after N seconds with an error\n\n**catchall**\n\nAdds `-c,--catch` to catch and output uncaughtExceptions and resume execution\n\n*Note: Plugins are automatically disabled if an option or switch of the same name is already defined*\n\n## LICENSE\n\n(MIT license)\n\nCopyright (c) 2010 Chris O'Hara \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\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n", - "readmeFilename": "README.md", - "_id": "cli@0.4.3", - "_from": "cli@0.4.3" -} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/README.md b/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/README.md deleted file mode 100644 index 2664c085c..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/README.md +++ /dev/null @@ -1,114 +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! -``` - -## Features - -Supports all glob features. - -See: - -* `man sh` -* `man fnmatch` -* `man 5 gitignore` - -### Departures from zsh/bash/ksh/sh - -If the pattern starts with a `!` character, then it is negated. - -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.) - -The double-star `**` is always supported, instead of requiring a special -flag. - -If an escaped pattern has no matches, and the `null` flag is not 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?"`. - -## Functions - -### minimatch(path, pattern, options) - -Main export. Tests a path against -the pattern using the options. - -### minimatch.filter(pattern, options) - -Returns a function that tests its -supplied argument, suitable for use with `Array.filter`. - -### minimatch.match(list, pattern, options) - -Match against the list of -files, in the style of fnmatch or glob. If nothing is matched, then -return the pattern (unless `{ null: true }` in the options.) - -### 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. - -### null - -Return an empty list from minimatch.match, instead of a list -containing the pattern itself. - -### nocase - -Perform a case-insensitive match. - -### cache - -An LRU cache with `.get(k)` and `.set(k,v)` methods. By -default, an instance of `node-lru-cache` is used, with 1000 max -entries. - -### slash - -If set, then `a/*` will match `a/` as well as `a/b`. - -### 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 `xyz/123/acb`. - -### partial - -Internal. Used by `minimatch.makeRe`. - -### dot - -Allow patterns to match paths starting with a period, even if -the pattern does not explicitly start with a period. diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/blerg.js b/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/blerg.js deleted file mode 100644 index 9eb56e238..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/blerg.js +++ /dev/null @@ -1,62 +0,0 @@ - -// Turn something like {a,b{c,d},}x{e,f} into -// ["axe", "axf", "bcxe", "bcxf", "bdxe", "bdxf", "xe", "xf"] -// Only {,} groups are expanded. While in many cases {x,y} is -// functionally equivalent to @(x|y), for the purpose of globbing -// files, only {x,y} gets expanded as multiple patterns. -minimatch.patternSet = patternSet -function patternSet (pattern) { - if (!pattern.match(/{/) || !pattern.match(/}/)) { - // shortcut - no sets. - return [pattern] - } - - // a{b,c{d,e},{f,g}h}x{y,z} - // - // t=[before set, set, after set] - // t=["a", ["b", "c{d,e}", "{f,g}h"], "x{y,z}"] - - // start walking, and note the position of the first { - // and the corresponding } - var p = pattern.indexOf("{") - , l = pattern.length - , d = 0 - , escaping = false - , inClass = false - while (++ p < l) { - switch (pattern.charAt(p)) { - case "{": - d ++ - continue - case "}": - - - - // t[2] = patternSet(t[2]) - // t = [t[0]].concat([t[1].map(patternSet)]).concat([t[2]]) - // - // t=["a",[["b"],[["cd","ce"]],[["fh","gh"]]],["xy","xz"]] - // - // // first turn into - // // [["ab"], ["acd", "ace"], ["afh", "agh"]] - // return t[1].map(function (p) { - // return p.map(function (p) { - // return t[0] + p - // }) - // }) - // // flatten into ["ab", "acd", "ace", "afh", "agh"] - // .reduce(function (l, r) { - // return l.concat(r) - // }, []) - // // tack all the endings onto each one - // .map(function (p) { - // return t[2].map(function (e) { - // return p + e - // }) - // }) - // // flatten again - // .reduce(function (l, r) { - // return l.concat(r) - // }, []) -} - diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/minimatch.js b/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/minimatch.js deleted file mode 100644 index c50ab71a5..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/minimatch.js +++ /dev/null @@ -1,372 +0,0 @@ -// This is a JavaScript implementation of the fnmatch-like -// stuff that git uses in its .gitignore files. -// See `man 5 gitignore`. - -module.exports = minimatch - -var path = require("path") - , LRU = require("lru-cache") - -minimatch.filter = function (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} - -minimatch.match = function (list, pattern, options) { - if (!options) options = {} - var ret = list.filter(minimatch.filter(pattern, options)) - if (options.debug) console.error("\nmatch: %s %j %j", pattern, list, ret) - - // set the null flag to allow empty match sets - // Note that minimatch itself, and filter(), do not - // respect this flag, only minimatch.match(list, pattern) does. - if (!options.null && !ret.length) { - return [pattern] - } - - return ret -} - -function minimatch (p, pattern, options) { - if (typeof pattern !== "string") { - throw new TypeError("glob pattern string required") - } - - options = options || {} - - // to set the cache, just replace with a different obj - // supporting set(k,v) and v=get(k) methods. - var cache = options.cache || minimatch.cache - if (!cache) cache = minimatch.cache = new LRU(1000) - - // "" only matches "" - if (!pattern) return p === "" - - // comments. - if (pattern.trim().charAt(0) === "#") return false - - // check the cache - var re = cache.get(pattern + "\n" + JSON.stringify(options)) - if (!re && re !== false) { - cache.set(pattern, re = minimatch.makeRe(pattern, options)) - } - - if (options.debug) { - console.error(pattern + "\t" + re, JSON.stringify(p)) - } - - // some kind of invalid thing - if (!re) return false - - - // patterns that end in / can only match dirs - // however, dirs also match the same thing that *doesn't* - // end in a slash. - var match = - // a/ should not match a/*, but will match */ - // accomplish this by not applying the regexp - // directly, unless the pattern would match - // trailing slash'ed things, or the thing isn't - // a trailing slash, or slashes are opted-in - ( ( options.slash || - p.substr(-1) !== "/" || - pattern.substr(-1) === "/" ) - && !!p.match(re) ) - - // a/ should match * or a - || ( p.substr(-1) === "/" && - !!p.slice(0, -1).match(re) ) - - // a pattern with *no* slashes will match against - // either the full path, or just the basename. - || ( options.matchBase && - pattern.indexOf("/") === -1 && - path.basename(p).match(re) ) - - //console.error(" MINIMATCH: %j %j %j %j", - // re.toString(), pattern, p, match) - return match -} - -minimatch.makeRe = makeRe -function makeRe (pattern, options) { - options = options || {} - - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case "*": - re += oneStar - break - case "?": - re += "." - break - default: - re += "\\"+stateChar - break - } - stateChar = false - } - } - - var braceDepth = 0 - , re = "" - , escaping = false - , oneStar = options.dot ? "[^\\/]*?" - : "(?:(?!(?:\\\/|^)\\.)[^\\/])*?" - , twoStar = options.dot ? ".*?" - // not a ^ or / followed by a dot, - // followed by anything, any number of times. - : "(?:(?!(?:\\\/|^)\\.).)*?" - , reSpecials = "().*{}+?[]^$/\\" - , patternListStack = [] - , stateChar - , negate = false - , negating = false - , inClass = false - , reClassStart = -1 - , classStart = -1 - , classStartPattern = options.dot ? "" - : "(?:(?!(?:\\\/|^)\\.)" - , classEndPattern = options.dot ? "" : ")" - - for ( var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i ++ ) { - - if (options.debug) { - console.error("%s\t%s %s %j", pattern, i, re, c) - } - - switch (c) { - case "\\": - if (stateChar) { - if (stateChar === "*") re += oneStar - else re += "\\" + stateChar - stateChar = false - } - if (escaping) { - re += "\\\\" // must match literal \ - escaping = false - } else { - escaping = true - } - continue - - // the various stateChar values - case "!": - if (i === 0 || negating) { - negate = !negate - negating = true - break - } else { - negating = false - } - // fallthrough - case "+": - case "@": - case "*": - case "?": - if (options.debug) { - console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c) - } - - negating = false - if (escaping) { - re += "\\" + c - escaping = false - } else if (inClass) { - re += c - } else if (c === "*" && stateChar === "*") { // ** - re += twoStar - stateChar = false - } else { - if (stateChar) { - if (stateChar === "*") re += oneStar - else if (stateChar === "?") re += "." - else re += "\\" + stateChar - } - stateChar = c - } - continue - - case "(": - if (escaping) { - re += "\\(" - escaping = false - } else if (inClass) { - re += "(" - } else if (stateChar) { - plType = stateChar - patternListStack.push(plType) - re += stateChar === "!" ? "(?!" : "(?:" - stateChar = false - } else { - re += "\\(" - } - continue - - case ")": - if (escaping || inClass) { - re += "\\)" - escaping = false - } else if (patternListStack.length) { - re += ")" - plType = patternListStack.pop() - switch (plType) { - case "?": - case "+": - case "*": re += plType - case "!": - case "@": break - } - } else { - re += "\\)" - } - continue - - case "|": - if (escaping || inClass) { - re += "\\|" - escaping = false - } else if (patternListStack.length) { - re += "|" - } else { - re += "\\|" - } - continue - - // these are mostly the same in regexp and glob :) - case "[": - // swallow any state-tracking char before the [ - clearStateChar() - - if (escaping || inClass) { - re += "\\" + c - escaping = false - } else { - inClass = true - classStart = i - reClassStart = re.length - re += classStartPattern - 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) escaping = true - - if (escaping || !inClass) { - re += "\\" + c - escaping = false - } else { - inClass = false - re += c + classEndPattern - } - continue - - case "{": - if (escaping || inClass) { - re += "\\{" - escaping = false - } else { - re += "(?:" - braceDepth ++ - } - continue - - case "}": - if (escaping || inClass || braceDepth === 0) { - re += "\\}" - escaping = false - } else { - // swallow any state char that wasn't consumed - clearStateChar() - re += ")" - braceDepth -- - } - continue - - case ",": - if (escaping || inClass || braceDepth === 0) { - re += "," - escaping = false - } else { - // swallow any state char that wasn't consumed - clearStateChar() - re += "|" - } - continue - - default: - // swallow any state char that wasn't consumed - clearStateChar() - - if (escaping) { - // no need - escaping = false - } else if (reSpecials.indexOf(c) !== -1 - && !(c === "^" && inClass)) { - re += "\\" - } - - re += c - - } // switch - - if (negating && c !== "!") negating = false - - } // for - - // handle trailing things that only matter at the very end. - if (stateChar) { - clearStateChar() - } else if (escaping) { - re += "\\\\" - } - - // "[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 = re.substr(reClassStart + classStartPattern.length + 1) - , csOpts = Object.create(options) - csOpts.partial = true - - re = re.substr(0, reClassStart) + "\\[" - + makeRe(cs, csOpts) - } - - if (options.partial) return re - - // must match entire pattern - // ending in a * or ** will make it less strict. - re = "^" + re + "$" - - // fail on the pattern, but allow anything otherwise. - if (negate) re = "^(?!" + re + ").*$" - - // really insane glob patterns can cause bad things. - var flags = "" - if (options.nocase) flags += "i" - - if (options.debug) { - console.error("/%s/%s", re, flags) - } - - try { - return new RegExp(re, flags) - } catch(ex) { - return false - } -} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/README.md b/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/README.md deleted file mode 100644 index 0f3908dd4..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# lru cache - -A cache object that deletes the least-recently-used items. - -Usage: - - var LRU = require("lru-cache") - , cache = LRU(10) // max 10 items. default = Infinity - cache.set("key", "value") - cache.get("key") // "value" - - cache.reset() // empty the cache - -RTFS for more info. diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js b/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js deleted file mode 100644 index c3e4feb3f..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js +++ /dev/null @@ -1,106 +0,0 @@ -;(function () { // closure for web browsers - -if (module) { - module.exports = LRUCache -} else { - // just set the global for non-node platforms. - ;(function () { return this })().LRUCache = LRUCache -} - -function hOP (obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key) -} - -function LRUCache (maxLength) { - if (!(this instanceof LRUCache)) { - return new LRUCache(maxLength) - } - var cache = {} // hash of items by key - , lruList = {} // list of items in order of use recency - , lru = 0 // least recently used - , mru = 0 // most recently used - , length = 0 // number of items in the list - - // resize the cache when the maxLength changes. - Object.defineProperty(this, "maxLength", - { set : function (mL) { - if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity - maxLength = mL - // if it gets above double maxLength, trim right away. - // otherwise, do it whenever it's convenient. - if (length > maxLength) trim() - } - , get : function () { return maxLength } - , enumerable : true - }) - - this.maxLength = maxLength - - Object.defineProperty(this, "length", - { get : function () { return length } - , enumerable : true - }) - - this.reset = function () { - cache = {} - lruList = {} - lru = 0 - mru = 0 - length = 0 - } - - // Provided for debugging/dev purposes only. No promises whatsoever that - // this API stays stable. - this.dump = function () { - return cache - } - - this.set = function (key, value) { - if (hOP(cache, key)) { - this.get(key) - cache[key].value = value - return undefined - } - var hit = {key:key, value:value, lu:mru++} - lruList[hit.lu] = cache[key] = hit - length ++ - if (length > maxLength) trim() - } - - this.get = function (key) { - if (!hOP(cache, key)) return undefined - var hit = cache[key] - delete lruList[hit.lu] - if (hit.lu === lru) lruWalk() - hit.lu = mru ++ - lruList[hit.lu] = hit - return hit.value - } - - this.del = function (key) { - if (!hOP(cache, key)) return undefined - var hit = cache[key] - delete cache[key] - delete lruList[hit.lu] - if (hit.lu === lru) lruWalk() - length -- - } - - function lruWalk () { - // lru has been deleted, hop up to the next hit. - lru = Object.keys(lruList).shift() - } - - function trim () { - if (length <= maxLength) return undefined - var prune = Object.keys(lruList).slice(0, length - maxLength) - for (var i = 0, l = (length - maxLength); i < l; i ++) { - delete cache[ lruList[prune[i]].key ] - delete lruList[prune[i]] - } - length = maxLength - lruWalk() - } -} - -})() diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/package.json b/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/package.json deleted file mode 100644 index 719497b87..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "lru-cache", - "description": "A cache object that deletes the least-recently-used items.", - "version": "1.0.6", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me" - }, - "scripts": { - "test": "tap test" - }, - "main": "lib/lru-cache.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/node-lru-cache.git" - }, - "devDependencies": { - "tap": "0" - }, - "license": { - "type": "MIT", - "url": "http://github.com/isaacs/node-lru-cache/raw/master/LICENSE" - }, - "readme": "# lru cache\n\nA cache object that deletes the least-recently-used items.\n\nUsage:\n\n var LRU = require(\"lru-cache\")\n , cache = LRU(10) // max 10 items. default = Infinity\n cache.set(\"key\", \"value\")\n cache.get(\"key\") // \"value\"\n\n cache.reset() // empty the cache\n\nRTFS for more info.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/node-lru-cache/issues" - }, - "_id": "lru-cache@1.0.6", - "_from": "lru-cache@~1.0.2" -} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/test/basic.js b/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/test/basic.js deleted file mode 100644 index f6d7a6da9..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/node_modules/lru-cache/test/basic.js +++ /dev/null @@ -1,117 +0,0 @@ -var test = require('tap').test - , LRU = require('../') - -test('basic', function (t) { - var cache = new LRU(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.maxLength, 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('maxLength', function (t) { - var cache = new LRU(3) - - // test changing the maxLength, verify that the LRU items get dropped. - cache.maxLength = 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.maxLength = 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 maxLength restriction, and try again. - cache.maxLength = "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.maxLength = 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.maxLength, 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() -}) diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/package.json b/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/package.json deleted file mode 100644 index d02397595..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/package.json +++ /dev/null @@ -1,40 +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.0.5", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/minimatch.git" - }, - "main": "minimatch.js", - "scripts": { - "test": "tap test" - }, - "engines": { - "node": "*" - }, - "dependencies": { - "lru-cache": "~1.0.2" - }, - "devDependencies": { - "tap": "~0.0.5" - }, - "licenses": [ - { - "type": "MIT", - "url": "http://github.com/isaacs/minimatch/raw/master/LICENSE" - } - ], - "readme": "# minimatch\n\nA minimal matching utility.\n\n[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch)\n\n\nThis is the matching library used internally by npm.\n\nEventually, it will replace the C binding in node-glob.\n\nIt works by converting glob expressions into JavaScript `RegExp`\nobjects.\n\n## Usage\n\n```javascript\nvar minimatch = require(\"minimatch\")\n\nminimatch(\"bar.foo\", \"*.foo\") // true!\nminimatch(\"bar.foo\", \"*.bar\") // false!\n```\n\n## Features\n\nSupports all glob features.\n\nSee:\n\n* `man sh`\n* `man fnmatch`\n* `man 5 gitignore`\n\n### Departures from zsh/bash/ksh/sh\n\nIf the pattern starts with a `!` character, then it is negated.\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.)\n\nThe double-star `**` is always supported, instead of requiring a special\nflag.\n\nIf an escaped pattern has no matches, and the `null` flag is not set,\nthen minimatch.match returns the pattern as-provided, rather than\ninterpreting the character escapes. For example,\n`minimatch.match([], \"\\\\*a\\\\?\")` will return `\"\\\\*a\\\\?\"` rather than\n`\"*a?\"`.\n\n## Functions\n\n### minimatch(path, pattern, options)\n\nMain export. Tests a path against\nthe pattern using the options.\n\n### minimatch.filter(pattern, options)\n\nReturns a function that tests its\nsupplied argument, suitable for use with `Array.filter`.\n\n### minimatch.match(list, pattern, options)\n\nMatch against the list of\nfiles, in the style of fnmatch or glob. If nothing is matched, then\nreturn the pattern (unless `{ null: true }` in the options.)\n\n### minimatch.makeRe(pattern, options)\n\nMake a regular expression object\nfrom the pattern.\n\n## Options\n\nAll options are `false` by default.\n\n### debug\n\nDump a ton of stuff to stderr.\n\n### null\n\nReturn an empty list from minimatch.match, instead of a list\ncontaining the pattern itself.\n\n### nocase\n\nPerform a case-insensitive match.\n\n### cache\n\nAn LRU cache with `.get(k)` and `.set(k,v)` methods. By\ndefault, an instance of `node-lru-cache` is used, with 1000 max\nentries.\n\n### slash\n\nIf set, then `a/*` will match `a/` as well as `a/b`.\n\n### matchBase\n\nIf set, then patterns without slashes will be matched\nagainst the basename of the path if it contains slashes. For example,\n`a?b` would match `xyz/123/acb`.\n\n### partial\n\nInternal. Used by `minimatch.makeRe`.\n\n### dot\n\nAllow patterns to match paths starting with a period, even if\nthe pattern does not explicitly start with a period.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/minimatch/issues" - }, - "_id": "minimatch@0.0.5", - "_from": "minimatch@0.0.x" -} diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/t.js b/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/t.js deleted file mode 100644 index e67bf8846..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/t.js +++ /dev/null @@ -1,4 +0,0 @@ -console.error(Object.keys(global).length) -var m = require("./") -console.log(m.makeRe("**")) -console.error(Object.keys(global).length) diff --git a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/test/basic.js b/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/test/basic.js deleted file mode 100644 index f4f585f87..000000000 --- a/node/node_modules/grunt/node_modules/jshint/node_modules/minimatch/test/basic.js +++ /dev/null @@ -1,167 +0,0 @@ -// http://www.bashcookbook.com/bashinfo/source/bash-1.14.7/tests/glob-test - -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*"]] - // allow null glob expansion - , ["X*", [], { null: true }] - - // 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 - , ["\\*", ["\\*"]] - , ["\\**", ["\\**"]] - - , ["b*/", ["bdir/"]] - , ["c*", ["c", "ca", "cb"]] - , ["**", files] - - - , ["\\.\\./*/", ["\\.\\./*/"]] - , ["s/\\..*//", ["s/\\..*//"]] - - , "legendary larry crashes bashes" - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/" - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\\1/"]] - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/" - , ["/^root:/{s/^[^:]*:[^:]*:\([^:]*\).*$/\1/"]] - - , "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"]] - , ["[/\\\\]*", ["/tmp"], null, ["/tmp"]] - , ["??**********?****?", [], { 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"]] - - // 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"]] - - ].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 r = mm.makeRe(pattern, options) - tapOpts.re = String(r) || JSON.stringify(r) - tapOpts.files = JSON.stringify(f) - tapOpts.pattern = pattern - - var actual = mm.match(f, pattern, options) - - 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/node_modules/grunt/node_modules/jshint/package.json b/node/node_modules/grunt/node_modules/jshint/package.json deleted file mode 100644 index 025eee68d..000000000 --- a/node/node_modules/grunt/node_modules/jshint/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "jshint", - "version": "0.9.1", - "description": "A CLI for JSHint", - "homepage": "http://github.com/jshint/node-jshint", - "author": { - "name": "Brent Lintner", - "email": "brent.lintner@gmail.com", - "url": "http://github.com/brentlintner" - }, - "licenses": [ - { - "type": "MIT", - "url": "http://www.opensource.org/licenses/mit-license.php" - } - ], - "bin": { - "jshint": "./bin/hint" - }, - "main": "packages/jshint/jshint", - "files": [ - "packages/jshint/README.markdown", - "packages/jshint/jshint.js", - "README.md", - "LICENSE", - "bin/hint", - "lib" - ], - "dependencies": { - "cli": "0.4.3", - "minimatch": "0.0.x" - }, - "devDependencies": { - "jasmine-node": "1.0.x" - }, - "preferGlobal": true, - "readme": "# node-jshint\n\nA command line interface and npm package for jshint.\n\n## Install\n\nTo use jshint from any location (for npm v1.x) you need to install using the global (-g) flag.\n\n npm install -g jshint\n\n## Usage\n\n jshint -h\n\nYou can also require JSHint itself as a module.\n\n var jshint = require('jshint');\n\nNote: If you are using npm v1.x be sure to install jshint locally (without the -g flag) or link it globally.\n\n## Text Editor Plugins\n\n* [gedit-node-jshint](https://github.com/niftylettuce/gedit-node-jshint) - Simply use CTRL+J in gedit to run JSHint using `node-jshint`.\n* [vim syntastic](https://github.com/scrooloose/syntastic) - Run node-jshint at each file save.\n* [sublime-jshint](https://github.com/uipoet/sublime-jshint) - `F7` or `command-B` on any .js file. `F4` next error line,column. `shift-F4` previous error line,column.\n\n## Custom Reporters\n\nSpecify a custom reporter module (see example/reporter.js).\n\n --reporter path/to/reporter.js\n\nUse a jslint compatible xml reporter.\n\n --jslint-reporter\n\nShow additional non-error data generated by jshint (unused globals etc).\n\n --show-non-errors\n\n## Configuration Options\n\n**Note:** This behavior described below is very different from versions prior to `0.6`.\n\nThe CLI uses the default options that come with JSHint. \n\nOnly one extra option is unique to node-jshint: `globals` \nallows you to define an object of globals that get ignored for every file.\nTo see an example you can look at how whitelisted globals are defined\nin the [jshint code](https://github.com/jshint/jshint/blob/c047ea1b01097fcc220fcd1a55c41f67ae2e6e81/jshint.js#L556)\n\nTo have your own configuration apply, there are several methods you can use:\n\n### Specify Manually\n\nSetting the `--config=/path/to/your/config` command line option to specify your own configuration file outside of the directory tree for your project.\n\n### Within your Project's Directory Tree\n\nWhen the CLI is called, and a configuration file isn't specified already, `node-jshint` will attempt to locate one for you starting in `pwd`. (or \"present working directory\") If this does not yield a `.jshintrc` file, it will move one level up (`..`) the directory tree all the way up to the filesystem root. If a file is found, it stops immediately and uses that set of configuration.\n\nThis setup allows you to set up **one** configuration file for your entire project. (place it in the root folder) As long as you run `jshint` from anywhere within your project directory tree, the same configuration file will be used.\n\n### Home Directory\n\nIf all the methods above do not yield a `.jshintrc` to use, the last place that will be checked is your user's `$HOME` directory.\n\n## File Extensions\n\nDefault extension for files is \".js\". If you want to use JSHint with other file extensions (.json), you need to pass this extra extension as an option :\n\n --extra-ext .json\n\n## Ignoring Files and Directories\n\nIf there is a .jshintignore file in your project's directory tree, (also provided you run `jshint` from within your project's directory) then any directories or files specified will be skipped over. (behaves just like a `.gitignore` file)\n\n**Note:** Pattern matching uses minimatch, with the nocase [option](https://github.com/isaacs/minimatch). When there is no match, it performs a left side match (when no forward slashes present and path is a directory).\n\n## Installing dependencies for development\n\n ./configure\n\n## Build Commands\n\n jake -T\n\n## Project Guidelines\n\n* All tests are passing.\n* No (new) JSHint errors are introduced.\n", - "readmeFilename": "README.md", - "_id": "jshint@0.9.1", - "_from": "jshint@~0.9.1" -} diff --git a/node/node_modules/grunt/node_modules/jshint/packages/jshint/README.md b/node/node_modules/grunt/node_modules/jshint/packages/jshint/README.md deleted file mode 100755 index 3a27978a2..000000000 --- a/node/node_modules/grunt/node_modules/jshint/packages/jshint/README.md +++ /dev/null @@ -1,104 +0,0 @@ -JSHint, A Static Code Analysis Tool for JavaScript -================================================== - -JSHint is a community-driven tool to detect errors and potential problems in -JavaScript code and to enforce your team's coding conventions. - -**IMPORTANT**: - - * This README is for people who are thinking about contributing to JSHint. For general usage - please refer to [our website](http://jshint.com/). - * If you want to report a bug about the website, please go to the - [jshint/site](https://github.com/jshint/site/) repository. - * If you want to report a bug or contribute to our NPM package, please go to the - [jshint/node-jshint](https://github.com/jshint/node-jshint/) repository. - -Reporting a bug ---------------- - -To report a bug simply create a [new GitHub Issue](https://github.com/jshint/jshint/issues/new) and -describe your problem or suggestion. We welcome all kind of feedback regarding JSHint including but -not limited to: - - * When JSHint doesn't work as expected - * When JSHint complains about valid JavaScript code that works in all browsers - * When you simply want a new option or feature - -Please, before reporting a bug look around to see if there are any open or closed tickets that -cover your issue. And remember the wisdom: pull request > bug report > tweet. - -Submitting patches ------------------- - -The best way to make sure your issue is addressed is to submit a patch. GitHub provides a very -nice interface--pull requests--for that but we accept patches through all mediums: email, issue -comment, tweet with a link to a snippet, etc. - -Before submitting a patch make sure that you comply to our style. We don't have specific style -guide so just look around the code you are changing. - -Also, make sure that you write tests for new features and make sure that all tests pass before -submitting a patch. Patches that break the build will be rejected. - -**FEATURE FREEZE**: Please note that we currently have a feature freeze on new environments and -styling options. The only patches we accept at this time are for bug fixes. - -Tests ------ - -To run tests you will need to install [node.js](http://nodejs.org/) and -expresso. You can install the latter with npm: - - npm install expresso - -After that, running the unit tests is as easy as: - - expresso tests/unit/*.js - -Attribution ------------ - -Core Team members: - - * [Anton Kovalyov](http://anton.kovalyov.net/) ([@valueof](http://twitter.com/valueof)) - * [Wolfgang Kluge](http://klugesoftware.de/) ([blog](http://gehirnwindung.de/)) - * [Josh Perez](http://www.goatslacker.com/) ([@goatslacker](http://twitter.com/goatslacker)) - -Maintainer: Anton Kovalyov - -License -------- - -JSHint is licensed under the same slightly modified MIT license that JSLint is. -It stops evil-doers everywhere. - -JSHint is a derivative work of JSLint: - -Copyright (c) 2002 Douglas Crockford (www.JSLint.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 shall be used for Good, not Evil. - -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. - -JSHint was forked from the 2010-12-16 edition of JSLint. - -Thank you! ----------- - -We really appreciate all kind of feedback and contributions. Thanks for using and supporting JSHint! diff --git a/node/node_modules/grunt/node_modules/jshint/packages/jshint/jshint.js b/node/node_modules/grunt/node_modules/jshint/packages/jshint/jshint.js deleted file mode 100644 index 53724f5c0..000000000 --- a/node/node_modules/grunt/node_modules/jshint/packages/jshint/jshint.js +++ /dev/null @@ -1,4832 +0,0 @@ -/*! - * JSHint, by JSHint Community. - * - * Licensed under the same slightly modified MIT license that JSLint is. - * It stops evil-doers everywhere. - * - * JSHint is a derivative work of JSLint: - * - * Copyright (c) 2002 Douglas Crockford (www.JSLint.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 shall be used for Good, not Evil. - * - * 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. - * - * JSHint was forked from the 2010-12-16 edition of JSLint. - * - */ - -/* - JSHINT is a global function. It takes two parameters. - - var myResult = JSHINT(source, option); - - The first parameter is either a string or an array of strings. If it is a - string, it will be split on '\n' or '\r'. If it is an array of strings, it - is assumed that each string represents one line. The source can be a - JavaScript text or a JSON text. - - The second parameter is an optional object of options which control the - operation of JSHINT. Most of the options are booleans: They are all - optional and have a default value of false. One of the options, predef, - can be an array of names, which will be used to declare global variables, - or an object whose keys are used as global names, with a boolean value - that determines if they are assignable. - - If it checks out, JSHINT returns true. Otherwise, it returns false. - - If false, you can inspect JSHINT.errors to find out the problems. - JSHINT.errors is an array of objects containing these members: - - { - line : The line (relative to 1) at which the lint was found - character : The character (relative to 1) at which the lint was found - reason : The problem - evidence : The text line in which the problem occurred - raw : The raw message before the details were inserted - a : The first detail - b : The second detail - c : The third detail - d : The fourth detail - } - - If a fatal error was found, a null will be the last element of the - JSHINT.errors array. - - You can request a data structure which contains JSHint's results. - - var myData = JSHINT.data(); - - It returns a structure with this form: - - { - errors: [ - { - line: NUMBER, - character: NUMBER, - reason: STRING, - evidence: STRING - } - ], - functions: [ - name: STRING, - line: NUMBER, - character: NUMBER, - last: NUMBER, - lastcharacter: NUMBER, - param: [ - STRING - ], - closure: [ - STRING - ], - var: [ - STRING - ], - exception: [ - STRING - ], - outer: [ - STRING - ], - unused: [ - STRING - ], - global: [ - STRING - ], - label: [ - STRING - ] - ], - globals: [ - STRING - ], - member: { - STRING: NUMBER - }, - unused: [ - { - name: STRING, - line: NUMBER - } - ], - implieds: [ - { - name: STRING, - line: NUMBER - } - ], - urls: [ - STRING - ], - json: BOOLEAN - } - - Empty arrays will not be included. - -*/ - -/*jshint - evil: true, nomen: false, onevar: false, regexp: false, strict: true, boss: true, - undef: true, maxlen: 100, indent: 4, quotmark: double, unused: true -*/ - -/*members "\b", "\t", "\n", "\f", "\r", "!=", "!==", "\"", "%", "(begin)", - "(breakage)", "(character)", "(context)", "(error)", "(explicitNewcap)", "(global)", - "(identifier)", "(last)", "(lastcharacter)", "(line)", "(loopage)", "(metrics)", - "(name)", "(onevar)", "(params)", "(scope)", "(statement)", "(verb)", "(tokens)", "(catch)", - "*", "+", "++", "-", "--", "\/", "<", "<=", "==", - "===", ">", ">=", $, $$, $A, $F, $H, $R, $break, $continue, $w, Abstract, Ajax, - __filename, __dirname, ActiveXObject, Array, ArrayBuffer, ArrayBufferView, Audio, - Autocompleter, Asset, Boolean, Builder, Buffer, Browser, Blob, COM, CScript, Canvas, - CustomAnimation, Class, Control, ComplexityCount, Chain, Color, Cookie, Core, DataView, Date, - Debug, Draggable, Draggables, Droppables, Document, DomReady, DOMEvent, DOMReady, DOMParser, - Drag, E, Enumerator, Enumerable, Element, Elements, Error, Effect, EvalError, Event, - Events, FadeAnimation, Field, Flash, Float32Array, Float64Array, Form, - FormField, Frame, FormData, Function, Fx, GetObject, Group, Hash, HotKey, - HTMLElement, HTMLAnchorElement, HTMLBaseElement, HTMLBlockquoteElement, - HTMLBodyElement, HTMLBRElement, HTMLButtonElement, HTMLCanvasElement, HTMLDirectoryElement, - HTMLDivElement, HTMLDListElement, HTMLFieldSetElement, - HTMLFontElement, HTMLFormElement, HTMLFrameElement, HTMLFrameSetElement, - HTMLHeadElement, HTMLHeadingElement, HTMLHRElement, HTMLHtmlElement, - HTMLIFrameElement, HTMLImageElement, HTMLInputElement, HTMLIsIndexElement, - HTMLLabelElement, HTMLLayerElement, HTMLLegendElement, HTMLLIElement, - HTMLLinkElement, HTMLMapElement, HTMLMenuElement, HTMLMetaElement, - HTMLModElement, HTMLObjectElement, HTMLOListElement, HTMLOptGroupElement, - HTMLOptionElement, HTMLParagraphElement, HTMLParamElement, HTMLPreElement, - HTMLQuoteElement, HTMLScriptElement, HTMLSelectElement, HTMLStyleElement, - HtmlTable, HTMLTableCaptionElement, HTMLTableCellElement, HTMLTableColElement, - HTMLTableElement, HTMLTableRowElement, HTMLTableSectionElement, - HTMLTextAreaElement, HTMLTitleElement, HTMLUListElement, HTMLVideoElement, - Iframe, IframeShim, Image, importScripts, Int16Array, Int32Array, Int8Array, - Insertion, InputValidator, JSON, Keyboard, Locale, LN10, LN2, LOG10E, LOG2E, - MAX_VALUE, MIN_VALUE, Map, Mask, Math, MenuItem, MessageChannel, MessageEvent, MessagePort, - MoveAnimation, MooTools, MutationObserver, NaN, Native, NEGATIVE_INFINITY, Node, NodeFilter, - Number, Object, ObjectRange, - Option, Options, OverText, PI, POSITIVE_INFINITY, PeriodicalExecuter, Point, Position, Prototype, - RangeError, Rectangle, ReferenceError, RegExp, ResizeAnimation, Request, RotateAnimation, Set, - SQRT1_2, SQRT2, ScrollBar, ScriptEngine, ScriptEngineBuildVersion, - ScriptEngineMajorVersion, ScriptEngineMinorVersion, Scriptaculous, Scroller, - Slick, Slider, Selector, SharedWorker, String, Style, SyntaxError, Sortable, Sortables, - SortableObserver, Sound, Spinner, System, Swiff, Text, TextArea, Template, - Timer, Tips, Type, TypeError, Toggle, Try, "use strict", unescape, URI, URIError, URL, - VBArray, WeakMap, WSH, WScript, XDomainRequest, Web, Window, XMLDOM, XMLHttpRequest, XMLSerializer, - XPathEvaluator, XPathException, XPathExpression, XPathNamespace, XPathNSResolver, XPathResult, - "\\", a, abs, addEventListener, address, alert, apply, applicationCache, arguments, arity, - asi, atob, b, basic, basicToken, bitwise, blacklist, block, blur, boolOptions, boss, - browser, btoa, c, call, callee, caller, camelcase, cases, charAt, charCodeAt, character, - clearInterval, clearTimeout, close, closed, closure, comment, complexityCount, condition, - confirm, console, constructor, content, couch, create, css, curly, d, data, datalist, dd, debug, - decodeURI, decodeURIComponent, defaultStatus, defineClass, deserialize, devel, document, - dojo, dijit, dojox, define, else, emit, encodeURI, encodeURIComponent, elem, - eqeq, eqeqeq, eqnull, errors, es5, escape, esnext, eval, event, evidence, evil, - ex, exception, exec, exps, expr, exports, FileReader, first, floor, focus, forEach, - forin, fragment, frames, from, fromCharCode, fud, funcscope, funct, function, functions, - g, gc, getComputedStyle, getRow, getter, getterToken, GLOBAL, global, globals, globalstrict, - hasOwnProperty, help, history, i, id, identifier, immed, implieds, importPackage, include, - indent, indexOf, init, ins, internals, instanceOf, isAlpha, isApplicationRunning, isArray, - isDigit, isFinite, isNaN, iterator, java, join, jshint, - JSHINT, json, jquery, jQuery, keys, label, labelled, last, lastcharacter, lastsemic, laxbreak, - laxcomma, latedef, lbp, led, left, length, line, load, loadClass, localStorage, location, - log, loopfunc, m, match, max, maxcomplexity, maxdepth, maxerr, maxlen, maxstatements, maxparams, - member, message, meta, module, moveBy, moveTo, mootools, multistr, name, navigator, new, newcap, - nestedBlockDepth, noarg, node, noempty, nomen, nonew, nonstandard, nud, onbeforeunload, onblur, - onerror, onevar, onecase, onfocus, onload, onresize, onunload, open, openDatabase, openURL, - opener, opera, options, outer, param, parent, parseFloat, parseInt, passfail, plusplus, - postMessage, pop, predef, print, process, prompt, proto, prototype, prototypejs, provides, push, - quit, quotmark, range, raw, reach, reason, regexp, readFile, readUrl, regexdash, - removeEventListener, replace, report, require, reserved, resizeBy, resizeTo, resolvePath, - resumeUpdates, respond, rhino, right, runCommand, scroll, scope, screen, scripturl, scrollBy, - scrollTo, scrollbar, search, seal, self, send, serialize, sessionStorage, setInterval, setTimeout, - setter, setterToken, shift, slice, smarttabs, sort, spawn, split, statement, statementCount, stack, - status, start, strict, sub, substr, supernew, shadow, supplant, sum, sync, test, toLowerCase, - toString, toUpperCase, toint32, token, tokens, top, trailing, type, typeOf, Uint16Array, - Uint32Array, Uint8Array, undef, undefs, unused, urls, validthis, value, valueOf, var, vars, - version, verifyMaxParametersPerFunction, verifyMaxStatementsPerFunction, - verifyMaxComplexityPerFunction, verifyMaxNestedBlockDepthPerFunction, WebSocket, withstmt, white, - window, windows, Worker, worker, wsh, yui, YUI, Y, YUI_config*/ - -/*global exports: false */ - -// We build the application inside a function so that we produce only a single -// global variable. That function will be invoked immediately, and its return -// value is the JSHINT function itself. - -var JSHINT = (function () { - "use strict"; - - var anonname, // The guessed name for anonymous functions. - -// These are operators that should not be used with the ! operator. - - bang = { - "<" : true, - "<=" : true, - "==" : true, - "===": true, - "!==": true, - "!=" : true, - ">" : true, - ">=" : true, - "+" : true, - "-" : true, - "*" : true, - "/" : true, - "%" : true - }, - - // These are the JSHint boolean options. - boolOptions = { - asi : true, // if automatic semicolon insertion should be tolerated - bitwise : true, // if bitwise operators should not be allowed - boss : true, // if advanced usage of assignments should be allowed - browser : true, // if the standard browser globals should be predefined - camelcase : true, // if identifiers should be required in camel case - couch : true, // if CouchDB globals should be predefined - curly : true, // if curly braces around all blocks should be required - debug : true, // if debugger statements should be allowed - devel : true, // if logging globals should be predefined (console, - // alert, etc.) - dojo : true, // if Dojo Toolkit globals should be predefined - eqeqeq : true, // if === should be required - eqnull : true, // if == null comparisons should be tolerated - es5 : true, // if ES5 syntax should be allowed - esnext : true, // if es.next specific syntax should be allowed - evil : true, // if eval should be allowed - expr : true, // if ExpressionStatement should be allowed as Programs - forin : true, // if for in statements must filter - funcscope : true, // if only function scope should be used for scope tests - globalstrict: true, // if global "use strict"; should be allowed (also - // enables 'strict') - immed : true, // if immediate invocations must be wrapped in parens - iterator : true, // if the `__iterator__` property should be allowed - jquery : true, // if jQuery globals should be predefined - lastsemic : true, // if semicolons may be ommitted for the trailing - // statements inside of a one-line blocks. - latedef : true, // if the use before definition should not be tolerated - laxbreak : true, // if line breaks should not be checked - laxcomma : true, // if line breaks should not be checked around commas - loopfunc : true, // if functions should be allowed to be defined within - // loops - mootools : true, // if MooTools globals should be predefined - multistr : true, // allow multiline strings - newcap : true, // if constructor names must be capitalized - noarg : true, // if arguments.caller and arguments.callee should be - // disallowed - node : true, // if the Node.js environment globals should be - // predefined - noempty : true, // if empty blocks should be disallowed - nonew : true, // if using `new` for side-effects should be disallowed - nonstandard : true, // if non-standard (but widely adopted) globals should - // be predefined - nomen : true, // if names should be checked - onevar : true, // if only one var statement per function should be - // allowed - onecase : true, // if one case switch statements should be allowed - passfail : true, // if the scan should stop on first error - plusplus : true, // if increment/decrement should not be allowed - proto : true, // if the `__proto__` property should be allowed - prototypejs : true, // if Prototype and Scriptaculous globals should be - // predefined - regexdash : true, // if unescaped first/last dash (-) inside brackets - // should be tolerated - regexp : true, // if the . should not be allowed in regexp literals - rhino : true, // if the Rhino environment globals should be predefined - undef : true, // if variables should be declared before used - unused : true, // if variables should be always used - scripturl : true, // if script-targeted URLs should be tolerated - shadow : true, // if variable shadowing should be tolerated - smarttabs : true, // if smarttabs should be tolerated - // (http://www.emacswiki.org/emacs/SmartTabs) - strict : true, // require the "use strict"; pragma - sub : true, // if all forms of subscript notation are tolerated - supernew : true, // if `new function () { ... };` and `new Object;` - // should be tolerated - trailing : true, // if trailing whitespace rules apply - validthis : true, // if 'this' inside a non-constructor function is valid. - // This is a function scoped option only. - withstmt : true, // if with statements should be allowed - white : true, // if strict whitespace rules apply - worker : true, // if Web Worker script symbols should be allowed - wsh : true, // if the Windows Scripting Host environment globals - // should be predefined - yui : true // YUI variables should be predefined - }, - - // These are the JSHint options that can take any value - // (we use this object to detect invalid options) - valOptions = { - maxlen : false, - indent : false, - maxerr : false, - predef : false, - quotmark : false, //'single'|'double'|true - scope : false, - maxstatements: false, // {int} max statements per function - maxdepth : false, // {int} max nested block depth per function - maxparams : false, // {int} max params per function - maxcomplexity: false // {int} max cyclomatic complexity per function - }, - - // These are JSHint boolean options which are shared with JSLint - // where the definition in JSHint is opposite JSLint - invertedOptions = { - bitwise : true, - forin : true, - newcap : true, - nomen : true, - plusplus : true, - regexp : true, - undef : true, - white : true, - - // Inverted and renamed, use JSHint name here - eqeqeq : true, - onevar : true - }, - - // These are JSHint boolean options which are shared with JSLint - // where the name has been changed but the effect is unchanged - renamedOptions = { - eqeq : "eqeqeq", - vars : "onevar", - windows : "wsh" - }, - - - // browser contains a set of global names which are commonly provided by a - // web browser environment. - browser = { - ArrayBuffer : false, - ArrayBufferView : false, - Audio : false, - Blob : false, - addEventListener : false, - applicationCache : false, - atob : false, - blur : false, - btoa : false, - clearInterval : false, - clearTimeout : false, - close : false, - closed : false, - DataView : false, - DOMParser : false, - defaultStatus : false, - document : false, - event : false, - FileReader : false, - Float32Array : false, - Float64Array : false, - FormData : false, - focus : false, - frames : false, - getComputedStyle : false, - HTMLElement : false, - HTMLAnchorElement : false, - HTMLBaseElement : false, - HTMLBlockquoteElement : false, - HTMLBodyElement : false, - HTMLBRElement : false, - HTMLButtonElement : false, - HTMLCanvasElement : false, - HTMLDirectoryElement : false, - HTMLDivElement : false, - HTMLDListElement : false, - HTMLFieldSetElement : false, - HTMLFontElement : false, - HTMLFormElement : false, - HTMLFrameElement : false, - HTMLFrameSetElement : false, - HTMLHeadElement : false, - HTMLHeadingElement : false, - HTMLHRElement : false, - HTMLHtmlElement : false, - HTMLIFrameElement : false, - HTMLImageElement : false, - HTMLInputElement : false, - HTMLIsIndexElement : false, - HTMLLabelElement : false, - HTMLLayerElement : false, - HTMLLegendElement : false, - HTMLLIElement : false, - HTMLLinkElement : false, - HTMLMapElement : false, - HTMLMenuElement : false, - HTMLMetaElement : false, - HTMLModElement : false, - HTMLObjectElement : false, - HTMLOListElement : false, - HTMLOptGroupElement : false, - HTMLOptionElement : false, - HTMLParagraphElement : false, - HTMLParamElement : false, - HTMLPreElement : false, - HTMLQuoteElement : false, - HTMLScriptElement : false, - HTMLSelectElement : false, - HTMLStyleElement : false, - HTMLTableCaptionElement : false, - HTMLTableCellElement : false, - HTMLTableColElement : false, - HTMLTableElement : false, - HTMLTableRowElement : false, - HTMLTableSectionElement : false, - HTMLTextAreaElement : false, - HTMLTitleElement : false, - HTMLUListElement : false, - HTMLVideoElement : false, - history : false, - Int16Array : false, - Int32Array : false, - Int8Array : false, - Image : false, - length : false, - localStorage : false, - location : false, - MessageChannel : false, - MessageEvent : false, - MessagePort : false, - moveBy : false, - moveTo : false, - MutationObserver : false, - name : false, - Node : false, - NodeFilter : false, - navigator : false, - onbeforeunload : true, - onblur : true, - onerror : true, - onfocus : true, - onload : true, - onresize : true, - onunload : true, - open : false, - openDatabase : false, - opener : false, - Option : false, - parent : false, - print : false, - removeEventListener : false, - resizeBy : false, - resizeTo : false, - screen : false, - scroll : false, - scrollBy : false, - scrollTo : false, - sessionStorage : false, - setInterval : false, - setTimeout : false, - SharedWorker : false, - status : false, - top : false, - Uint16Array : false, - Uint32Array : false, - Uint8Array : false, - WebSocket : false, - window : false, - Worker : false, - XMLHttpRequest : false, - XMLSerializer : false, - XPathEvaluator : false, - XPathException : false, - XPathExpression : false, - XPathNamespace : false, - XPathNSResolver : false, - XPathResult : false - }, - - couch = { - "require" : false, - respond : false, - getRow : false, - emit : false, - send : false, - start : false, - sum : false, - log : false, - exports : false, - module : false, - provides : false - }, - - declared, // Globals that were declared using /*global ... */ syntax. - - devel = { - alert : false, - confirm : false, - console : false, - Debug : false, - opera : false, - prompt : false - }, - - dojo = { - dojo : false, - dijit : false, - dojox : false, - define : false, - "require" : false - }, - - funct, // The current function - - functionicity = [ - "closure", "exception", "global", "label", - "outer", "unused", "var" - ], - - functions, // All of the functions - - global, // The global scope - implied, // Implied globals - inblock, - indent, - jsonmode, - - jquery = { - "$" : false, - jQuery : false - }, - - lines, - lookahead, - member, - membersOnly, - - mootools = { - "$" : false, - "$$" : false, - Asset : false, - Browser : false, - Chain : false, - Class : false, - Color : false, - Cookie : false, - Core : false, - Document : false, - DomReady : false, - DOMEvent : false, - DOMReady : false, - Drag : false, - Element : false, - Elements : false, - Event : false, - Events : false, - Fx : false, - Group : false, - Hash : false, - HtmlTable : false, - Iframe : false, - IframeShim : false, - InputValidator : false, - instanceOf : false, - Keyboard : false, - Locale : false, - Mask : false, - MooTools : false, - Native : false, - Options : false, - OverText : false, - Request : false, - Scroller : false, - Slick : false, - Slider : false, - Sortables : false, - Spinner : false, - Swiff : false, - Tips : false, - Type : false, - typeOf : false, - URI : false, - Window : false - }, - - nexttoken, - - node = { - __filename : false, - __dirname : false, - Buffer : false, - console : false, - exports : true, // In Node it is ok to exports = module.exports = foo(); - GLOBAL : false, - global : false, - module : false, - process : false, - require : false, - setTimeout : false, - clearTimeout : false, - setInterval : false, - clearInterval : false - }, - - noreach, - option, - predefined, // Global variables defined by option - prereg, - prevtoken, - - prototypejs = { - "$" : false, - "$$" : false, - "$A" : false, - "$F" : false, - "$H" : false, - "$R" : false, - "$break" : false, - "$continue" : false, - "$w" : false, - Abstract : false, - Ajax : false, - Class : false, - Enumerable : false, - Element : false, - Event : false, - Field : false, - Form : false, - Hash : false, - Insertion : false, - ObjectRange : false, - PeriodicalExecuter: false, - Position : false, - Prototype : false, - Selector : false, - Template : false, - Toggle : false, - Try : false, - Autocompleter : false, - Builder : false, - Control : false, - Draggable : false, - Draggables : false, - Droppables : false, - Effect : false, - Sortable : false, - SortableObserver : false, - Sound : false, - Scriptaculous : false - }, - - quotmark, - - rhino = { - defineClass : false, - deserialize : false, - gc : false, - help : false, - importPackage: false, - "java" : false, - load : false, - loadClass : false, - print : false, - quit : false, - readFile : false, - readUrl : false, - runCommand : false, - seal : false, - serialize : false, - spawn : false, - sync : false, - toint32 : false, - version : false - }, - - scope, // The current scope - stack, - - // standard contains the global names that are provided by the - // ECMAScript standard. - standard = { - Array : false, - Boolean : false, - Date : false, - decodeURI : false, - decodeURIComponent : false, - encodeURI : false, - encodeURIComponent : false, - Error : false, - "eval" : false, - EvalError : false, - Function : false, - hasOwnProperty : false, - isFinite : false, - isNaN : false, - JSON : false, - Map : false, - Math : false, - NaN : false, - Number : false, - Object : false, - parseInt : false, - parseFloat : false, - RangeError : false, - ReferenceError : false, - RegExp : false, - Set : false, - String : false, - SyntaxError : false, - TypeError : false, - URIError : false, - WeakMap : false - }, - - // widely adopted global names that are not part of ECMAScript standard - nonstandard = { - escape : false, - unescape : false - }, - - directive, - syntax = {}, - tab, - token, - unuseds, - urls, - useESNextSyntax, - warnings, - - worker = { - importScripts : true, - postMessage : true, - self : true - }, - - wsh = { - ActiveXObject : true, - Enumerator : true, - GetObject : true, - ScriptEngine : true, - ScriptEngineBuildVersion : true, - ScriptEngineMajorVersion : true, - ScriptEngineMinorVersion : true, - VBArray : true, - WSH : true, - WScript : true, - XDomainRequest : true - }, - - yui = { - YUI : false, - Y : false, - YUI_config : false - }; - // Regular expressions. Some of these are stupidly long. - var ax, cx, tx, nx, nxg, lx, ix, jx, ft; - (function () { - /*jshint maxlen:300 */ - - // unsafe comment or string - ax = /@cc|<\/?|script|\]\s*\]|<\s*!|</i; - - // unsafe characters that are silently deleted by one or more browsers - cx = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; - - // token - tx = /^\s*([(){}\[.,:;'"~\?\]#@]|==?=?|\/=(?!(\S*\/[gim]?))|\/(\*(jshint|jslint|members?|global)?|\/)?|\*[\/=]?|\+(?:=|\++)?|-(?:=|-+)?|%=?|&[&=]?|\|[|=]?|>>?>?=?|<([\/=!]|\!(\[|--)?|<=?)?|\^=?|\!=?=?|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+([xX][0-9a-fA-F]+|\.[0-9]*)?([eE][+\-]?[0-9]+)?)/; - - // characters in strings that need escapement - nx = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; - nxg = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; - - // star slash - lx = /\*\//; - - // identifier - ix = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/; - - // javascript url - jx = /^(?:javascript|jscript|ecmascript|vbscript|mocha|livescript)\s*:/i; - - // catches /* falls through */ comments - ft = /^\s*\/\*\s*falls\sthrough\s*\*\/\s*$/; - }()); - - function F() {} // Used by Object.create - - function is_own(object, name) { - // The object.hasOwnProperty method fails when the property under consideration - // is named 'hasOwnProperty'. So we have to use this more convoluted form. - return Object.prototype.hasOwnProperty.call(object, name); - } - - function checkOption(name, t) { - if (valOptions[name] === undefined && boolOptions[name] === undefined) { - warning("Bad option: '" + name + "'.", t); - } - } - - function isString(obj) { - return Object.prototype.toString.call(obj) === "[object String]"; - } - - // Provide critical ES5 functions to ES3. - - if (typeof Array.isArray !== "function") { - Array.isArray = function (o) { - return Object.prototype.toString.apply(o) === "[object Array]"; - }; - } - - if (!Array.prototype.forEach) { - Array.prototype.forEach = function (fn, scope) { - var len = this.length; - - for (var i = 0; i < len; i++) { - fn.call(scope || this, this[i], i, this); - } - }; - } - - if (!Array.prototype.indexOf) { - Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) { - if (this === null || this === undefined) { - throw new TypeError(); - } - - var t = new Object(this); - var len = t.length >>> 0; - - if (len === 0) { - return -1; - } - - var n = 0; - if (arguments.length > 0) { - n = Number(arguments[1]); - if (n != n) { // shortcut for verifying if it's NaN - n = 0; - } else if (n !== 0 && n != Infinity && n != -Infinity) { - n = (n > 0 || -1) * Math.floor(Math.abs(n)); - } - } - - if (n >= len) { - return -1; - } - - var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); - for (; k < len; k++) { - if (k in t && t[k] === searchElement) { - return k; - } - } - - return -1; - }; - } - - if (typeof Object.create !== "function") { - Object.create = function (o) { - F.prototype = o; - return new F(); - }; - } - - if (typeof Object.keys !== "function") { - Object.keys = function (o) { - var a = [], k; - for (k in o) { - if (is_own(o, k)) { - a.push(k); - } - } - return a; - }; - } - - // Non standard methods - - function isAlpha(str) { - return (str >= "a" && str <= "z\uffff") || - (str >= "A" && str <= "Z\uffff"); - } - - function isDigit(str) { - return (str >= "0" && str <= "9"); - } - - function isIdentifier(token, value) { - if (!token) - return false; - - if (!token.identifier || token.value !== value) - return false; - - return true; - } - - function supplant(str, data) { - return str.replace(/\{([^{}]*)\}/g, function (a, b) { - var r = data[b]; - return typeof r === "string" || typeof r === "number" ? r : a; - }); - } - - function combine(t, o) { - var n; - for (n in o) { - if (is_own(o, n) && !is_own(JSHINT.blacklist, n)) { - t[n] = o[n]; - } - } - } - - function updatePredefined() { - Object.keys(JSHINT.blacklist).forEach(function (key) { - delete predefined[key]; - }); - } - - function assume() { - if (option.couch) { - combine(predefined, couch); - } - - if (option.rhino) { - combine(predefined, rhino); - } - - if (option.prototypejs) { - combine(predefined, prototypejs); - } - - if (option.node) { - combine(predefined, node); - option.globalstrict = true; - } - - if (option.devel) { - combine(predefined, devel); - } - - if (option.dojo) { - combine(predefined, dojo); - } - - if (option.browser) { - combine(predefined, browser); - } - - if (option.nonstandard) { - combine(predefined, nonstandard); - } - - if (option.jquery) { - combine(predefined, jquery); - } - - if (option.mootools) { - combine(predefined, mootools); - } - - if (option.worker) { - combine(predefined, worker); - } - - if (option.wsh) { - combine(predefined, wsh); - } - - if (option.esnext) { - useESNextSyntax(); - } - - if (option.globalstrict && option.strict !== false) { - option.strict = true; - } - - if (option.yui) { - combine(predefined, yui); - } - } - - - // Produce an error warning. - function quit(message, line, chr) { - var percentage = Math.floor((line / lines.length) * 100); - - throw { - name: "JSHintError", - line: line, - character: chr, - message: message + " (" + percentage + "% scanned).", - raw: message - }; - } - - function isundef(scope, m, t, a) { - return JSHINT.undefs.push([scope, m, t, a]); - } - - function warning(m, t, a, b, c, d) { - var ch, l, w; - t = t || nexttoken; - if (t.id === "(end)") { // `~ - t = token; - } - l = t.line || 0; - ch = t.from || 0; - w = { - id: "(error)", - raw: m, - evidence: lines[l - 1] || "", - line: l, - character: ch, - scope: JSHINT.scope, - a: a, - b: b, - c: c, - d: d - }; - w.reason = supplant(m, w); - JSHINT.errors.push(w); - if (option.passfail) { - quit("Stopping. ", l, ch); - } - warnings += 1; - if (warnings >= option.maxerr) { - quit("Too many errors.", l, ch); - } - return w; - } - - function warningAt(m, l, ch, a, b, c, d) { - return warning(m, { - line: l, - from: ch - }, a, b, c, d); - } - - function error(m, t, a, b, c, d) { - warning(m, t, a, b, c, d); - } - - function errorAt(m, l, ch, a, b, c, d) { - return error(m, { - line: l, - from: ch - }, a, b, c, d); - } - - // Tracking of "internal" scripts, like eval containing a static string - function addInternalSrc(elem, src) { - var i; - i = { - id: "(internal)", - elem: elem, - value: src - }; - JSHINT.internals.push(i); - return i; - } - - -// lexical analysis and token construction - - var lex = (function lex() { - var character, from, line, s; - -// Private lex methods - - function nextLine() { - var at, - match, - tw; // trailing whitespace check - - if (line >= lines.length) - return false; - - character = 1; - s = lines[line]; - line += 1; - - // If smarttabs option is used check for spaces followed by tabs only. - // Otherwise check for any occurence of mixed tabs and spaces. - // Tabs and one space followed by block comment is allowed. - if (option.smarttabs) { - // negative look-behind for "//" - match = s.match(/(\/\/)? \t/); - at = match && !match[1] ? 0 : -1; - } else { - at = s.search(/ \t|\t [^\*]/); - } - - if (at >= 0) - warningAt("Mixed spaces and tabs.", line, at + 1); - - s = s.replace(/\t/g, tab); - at = s.search(cx); - - if (at >= 0) - warningAt("Unsafe character.", line, at); - - if (option.maxlen && option.maxlen < s.length) - warningAt("Line too long.", line, s.length); - - // Check for trailing whitespaces - tw = option.trailing && s.match(/^(.*?)\s+$/); - if (tw && !/^\s+$/.test(s)) { - warningAt("Trailing whitespace.", line, tw[1].length + 1); - } - return true; - } - -// Produce a token object. The token inherits from a syntax symbol. - - function it(type, value) { - var i, t; - - function checkName(name) { - if (!option.proto && name === "__proto__") { - warningAt("The '{a}' property is deprecated.", line, from, name); - return; - } - - if (!option.iterator && name === "__iterator__") { - warningAt("'{a}' is only available in JavaScript 1.7.", line, from, name); - return; - } - - // Check for dangling underscores unless we're in Node - // environment and this identifier represents built-in - // Node globals with underscores. - - var hasDangling = /^(_+.*|.*_+)$/.test(name); - - if (option.nomen && hasDangling && name !== "_") { - if (option.node && token.id !== "." && /^(__dirname|__filename)$/.test(name)) - return; - - warningAt("Unexpected {a} in '{b}'.", line, from, "dangling '_'", name); - return; - } - - // Check for non-camelcase names. Names like MY_VAR and - // _myVar are okay though. - - if (option.camelcase) { - if (name.replace(/^_+/, "").indexOf("_") > -1 && !name.match(/^[A-Z0-9_]*$/)) { - warningAt("Identifier '{a}' is not in camel case.", line, from, value); - } - } - } - - if (type === "(color)" || type === "(range)") { - t = {type: type}; - } else if (type === "(punctuator)" || - (type === "(identifier)" && is_own(syntax, value))) { - t = syntax[value] || syntax["(error)"]; - } else { - t = syntax[type]; - } - - t = Object.create(t); - - if (type === "(string)" || type === "(range)") { - if (!option.scripturl && jx.test(value)) { - warningAt("Script URL.", line, from); - } - } - - if (type === "(identifier)") { - t.identifier = true; - checkName(value); - } - - t.value = value; - t.line = line; - t.character = character; - t.from = from; - i = t.id; - if (i !== "(endline)") { - prereg = i && - (("(,=:[!&|?{};".indexOf(i.charAt(i.length - 1)) >= 0) || - i === "return" || - i === "case"); - } - return t; - } - - // Public lex methods - return { - init: function (source) { - if (typeof source === "string") { - lines = source - .replace(/\r\n/g, "\n") - .replace(/\r/g, "\n") - .split("\n"); - } else { - lines = source; - } - - // If the first line is a shebang (#!), make it a blank and move on. - // Shebangs are used by Node scripts. - if (lines[0] && lines[0].substr(0, 2) === "#!") - lines[0] = ""; - - line = 0; - nextLine(); - from = 1; - }, - - range: function (begin, end) { - var c, value = ""; - from = character; - if (s.charAt(0) !== begin) { - errorAt("Expected '{a}' and instead saw '{b}'.", - line, character, begin, s.charAt(0)); - } - for (;;) { - s = s.slice(1); - character += 1; - c = s.charAt(0); - switch (c) { - case "": - errorAt("Missing '{a}'.", line, character, c); - break; - case end: - s = s.slice(1); - character += 1; - return it("(range)", value); - case "\\": - warningAt("Unexpected '{a}'.", line, character, c); - } - value += c; - } - - }, - - - // token -- this is called by advance to get the next token - token: function () { - var b, c, captures, d, depth, high, i, l, low, q, t, isLiteral, isInRange, n; - - function match(x) { - var r = x.exec(s), r1; - - if (r) { - l = r[0].length; - r1 = r[1]; - c = r1.charAt(0); - s = s.substr(l); - from = character + l - r1.length; - character += l; - return r1; - } - } - - function string(x) { - var c, j, r = "", allowNewLine = false; - - if (jsonmode && x !== "\"") { - warningAt("Strings must use doublequote.", - line, character); - } - - if (option.quotmark) { - if (option.quotmark === "single" && x !== "'") { - warningAt("Strings must use singlequote.", - line, character); - } else if (option.quotmark === "double" && x !== "\"") { - warningAt("Strings must use doublequote.", - line, character); - } else if (option.quotmark === true) { - quotmark = quotmark || x; - if (quotmark !== x) { - warningAt("Mixed double and single quotes.", - line, character); - } - } - } - - function esc(n) { - var i = parseInt(s.substr(j + 1, n), 16); - j += n; - if (i >= 32 && i <= 126 && - i !== 34 && i !== 92 && i !== 39) { - warningAt("Unnecessary escapement.", line, character); - } - character += n; - c = String.fromCharCode(i); - } - - j = 0; -unclosedString: for (;;) { - while (j >= s.length) { - j = 0; - - var cl = line, cf = from; - if (!nextLine()) { - errorAt("Unclosed string.", cl, cf); - break unclosedString; - } - - if (allowNewLine) { - allowNewLine = false; - } else { - warningAt("Unclosed string.", cl, cf); - } - } - - c = s.charAt(j); - if (c === x) { - character += 1; - s = s.substr(j + 1); - return it("(string)", r, x); - } - - if (c < " ") { - if (c === "\n" || c === "\r") { - break; - } - warningAt("Control character in string: {a}.", - line, character + j, s.slice(0, j)); - } else if (c === "\\") { - j += 1; - character += 1; - c = s.charAt(j); - n = s.charAt(j + 1); - switch (c) { - case "\\": - case "\"": - case "/": - break; - case "\'": - if (jsonmode) { - warningAt("Avoid \\'.", line, character); - } - break; - case "b": - c = "\b"; - break; - case "f": - c = "\f"; - break; - case "n": - c = "\n"; - break; - case "r": - c = "\r"; - break; - case "t": - c = "\t"; - break; - case "0": - c = "\0"; - // Octal literals fail in strict mode - // check if the number is between 00 and 07 - // where 'n' is the token next to 'c' - if (n >= 0 && n <= 7 && directive["use strict"]) { - warningAt( - "Octal literals are not allowed in strict mode.", - line, character); - } - break; - case "u": - esc(4); - break; - case "v": - if (jsonmode) { - warningAt("Avoid \\v.", line, character); - } - c = "\v"; - break; - case "x": - if (jsonmode) { - warningAt("Avoid \\x-.", line, character); - } - esc(2); - break; - case "": - // last character is escape character - // always allow new line if escaped, but show - // warning if option is not set - allowNewLine = true; - if (option.multistr) { - if (jsonmode) { - warningAt("Avoid EOL escapement.", line, character); - } - c = ""; - character -= 1; - break; - } - warningAt("Bad escapement of EOL. Use option multistr if needed.", - line, character); - break; - case "!": - if (s.charAt(j - 2) === "<") - break; - /*falls through*/ - default: - warningAt("Bad escapement.", line, character); - } - } - r += c; - character += 1; - j += 1; - } - } - - for (;;) { - if (!s) { - return it(nextLine() ? "(endline)" : "(end)", ""); - } - - t = match(tx); - - if (!t) { - t = ""; - c = ""; - while (s && s < "!") { - s = s.substr(1); - } - if (s) { - errorAt("Unexpected '{a}'.", line, character, s.substr(0, 1)); - s = ""; - } - } else { - - // identifier - - if (isAlpha(c) || c === "_" || c === "$") { - return it("(identifier)", t); - } - - // number - - if (isDigit(c)) { - if (!isFinite(Number(t))) { - warningAt("Bad number '{a}'.", - line, character, t); - } - if (isAlpha(s.substr(0, 1))) { - warningAt("Missing space after '{a}'.", - line, character, t); - } - if (c === "0") { - d = t.substr(1, 1); - if (isDigit(d)) { - if (token.id !== ".") { - warningAt("Don't use extra leading zeros '{a}'.", - line, character, t); - } - } else if (jsonmode && (d === "x" || d === "X")) { - warningAt("Avoid 0x-. '{a}'.", - line, character, t); - } - } - if (t.substr(t.length - 1) === ".") { - warningAt( -"A trailing decimal point can be confused with a dot '{a}'.", line, character, t); - } - return it("(number)", t); - } - switch (t) { - - // string - - case "\"": - case "'": - return string(t); - - // // comment - - case "//": - s = ""; - token.comment = true; - break; - - // /* comment - - case "/*": - for (;;) { - i = s.search(lx); - if (i >= 0) { - break; - } - if (!nextLine()) { - errorAt("Unclosed comment.", line, character); - } - } - s = s.substr(i + 2); - token.comment = true; - break; - - // /*members /*jshint /*global - - case "/*members": - case "/*member": - case "/*jshint": - case "/*jslint": - case "/*global": - case "*/": - return { - value: t, - type: "special", - line: line, - character: character, - from: from - }; - - case "": - break; - // / - case "/": - if (s.charAt(0) === "=") { - errorAt("A regular expression literal can be confused with '/='.", - line, from); - } - - if (prereg) { - depth = 0; - captures = 0; - l = 0; - for (;;) { - b = true; - c = s.charAt(l); - l += 1; - switch (c) { - case "": - errorAt("Unclosed regular expression.", line, from); - return quit("Stopping.", line, from); - case "/": - if (depth > 0) { - warningAt("{a} unterminated regular expression " + - "group(s).", line, from + l, depth); - } - c = s.substr(0, l - 1); - q = { - g: true, - i: true, - m: true - }; - while (q[s.charAt(l)] === true) { - q[s.charAt(l)] = false; - l += 1; - } - character += l; - s = s.substr(l); - q = s.charAt(0); - if (q === "/" || q === "*") { - errorAt("Confusing regular expression.", - line, from); - } - return it("(regexp)", c); - case "\\": - c = s.charAt(l); - if (c < " ") { - warningAt( -"Unexpected control character in regular expression.", line, from + l); - } else if (c === "<") { - warningAt( -"Unexpected escaped character '{a}' in regular expression.", line, from + l, c); - } - l += 1; - break; - case "(": - depth += 1; - b = false; - if (s.charAt(l) === "?") { - l += 1; - switch (s.charAt(l)) { - case ":": - case "=": - case "!": - l += 1; - break; - default: - warningAt( -"Expected '{a}' and instead saw '{b}'.", line, from + l, ":", s.charAt(l)); - } - } else { - captures += 1; - } - break; - case "|": - b = false; - break; - case ")": - if (depth === 0) { - warningAt("Unescaped '{a}'.", - line, from + l, ")"); - } else { - depth -= 1; - } - break; - case " ": - q = 1; - while (s.charAt(l) === " ") { - l += 1; - q += 1; - } - if (q > 1) { - warningAt( -"Spaces are hard to count. Use {{a}}.", line, from + l, q); - } - break; - case "[": - c = s.charAt(l); - if (c === "^") { - l += 1; - if (s.charAt(l) === "]") { - errorAt("Unescaped '{a}'.", - line, from + l, "^"); - } - } - if (c === "]") { - warningAt("Empty class.", line, - from + l - 1); - } - isLiteral = false; - isInRange = false; -klass: do { - c = s.charAt(l); - l += 1; - switch (c) { - case "[": - case "^": - warningAt("Unescaped '{a}'.", - line, from + l, c); - if (isInRange) { - isInRange = false; - } else { - isLiteral = true; - } - break; - case "-": - if (isLiteral && !isInRange) { - isLiteral = false; - isInRange = true; - } else if (isInRange) { - isInRange = false; - } else if (s.charAt(l) === "]") { - isInRange = true; - } else { - if (option.regexdash !== (l === 2 || (l === 3 && - s.charAt(1) === "^"))) { - warningAt("Unescaped '{a}'.", - line, from + l - 1, "-"); - } - isLiteral = true; - } - break; - case "]": - if (isInRange && !option.regexdash) { - warningAt("Unescaped '{a}'.", - line, from + l - 1, "-"); - } - break klass; - case "\\": - c = s.charAt(l); - if (c < " ") { - warningAt( -"Unexpected control character in regular expression.", line, from + l); - } else if (c === "<") { - warningAt( -"Unexpected escaped character '{a}' in regular expression.", line, from + l, c); - } - l += 1; - - // \w, \s and \d are never part of a character range - if (/[wsd]/i.test(c)) { - if (isInRange) { - warningAt("Unescaped '{a}'.", - line, from + l, "-"); - isInRange = false; - } - isLiteral = false; - } else if (isInRange) { - isInRange = false; - } else { - isLiteral = true; - } - break; - case "/": - warningAt("Unescaped '{a}'.", - line, from + l - 1, "/"); - - if (isInRange) { - isInRange = false; - } else { - isLiteral = true; - } - break; - case "<": - if (isInRange) { - isInRange = false; - } else { - isLiteral = true; - } - break; - default: - if (isInRange) { - isInRange = false; - } else { - isLiteral = true; - } - } - } while (c); - break; - case ".": - if (option.regexp) { - warningAt("Insecure '{a}'.", line, - from + l, c); - } - break; - case "]": - case "?": - case "{": - case "}": - case "+": - case "*": - warningAt("Unescaped '{a}'.", line, - from + l, c); - } - if (b) { - switch (s.charAt(l)) { - case "?": - case "+": - case "*": - l += 1; - if (s.charAt(l) === "?") { - l += 1; - } - break; - case "{": - l += 1; - c = s.charAt(l); - if (c < "0" || c > "9") { - warningAt( -"Expected a number and instead saw '{a}'.", line, from + l, c); - break; // No reason to continue checking numbers. - } - l += 1; - low = +c; - for (;;) { - c = s.charAt(l); - if (c < "0" || c > "9") { - break; - } - l += 1; - low = +c + (low * 10); - } - high = low; - if (c === ",") { - l += 1; - high = Infinity; - c = s.charAt(l); - if (c >= "0" && c <= "9") { - l += 1; - high = +c; - for (;;) { - c = s.charAt(l); - if (c < "0" || c > "9") { - break; - } - l += 1; - high = +c + (high * 10); - } - } - } - if (s.charAt(l) !== "}") { - warningAt( -"Expected '{a}' and instead saw '{b}'.", line, from + l, "}", c); - } else { - l += 1; - } - if (s.charAt(l) === "?") { - l += 1; - } - if (low > high) { - warningAt( -"'{a}' should not be greater than '{b}'.", line, from + l, low, high); - } - } - } - } - c = s.substr(0, l - 1); - character += l; - s = s.substr(l); - return it("(regexp)", c); - } - return it("(punctuator)", t); - - // punctuator - - case "#": - return it("(punctuator)", t); - default: - return it("(punctuator)", t); - } - } - } - } - }; - }()); - - - function addlabel(t, type, token) { - if (t === "hasOwnProperty") { - warning("'hasOwnProperty' is a really bad name."); - } - - // Define t in the current function in the current scope. - if (type === "exception") { - if (is_own(funct["(context)"], t)) { - if (funct[t] !== true && !option.node) { - warning("Value of '{a}' may be overwritten in IE.", nexttoken, t); - } - } - } - - if (is_own(funct, t) && !funct["(global)"]) { - if (funct[t] === true) { - if (option.latedef) - warning("'{a}' was used before it was defined.", nexttoken, t); - } else { - if (!option.shadow && type !== "exception") { - warning("'{a}' is already defined.", nexttoken, t); - } - } - } - - funct[t] = type; - - if (token) { - funct["(tokens)"][t] = token; - } - - if (funct["(global)"]) { - global[t] = funct; - if (is_own(implied, t)) { - if (option.latedef) - warning("'{a}' was used before it was defined.", nexttoken, t); - delete implied[t]; - } - } else { - scope[t] = funct; - } - } - - - function doOption() { - var nt = nexttoken; - var o = nt.value; - var quotmarkValue = option.quotmark; - var predef = {}; - var b, obj, filter, t, tn, v, minus; - - switch (o) { - case "*/": - error("Unbegun comment."); - break; - case "/*members": - case "/*member": - o = "/*members"; - if (!membersOnly) { - membersOnly = {}; - } - obj = membersOnly; - option.quotmark = false; - break; - case "/*jshint": - case "/*jslint": - obj = option; - filter = boolOptions; - break; - case "/*global": - obj = predef; - break; - default: - error("What?"); - } - - t = lex.token(); -loop: for (;;) { - minus = false; - for (;;) { - if (t.type === "special" && t.value === "*/") { - break loop; - } - if (t.id !== "(endline)" && t.id !== ",") { - break; - } - t = lex.token(); - } - - if (o === "/*global" && t.value === "-") { - minus = true; - t = lex.token(); - } - - if (t.type !== "(string)" && t.type !== "(identifier)" && o !== "/*members") { - error("Bad option.", t); - } - - v = lex.token(); - if (v.id === ":") { - v = lex.token(); - - if (obj === membersOnly) { - error("Expected '{a}' and instead saw '{b}'.", t, "*/", ":"); - } - - if (o === "/*jshint") { - checkOption(t.value, t); - } - - var numericVals = [ - "maxstatements", - "maxparams", - "maxdepth", - "maxcomplexity", - "maxerr", - "maxlen", - "indent" - ]; - - if (numericVals.indexOf(t.value) > -1 && (o === "/*jshint" || o === "/*jslint")) { - b = +v.value; - - if (typeof b !== "number" || !isFinite(b) || b <= 0 || Math.floor(b) !== b) { - error("Expected a small integer and instead saw '{a}'.", v, v.value); - } - - if (t.value === "indent") - obj.white = true; - - obj[t.value] = b; - } else if (t.value === "validthis") { - if (funct["(global)"]) { - error("Option 'validthis' can't be used in a global scope."); - } else { - if (v.value === "true" || v.value === "false") - obj[t.value] = v.value === "true"; - else - error("Bad option value.", v); - } - } else if (t.value === "quotmark" && (o === "/*jshint")) { - switch (v.value) { - case "true": - obj.quotmark = true; - break; - case "false": - obj.quotmark = false; - break; - case "double": - case "single": - obj.quotmark = v.value; - break; - default: - error("Bad option value.", v); - } - } else if (v.value === "true" || v.value === "false") { - if (o === "/*jslint") { - tn = renamedOptions[t.value] || t.value; - obj[tn] = v.value === "true"; - if (invertedOptions[tn] !== undefined) { - obj[tn] = !obj[tn]; - } - } else { - obj[t.value] = v.value === "true"; - } - - if (t.value === "newcap") - obj["(explicitNewcap)"] = true; - } else { - error("Bad option value.", v); - } - t = lex.token(); - } else { - if (o === "/*jshint" || o === "/*jslint") { - error("Missing option value.", t); - } - - obj[t.value] = false; - - if (o === "/*global" && minus === true) { - JSHINT.blacklist[t.value] = t.value; - updatePredefined(); - } - - t = v; - } - } - - if (o === "/*members") { - option.quotmark = quotmarkValue; - } - - combine(predefined, predef); - - for (var key in predef) { - if (is_own(predef, key)) { - declared[key] = nt; - } - } - - if (filter) { - assume(); - } - } - - -// We need a peek function. If it has an argument, it peeks that much farther -// ahead. It is used to distinguish -// for ( var i in ... -// from -// for ( var i = ... - - function peek(p) { - var i = p || 0, j = 0, t; - - while (j <= i) { - t = lookahead[j]; - if (!t) { - t = lookahead[j] = lex.token(); - } - j += 1; - } - return t; - } - - - -// Produce the next token. It looks for programming errors. - - function advance(id, t) { - switch (token.id) { - case "(number)": - if (nexttoken.id === ".") { - warning("A dot following a number can be confused with a decimal point.", token); - } - break; - case "-": - if (nexttoken.id === "-" || nexttoken.id === "--") { - warning("Confusing minusses."); - } - break; - case "+": - if (nexttoken.id === "+" || nexttoken.id === "++") { - warning("Confusing plusses."); - } - break; - } - - if (token.type === "(string)" || token.identifier) { - anonname = token.value; - } - - if (id && nexttoken.id !== id) { - if (t) { - if (nexttoken.id === "(end)") { - warning("Unmatched '{a}'.", t, t.id); - } else { - warning("Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.", - nexttoken, id, t.id, t.line, nexttoken.value); - } - } else if (nexttoken.type !== "(identifier)" || - nexttoken.value !== id) { - warning("Expected '{a}' and instead saw '{b}'.", - nexttoken, id, nexttoken.value); - } - } - - prevtoken = token; - token = nexttoken; - for (;;) { - nexttoken = lookahead.shift() || lex.token(); - if (nexttoken.id === "(end)" || nexttoken.id === "(error)") { - return; - } - if (nexttoken.type === "special") { - doOption(); - } else { - if (nexttoken.id !== "(endline)") { - break; - } - } - } - } - - -// This is the heart of JSHINT, the Pratt parser. In addition to parsing, it -// is looking for ad hoc lint patterns. We add .fud to Pratt's model, which is -// like .nud except that it is only used on the first token of a statement. -// Having .fud makes it much easier to define statement-oriented languages like -// JavaScript. I retained Pratt's nomenclature. - -// .nud Null denotation -// .fud First null denotation -// .led Left denotation -// lbp Left binding power -// rbp Right binding power - -// They are elements of the parsing method called Top Down Operator Precedence. - - function expression(rbp, initial) { - var left, isArray = false, isObject = false; - - if (nexttoken.id === "(end)") - error("Unexpected early end of program.", token); - - advance(); - if (initial) { - anonname = "anonymous"; - funct["(verb)"] = token.value; - } - if (initial === true && token.fud) { - left = token.fud(); - } else { - if (token.nud) { - left = token.nud(); - } else { - if (nexttoken.type === "(number)" && token.id === ".") { - warning("A leading decimal point can be confused with a dot: '.{a}'.", - token, nexttoken.value); - advance(); - return token; - } else { - error("Expected an identifier and instead saw '{a}'.", - token, token.id); - } - } - while (rbp < nexttoken.lbp) { - isArray = token.value === "Array"; - isObject = token.value === "Object"; - - // #527, new Foo.Array(), Foo.Array(), new Foo.Object(), Foo.Object() - // Line breaks in IfStatement heads exist to satisfy the checkJSHint - // "Line too long." error. - if (left && (left.value || (left.first && left.first.value))) { - // If the left.value is not "new", or the left.first.value is a "." - // then safely assume that this is not "new Array()" and possibly - // not "new Object()"... - if (left.value !== "new" || - (left.first && left.first.value && left.first.value === ".")) { - isArray = false; - // ...In the case of Object, if the left.value and token.value - // are not equal, then safely assume that this not "new Object()" - if (left.value !== token.value) { - isObject = false; - } - } - } - - advance(); - if (isArray && token.id === "(" && nexttoken.id === ")") - warning("Use the array literal notation [].", token); - if (isObject && token.id === "(" && nexttoken.id === ")") - warning("Use the object literal notation {}.", token); - if (token.led) { - left = token.led(left); - } else { - error("Expected an operator and instead saw '{a}'.", - token, token.id); - } - } - } - return left; - } - - -// Functions for conformance of style. - - function adjacent(left, right) { - left = left || token; - right = right || nexttoken; - if (option.white) { - if (left.character !== right.from && left.line === right.line) { - left.from += (left.character - left.from); - warning("Unexpected space after '{a}'.", left, left.value); - } - } - } - - function nobreak(left, right) { - left = left || token; - right = right || nexttoken; - if (option.white && (left.character !== right.from || left.line !== right.line)) { - warning("Unexpected space before '{a}'.", right, right.value); - } - } - - function nospace(left, right) { - left = left || token; - right = right || nexttoken; - if (option.white && !left.comment) { - if (left.line === right.line) { - adjacent(left, right); - } - } - } - - function nonadjacent(left, right) { - if (option.white) { - left = left || token; - right = right || nexttoken; - if (left.value === ";" && right.value === ";") { - return; - } - if (left.line === right.line && left.character === right.from) { - left.from += (left.character - left.from); - warning("Missing space after '{a}'.", - left, left.value); - } - } - } - - function nobreaknonadjacent(left, right) { - left = left || token; - right = right || nexttoken; - if (!option.laxbreak && left.line !== right.line) { - warning("Bad line breaking before '{a}'.", right, right.id); - } else if (option.white) { - left = left || token; - right = right || nexttoken; - if (left.character === right.from) { - left.from += (left.character - left.from); - warning("Missing space after '{a}'.", - left, left.value); - } - } - } - - function indentation(bias) { - var i; - if (option.white && nexttoken.id !== "(end)") { - i = indent + (bias || 0); - if (nexttoken.from !== i) { - warning( -"Expected '{a}' to have an indentation at {b} instead at {c}.", - nexttoken, nexttoken.value, i, nexttoken.from); - } - } - } - - function nolinebreak(t) { - t = t || token; - if (t.line !== nexttoken.line) { - warning("Line breaking error '{a}'.", t, t.value); - } - } - - - function comma() { - if (token.line !== nexttoken.line) { - if (!option.laxcomma) { - if (comma.first) { - warning("Comma warnings can be turned off with 'laxcomma'"); - comma.first = false; - } - warning("Bad line breaking before '{a}'.", token, nexttoken.id); - } - } else if (!token.comment && token.character !== nexttoken.from && option.white) { - token.from += (token.character - token.from); - warning("Unexpected space after '{a}'.", token, token.value); - } - advance(","); - nonadjacent(token, nexttoken); - } - - -// Functional constructors for making the symbols that will be inherited by -// tokens. - - function symbol(s, p) { - var x = syntax[s]; - if (!x || typeof x !== "object") { - syntax[s] = x = { - id: s, - lbp: p, - value: s - }; - } - return x; - } - - - function delim(s) { - return symbol(s, 0); - } - - - function stmt(s, f) { - var x = delim(s); - x.identifier = x.reserved = true; - x.fud = f; - return x; - } - - - function blockstmt(s, f) { - var x = stmt(s, f); - x.block = true; - return x; - } - - - function reserveName(x) { - var c = x.id.charAt(0); - if ((c >= "a" && c <= "z") || (c >= "A" && c <= "Z")) { - x.identifier = x.reserved = true; - } - return x; - } - - - function prefix(s, f) { - var x = symbol(s, 150); - reserveName(x); - x.nud = (typeof f === "function") ? f : function () { - this.right = expression(150); - this.arity = "unary"; - if (this.id === "++" || this.id === "--") { - if (option.plusplus) { - warning("Unexpected use of '{a}'.", this, this.id); - } else if ((!this.right.identifier || this.right.reserved) && - this.right.id !== "." && this.right.id !== "[") { - warning("Bad operand.", this); - } - } - return this; - }; - return x; - } - - - function type(s, f) { - var x = delim(s); - x.type = s; - x.nud = f; - return x; - } - - - function reserve(s, f) { - var x = type(s, f); - x.identifier = x.reserved = true; - return x; - } - - - function reservevar(s, v) { - return reserve(s, function () { - if (typeof v === "function") { - v(this); - } - return this; - }); - } - - - function infix(s, f, p, w) { - var x = symbol(s, p); - reserveName(x); - x.led = function (left) { - if (!w) { - nobreaknonadjacent(prevtoken, token); - nonadjacent(token, nexttoken); - } - if (s === "in" && left.id === "!") { - warning("Confusing use of '{a}'.", left, "!"); - } - if (typeof f === "function") { - return f(left, this); - } else { - this.left = left; - this.right = expression(p); - return this; - } - }; - return x; - } - - - function relation(s, f) { - var x = symbol(s, 100); - x.led = function (left) { - nobreaknonadjacent(prevtoken, token); - nonadjacent(token, nexttoken); - var right = expression(100); - - if (isIdentifier(left, "NaN") || isIdentifier(right, "NaN")) { - warning("Use the isNaN function to compare with NaN.", this); - } else if (f) { - f.apply(this, [left, right]); - } - if (left.id === "!") { - warning("Confusing use of '{a}'.", left, "!"); - } - if (right.id === "!") { - warning("Confusing use of '{a}'.", right, "!"); - } - this.left = left; - this.right = right; - return this; - }; - return x; - } - - - function isPoorRelation(node) { - return node && - ((node.type === "(number)" && +node.value === 0) || - (node.type === "(string)" && node.value === "") || - (node.type === "null" && !option.eqnull) || - node.type === "true" || - node.type === "false" || - node.type === "undefined"); - } - - - function assignop(s) { - symbol(s, 20).exps = true; - - return infix(s, function (left, that) { - that.left = left; - - if (predefined[left.value] === false && - scope[left.value]["(global)"] === true) { - warning("Read only.", left); - } else if (left["function"]) { - warning("'{a}' is a function.", left, left.value); - } - - if (left) { - if (option.esnext && funct[left.value] === "const") { - warning("Attempting to override '{a}' which is a constant", left, left.value); - } - - if (left.id === "." || left.id === "[") { - if (!left.left || left.left.value === "arguments") { - warning("Bad assignment.", that); - } - that.right = expression(19); - return that; - } else if (left.identifier && !left.reserved) { - if (funct[left.value] === "exception") { - warning("Do not assign to the exception parameter.", left); - } - that.right = expression(19); - return that; - } - - if (left === syntax["function"]) { - warning( -"Expected an identifier in an assignment and instead saw a function invocation.", - token); - } - } - - error("Bad assignment.", that); - }, 20); - } - - - function bitwise(s, f, p) { - var x = symbol(s, p); - reserveName(x); - x.led = (typeof f === "function") ? f : function (left) { - if (option.bitwise) { - warning("Unexpected use of '{a}'.", this, this.id); - } - this.left = left; - this.right = expression(p); - return this; - }; - return x; - } - - - function bitwiseassignop(s) { - symbol(s, 20).exps = true; - return infix(s, function (left, that) { - if (option.bitwise) { - warning("Unexpected use of '{a}'.", that, that.id); - } - nonadjacent(prevtoken, token); - nonadjacent(token, nexttoken); - if (left) { - if (left.id === "." || left.id === "[" || - (left.identifier && !left.reserved)) { - expression(19); - return that; - } - if (left === syntax["function"]) { - warning( -"Expected an identifier in an assignment, and instead saw a function invocation.", - token); - } - return that; - } - error("Bad assignment.", that); - }, 20); - } - - - function suffix(s) { - var x = symbol(s, 150); - x.led = function (left) { - if (option.plusplus) { - warning("Unexpected use of '{a}'.", this, this.id); - } else if ((!left.identifier || left.reserved) && - left.id !== "." && left.id !== "[") { - warning("Bad operand.", this); - } - this.left = left; - return this; - }; - return x; - } - - - // fnparam means that this identifier is being defined as a function - // argument (see identifier()) - function optionalidentifier(fnparam) { - if (nexttoken.identifier) { - advance(); - if (token.reserved && !option.es5) { - // `undefined` as a function param is a common pattern to protect - // against the case when somebody does `undefined = true` and - // help with minification. More info: https://gist.github.com/315916 - if (!fnparam || token.value !== "undefined") { - warning("Expected an identifier and instead saw '{a}' (a reserved word).", - token, token.id); - } - } - return token.value; - } - } - - // fnparam means that this identifier is being defined as a function - // argument - function identifier(fnparam) { - var i = optionalidentifier(fnparam); - if (i) { - return i; - } - if (token.id === "function" && nexttoken.id === "(") { - warning("Missing name in function declaration."); - } else { - error("Expected an identifier and instead saw '{a}'.", - nexttoken, nexttoken.value); - } - } - - - function reachable(s) { - var i = 0, t; - if (nexttoken.id !== ";" || noreach) { - return; - } - for (;;) { - t = peek(i); - if (t.reach) { - return; - } - if (t.id !== "(endline)") { - if (t.id === "function") { - if (!option.latedef) { - break; - } - warning( -"Inner functions should be listed at the top of the outer function.", t); - break; - } - warning("Unreachable '{a}' after '{b}'.", t, t.value, s); - break; - } - i += 1; - } - } - - - function statement(noindent) { - var i = indent, r, s = scope, t = nexttoken; - - if (t.id === ";") { - advance(";"); - return; - } - - // Is this a labelled statement? - - if (t.identifier && !t.reserved && peek().id === ":") { - advance(); - advance(":"); - scope = Object.create(s); - addlabel(t.value, "label"); - - if (!nexttoken.labelled && nexttoken.value !== "{") { - warning("Label '{a}' on {b} statement.", nexttoken, t.value, nexttoken.value); - } - - if (jx.test(t.value + ":")) { - warning("Label '{a}' looks like a javascript url.", t, t.value); - } - - nexttoken.label = t.value; - t = nexttoken; - } - - // Is it a lonely block? - - if (t.id === "{") { - block(true, true); - return; - } - - // Parse the statement. - - if (!noindent) { - indentation(); - } - r = expression(0, true); - - // Look for the final semicolon. - - if (!t.block) { - if (!option.expr && (!r || !r.exps)) { - warning("Expected an assignment or function call and instead saw an expression.", - token); - } else if (option.nonew && r.id === "(" && r.left.id === "new") { - warning("Do not use 'new' for side effects.", t); - } - - if (nexttoken.id === ",") { - return comma(); - } - - if (nexttoken.id !== ";") { - if (!option.asi) { - // If this is the last statement in a block that ends on - // the same line *and* option lastsemic is on, ignore the warning. - // Otherwise, complain about missing semicolon. - if (!option.lastsemic || nexttoken.id !== "}" || - nexttoken.line !== token.line) { - warningAt("Missing semicolon.", token.line, token.character); - } - } - } else { - adjacent(token, nexttoken); - advance(";"); - nonadjacent(token, nexttoken); - } - } - -// Restore the indentation. - - indent = i; - scope = s; - return r; - } - - - function statements(startLine) { - var a = [], p; - - while (!nexttoken.reach && nexttoken.id !== "(end)") { - if (nexttoken.id === ";") { - p = peek(); - if (!p || p.id !== "(") { - warning("Unnecessary semicolon."); - } - advance(";"); - } else { - a.push(statement(startLine === nexttoken.line)); - } - } - return a; - } - - - /* - * read all directives - * recognizes a simple form of asi, but always - * warns, if it is used - */ - function directives() { - var i, p, pn; - - for (;;) { - if (nexttoken.id === "(string)") { - p = peek(0); - if (p.id === "(endline)") { - i = 1; - do { - pn = peek(i); - i = i + 1; - } while (pn.id === "(endline)"); - - if (pn.id !== ";") { - if (pn.id !== "(string)" && pn.id !== "(number)" && - pn.id !== "(regexp)" && pn.identifier !== true && - pn.id !== "}") { - break; - } - warning("Missing semicolon.", nexttoken); - } else { - p = pn; - } - } else if (p.id === "}") { - // directive with no other statements, warn about missing semicolon - warning("Missing semicolon.", p); - } else if (p.id !== ";") { - break; - } - - indentation(); - advance(); - if (directive[token.value]) { - warning("Unnecessary directive \"{a}\".", token, token.value); - } - - if (token.value === "use strict") { - if (!option["(explicitNewcap)"]) - option.newcap = true; - option.undef = true; - } - - // there's no directive negation, so always set to true - directive[token.value] = true; - - if (p.id === ";") { - advance(";"); - } - continue; - } - break; - } - } - - - /* - * Parses a single block. A block is a sequence of statements wrapped in - * braces. - * - * ordinary - true for everything but function bodies and try blocks. - * stmt - true if block can be a single statement (e.g. in if/for/while). - * isfunc - true if block is a function body - */ - function block(ordinary, stmt, isfunc) { - var a, - b = inblock, - old_indent = indent, - m, - s = scope, - t, - line, - d; - - inblock = ordinary; - - if (!ordinary || !option.funcscope) - scope = Object.create(scope); - - nonadjacent(token, nexttoken); - t = nexttoken; - - var metrics = funct["(metrics)"]; - metrics.nestedBlockDepth += 1; - metrics.verifyMaxNestedBlockDepthPerFunction(); - - if (nexttoken.id === "{") { - advance("{"); - line = token.line; - if (nexttoken.id !== "}") { - indent += option.indent; - while (!ordinary && nexttoken.from > indent) { - indent += option.indent; - } - - if (isfunc) { - m = {}; - for (d in directive) { - if (is_own(directive, d)) { - m[d] = directive[d]; - } - } - directives(); - - if (option.strict && funct["(context)"]["(global)"]) { - if (!m["use strict"] && !directive["use strict"]) { - warning("Missing \"use strict\" statement."); - } - } - } - - a = statements(line); - - metrics.statementCount += a.length; - - if (isfunc) { - directive = m; - } - - indent -= option.indent; - if (line !== nexttoken.line) { - indentation(); - } - } else if (line !== nexttoken.line) { - indentation(); - } - advance("}", t); - indent = old_indent; - } else if (!ordinary) { - error("Expected '{a}' and instead saw '{b}'.", - nexttoken, "{", nexttoken.value); - } else { - if (!stmt || option.curly) - warning("Expected '{a}' and instead saw '{b}'.", - nexttoken, "{", nexttoken.value); - - noreach = true; - indent += option.indent; - // test indentation only if statement is in new line - a = [statement(nexttoken.line === token.line)]; - indent -= option.indent; - noreach = false; - } - funct["(verb)"] = null; - if (!ordinary || !option.funcscope) scope = s; - inblock = b; - if (ordinary && option.noempty && (!a || a.length === 0)) { - warning("Empty block."); - } - metrics.nestedBlockDepth -= 1; - return a; - } - - - function countMember(m) { - if (membersOnly && typeof membersOnly[m] !== "boolean") { - warning("Unexpected /*member '{a}'.", token, m); - } - if (typeof member[m] === "number") { - member[m] += 1; - } else { - member[m] = 1; - } - } - - - function note_implied(token) { - var name = token.value, line = token.line, a = implied[name]; - if (typeof a === "function") { - a = false; - } - - if (!a) { - a = [line]; - implied[name] = a; - } else if (a[a.length - 1] !== line) { - a.push(line); - } - } - - - // Build the syntax table by declaring the syntactic elements of the language. - - type("(number)", function () { - return this; - }); - - type("(string)", function () { - return this; - }); - - syntax["(identifier)"] = { - type: "(identifier)", - lbp: 0, - identifier: true, - nud: function () { - var v = this.value, - s = scope[v], - f; - - if (typeof s === "function") { - // Protection against accidental inheritance. - s = undefined; - } else if (typeof s === "boolean") { - f = funct; - funct = functions[0]; - addlabel(v, "var"); - s = funct; - funct = f; - } - - // The name is in scope and defined in the current function. - if (funct === s) { - // Change 'unused' to 'var', and reject labels. - switch (funct[v]) { - case "unused": - funct[v] = "var"; - break; - case "unction": - funct[v] = "function"; - this["function"] = true; - break; - case "function": - this["function"] = true; - break; - case "label": - warning("'{a}' is a statement label.", token, v); - break; - } - } else if (funct["(global)"]) { - // The name is not defined in the function. If we are in the global - // scope, then we have an undefined variable. - // - // Operators typeof and delete do not raise runtime errors even if - // the base object of a reference is null so no need to display warning - // if we're inside of typeof or delete. - - if (option.undef && typeof predefined[v] !== "boolean") { - // Attempting to subscript a null reference will throw an - // error, even within the typeof and delete operators - if (!(anonname === "typeof" || anonname === "delete") || - (nexttoken && (nexttoken.value === "." || nexttoken.value === "["))) { - - isundef(funct, "'{a}' is not defined.", token, v); - } - } - - note_implied(token); - } else { - // If the name is already defined in the current - // function, but not as outer, then there is a scope error. - - switch (funct[v]) { - case "closure": - case "function": - case "var": - case "unused": - warning("'{a}' used out of scope.", token, v); - break; - case "label": - warning("'{a}' is a statement label.", token, v); - break; - case "outer": - case "global": - break; - default: - // If the name is defined in an outer function, make an outer entry, - // and if it was unused, make it var. - if (s === true) { - funct[v] = true; - } else if (s === null) { - warning("'{a}' is not allowed.", token, v); - note_implied(token); - } else if (typeof s !== "object") { - // Operators typeof and delete do not raise runtime errors even - // if the base object of a reference is null so no need to - // display warning if we're inside of typeof or delete. - if (option.undef) { - // Attempting to subscript a null reference will throw an - // error, even within the typeof and delete operators - if (!(anonname === "typeof" || anonname === "delete") || - (nexttoken && - (nexttoken.value === "." || nexttoken.value === "["))) { - - isundef(funct, "'{a}' is not defined.", token, v); - } - } - funct[v] = true; - note_implied(token); - } else { - switch (s[v]) { - case "function": - case "unction": - this["function"] = true; - s[v] = "closure"; - funct[v] = s["(global)"] ? "global" : "outer"; - break; - case "var": - case "unused": - s[v] = "closure"; - funct[v] = s["(global)"] ? "global" : "outer"; - break; - case "closure": - funct[v] = s["(global)"] ? "global" : "outer"; - break; - case "label": - warning("'{a}' is a statement label.", token, v); - } - } - } - } - return this; - }, - led: function () { - error("Expected an operator and instead saw '{a}'.", - nexttoken, nexttoken.value); - } - }; - - type("(regexp)", function () { - return this; - }); - - -// ECMAScript parser - - delim("(endline)"); - delim("(begin)"); - delim("(end)").reach = true; - delim(""); - delim("(error)").reach = true; - delim("}").reach = true; - delim(")"); - delim("]"); - delim("\"").reach = true; - delim("'").reach = true; - delim(";"); - delim(":").reach = true; - delim(","); - delim("#"); - delim("@"); - reserve("else"); - reserve("case").reach = true; - reserve("catch"); - reserve("default").reach = true; - reserve("finally"); - reservevar("arguments", function (x) { - if (directive["use strict"] && funct["(global)"]) { - warning("Strict violation.", x); - } - }); - reservevar("eval"); - reservevar("false"); - reservevar("Infinity"); - reservevar("null"); - reservevar("this", function (x) { - if (directive["use strict"] && !option.validthis && ((funct["(statement)"] && - funct["(name)"].charAt(0) > "Z") || funct["(global)"])) { - warning("Possible strict violation.", x); - } - }); - reservevar("true"); - reservevar("undefined"); - assignop("=", "assign", 20); - assignop("+=", "assignadd", 20); - assignop("-=", "assignsub", 20); - assignop("*=", "assignmult", 20); - assignop("/=", "assigndiv", 20).nud = function () { - error("A regular expression literal can be confused with '/='."); - }; - assignop("%=", "assignmod", 20); - bitwiseassignop("&=", "assignbitand", 20); - bitwiseassignop("|=", "assignbitor", 20); - bitwiseassignop("^=", "assignbitxor", 20); - bitwiseassignop("<<=", "assignshiftleft", 20); - bitwiseassignop(">>=", "assignshiftright", 20); - bitwiseassignop(">>>=", "assignshiftrightunsigned", 20); - infix("?", function (left, that) { - that.left = left; - that.right = expression(10); - advance(":"); - that["else"] = expression(10); - return that; - }, 30); - - infix("||", "or", 40); - infix("&&", "and", 50); - bitwise("|", "bitor", 70); - bitwise("^", "bitxor", 80); - bitwise("&", "bitand", 90); - relation("==", function (left, right) { - var eqnull = option.eqnull && (left.value === "null" || right.value === "null"); - - if (!eqnull && option.eqeqeq) - warning("Expected '{a}' and instead saw '{b}'.", this, "===", "=="); - else if (isPoorRelation(left)) - warning("Use '{a}' to compare with '{b}'.", this, "===", left.value); - else if (isPoorRelation(right)) - warning("Use '{a}' to compare with '{b}'.", this, "===", right.value); - - return this; - }); - relation("==="); - relation("!=", function (left, right) { - var eqnull = option.eqnull && - (left.value === "null" || right.value === "null"); - - if (!eqnull && option.eqeqeq) { - warning("Expected '{a}' and instead saw '{b}'.", - this, "!==", "!="); - } else if (isPoorRelation(left)) { - warning("Use '{a}' to compare with '{b}'.", - this, "!==", left.value); - } else if (isPoorRelation(right)) { - warning("Use '{a}' to compare with '{b}'.", - this, "!==", right.value); - } - return this; - }); - relation("!=="); - relation("<"); - relation(">"); - relation("<="); - relation(">="); - bitwise("<<", "shiftleft", 120); - bitwise(">>", "shiftright", 120); - bitwise(">>>", "shiftrightunsigned", 120); - infix("in", "in", 120); - infix("instanceof", "instanceof", 120); - infix("+", function (left, that) { - var right = expression(130); - if (left && right && left.id === "(string)" && right.id === "(string)") { - left.value += right.value; - left.character = right.character; - if (!option.scripturl && jx.test(left.value)) { - warning("JavaScript URL.", left); - } - return left; - } - that.left = left; - that.right = right; - return that; - }, 130); - prefix("+", "num"); - prefix("+++", function () { - warning("Confusing pluses."); - this.right = expression(150); - this.arity = "unary"; - return this; - }); - infix("+++", function (left) { - warning("Confusing pluses."); - this.left = left; - this.right = expression(130); - return this; - }, 130); - infix("-", "sub", 130); - prefix("-", "neg"); - prefix("---", function () { - warning("Confusing minuses."); - this.right = expression(150); - this.arity = "unary"; - return this; - }); - infix("---", function (left) { - warning("Confusing minuses."); - this.left = left; - this.right = expression(130); - return this; - }, 130); - infix("*", "mult", 140); - infix("/", "div", 140); - infix("%", "mod", 140); - - suffix("++", "postinc"); - prefix("++", "preinc"); - syntax["++"].exps = true; - - suffix("--", "postdec"); - prefix("--", "predec"); - syntax["--"].exps = true; - prefix("delete", function () { - var p = expression(0); - if (!p || (p.id !== "." && p.id !== "[")) { - warning("Variables should not be deleted."); - } - this.first = p; - return this; - }).exps = true; - - prefix("~", function () { - if (option.bitwise) { - warning("Unexpected '{a}'.", this, "~"); - } - expression(150); - return this; - }); - - prefix("!", function () { - this.right = expression(150); - this.arity = "unary"; - if (bang[this.right.id] === true) { - warning("Confusing use of '{a}'.", this, "!"); - } - return this; - }); - prefix("typeof", "typeof"); - prefix("new", function () { - var c = expression(155), i; - if (c && c.id !== "function") { - if (c.identifier) { - c["new"] = true; - switch (c.value) { - case "Number": - case "String": - case "Boolean": - case "Math": - case "JSON": - warning("Do not use {a} as a constructor.", prevtoken, c.value); - break; - case "Function": - if (!option.evil) { - warning("The Function constructor is eval."); - } - break; - case "Date": - case "RegExp": - break; - default: - if (c.id !== "function") { - i = c.value.substr(0, 1); - if (option.newcap && (i < "A" || i > "Z") && !is_own(global, c.value)) { - warning("A constructor name should start with an uppercase letter.", - token); - } - } - } - } else { - if (c.id !== "." && c.id !== "[" && c.id !== "(") { - warning("Bad constructor.", token); - } - } - } else { - if (!option.supernew) - warning("Weird construction. Delete 'new'.", this); - } - adjacent(token, nexttoken); - if (nexttoken.id !== "(" && !option.supernew) { - warning("Missing '()' invoking a constructor.", - token, token.value); - } - this.first = c; - return this; - }); - syntax["new"].exps = true; - - prefix("void").exps = true; - - infix(".", function (left, that) { - adjacent(prevtoken, token); - nobreak(); - var m = identifier(); - if (typeof m === "string") { - countMember(m); - } - that.left = left; - that.right = m; - if (left && left.value === "arguments" && (m === "callee" || m === "caller")) { - if (option.noarg) - warning("Avoid arguments.{a}.", left, m); - else if (directive["use strict"]) - error("Strict violation."); - } else if (!option.evil && left && left.value === "document" && - (m === "write" || m === "writeln")) { - warning("document.write can be a form of eval.", left); - } - if (!option.evil && (m === "eval" || m === "execScript")) { - warning("eval is evil."); - } - return that; - }, 160, true); - - infix("(", function (left, that) { - if (prevtoken.id !== "}" && prevtoken.id !== ")") { - nobreak(prevtoken, token); - } - nospace(); - if (option.immed && !left.immed && left.id === "function") { - warning("Wrap an immediate function invocation in parentheses " + - "to assist the reader in understanding that the expression " + - "is the result of a function, and not the function itself."); - } - var n = 0, - p = []; - if (left) { - if (left.type === "(identifier)") { - if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) { - if ("Number String Boolean Date Object".indexOf(left.value) === -1) { - if (left.value === "Math") { - warning("Math is not a function.", left); - } else if (option.newcap) { - warning("Missing 'new' prefix when invoking a constructor.", left); - } - } - } - } - } - if (nexttoken.id !== ")") { - for (;;) { - p[p.length] = expression(10); - n += 1; - if (nexttoken.id !== ",") { - break; - } - comma(); - } - } - advance(")"); - nospace(prevtoken, token); - if (typeof left === "object") { - if (left.value === "parseInt" && n === 1) { - warning("Missing radix parameter.", token); - } - if (!option.evil) { - if (left.value === "eval" || left.value === "Function" || - left.value === "execScript") { - warning("eval is evil.", left); - - if (p[0] && [0].id === "(string)") { - addInternalSrc(left, p[0].value); - } - } else if (p[0] && p[0].id === "(string)" && - (left.value === "setTimeout" || - left.value === "setInterval")) { - warning( - "Implied eval is evil. Pass a function instead of a string.", left); - addInternalSrc(left, p[0].value); - - // window.setTimeout/setInterval - } else if (p[0] && p[0].id === "(string)" && - left.value === "." && - left.left.value === "window" && - (left.right === "setTimeout" || - left.right === "setInterval")) { - warning( - "Implied eval is evil. Pass a function instead of a string.", left); - addInternalSrc(left, p[0].value); - } - } - if (!left.identifier && left.id !== "." && left.id !== "[" && - left.id !== "(" && left.id !== "&&" && left.id !== "||" && - left.id !== "?") { - warning("Bad invocation.", left); - } - } - that.left = left; - return that; - }, 155, true).exps = true; - - prefix("(", function () { - nospace(); - if (nexttoken.id === "function") { - nexttoken.immed = true; - } - var v = expression(0); - advance(")", this); - nospace(prevtoken, token); - if (option.immed && v.id === "function") { - if (nexttoken.id !== "(" && - (nexttoken.id !== "." || (peek().value !== "call" && peek().value !== "apply"))) { - warning( -"Do not wrap function literals in parens unless they are to be immediately invoked.", - this); - } - } - - return v; - }); - - infix("[", function (left, that) { - nobreak(prevtoken, token); - nospace(); - var e = expression(0), s; - if (e && e.type === "(string)") { - if (!option.evil && (e.value === "eval" || e.value === "execScript")) { - warning("eval is evil.", that); - } - countMember(e.value); - if (!option.sub && ix.test(e.value)) { - s = syntax[e.value]; - if (!s || !s.reserved) { - warning("['{a}'] is better written in dot notation.", - prevtoken, e.value); - } - } - } - advance("]", that); - nospace(prevtoken, token); - that.left = left; - that.right = e; - return that; - }, 160, true); - - prefix("[", function () { - var b = token.line !== nexttoken.line; - this.first = []; - if (b) { - indent += option.indent; - if (nexttoken.from === indent + option.indent) { - indent += option.indent; - } - } - while (nexttoken.id !== "(end)") { - while (nexttoken.id === ",") { - if (!option.es5) - warning("Extra comma."); - advance(","); - } - if (nexttoken.id === "]") { - break; - } - if (b && token.line !== nexttoken.line) { - indentation(); - } - this.first.push(expression(10)); - if (nexttoken.id === ",") { - comma(); - if (nexttoken.id === "]" && !option.es5) { - warning("Extra comma.", token); - break; - } - } else { - break; - } - } - if (b) { - indent -= option.indent; - indentation(); - } - advance("]", this); - return this; - }, 160); - - - function property_name() { - var id = optionalidentifier(true); - if (!id) { - if (nexttoken.id === "(string)") { - id = nexttoken.value; - advance(); - } else if (nexttoken.id === "(number)") { - id = nexttoken.value.toString(); - advance(); - } - } - return id; - } - - - function functionparams() { - var next = nexttoken; - var params = []; - var ident; - - advance("("); - nospace(); - - if (nexttoken.id === ")") { - advance(")"); - return; - } - - for (;;) { - ident = identifier(true); - params.push(ident); - addlabel(ident, "unused", token); - if (nexttoken.id === ",") { - comma(); - } else { - advance(")", next); - nospace(prevtoken, token); - return params; - } - } - } - - - function doFunction(name, statement) { - var f; - var oldOption = option; - var oldScope = scope; - - option = Object.create(option); - scope = Object.create(scope); - - funct = { - "(name)" : name || "\"" + anonname + "\"", - "(line)" : nexttoken.line, - "(character)": nexttoken.character, - "(context)" : funct, - "(breakage)" : 0, - "(loopage)" : 0, - "(metrics)" : createMetrics(nexttoken), - "(scope)" : scope, - "(statement)": statement, - "(tokens)" : {} - }; - - f = funct; - token.funct = funct; - - functions.push(funct); - - if (name) { - addlabel(name, "function"); - } - - funct["(params)"] = functionparams(); - funct["(metrics)"].verifyMaxParametersPerFunction(funct["(params)"]); - - block(false, false, true); - - funct["(metrics)"].verifyMaxStatementsPerFunction(); - funct["(metrics)"].verifyMaxComplexityPerFunction(); - - scope = oldScope; - option = oldOption; - funct["(last)"] = token.line; - funct["(lastcharacter)"] = token.character; - funct = funct["(context)"]; - - return f; - } - - function createMetrics(functionStartToken) { - return { - statementCount: 0, - nestedBlockDepth: -1, - ComplexityCount: 1, - verifyMaxStatementsPerFunction: function () { - if (option.maxstatements && - this.statementCount > option.maxstatements) { - var message = "Too many statements per function (" + this.statementCount + ")."; - warning(message, functionStartToken); - } - }, - - verifyMaxParametersPerFunction: function (params) { - params = params || []; - - if (option.maxparams && params.length > option.maxparams) { - var message = "Too many parameters per function (" + params.length + ")."; - warning(message, functionStartToken); - } - }, - - verifyMaxNestedBlockDepthPerFunction: function () { - if (option.maxdepth && - this.nestedBlockDepth > 0 && - this.nestedBlockDepth === option.maxdepth + 1) { - var message = "Blocks are nested too deeply (" + this.nestedBlockDepth + ")."; - warning(message); - } - }, - - verifyMaxComplexityPerFunction: function () { - var max = option.maxcomplexity; - var cc = this.ComplexityCount; - if (max && cc > max) { - var message = "Cyclomatic complexity is too high per function (" + cc + ")."; - warning(message, functionStartToken); - } - } - }; - } - - function increaseComplexityCount() { - funct["(metrics)"].ComplexityCount += 1; - } - - - (function (x) { - x.nud = function () { - var b, f, i, p, t; - var props = {}; // All properties, including accessors - - function saveProperty(name, token) { - if (props[name] && is_own(props, name)) - warning("Duplicate member '{a}'.", nexttoken, i); - else - props[name] = {}; - - props[name].basic = true; - props[name].basicToken = token; - } - - function saveSetter(name, token) { - if (props[name] && is_own(props, name)) { - if (props[name].basic || props[name].setter) - warning("Duplicate member '{a}'.", nexttoken, i); - } else { - props[name] = {}; - } - - props[name].setter = true; - props[name].setterToken = token; - } - - function saveGetter(name) { - if (props[name] && is_own(props, name)) { - if (props[name].basic || props[name].getter) - warning("Duplicate member '{a}'.", nexttoken, i); - } else { - props[name] = {}; - } - - props[name].getter = true; - props[name].getterToken = token; - } - - b = token.line !== nexttoken.line; - if (b) { - indent += option.indent; - if (nexttoken.from === indent + option.indent) { - indent += option.indent; - } - } - for (;;) { - if (nexttoken.id === "}") { - break; - } - if (b) { - indentation(); - } - if (nexttoken.value === "get" && peek().id !== ":") { - advance("get"); - if (!option.es5) { - error("get/set are ES5 features."); - } - i = property_name(); - if (!i) { - error("Missing property name."); - } - saveGetter(i); - t = nexttoken; - adjacent(token, nexttoken); - f = doFunction(); - p = f["(params)"]; - if (p) { - warning("Unexpected parameter '{a}' in get {b} function.", t, p[0], i); - } - adjacent(token, nexttoken); - } else if (nexttoken.value === "set" && peek().id !== ":") { - advance("set"); - if (!option.es5) { - error("get/set are ES5 features."); - } - i = property_name(); - if (!i) { - error("Missing property name."); - } - saveSetter(i, nexttoken); - t = nexttoken; - adjacent(token, nexttoken); - f = doFunction(); - p = f["(params)"]; - if (!p || p.length !== 1) { - warning("Expected a single parameter in set {a} function.", t, i); - } - } else { - i = property_name(); - saveProperty(i, nexttoken); - if (typeof i !== "string") { - break; - } - advance(":"); - nonadjacent(token, nexttoken); - expression(10); - } - - countMember(i); - if (nexttoken.id === ",") { - comma(); - if (nexttoken.id === ",") { - warning("Extra comma.", token); - } else if (nexttoken.id === "}" && !option.es5) { - warning("Extra comma.", token); - } - } else { - break; - } - } - if (b) { - indent -= option.indent; - indentation(); - } - advance("}", this); - - // Check for lonely setters if in the ES5 mode. - if (option.es5) { - for (var name in props) { - if (is_own(props, name) && props[name].setter && !props[name].getter) { - warning("Setter is defined without getter.", props[name].setterToken); - } - } - } - return this; - }; - x.fud = function () { - error("Expected to see a statement and instead saw a block.", token); - }; - }(delim("{"))); - -// This Function is called when esnext option is set to true -// it adds the `const` statement to JSHINT - - useESNextSyntax = function () { - var conststatement = stmt("const", function (prefix) { - var id, name, value; - - this.first = []; - for (;;) { - nonadjacent(token, nexttoken); - id = identifier(); - if (funct[id] === "const") { - warning("const '" + id + "' has already been declared"); - } - if (funct["(global)"] && predefined[id] === false) { - warning("Redefinition of '{a}'.", token, id); - } - addlabel(id, "const"); - if (prefix) { - break; - } - name = token; - this.first.push(token); - - if (nexttoken.id !== "=") { - warning("const " + - "'{a}' is initialized to 'undefined'.", token, id); - } - - if (nexttoken.id === "=") { - nonadjacent(token, nexttoken); - advance("="); - nonadjacent(token, nexttoken); - if (nexttoken.id === "undefined") { - warning("It is not necessary to initialize " + - "'{a}' to 'undefined'.", token, id); - } - if (peek(0).id === "=" && nexttoken.identifier) { - error("Constant {a} was not declared correctly.", - nexttoken, nexttoken.value); - } - value = expression(0); - name.first = value; - } - - if (nexttoken.id !== ",") { - break; - } - comma(); - } - return this; - }); - conststatement.exps = true; - }; - - var varstatement = stmt("var", function (prefix) { - // JavaScript does not have block scope. It only has function scope. So, - // declaring a variable in a block can have unexpected consequences. - var id, name, value; - - if (funct["(onevar)"] && option.onevar) { - warning("Too many var statements."); - } else if (!funct["(global)"]) { - funct["(onevar)"] = true; - } - - this.first = []; - - for (;;) { - nonadjacent(token, nexttoken); - id = identifier(); - - if (option.esnext && funct[id] === "const") { - warning("const '" + id + "' has already been declared"); - } - - if (funct["(global)"] && predefined[id] === false) { - warning("Redefinition of '{a}'.", token, id); - } - - addlabel(id, "unused", token); - - if (prefix) { - break; - } - - name = token; - this.first.push(token); - - if (nexttoken.id === "=") { - nonadjacent(token, nexttoken); - advance("="); - nonadjacent(token, nexttoken); - if (nexttoken.id === "undefined") { - warning("It is not necessary to initialize '{a}' to 'undefined'.", token, id); - } - if (peek(0).id === "=" && nexttoken.identifier) { - error("Variable {a} was not declared correctly.", - nexttoken, nexttoken.value); - } - value = expression(0); - name.first = value; - } - if (nexttoken.id !== ",") { - break; - } - comma(); - } - return this; - }); - varstatement.exps = true; - - blockstmt("function", function () { - if (inblock) { - warning("Function declarations should not be placed in blocks. " + - "Use a function expression or move the statement to the top of " + - "the outer function.", token); - - } - var i = identifier(); - if (option.esnext && funct[i] === "const") { - warning("const '" + i + "' has already been declared"); - } - adjacent(token, nexttoken); - addlabel(i, "unction", token); - - doFunction(i, { statement: true }); - if (nexttoken.id === "(" && nexttoken.line === token.line) { - error( -"Function declarations are not invocable. Wrap the whole function invocation in parens."); - } - return this; - }); - - prefix("function", function () { - var i = optionalidentifier(); - if (i) { - adjacent(token, nexttoken); - } else { - nonadjacent(token, nexttoken); - } - doFunction(i); - if (!option.loopfunc && funct["(loopage)"]) { - warning("Don't make functions within a loop."); - } - return this; - }); - - blockstmt("if", function () { - var t = nexttoken; - increaseComplexityCount(); - advance("("); - nonadjacent(this, t); - nospace(); - expression(20); - if (nexttoken.id === "=") { - if (!option.boss) - warning("Expected a conditional expression and instead saw an assignment."); - advance("="); - expression(20); - } - advance(")", t); - nospace(prevtoken, token); - block(true, true); - if (nexttoken.id === "else") { - nonadjacent(token, nexttoken); - advance("else"); - if (nexttoken.id === "if" || nexttoken.id === "switch") { - statement(true); - } else { - block(true, true); - } - } - return this; - }); - - blockstmt("try", function () { - var b; - - function doCatch() { - var oldScope = scope; - var e; - - advance("catch"); - nonadjacent(token, nexttoken); - advance("("); - - scope = Object.create(oldScope); - - e = nexttoken.value; - if (nexttoken.type !== "(identifier)") { - e = null; - warning("Expected an identifier and instead saw '{a}'.", nexttoken, e); - } - - advance(); - advance(")"); - - funct = { - "(name)" : "(catch)", - "(line)" : nexttoken.line, - "(character)": nexttoken.character, - "(context)" : funct, - "(breakage)" : funct["(breakage)"], - "(loopage)" : funct["(loopage)"], - "(scope)" : scope, - "(statement)": false, - "(metrics)" : createMetrics(nexttoken), - "(catch)" : true, - "(tokens)" : {} - }; - - if (e) { - addlabel(e, "exception"); - } - - token.funct = funct; - functions.push(funct); - - block(false); - - scope = oldScope; - - funct["(last)"] = token.line; - funct["(lastcharacter)"] = token.character; - funct = funct["(context)"]; - } - - block(false); - - if (nexttoken.id === "catch") { - increaseComplexityCount(); - doCatch(); - b = true; - } - - if (nexttoken.id === "finally") { - advance("finally"); - block(false); - return; - } else if (!b) { - error("Expected '{a}' and instead saw '{b}'.", - nexttoken, "catch", nexttoken.value); - } - - return this; - }); - - blockstmt("while", function () { - var t = nexttoken; - funct["(breakage)"] += 1; - funct["(loopage)"] += 1; - increaseComplexityCount(); - advance("("); - nonadjacent(this, t); - nospace(); - expression(20); - if (nexttoken.id === "=") { - if (!option.boss) - warning("Expected a conditional expression and instead saw an assignment."); - advance("="); - expression(20); - } - advance(")", t); - nospace(prevtoken, token); - block(true, true); - funct["(breakage)"] -= 1; - funct["(loopage)"] -= 1; - return this; - }).labelled = true; - - blockstmt("with", function () { - var t = nexttoken; - if (directive["use strict"]) { - error("'with' is not allowed in strict mode.", token); - } else if (!option.withstmt) { - warning("Don't use 'with'.", token); - } - - advance("("); - nonadjacent(this, t); - nospace(); - expression(0); - advance(")", t); - nospace(prevtoken, token); - block(true, true); - - return this; - }); - - blockstmt("switch", function () { - var t = nexttoken, - g = false; - funct["(breakage)"] += 1; - advance("("); - nonadjacent(this, t); - nospace(); - this.condition = expression(20); - advance(")", t); - nospace(prevtoken, token); - nonadjacent(token, nexttoken); - t = nexttoken; - advance("{"); - nonadjacent(token, nexttoken); - indent += option.indent; - this.cases = []; - for (;;) { - switch (nexttoken.id) { - case "case": - switch (funct["(verb)"]) { - case "break": - case "case": - case "continue": - case "return": - case "switch": - case "throw": - break; - default: - // You can tell JSHint that you don't use break intentionally by - // adding a comment /* falls through */ on a line just before - // the next `case`. - if (!ft.test(lines[nexttoken.line - 2])) { - warning( - "Expected a 'break' statement before 'case'.", - token); - } - } - indentation(-option.indent); - advance("case"); - this.cases.push(expression(20)); - increaseComplexityCount(); - g = true; - advance(":"); - funct["(verb)"] = "case"; - break; - case "default": - switch (funct["(verb)"]) { - case "break": - case "continue": - case "return": - case "throw": - break; - default: - if (!ft.test(lines[nexttoken.line - 2])) { - warning( - "Expected a 'break' statement before 'default'.", - token); - } - } - indentation(-option.indent); - advance("default"); - g = true; - advance(":"); - break; - case "}": - indent -= option.indent; - indentation(); - advance("}", t); - if (this.cases.length === 1 || this.condition.id === "true" || - this.condition.id === "false") { - if (!option.onecase) - warning("This 'switch' should be an 'if'.", this); - } - funct["(breakage)"] -= 1; - funct["(verb)"] = undefined; - return; - case "(end)": - error("Missing '{a}'.", nexttoken, "}"); - return; - default: - if (g) { - switch (token.id) { - case ",": - error("Each value should have its own case label."); - return; - case ":": - g = false; - statements(); - break; - default: - error("Missing ':' on a case clause.", token); - return; - } - } else { - if (token.id === ":") { - advance(":"); - error("Unexpected '{a}'.", token, ":"); - statements(); - } else { - error("Expected '{a}' and instead saw '{b}'.", - nexttoken, "case", nexttoken.value); - return; - } - } - } - } - }).labelled = true; - - stmt("debugger", function () { - if (!option.debug) { - warning("All 'debugger' statements should be removed."); - } - return this; - }).exps = true; - - (function () { - var x = stmt("do", function () { - funct["(breakage)"] += 1; - funct["(loopage)"] += 1; - increaseComplexityCount(); - - this.first = block(true); - advance("while"); - var t = nexttoken; - nonadjacent(token, t); - advance("("); - nospace(); - expression(20); - if (nexttoken.id === "=") { - if (!option.boss) - warning("Expected a conditional expression and instead saw an assignment."); - advance("="); - expression(20); - } - advance(")", t); - nospace(prevtoken, token); - funct["(breakage)"] -= 1; - funct["(loopage)"] -= 1; - return this; - }); - x.labelled = true; - x.exps = true; - }()); - - blockstmt("for", function () { - var s, t = nexttoken; - funct["(breakage)"] += 1; - funct["(loopage)"] += 1; - increaseComplexityCount(); - advance("("); - nonadjacent(this, t); - nospace(); - if (peek(nexttoken.id === "var" ? 1 : 0).id === "in") { - if (nexttoken.id === "var") { - advance("var"); - varstatement.fud.call(varstatement, true); - } else { - switch (funct[nexttoken.value]) { - case "unused": - funct[nexttoken.value] = "var"; - break; - case "var": - break; - default: - warning("Bad for in variable '{a}'.", - nexttoken, nexttoken.value); - } - advance(); - } - advance("in"); - expression(20); - advance(")", t); - s = block(true, true); - if (option.forin && s && (s.length > 1 || typeof s[0] !== "object" || - s[0].value !== "if")) { - warning("The body of a for in should be wrapped in an if statement to filter " + - "unwanted properties from the prototype.", this); - } - funct["(breakage)"] -= 1; - funct["(loopage)"] -= 1; - return this; - } else { - if (nexttoken.id !== ";") { - if (nexttoken.id === "var") { - advance("var"); - varstatement.fud.call(varstatement); - } else { - for (;;) { - expression(0, "for"); - if (nexttoken.id !== ",") { - break; - } - comma(); - } - } - } - nolinebreak(token); - advance(";"); - if (nexttoken.id !== ";") { - expression(20); - if (nexttoken.id === "=") { - if (!option.boss) - warning("Expected a conditional expression and instead saw an assignment."); - advance("="); - expression(20); - } - } - nolinebreak(token); - advance(";"); - if (nexttoken.id === ";") { - error("Expected '{a}' and instead saw '{b}'.", - nexttoken, ")", ";"); - } - if (nexttoken.id !== ")") { - for (;;) { - expression(0, "for"); - if (nexttoken.id !== ",") { - break; - } - comma(); - } - } - advance(")", t); - nospace(prevtoken, token); - block(true, true); - funct["(breakage)"] -= 1; - funct["(loopage)"] -= 1; - return this; - } - }).labelled = true; - - - stmt("break", function () { - var v = nexttoken.value; - - if (funct["(breakage)"] === 0) - warning("Unexpected '{a}'.", nexttoken, this.value); - - if (!option.asi) - nolinebreak(this); - - if (nexttoken.id !== ";") { - if (token.line === nexttoken.line) { - if (funct[v] !== "label") { - warning("'{a}' is not a statement label.", nexttoken, v); - } else if (scope[v] !== funct) { - warning("'{a}' is out of scope.", nexttoken, v); - } - this.first = nexttoken; - advance(); - } - } - reachable("break"); - return this; - }).exps = true; - - - stmt("continue", function () { - var v = nexttoken.value; - - if (funct["(breakage)"] === 0) - warning("Unexpected '{a}'.", nexttoken, this.value); - - if (!option.asi) - nolinebreak(this); - - if (nexttoken.id !== ";") { - if (token.line === nexttoken.line) { - if (funct[v] !== "label") { - warning("'{a}' is not a statement label.", nexttoken, v); - } else if (scope[v] !== funct) { - warning("'{a}' is out of scope.", nexttoken, v); - } - this.first = nexttoken; - advance(); - } - } else if (!funct["(loopage)"]) { - warning("Unexpected '{a}'.", nexttoken, this.value); - } - reachable("continue"); - return this; - }).exps = true; - - - stmt("return", function () { - if (this.line === nexttoken.line) { - if (nexttoken.id === "(regexp)") - warning("Wrap the /regexp/ literal in parens to disambiguate the slash operator."); - - if (nexttoken.id !== ";" && !nexttoken.reach) { - nonadjacent(token, nexttoken); - if (peek().value === "=" && !option.boss) { - warningAt("Did you mean to return a conditional instead of an assignment?", - token.line, token.character + 1); - } - this.first = expression(0); - } - } else if (!option.asi) { - nolinebreak(this); // always warn (Line breaking error) - } - reachable("return"); - return this; - }).exps = true; - - - stmt("throw", function () { - nolinebreak(this); - nonadjacent(token, nexttoken); - this.first = expression(20); - reachable("throw"); - return this; - }).exps = true; - -// Superfluous reserved words - - reserve("class"); - reserve("const"); - reserve("enum"); - reserve("export"); - reserve("extends"); - reserve("import"); - reserve("super"); - - reserve("let"); - reserve("yield"); - reserve("implements"); - reserve("interface"); - reserve("package"); - reserve("private"); - reserve("protected"); - reserve("public"); - reserve("static"); - - -// Parse JSON - - function jsonValue() { - - function jsonObject() { - var o = {}, t = nexttoken; - advance("{"); - if (nexttoken.id !== "}") { - for (;;) { - if (nexttoken.id === "(end)") { - error("Missing '}' to match '{' from line {a}.", - nexttoken, t.line); - } else if (nexttoken.id === "}") { - warning("Unexpected comma.", token); - break; - } else if (nexttoken.id === ",") { - error("Unexpected comma.", nexttoken); - } else if (nexttoken.id !== "(string)") { - warning("Expected a string and instead saw {a}.", - nexttoken, nexttoken.value); - } - if (o[nexttoken.value] === true) { - warning("Duplicate key '{a}'.", - nexttoken, nexttoken.value); - } else if ((nexttoken.value === "__proto__" && - !option.proto) || (nexttoken.value === "__iterator__" && - !option.iterator)) { - warning("The '{a}' key may produce unexpected results.", - nexttoken, nexttoken.value); - } else { - o[nexttoken.value] = true; - } - advance(); - advance(":"); - jsonValue(); - if (nexttoken.id !== ",") { - break; - } - advance(","); - } - } - advance("}"); - } - - function jsonArray() { - var t = nexttoken; - advance("["); - if (nexttoken.id !== "]") { - for (;;) { - if (nexttoken.id === "(end)") { - error("Missing ']' to match '[' from line {a}.", - nexttoken, t.line); - } else if (nexttoken.id === "]") { - warning("Unexpected comma.", token); - break; - } else if (nexttoken.id === ",") { - error("Unexpected comma.", nexttoken); - } - jsonValue(); - if (nexttoken.id !== ",") { - break; - } - advance(","); - } - } - advance("]"); - } - - switch (nexttoken.id) { - case "{": - jsonObject(); - break; - case "[": - jsonArray(); - break; - case "true": - case "false": - case "null": - case "(number)": - case "(string)": - advance(); - break; - case "-": - advance("-"); - if (token.character !== nexttoken.from) { - warning("Unexpected space after '-'.", token); - } - adjacent(token, nexttoken); - advance("(number)"); - break; - default: - error("Expected a JSON value.", nexttoken); - } - } - - - // The actual JSHINT function itself. - var itself = function (s, o, g) { - var a, i, k, x; - var optionKeys; - var newOptionObj = {}; - - if (o && o.scope) { - JSHINT.scope = o.scope; - } else { - JSHINT.errors = []; - JSHINT.undefs = []; - JSHINT.internals = []; - JSHINT.blacklist = {}; - JSHINT.scope = "(main)"; - } - - predefined = Object.create(standard); - declared = Object.create(null); - combine(predefined, g || {}); - - if (o) { - a = o.predef; - if (a) { - if (!Array.isArray(a) && typeof a === "object") { - a = Object.keys(a); - } - a.forEach(function (item) { - var slice; - if (item[0] === "-") { - slice = item.slice(1); - JSHINT.blacklist[slice] = slice; - } else { - predefined[item] = true; - } - }); - } - - optionKeys = Object.keys(o); - for (x = 0; x < optionKeys.length; x++) { - newOptionObj[optionKeys[x]] = o[optionKeys[x]]; - - if (optionKeys[x] === "newcap" && o[optionKeys[x]] === false) - newOptionObj["(explicitNewcap)"] = true; - - if (optionKeys[x] === "indent") - newOptionObj.white = true; - } - } - - option = newOptionObj; - - option.indent = option.indent || 4; - option.maxerr = option.maxerr || 50; - - tab = ""; - for (i = 0; i < option.indent; i += 1) { - tab += " "; - } - indent = 1; - global = Object.create(predefined); - scope = global; - funct = { - "(global)": true, - "(name)": "(global)", - "(scope)": scope, - "(breakage)": 0, - "(loopage)": 0, - "(tokens)": {}, - "(metrics)": createMetrics(nexttoken) - }; - functions = [funct]; - urls = []; - stack = null; - member = {}; - membersOnly = null; - implied = {}; - inblock = false; - lookahead = []; - jsonmode = false; - warnings = 0; - lines = []; - unuseds = []; - - if (!isString(s) && !Array.isArray(s)) { - errorAt("Input is neither a string nor an array of strings.", 0); - return false; - } - - if (isString(s) && /^\s*$/g.test(s)) { - errorAt("Input is an empty string.", 0); - return false; - } - - if (s.length === 0) { - errorAt("Input is an empty array.", 0); - return false; - } - - lex.init(s); - - prereg = true; - directive = {}; - - prevtoken = token = nexttoken = syntax["(begin)"]; - - // Check options - for (var name in o) { - if (is_own(o, name)) { - checkOption(name, token); - } - } - - assume(); - - // combine the passed globals after we've assumed all our options - combine(predefined, g || {}); - - //reset values - comma.first = true; - quotmark = undefined; - - try { - advance(); - switch (nexttoken.id) { - case "{": - case "[": - option.laxbreak = true; - jsonmode = true; - jsonValue(); - break; - default: - directives(); - if (directive["use strict"] && !option.globalstrict) { - warning("Use the function form of \"use strict\".", prevtoken); - } - - statements(); - } - advance((nexttoken && nexttoken.value !== ".") ? "(end)" : undefined); - - var markDefined = function (name, context) { - do { - if (typeof context[name] === "string") { - // JSHINT marks unused variables as 'unused' and - // unused function declaration as 'unction'. This - // code changes such instances back 'var' and - // 'closure' so that the code in JSHINT.data() - // doesn't think they're unused. - - if (context[name] === "unused") - context[name] = "var"; - else if (context[name] === "unction") - context[name] = "closure"; - - return true; - } - - context = context["(context)"]; - } while (context); - - return false; - }; - - var clearImplied = function (name, line) { - if (!implied[name]) - return; - - var newImplied = []; - for (var i = 0; i < implied[name].length; i += 1) { - if (implied[name][i] !== line) - newImplied.push(implied[name][i]); - } - - if (newImplied.length === 0) - delete implied[name]; - else - implied[name] = newImplied; - }; - - var warnUnused = function (name, token) { - var line = token.line; - var chr = token.character; - - if (option.unused) - warningAt("'{a}' is defined but never used.", line, chr, name); - - unuseds.push({ - name: name, - line: line, - character: chr - }); - }; - - var checkUnused = function (func, key) { - var type = func[key]; - var token = func["(tokens)"][key]; - - if (key.charAt(0) === "(") - return; - - if (type !== "unused" && type !== "unction") - return; - - // Params are checked separately from other variables. - if (func["(params)"] && func["(params)"].indexOf(key) !== -1) - return; - - warnUnused(key, token); - }; - - // Check queued 'x is not defined' instances to see if they're still undefined. - for (i = 0; i < JSHINT.undefs.length; i += 1) { - k = JSHINT.undefs[i].slice(0); - - if (markDefined(k[2].value, k[0])) { - clearImplied(k[2].value, k[2].line); - } else { - warning.apply(warning, k.slice(1)); - } - } - - functions.forEach(function (func) { - for (var key in func) { - if (is_own(func, key)) { - checkUnused(func, key); - } - } - - if (!func["(params)"]) - return; - - var params = func["(params)"].slice(); - var param = params.pop(); - var type; - - while (param) { - type = func[param]; - - // 'undefined' is a special case for (function (window, undefined) { ... })(); - // patterns. - - if (param === "undefined") - return; - - if (type !== "unused" && type !== "unction") - return; - - warnUnused(param, func["(tokens)"][param]); - param = params.pop(); - } - }); - - for (var key in declared) { - if (is_own(declared, key) && !is_own(global, key)) { - warnUnused(key, declared[key]); - } - } - } catch (e) { - if (e) { - var nt = nexttoken || {}; - JSHINT.errors.push({ - raw : e.raw, - reason : e.message, - line : e.line || nt.line, - character : e.character || nt.from - }, null); - } - } - - // Loop over the listed "internals", and check them as well. - - if (JSHINT.scope === "(main)") { - o = o || {}; - - for (i = 0; i < JSHINT.internals.length; i += 1) { - k = JSHINT.internals[i]; - o.scope = k.elem; - itself(k.value, o, g); - } - } - - return JSHINT.errors.length === 0; - }; - - // Data summary. - itself.data = function () { - var data = { - functions: [], - options: option - }; - var implieds = []; - var members = []; - var fu, f, i, j, n, globals; - - if (itself.errors.length) { - data.errors = itself.errors; - } - - if (jsonmode) { - data.json = true; - } - - for (n in implied) { - if (is_own(implied, n)) { - implieds.push({ - name: n, - line: implied[n] - }); - } - } - - if (implieds.length > 0) { - data.implieds = implieds; - } - - if (urls.length > 0) { - data.urls = urls; - } - - globals = Object.keys(scope); - if (globals.length > 0) { - data.globals = globals; - } - - for (i = 1; i < functions.length; i += 1) { - f = functions[i]; - fu = {}; - - for (j = 0; j < functionicity.length; j += 1) { - fu[functionicity[j]] = []; - } - - for (j = 0; j < functionicity.length; j += 1) { - if (fu[functionicity[j]].length === 0) { - delete fu[functionicity[j]]; - } - } - - fu.name = f["(name)"]; - fu.param = f["(params)"]; - fu.line = f["(line)"]; - fu.character = f["(character)"]; - fu.last = f["(last)"]; - fu.lastcharacter = f["(lastcharacter)"]; - data.functions.push(fu); - } - - if (unuseds.length > 0) { - data.unused = unuseds; - } - - members = []; - for (n in member) { - if (typeof member[n] === "number") { - data.member = member; - break; - } - } - - return data; - }; - - itself.jshint = itself; - - return itself; -}()); - -// Make JSHINT a Node module, if possible. -if (typeof exports === "object" && exports) { - exports.JSHINT = JSHINT; -} diff --git a/node/node_modules/grunt/node_modules/lodash/LICENSE.txt b/node/node_modules/grunt/node_modules/lodash/LICENSE.txt new file mode 100644 index 000000000..b194ad1de --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/LICENSE.txt @@ -0,0 +1,22 @@ +Copyright 2012 John-David Dalton +Based on Underscore.js 1.3.3, copyright 2009-2012 Jeremy Ashkenas, +DocumentCloud Inc. + +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/node_modules/grunt/node_modules/lodash/README.md b/node/node_modules/grunt/node_modules/lodash/README.md new file mode 100644 index 000000000..cde0ebb99 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/README.md @@ -0,0 +1,247 @@ +# Lo-Dash v0.9.2 +[![build status](https://secure.travis-ci.org/bestiejs/lodash.png)](http://travis-ci.org/bestiejs/lodash) + +A drop-in replacement[*](https://github.com/bestiejs/lodash/wiki/Drop-in-Disclaimer) for Underscore.js, from the devs behind [jsPerf.com](http://jsperf.com), delivering [performance](http://lodash.com/benchmarks), [bug fixes](https://github.com/bestiejs/lodash#resolved-underscorejs-issues), and [additional features](http://lodash.com/#features). + +Lo-Dash’s performance is gained by avoiding slower native methods, instead opting for simplified non-ES5 compliant methods optimized for common usage, and by leveraging function compilation to reduce the number of overall function calls. + +## Download + + * [Development build](https://raw.github.com/bestiejs/lodash/v0.9.2/lodash.js) + * [Production build](https://raw.github.com/bestiejs/lodash/v0.9.2/lodash.min.js) + * [Underscore build](https://raw.github.com/bestiejs/lodash/v0.9.2/lodash.underscore.min.js) tailored for projects already using Underscore + * CDN copies of ≤ v0.9.2’s [Production](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.9.2/lodash.min.js), [Underscore](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.9.2/lodash.underscore.min.js), and [Development](http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.9.2/lodash.js) builds are available on [cdnjs](http://cdnjs.com/) thanks to [CloudFlare](http://www.cloudflare.com/) + * For optimal file size, [create a custom build](https://github.com/bestiejs/lodash#custom-builds) with only the features you need + +## Dive in + +We’ve got [API docs](http://lodash.com/docs), [benchmarks](http://lodash.com/benchmarks), and [unit tests](http://lodash.com/tests). + +Create your own benchmarks at [jsPerf](http://jsperf.com), or [search](http://jsperf.com/search?q=lodash) for existing ones. + +For a list of upcoming features, check out our [roadmap](https://github.com/bestiejs/lodash/wiki/Roadmap). + +## Screencasts + +For more information check out these screencasts over Lo-Dash: + + * [Introducing Lo-Dash](https://vimeo.com/44154599) + * [Lo-Dash optimizations and custom builds](https://vimeo.com/44154601) + * [Lo-Dash’s origin and why it’s a better utility belt](https://vimeo.com/44154600) + * [Unit testing in Lo-Dash](https://vimeo.com/45865290) + * [Lo-Dash’s approach to native method use](https://vimeo.com/48576012) + +## Features + + * AMD loader support ([RequireJS](http://requirejs.org/), [curl.js](https://github.com/cujojs/curl), etc.) + * [_.clone](http://lodash.com/docs#clone) supports *“deep”* cloning + * [_.contains](http://lodash.com/docs#contains) accepts a `fromIndex` argument + * [_.forEach](http://lodash.com/docs#forEach) is chainable and supports exiting iteration early + * [_.forIn](http://lodash.com/docs#forIn) for iterating over an object’s own and inherited properties + * [_.forOwn](http://lodash.com/docs#forOwn) for iterating over an object’s own properties + * [_.isPlainObject](http://lodash.com/docs#isPlainObject) checks if values are created by the `Object` constructor + * [_.lateBind](http://lodash.com/docs#lateBind) for late binding + * [_.merge](http://lodash.com/docs#merge) for a *“deep”* [_.extend](http://lodash.com/docs#extend) + * [_.partial](http://lodash.com/docs#partial) for partial application without `this` binding + * [_.pick](http://lodash.com/docs#pick) and [_.omit](http://lodash.com/docs#omit) accepts `callback` and `thisArg` arguments + * [_.template](http://lodash.com/docs#template) supports [ES6 delimiters](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6) and utilizes [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) for easier debugging + * [_.contains](http://lodash.com/docs#contains), [_.size](http://lodash.com/docs#size), [_.toArray](http://lodash.com/docs#toArray), + [and more…](http://lodash.com/docs "_.countBy, _.every, _.filter, _.find, _.forEach, _.groupBy, _.invoke, _.map, _.max, _.min, _.pluck, _.reduce, _.reduceRight, _.reject, _.shuffle, _.some, _.sortBy, _.where") accept strings + +## Support + +Lo-Dash has been tested in at least Chrome 5~23, Firefox 1~16, IE 6-10, Opera 9.25-12, Safari 3-6, Node.js 0.4.8-0.8.14, Narwhal 0.3.2, RingoJS 0.8, and Rhino 1.7RC5. + +## Custom builds + +Custom builds make it easy to create lightweight versions of Lo-Dash containing only the methods you need. +To top it off, we handle all method dependency and alias mapping for you. + + * Backbone builds, with only methods required by Backbone, may be created using the `backbone` modifier argument. +```bash +lodash backbone +``` + + * CSP builds, supporting default Content Security Policy restrictions, may be created using the `csp` modifier argument. +```bash +lodash csp +``` + + * Legacy builds, tailored for older browsers without [ES5 support](http://es5.github.com/), may be created using the `legacy` modifier argument. +```bash +lodash legacy +``` + + * Mobile builds, with IE < 9 bug fixes and method compilation removed, may be created using the `mobile` modifier argument. +```bash +lodash mobile +``` + + * Strict builds, with `_.bindAll`, `_.defaults`, and `_.extend` in [strict mode](http://es5.github.com/#C), may be created using the `strict` modifier argument. +```bash +lodash strict +``` + + * Underscore builds, tailored for projects already using Underscore, may be created using the `underscore` modifier argument. +```bash +lodash underscore +``` + +Custom builds may be created using the following commands: + + * Use the `category` argument to pass comma separated categories of methods to include in the build.
      + Valid categories (case-insensitive) are *“arrays”*, *“chaining”*, *“collections”*, *“functions”*, *“objects”*, and *“utilities”*. +```bash +lodash category=collections,functions +lodash category="collections, functions" +``` + + * Use the `exports` argument to pass comma separated names of ways to export the `LoDash` function.
      + Valid exports are *“amd”*, *“commonjs”*, *“global”*, *“node”*, and *“none”*. +```bash +lodash exports=amd,commonjs,node +lodash exports="amd, commonjs, node" +``` + + * Use the `iife` argument to specify code to replace the immediately-invoked function expression that wraps Lo-Dash. +```bash +lodash iife="!function(window,undefined){%output%}(this)" +``` + + * Use the `include` argument to pass comma separated method/category names to include in the build. +```bash +lodash include=each,filter,map +lodash include="each, filter, map" +``` + + * Use the `minus` argument to pass comma separated method/category names to remove from those included in the build. +```bash +lodash underscore minus=result,shuffle +lodash underscore minus="result, shuffle" +``` + + * Use the `plus` argument to pass comma separated method/category names to add to those included in the build. +```bash +lodash backbone plus=random,template +lodash backbone plus="random, template" +``` + + * Use the `template` argument to pass the file path pattern used to match template files to precompile. +```bash +lodash template="./*.jst" +``` + + * Use the `settings` argument to pass the template settings used when precompiling templates. +```bash +lodash settings="{interpolate:/\\{\\{([\\s\\S]+?)\\}\\}/g}" +``` + + * Use the `moduleId` argument to specify the AMD module ID of Lo-Dash, which defaults to “lodash”, used by precompiled templates. +```bash +lodash moduleId="underscore" +``` + +All arguments, except `legacy` with `csp` or `mobile`, may be combined.
      +Unless specified by `-o` or `--output`, all files created are saved to the current working directory. + +The following options are also supported: + + * `-c`, `--stdout`     Write output to standard output + * `-d`, `--debug`       Write only the debug output + * `-h`, `--help`         Display help information + * `-m`, `--minify`     Write only the minified output + * `-o`, `--output`     Write output to a given path/filename + * `-s`, `--silent`     Skip status updates normally logged to the console + * `-V`, `--version`   Output current version of Lo-Dash + +The `lodash` command-line utility is available when Lo-Dash is installed as a global package (i.e. `npm install -g lodash`). + +## Installation and usage + +In browsers: + +```html + +``` + +Using [npm](http://npmjs.org/): + +```bash +npm install lodash + +npm install -g lodash +npm link lodash +``` + +In [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/): + +```js +var _ = require('lodash'); +``` + +**Note:** If Lo-Dash is installed globally, [run `npm link lodash`](http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/) in your project’s root directory before requiring it. + +In [RingoJS v0.7.0-](http://ringojs.org/): + +```js +var _ = require('lodash')._; +``` + +In [Rhino](http://www.mozilla.org/rhino/): + +```js +load('lodash.js'); +``` + +In an AMD loader like [RequireJS](http://requirejs.org/): + +```js +require({ + 'paths': { + 'underscore': 'path/to/lodash' + } +}, +['underscore'], function(_) { + console.log(_.VERSION); +}); +``` + +## Resolved Underscore.js issues + + * Allow iteration of objects with a `length` property [[#799](https://github.com/documentcloud/underscore/pull/799), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L545-551)] + * Fix cross-browser object iteration bugs [[#60](https://github.com/documentcloud/underscore/issues/60), [#376](https://github.com/documentcloud/underscore/issues/376), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L558-582)] + * Methods should work on pages with incorrectly shimmed native methods [[#7](https://github.com/documentcloud/underscore/issues/7), [#742](https://github.com/documentcloud/underscore/issues/742), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L140-146)] + * `_.isEmpty` should support jQuery/MooTools DOM query collections [[#690](https://github.com/documentcloud/underscore/pull/690), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L747-752)] + * `_.isObject` should avoid V8 bug [#2291](http://code.google.com/p/v8/issues/detail?id=2291) [[#605](https://github.com/documentcloud/underscore/issues/605), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L828-840)] + * `_.keys` should work with `arguments` objects cross-browser [[#396](https://github.com/documentcloud/underscore/issues/396), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L921-923)] + * `_.range` should coerce arguments to numbers [[#634](https://github.com/documentcloud/underscore/issues/634), [#683](https://github.com/documentcloud/underscore/issues/683), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L1337-1340)] + +## Release Notes + +### v0.9.2 + + * Added `fromIndex` argument to `_.contains` + * Added `moduleId` build option + * Added Closure Compiler *“simple”* optimizations to the build process + * Added support for strings in `_.max` and `_.min` + * Added support for ES6 template delimiters to `_.template` + * Ensured re-minification of Lo-Dash by third parties avoids Closure Compiler bugs + * Optimized `_.every`, `_.find`, `_.some`, and `_.uniq` + +The full changelog is available [here](https://github.com/bestiejs/lodash/wiki/Changelog). + +## BestieJS + +Lo-Dash is part of the BestieJS *“Best in Class”* module collection. This means we promote solid browser/environment support, ES5 precedents, unit testing, and plenty of documentation. + +## Author + +* [John-David Dalton](http://allyoucanleet.com/) + [![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") + +## Contributors + +* [Kit Cambridge](http://kitcambridge.github.com/) + [![twitter/kitcambridge](http://gravatar.com/avatar/6662a1d02f351b5ef2f8b4d815804661?s=70)](https://twitter.com/kitcambridge "Follow @kitcambridge on Twitter") +* [Mathias Bynens](http://mathiasbynens.be/) + [![twitter/mathias](http://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") diff --git a/node/node_modules/grunt/node_modules/lodash/build.js b/node/node_modules/grunt/node_modules/lodash/build.js new file mode 100755 index 000000000..af116d555 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/build.js @@ -0,0 +1,1736 @@ +#!/usr/bin/env node +;(function() { + 'use strict'; + + /** Load modules */ + var fs = require('fs'), + path = require('path'), + vm = require('vm'), + minify = require(path.join(__dirname, 'build', 'minify.js')), + _ = require(path.join(__dirname, 'lodash.js')); + + /** The current working directory */ + var cwd = process.cwd(); + + /** Used for array method references */ + var arrayRef = []; + + /** Shortcut used to push arrays of values to an array */ + var push = arrayRef.push; + + /** Shortcut used to convert array-like objects to arrays */ + var slice = arrayRef.slice; + + /** Shortcut to the `stdout` object */ + var stdout = process.stdout; + + /** Used to associate aliases with their real names */ + var aliasToRealMap = { + 'all': 'every', + 'any': 'some', + 'collect': 'map', + 'detect': 'find', + 'drop': 'rest', + 'each': 'forEach', + 'foldl': 'reduce', + 'foldr': 'reduceRight', + 'head': 'first', + 'include': 'contains', + 'inject': 'reduce', + 'methods': 'functions', + 'select': 'filter', + 'tail': 'rest', + 'take': 'first', + 'unique': 'uniq' + }; + + /** Used to associate real names with their aliases */ + var realToAliasMap = { + 'contains': ['include'], + 'every': ['all'], + 'filter': ['select'], + 'find': ['detect'], + 'first': ['head', 'take'], + 'forEach': ['each'], + 'functions': ['methods'], + 'map': ['collect'], + 'reduce': ['foldl', 'inject'], + 'reduceRight': ['foldr'], + 'rest': ['drop', 'tail'], + 'some': ['any'], + 'uniq': ['unique'] + }; + + /** Used to track function dependencies */ + var dependencyMap = { + 'after': [], + 'bind': ['isFunction', 'isObject'], + 'bindAll': ['bind', 'functions'], + 'chain': ['mixin'], + 'clone': ['extend', 'forEach', 'forOwn', 'isArguments', 'isObject', 'isPlainObject'], + 'compact': [], + 'compose': [], + 'contains': ['indexOf', 'isString', 'some'], + 'countBy': ['forEach'], + 'debounce': [], + 'defaults': ['isArguments'], + 'defer': [], + 'delay': [], + 'difference': ['indexOf'], + 'escape': [], + 'every': ['forEach', 'isArray'], + 'extend': ['isArguments'], + 'filter': ['forEach'], + 'find': ['forEach'], + 'first': [], + 'flatten': ['isArray'], + 'forEach': ['identity', 'isString'], + 'forIn': ['identity', 'isArguments'], + 'forOwn': ['identity', 'isArguments'], + 'functions': ['forIn', 'isFunction'], + 'groupBy': ['forEach'], + 'has': [], + 'identity': [], + 'indexOf': ['sortedIndex'], + 'initial': [], + 'intersection': ['filter', 'indexOf'], + 'invert': ['forOwn'], + 'invoke': ['forEach'], + 'isArguments': [], + 'isArray': [], + 'isBoolean': [], + 'isDate': [], + 'isElement': [], + 'isEmpty': ['forOwn', 'isArguments', 'isFunction'], + 'isEqual': ['isArguments', 'isFunction'], + 'isFinite': [], + 'isFunction': [], + 'isNaN': [], + 'isNull': [], + 'isNumber': [], + 'isObject': [], + 'isPlainObject': ['forIn', 'isArguments', 'isFunction'], + 'isRegExp': [], + 'isString': [], + 'isUndefined': [], + 'keys': ['forOwn', 'isArguments', 'isObject'], + 'last': [], + 'lastIndexOf': [], + 'lateBind': ['isFunction', 'isObject'], + 'map': ['forEach', 'isArray'], + 'max': ['forEach', 'isArray', 'isString'], + 'memoize': [], + 'merge': ['forOwn', 'isArray', 'isPlainObject'], + 'min': ['forEach', 'isArray', 'isString'], + 'mixin': ['forEach', 'functions'], + 'noConflict': [], + 'object': [], + 'omit': ['forIn', 'indexOf'], + 'once': [], + 'pairs': ['forOwn'], + 'partial': ['isFunction', 'isObject'], + 'pick': ['forIn'], + 'pluck': ['forEach'], + 'random': [], + 'range': [], + 'reduce': ['forEach'], + 'reduceRight': ['forEach', 'isString', 'keys'], + 'reject': ['filter'], + 'rest': [], + 'result': ['isFunction'], + 'shuffle': ['forEach'], + 'size': ['keys'], + 'some': ['forEach', 'isArray'], + 'sortBy': ['forEach'], + 'sortedIndex': ['identity'], + 'tap': ['mixin'], + 'template': ['escape'], + 'throttle': [], + 'times': [], + 'toArray': ['values'], + 'unescape': [], + 'union': ['uniq'], + 'uniq': ['identity', 'indexOf'], + 'uniqueId': [], + 'value': ['mixin'], + 'values': ['forOwn'], + 'where': ['filter', 'forIn'], + 'without': ['indexOf'], + 'wrap': [], + 'zip': ['max', 'pluck'] + }; + + /** Used to inline `iteratorTemplate` */ + var iteratorOptions = [ + 'args', + 'arrayLoop', + 'bottom', + 'firstArg', + 'hasDontEnumBug', + 'isKeysFast', + 'objectLoop', + 'noArgsEnum', + 'noCharByIndex', + 'shadowed', + 'top', + 'useHas', + 'useStrict' + ]; + + /** List of all Lo-Dash methods */ + var allMethods = _.keys(dependencyMap); + + /** List Backbone's Lo-Dash dependencies */ + var backboneDependencies = [ + 'bind', + 'bindAll', + 'clone', + 'contains', + 'escape', + 'every', + 'extend', + 'filter', + 'find', + 'first', + 'forEach', + 'groupBy', + 'has', + 'indexOf', + 'initial', + 'invoke', + 'isArray', + 'isEmpty', + 'isEqual', + 'isFunction', + 'isObject', + 'isRegExp', + 'keys', + 'last', + 'lastIndexOf', + 'lateBind', + 'map', + 'max', + 'min', + 'mixin', + 'reduce', + 'reduceRight', + 'reject', + 'rest', + 'result', + 'shuffle', + 'size', + 'some', + 'sortBy', + 'sortedIndex', + 'toArray', + 'uniqueId', + 'without' + ]; + + /** List of methods used by Underscore */ + var underscoreMethods = _.without.apply(_, [allMethods].concat([ + 'forIn', + 'forOwn', + 'isPlainObject', + 'lateBind', + 'merge', + 'partial' + ])); + + /** List of ways to export the `lodash` function */ + var exportsAll = [ + 'amd', + 'commonjs', + 'global', + 'node' + ]; + + /*--------------------------------------------------------------------------*/ + + /** + * Compiles template files matched by the given file path `pattern` into a + * single source, extending `_.templates` with precompiled templates named after + * each template file's basename. + * + * @private + * @param {String} [pattern='/*.jst'] The file path pattern. + * @param {Object} options The options object. + * @returns {String} Returns the compiled source. + */ + function buildTemplate(pattern, options) { + pattern || (pattern = path.join(cwd, '*.jst')); + + var directory = path.dirname(pattern); + + var source = [ + ';(function(window) {', + " var freeExports = typeof exports == 'object' && exports &&", + " (typeof global == 'object' && global && global == global.global && (window = global), exports);", + '', + ' var templates = {},', + ' _ = window._;', + '' + ]; + + // convert to a regexp + pattern = RegExp( + path.basename(pattern) + .replace(/[.+?^=!:${}()|[\]\/\\]/g, '\\$&') + .replace(/\*/g, '.*?') + '$' + ); + + fs.readdirSync(directory).forEach(function(filename) { + var filePath = path.join(directory, filename); + if (pattern.test(filename)) { + var text = fs.readFileSync(filePath, 'utf8'), + precompiled = getFunctionSource(_.template(text, null, options)), + prop = filename.replace(/\..*$/, ''); + + source.push(" templates['" + prop.replace(/'/g, "\\'") + "'] = " + precompiled + ';', ''); + } + }); + + source.push( + " if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {", + " define(['" + options.moduleId + "'], function(lodash) {", + ' lodash.templates = lodash.extend(lodash.templates || {}, templates);', + ' });', + " } else if (freeExports) {", + " if (typeof module == 'object' && module && module.exports == freeExports) {", + ' (module.exports = templates).templates = templates;', + ' } else {', + ' freeExports.templates = templates;', + ' }', + ' } else if (_) {', + ' _.templates = _.extend(_.templates || {}, templates);', + ' }', + '}(this));' + ); + + return source.join('\n'); + } + + /** + * Removes unnecessary comments, whitespace, and pseudo private properties. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function cleanupSource(source) { + return source + // remove pseudo private properties + .replace(/(?:(?:\s*\/\/.*)*\s*lodash\._[^=]+=.+\n)+/g, '\n') + // remove lines with just whitespace and semicolons + .replace(/^ *;\n/gm, '') + // consolidate consecutive horizontal rule comment separators + .replace(/(?:\s*\/\*-+\*\/\s*){2,}/g, function(separators) { + return separators.match(/^\s*/)[0] + separators.slice(separators.lastIndexOf('/*')); + }); + } + + /** + * Writes the help message to standard output. + * + * @private + */ + function displayHelp() { + console.log([ + '', + ' Commands:', + '', + ' lodash backbone Build with only methods required by Backbone', + ' lodash csp Build supporting default Content Security Policy restrictions', + ' lodash legacy Build tailored for older browsers without ES5 support', + ' lodash mobile Build with IE < 9 bug fixes & method compilation removed', + ' lodash strict Build with `_.bindAll`, `_.defaults`, & `_.extend` in strict mode', + ' lodash underscore Build tailored for projects already using Underscore', + ' lodash include=... Comma separated method/category names to include in the build', + ' lodash minus=... Comma separated method/category names to remove from those included in the build', + ' lodash plus=... Comma separated method/category names to add to those included in the build', + ' lodash category=... Comma separated categories of methods to include in the build (case-insensitive)', + ' (i.e. “arrays”, “chaining”, “collections”, “functions”, “objects”, and “utilities”)', + ' lodash exports=... Comma separated names of ways to export the `lodash` function', + ' (i.e. “amd”, “commonjs”, “global”, “node”, and “none”)', + ' lodash iife=... Code to replace the immediately-invoked function expression that wraps Lo-Dash', + ' (e.g. `lodash iife="!function(window,undefined){%output%}(this)"`)', + '', + ' lodash template=... File path pattern used to match template files to precompile', + ' (e.g. `lodash template=./*.jst`)', + ' lodash settings=... Template settings used when precompiling templates', + ' (e.g. `lodash settings="{interpolate:/\\\\{\\\\{([\\\\s\\\\S]+?)\\\\}\\\\}/g}"`)', + ' lodash moduleId=... The AMD module ID of Lo-Dash, which defaults to “lodash”, used by precompiled templates', + '', + ' All arguments, except `legacy` with `csp` or `mobile`, may be combined.', + ' Unless specified by `-o` or `--output`, all files created are saved to the current working directory.', + '', + ' Options:', + '', + ' -c, --stdout Write output to standard output', + ' -d, --debug Write only the debug output', + ' -h, --help Display help information', + ' -m, --minify Write only the minified output', + ' -o, --output Write output to a given path/filename', + ' -s, --silent Skip status updates normally logged to the console', + ' -V, --version Output current version of Lo-Dash', + '' + ].join('\n')); + } + + /** + * Gets the aliases associated with a given function name. + * + * @private + * @param {String} methodName The name of the method to get aliases for. + * @returns {Array} Returns an array of aliases. + */ + function getAliases(methodName) { + return realToAliasMap[methodName] || []; + } + + /** + * Gets the Lo-Dash method assignments snippet from `source`. + * + * @private + * @param {String} source The source to inspect. + * @returns {String} Returns the method assignments snippet. + */ + function getMethodAssignments(source) { + return (source.match(/lodash\.VERSION *= *[\s\S]+?\/\*-+\*\/\n/) || [''])[0]; + } + + /** + * Gets an array of depenants for a method by a given name. + * + * @private + * @param {String} methodName The name of the method to query. + * @returns {Array} Returns an array of method dependants. + */ + function getDependants(methodName) { + // iterate over the `dependencyMap`, adding the names of methods that + // have `methodName` as a dependency + return _.reduce(dependencyMap, function(result, dependencies, otherName) { + if (_.contains(dependencies, methodName)) { + result.push(otherName); + } + return result; + }, []); + } + + /** + * Gets an array of dependencies for a given method name. If passed an array + * of dependencies it will return an array containing the given dependencies + * plus any additional detected sub-dependencies. + * + * @private + * @param {Array|String} methodName A single method name or array of + * dependencies to query. + * @returns {Array} Returns an array of method dependencies. + */ + function getDependencies(methodName) { + var dependencies = Array.isArray(methodName) ? methodName : dependencyMap[methodName]; + if (!dependencies) { + return []; + } + // recursively accumulate the dependencies of the `methodName` function, and + // the dependencies of its dependencies, and so on. + return _.uniq(dependencies.reduce(function(result, otherName) { + result.push.apply(result, getDependencies(otherName).concat(otherName)); + return result; + }, [])); + } + + /** + * Gets the formatted source of the given function. + * + * @private + * @param {Function} func The function to process. + * @returns {String} Returns the formatted source. + */ + function getFunctionSource(func) { + var source = func.source || (func + ''); + + // format leading whitespace + return source.replace(/\n(?:.*)/g, function(match, index) { + match = match.slice(1); + return ( + match == '}' && source.indexOf('}', index + 2) == -1 ? '\n ' : '\n ' + ) + match; + }); + } + + /** + * Gets the `_.isArguments` fallback from `source`. + * + * @private + * @param {String} source The source to inspect. + * @returns {String} Returns the `isArguments` fallback. + */ + function getIsArgumentsFallback(source) { + return (source.match(/(?:\s*\/\/.*)*\n( *)if *\(noArgsClass\)[\s\S]+?};\n\1}/) || [''])[0]; + } + + /** + * Gets the `_.isFunction` fallback from `source`. + * + * @private + * @param {String} source The source to inspect. + * @returns {String} Returns the `isFunction` fallback. + */ + function getIsFunctionFallback(source) { + return (source.match(/(?:\s*\/\/.*)*\n( *)if *\(isFunction\(\/x\/[\s\S]+?};\n\1}/) || [''])[0]; + } + + /** + * Gets the names of methods in `source` belonging to the given `category`. + * + * @private + * @param {String} source The source to inspect. + * @param {String} category The category to filter by. + * @returns {Array} Returns a new array of method names belonging to the given category. + */ + function getMethodsByCategory(source, category) { + return allMethods.filter(function(methodName) { + return category && RegExp('@category ' + category + '\\b').test(matchFunction(source, methodName)); + }); + } + + /** + * Gets the real name, not alias, of a given method name. + * + * @private + * @param {String} methodName The name of the method to resolve. + * @returns {String} Returns the real method name. + */ + function getRealName(methodName) { + return aliasToRealMap[methodName] || methodName; + } + + /** + * Determines if all functions of the given names have been removed from `source`. + * + * @private + * @param {String} source The source to inspect. + * @param {String} [funcName1, funcName2, ...] The names of functions to check. + * @returns {Boolean} Returns `true` if all functions have been removed, else `false`. + */ + function isRemoved(source) { + return slice.call(arguments, 1).every(function(funcName) { + return !matchFunction(source, funcName); + }); + } + + /** + * Searches `source` for a `funcName` function declaration, expression, or + * assignment and returns the matched snippet. + * + * @private + * @param {String} source The source to inspect. + * @param {String} funcName The name of the function to match. + * @returns {String} Returns the matched function snippet. + */ + function matchFunction(source, funcName) { + var result = source.match(RegExp( + // match multi-line comment block (could be on a single line) + '(?:\\n +/\\*[^*]*\\*+(?:[^/][^*]*\\*+)*/\\n)?' + + // begin non-capturing group + '(?:' + + // match a function declaration + '( *)function ' + funcName + '\\b[\\s\\S]+?\\n\\1}|' + + // match a variable declaration with `createIterator` + ' +var ' + funcName + ' *=.*?createIterator\\((?:{|[a-zA-Z])[\\s\\S]+?\\);|' + + // match a variable declaration with function expression + '( *)var ' + funcName + ' *=.*?function[\\s\\S]+?\\n\\2};' + + // end non-capturing group + ')\\n' + )); + + return result ? result[0] : ''; + } + + /** + * Converts a comma separated options string into an array. + * + * @private + * @param {String} value The option to convert. + * @returns {Array} Returns the new converted array. + */ + function optionToArray(value) { + return value.match(/\w+=(.*)$/)[1].split(/, */); + } + + /** + * Converts a comma separated options string into an array containing + * only real method names. + * + * @private + * @param {String} source The source to inspect. + * @param {String} value The option to convert. + * @returns {Array} Returns the new converted array. + */ + function optionToMethodsArray(source, value) { + var methodNames = optionToArray(value); + + // convert categories to method names + methodNames.forEach(function(category) { + push.apply(methodNames, getMethodsByCategory(source, category)); + }); + + // convert aliases to real method names + methodNames = methodNames.map(getRealName); + + // remove nonexistent and duplicate method names + return _.uniq(_.intersection(allMethods, methodNames)); + } + + /** + * Removes the all references to `refName` from `createIterator` in `source`. + * + * @private + * @param {String} source The source to process. + * @param {String} refName The name of the reference to remove. + * @returns {String} Returns the modified source. + */ + function removeFromCreateIterator(source, refName) { + var snippet = matchFunction(source, 'createIterator'); + if (snippet) { + // clip the snippet at the `factory` assignment + snippet = snippet.match(/Function\([\s\S]+$/)[0]; + var modified = snippet.replace(RegExp('\\b' + refName + '\\b,? *', 'g'), ''); + source = source.replace(snippet, modified); + } + return source; + } + + /** + * Removes the `funcName` function declaration, expression, or assignment and + * associated code from `source`. + * + * @private + * @param {String} source The source to process. + * @param {String} funcName The name of the function to remove. + * @returns {String} Returns the source with the function removed. + */ + function removeFunction(source, funcName) { + var modified, + snippet = matchFunction(source, funcName); + + // exit early if function is not found + if (!snippet) { + return source; + } + // remove function + source = source.replace(snippet, ''); + + // grab the method assignments snippet + snippet = getMethodAssignments(source); + + // remove assignment and aliases + modified = getAliases(funcName).concat(funcName).reduce(function(result, otherName) { + return result.replace(RegExp('(?:\\n *//.*\\s*)* *lodash\\.' + otherName + ' *= *.+\\n'), ''); + }, snippet); + + // replace with the modified snippet + source = source.replace(snippet, modified); + + return removeFromCreateIterator(source, funcName); + } + + /** + * Removes the `_.isArguments` fallback from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the source with the `isArguments` fallback removed. + */ + function removeIsArgumentsFallback(source) { + return source.replace(getIsArgumentsFallback(source), ''); + } + + /** + * Removes the `_.isFunction` fallback from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the source with the `isFunction` fallback removed. + */ + function removeIsFunctionFallback(source) { + return source.replace(getIsFunctionFallback(source), ''); + } + + /** + * Removes the `Object.keys` object iteration optimization from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeKeysOptimization(source) { + return removeVar(source, 'isKeysFast') + // remove optimized branch in `iteratorTemplate` + .replace(/(?: *\/\/.*\n)* *'( *)<% *if *\(isKeysFast[\s\S]+?'\1<% *} *else *\{ *%>.+\n([\s\S]+?) *'\1<% *} *%>.+/, "'\\n' +\n$2") + // remove data object property assignment in `createIterator` + .replace(/ *'isKeysFast':.+\n/, ''); + } + + /** + * Removes all `noArgsClass` references from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeNoArgsClass(source) { + return removeVar(source, 'noArgsClass') + // remove `noArgsClass` from `_.clone` and `_.isEqual` + .replace(/ *\|\| *\(noArgsClass *&&[^)]+?\)\)/g, '') + // remove `noArgsClass` from `_.isEqual` + .replace(/if *\(noArgsClass[^}]+?}\n/, '\n'); + } + + /** + * Removes all `noNodeClass` references from `source`. + * + * @private + * @param {String} source The source to process. + * @returns {String} Returns the modified source. + */ + function removeNoNodeClass(source) { + return source + // remove `noNodeClass` assignment + .replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *try *\{(?:\s*\/\/.*)*\n *var noNodeClass[\s\S]+?catch[^}]+}\n/, '') + // remove `noNodeClass` from `isPlainObject` + .replace(/\(!noNodeClass *\|\|[\s\S]+?\)\) *&&/, '') + // remove `noNodeClass` from `_.isEqual` + .replace(/ *\|\| *\(noNodeClass *&&[\s\S]+?\)\)\)/, ''); + } + + /** + * Removes a given variable from `source`. + * + * @private + * @param {String} source The source to process. + * @param {String} varName The name of the variable to remove. + * @returns {String} Returns the source with the variable removed. + */ + function removeVar(source, varName) { + // simplify `cloneableClasses` + if (varName == 'cloneableClasses') { + source = source.replace(/(var cloneableClasses *=)[\s\S]+?(true;\n)/, '$1$2'); + } + // simplify `hasObjectSpliceBug` + if (varName == 'hasObjectSpliceBug') { + source = source.replace(/(var hasObjectSpliceBug *=)[^;]+/, '$1false'); + } + source = source.replace(RegExp( + // match multi-line comment block + '(?:\\n +/\\*[^*]*\\*+(?:[^/][^*]*\\*+)*/)?\\n' + + // match a variable declaration that's not part of a declaration list + '( *)var ' + varName + ' *= *(?:.+?(?:;|&&\\n[^;]+;)|(?:\\w+\\(|{)[\\s\\S]+?\\n\\1.+?;)\\n|' + + // match a variable in a declaration list + '\\n +' + varName + ' *=.+?,' + ), ''); + + // remove a varaible at the start of a variable declaration list + source = source.replace(RegExp('(var +)' + varName + ' *=.+?,\\s+'), '$1'); + + // remove a variable at the end of a variable declaration list + source = source.replace(RegExp(',\\s*' + varName + ' *=.+?;'), ';'); + + // remove variable reference from `cloneableClasses` assignments + source = source.replace(RegExp('cloneableClasses\\[' + varName + '\\] *= *(?:false|true)?', 'g'), ''); + + return removeFromCreateIterator(source, varName); + } + + /** + * Searches `source` for a `varName` variable declaration and replaces its + * assigned value with `varValue`. + * + * @private + * @param {String} source The source to inspect. + * @param {String} varName The name of the variable to replace. + * @returns {String} Returns the source with the variable replaced. + */ + function replaceVar(source, varName, varValue) { + // replace a variable that's not part of a declaration list + var result = source.replace(RegExp( + '(( *)var ' + varName + ' *= *)' + + '(?:.+?;|(?:Function\\(.+?|.*?[^,])\\n[\\s\\S]+?\\n\\2.+?;)\\n' + ), '$1' + varValue + ';\n'); + + if (source == result) { + // replace a varaible at the start or middle of a declaration list + result = source.replace(RegExp('((?:var|\\n) +' + varName + ' *=).+?,'), '$1 ' + varValue + ','); + } + if (source == result) { + // replace a variable at the end of a variable declaration list + result = source.replace(RegExp('(,\\s*' + varName + ' *=).+?;'), '$1 ' + varValue + ';'); + } + return result; + } + + /** + * Hard-codes the `useStrict` template option value for `iteratorTemplate`. + * + * @private + * @param {String} source The source to process. + * @param {Boolean} value The value to set. + * @returns {String} Returns the modified source. + */ + function setUseStrictOption(source, value) { + // inject "use strict" + if (value) { + source = source.replace(/^[\s\S]*?function[^{]+{/, "$&\n 'use strict';"); + } + // replace `useStrict` branch in `value` with hard-coded option + return source.replace(/(?: *\/\/.*\n)*(\s*)' *<%.+?useStrict.+/, value ? "$1'\\'use strict\\';\\n' +" : ''); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a debug and/or minified build, executing the `callback` for each. + * The `callback` is invoked with two arguments; (filePath, outputSource). + * + * Note: For a list of commands see `displayHelp()` or run `lodash --help`. + * + * @param {Array} [options=[]] An array of commands. + * @param {Function} callback The function called per build. + */ + function build(options, callback) { + options || (options = []); + + // the debug version of `source` + var debugSource; + + // used to report invalid command-line arguments + var invalidArgs = _.reject(options.slice(options[0] == 'node' ? 2 : 0), function(value, index, options) { + if (/^(?:-o|--output)$/.test(options[index - 1]) || + /^(?:category|exclude|exports|iife|include|moduleId|minus|plus|settings|template)=.*$/i.test(value)) { + return true; + } + return [ + 'backbone', + 'csp', + 'legacy', + 'mobile', + 'strict', + 'underscore', + '-c', '--stdout', + '-d', '--debug', + '-h', '--help', + '-m', '--minify', + '-o', '--output', + '-s', '--silent', + '-V', '--version' + ].indexOf(value) > -1; + }); + + // report invalid arguments + if (invalidArgs.length) { + console.log( + '\n' + + 'Invalid argument' + (invalidArgs.length > 1 ? 's' : '') + + ' passed: ' + invalidArgs.join(', ') + ); + displayHelp(); + return; + } + + // display help message + if (_.find(options, function(arg) { + return /^(?:-h|--help)$/.test(arg); + })) { + displayHelp(); + return; + } + + // display `lodash.VERSION` + if (_.find(options, function(arg) { + return /^(?:-V|--version)$/.test(arg); + })) { + console.log(_.VERSION); + return; + } + + /*------------------------------------------------------------------------*/ + + // backup `dependencyMap` to restore later + var dependencyBackup = _.clone(dependencyMap, true); + + // used to specify a custom IIFE to wrap Lo-Dash + var iife = options.reduce(function(result, value) { + var match = value.match(/iife=(.*)/); + return match ? match[1] : result; + }, null); + + // flag used to specify a Backbone build + var isBackbone = options.indexOf('backbone') > -1; + + // flag used to specify a Content Security Policy build + var isCSP = options.indexOf('csp') > -1 || options.indexOf('CSP') > -1; + + // flag used to specify only creating the debug build + var isDebug = options.indexOf('-d') > -1 || options.indexOf('--debug') > -1; + + // flag used to specify a legacy build + var isLegacy = options.indexOf('legacy') > -1; + + // flag used to specify an Underscore build + var isUnderscore = options.indexOf('underscore') > -1; + + // flag used to specify only creating the minified build + var isMinify = !isDebug && options.indexOf('-m') > -1 || options.indexOf('--minify')> -1; + + // flag used to specify a mobile build + var isMobile = !isLegacy && (isCSP || isUnderscore || options.indexOf('mobile') > -1); + + // flag used to specify writing output to standard output + var isStdOut = options.indexOf('-c') > -1 || options.indexOf('--stdout') > -1; + + // flag used to specify skipping status updates normally logged to the console + var isSilent = isStdOut || options.indexOf('-s') > -1 || options.indexOf('--silent') > -1; + + // flag used to specify `_.bindAll`, `_.extend`, and `_.defaults` are + // constructed using the "use strict" directive + var isStrict = options.indexOf('strict') > -1; + + // used to specify the ways to export the `lodash` function + var exportsOptions = options.reduce(function(result, value) { + return /exports/.test(value) ? optionToArray(value).sort() : result; + }, isUnderscore + ? ['commonjs', 'global', 'node'] + : exportsAll.slice() + ); + + // used to specify the AMD module ID of Lo-Dash used by precompiled templates + var moduleId = options.reduce(function(result, value) { + var match = value.match(/moduleId=(.*)/); + return match ? match[1] : result; + }, 'lodash'); + + // used to specify the output path for builds + var outputPath = options.reduce(function(result, value, index) { + if (/-o|--output/.test(value)) { + result = options[index + 1]; + result = path.join(fs.realpathSync(path.dirname(result)), path.basename(result)); + } + return result; + }, ''); + + // used to match external template files to precompile + var templatePattern = options.reduce(function(result, value) { + var match = value.match(/template=(.+)$/); + return match + ? path.join(fs.realpathSync(path.dirname(match[1])), path.basename(match[1])) + : result; + }, ''); + + // used when precompiling template files + var templateSettings = options.reduce(function(result, value) { + var match = value.match(/settings=(.+)$/); + return match + ? Function('return {' + match[1].replace(/^{|}$/g, '') + '}')() + : result; + }, _.extend(_.clone(_.templateSettings), { + 'moduleId': moduleId + })); + + // flag used to specify a template build + var isTemplate = !!templatePattern; + + // the lodash.js source + var source = fs.readFileSync(path.join(__dirname, 'lodash.js'), 'utf8'); + + // flag used to specify replacing Lo-Dash's `_.clone` with Underscore's + var useUnderscoreClone = isUnderscore; + + // flags used to specify exposing Lo-Dash methods in an Underscore build + var exposeForIn = !isUnderscore, + exposeForOwn = !isUnderscore, + exposeIsPlainObject = !isUnderscore; + + /*------------------------------------------------------------------------*/ + + // names of methods to include in the build + var buildMethods = !isTemplate && (function() { + var result; + + var minusMethods = options.reduce(function(accumulator, value) { + return /exclude|minus/.test(value) + ? _.union(accumulator, optionToMethodsArray(source, value)) + : accumulator; + }, []); + + var plusMethods = options.reduce(function(accumulator, value) { + return /plus/.test(value) + ? _.union(accumulator, optionToMethodsArray(source, value)) + : accumulator; + }, []); + + // update dependencies + if (isMobile) { + dependencyMap.reduceRight = ['forEach', 'keys']; + } + if (isUnderscore) { + dependencyMap.contains = ['indexOf', 'some'], + dependencyMap.isEqual = ['isArray', 'isFunction']; + dependencyMap.isEmpty = ['isArray', 'isString']; + dependencyMap.max = ['forEach', 'isArray']; + dependencyMap.min = ['forEach', 'isArray']; + dependencyMap.pick = []; + dependencyMap.template = ['defaults', 'escape']; + + if (useUnderscoreClone) { + dependencyMap.clone = ['extend', 'isArray']; + } + } + // add method names explicitly + options.some(function(value) { + return /include/.test(value) && + (result = getDependencies(optionToMethodsArray(source, value))); + }); + + // include Lo-Dash's methods if explicitly requested + if (result) { + exposeForIn = result.indexOf('forIn') > -1; + exposeForOwn = result.indexOf('forOwn') > -1; + exposeIsPlainObject = result.indexOf('isPlainObject') > -1; + useUnderscoreClone = result.indexOf('clone') < 0; + } + // add method names required by Backbone and Underscore builds + if (isBackbone && !result) { + result = getDependencies(backboneDependencies); + } + if (isUnderscore && !result) { + result = getDependencies(underscoreMethods); + } + + // add method names by category + options.some(function(value) { + if (!/category/.test(value)) { + return false; + } + // resolve method names belonging to each category (case-insensitive) + var methodNames = optionToArray(value).reduce(function(accumulator, category) { + var capitalized = category[0].toUpperCase() + category.toLowerCase().slice(1); + return accumulator.concat(getMethodsByCategory(source, capitalized)); + }, []); + + return (result = _.union(result || [], getDependencies(methodNames))); + }); + + if (!result) { + result = allMethods.slice(); + } + if (plusMethods.length) { + result = _.union(result, getDependencies(plusMethods)); + } + if (minusMethods.length) { + result = _.without.apply(_, [result].concat(minusMethods, getDependants(result))); + } + return result; + }()); + + /*------------------------------------------------------------------------*/ + + // load customized Lo-Dash module + var lodash = !isTemplate && (function() { + var context = vm.createContext({ + 'clearTimeout': clearTimeout, + 'console': console, + 'setTimeout': setTimeout + }); + + source = setUseStrictOption(source, isStrict); + + if (isLegacy) { + _.each(['getPrototypeOf', 'isBindFast', 'isKeysFast', 'nativeBind', 'nativeIsArray', 'nativeKeys'], function(varName) { + source = replaceVar(source, varName, 'false'); + }); + + source = replaceVar(source, 'noArgsClass', 'true'); + source = removeKeysOptimization(source); + } + else if (isUnderscore) { + // remove unneeded variables + source = removeVar(source, 'cloneableClasses'); + + // remove large array optimizations + source = removeFunction(source, 'cachedContains'); + source = removeVar(source, 'largeArraySize'); + + // replace `_.clone` + if (useUnderscoreClone) { + source = source.replace(/^( *)function clone[\s\S]+?\n\1}/m, [ + ' function clone(value) {', + ' return value && objectTypes[typeof value]', + ' ? (isArray(value) ? slice.call(value) : extend({}, value))', + ' : value', + ' }' + ].join('\n')); + } + + // replace `_.contains` + source = source.replace(/^( *)function contains[\s\S]+?\n\1}/m, [ + ' function contains(collection, target) {', + ' var length = collection ? collection.length : 0;', + " return typeof length == 'number'", + ' ? indexOf(collection, target) > -1', + ' : some(collection, function(value) { return value === target; });', + ' }' + ].join('\n')); + + // replace `_.difference` + source = source.replace(/^( *)function difference[\s\S]+?\n\1}/m, [ + ' function difference(array) {', + ' var index = -1,', + ' length = array.length,', + ' flattened = concat.apply(arrayRef, arguments),', + ' result = [];', + '', + ' while (++index < length) {', + ' var value = array[index]', + ' if (indexOf(flattened, value, length) < 0) {', + ' result.push(value);', + ' }', + ' }', + ' return result', + ' }' + ].join('\n')); + + // replace `_.intersection` + source = source.replace(/^( *)function intersection[\s\S]+?\n\1}/m, [ + ' function intersection(array) {', + ' var args = arguments,', + ' argsLength = args.length,', + ' result = [];', + '', + ' forEach(array, function(value) {', + ' if (indexOf(result, value) < 0) {', + ' var length = argsLength;', + ' while (--length) {', + ' if (indexOf(args[length], value) < 0) {', + ' return;', + ' }', + ' }', + ' result.push(value);', + ' }', + ' });', + ' return result;', + ' }' + ].join('\n')); + + // replace `_.isEmpty` + source = source.replace(/^( *)function isEmpty[\s\S]+?\n\1}/m, [ + ' function isEmpty(value) {', + ' if (!value) {', + ' return true;', + ' }', + ' if (isArray(value) || isString(value)) {', + ' return !value.length;', + ' }', + ' for (var key in value) {', + ' if (hasOwnProperty.call(value, key)) {', + ' return false;', + ' }', + ' }', + ' return true;', + ' }' + ].join('\n')); + + // replace `_.isFinite` + source = source.replace(/^( *)function isFinite[\s\S]+?\n\1}/m, [ + ' function isFinite(value) {', + ' return nativeIsFinite(value) && toString.call(value) == numberClass;', + ' }' + ].join('\n')); + + // replace `_.omit` + source = source.replace(/^( *)function omit[\s\S]+?\n\1}/m, [ + ' function omit(object) {', + ' var props = concat.apply(arrayRef, arguments),', + ' result = {};', + '', + ' forIn(object, function(value, key) {', + ' if (indexOf(props, key, 1) < 0) {', + ' result[key] = value;', + ' }', + ' });', + ' return result;', + ' }' + ].join('\n')); + + // replace `_.pick` + source = source.replace(/^( *)function pick[\s\S]+?\n\1}/m, [ + ' function pick(object) {', + ' var index = 0,', + ' props = concat.apply(arrayRef, arguments),', + ' length = props.length,', + ' result = {};', + '', + ' while (++index < length) {', + ' var prop = props[index];', + ' if (prop in object) {', + ' result[prop] = object[prop];', + ' }', + ' }', + ' return result;', + ' }' + ].join('\n')); + + // replace `_.uniq` + source = source.replace(/^( *)function uniq[\s\S]+?\n\1}/m, [ + ' function uniq(array, isSorted, callback, thisArg) {', + ' var index = -1,', + ' length = array ? array.length : 0,', + ' result = [],', + ' seen = result;', + '', + ' if (callback) {', + ' seen = [];', + ' callback = createCallback(callback, thisArg);', + ' }', + ' while (++index < length) {', + ' var value = array[index],', + ' computed = callback ? callback(value, index, array) : value;', + '', + ' if (isSorted', + ' ? !index || seen[seen.length - 1] !== computed', + ' : indexOf(seen, computed) < 0', + ' ) {', + ' if (callback) {', + ' seen.push(computed);', + ' }', + ' result.push(value);', + ' }', + ' }', + ' return result;', + ' }' + ].join('\n')); + + // replace `_.without` + source = source.replace(/^( *)function without[\s\S]+?\n\1}/m, [ + ' function without(array) {', + ' var index = -1,', + ' length = array.length,', + ' result = [];', + '', + ' while (++index < length) {', + ' var value = array[index]', + ' if (indexOf(arguments, value, 1) < 0) {', + ' result.push(value);', + ' }', + ' }', + ' return result', + ' }' + ].join('\n')); + + // remove `arguments` object check from `_.isEqual` + source = source.replace(/ *\|\| *className *== *argsClass/, ''); + + // simplify DOM node check from `_.isEqual` + source = source.replace(/(if *\(className *!= *objectClass).+?noNodeClass[\s\S]+?{/, '$1) {'); + + // remove conditional `charCodeCallback` use from `_.max` and `_.min` + source = source.replace(/!callback *&& *isString\(collection\)[\s\S]+?: */g, ''); + + // remove unused features from `createBound` + if (buildMethods.indexOf('partial') == -1) { + source = source.replace(matchFunction(source, 'createBound'), function(match) { + return match + .replace(/(function createBound\([^{]+{)[\s\S]+?(\n *function bound)/, '$1$2') + .replace(/thisBinding *=[^}]+}/, 'thisBinding = thisArg;\n'); + }); + } + } + if (isMobile) { + source = replaceVar(source, 'isKeysFast', 'false'); + source = removeKeysOptimization(source); + + // remove `prototype` [[Enumerable]] fix from `_.keys` + source = source.replace(/(?:\s*\/\/.*)*(\s*return *).+?propertyIsEnumerable[\s\S]+?: */, '$1'); + + // remove `prototype` [[Enumerable]] fix from `iteratorTemplate` + source = source + .replace(/(?: *\/\/.*\n)* *' *(?:<% *)?if *\(!hasDontEnumBug *(?:&&|\))[\s\S]+?<% *} *(?:%>|').+/g, '') + .replace(/!hasDontEnumBug *\|\|/g, ''); + } + vm.runInContext(source, context); + return context._; + }()); + + /*------------------------------------------------------------------------*/ + + if (isTemplate) { + source = buildTemplate(templatePattern, templateSettings); + } + else { + // simplify template snippets by removing unnecessary brackets + source = source.replace( + RegExp("{(\\\\n' *\\+\\s*.*?\\+\\n\\s*' *)}(?:\\\\n)?' *([,\\n])", 'g'), "$1'$2" + ); + + source = source.replace( + RegExp("{(\\\\n' *\\+\\s*.*?\\+\\n\\s*' *)}(?:\\\\n)?' *\\+", 'g'), "$1;\\n'+" + ); + + // remove methods from the build + allMethods.forEach(function(otherName) { + if (!_.contains(buildMethods, otherName)) { + source = removeFunction(source, otherName); + } + }); + + // remove `isArguments` fallback before `isArguments` is transformed by + // other parts of the build process + if (isRemoved(source, 'isArguments')) { + source = removeIsArgumentsFallback(source); + } + + /*----------------------------------------------------------------------*/ + + if (isLegacy) { + _.each(['isBindFast', 'nativeBind', 'nativeIsArray', 'nativeKeys'], function(varName) { + source = removeVar(source, varName); + }); + + _.each(['bind', 'isArray'], function(methodName) { + var snippet = matchFunction(source, methodName), + modified = snippet; + + // remove native `Function#bind` branch in `_.bind` + if (methodName == 'bind') { + modified = modified.replace(/(?:\s*\/\/.*)*\s*return isBindFast[^:]+:\s*/, 'return '); + } + // remove native `Array.isArray` branch in `_.isArray` + else { + modified = modified.replace(/nativeIsArray * \|\|/, ''); + } + source = source.replace(snippet, modified); + }); + + // replace `_.keys` with `shimKeys` + if (!isRemoved(source, 'keys')) { + source = source.replace( + matchFunction(source, 'keys').replace(/[\s\S]+?var keys *= */, ''), + matchFunction(source, 'shimKeys').replace(/[\s\S]+?function shimKeys/, 'function').replace(/}\n$/, '};\n') + ); + + source = removeFunction(source, 'shimKeys'); + } + // replace `_.isArguments` with fallback + if (!isRemoved(source, 'isArguments')) { + source = source.replace( + matchFunction(source, 'isArguments').replace(/[\s\S]+?function isArguments/, ''), + getIsArgumentsFallback(source).match(/isArguments *= *function([\s\S]+?) *};/)[1] + ' }\n' + ); + + source = removeIsArgumentsFallback(source); + } + + source = removeVar(source, 'reNative'); + source = removeFromCreateIterator(source, 'nativeKeys'); + } + + /*----------------------------------------------------------------------*/ + + if (isMobile) { + // inline all functions defined with `createIterator` + _.functions(lodash).forEach(function(methodName) { + var reFunc = RegExp('(\\bvar ' + methodName + ' *= *)createIterator\\(((?:{|[a-zA-Z])[\\s\\S]+?)\\);\\n'); + + // skip if not defined with `createIterator` + if (!reFunc.test(source)) { + return; + } + // extract, format, and inject the compiled function's source code + source = source.replace(reFunc, '$1' + getFunctionSource(lodash[methodName]) + ';\n'); + }); + + if (isUnderscore) { + // remove `_.forIn`, `_.forOwn`, and `_.isPlainObject` assignments + (function() { + var snippet = getMethodAssignments(source), + modified = snippet; + + if (!exposeForIn) { + modified = modified.replace(/(?:\n *\/\/.*\s*)* *lodash\.forIn *= *.+\n/, ''); + } + if (!exposeForOwn) { + modified = modified.replace(/(?:\n *\/\/.*\s*)* *lodash\.forOwn *= *.+\n/, ''); + } + if (!exposeIsPlainObject) { + modified = modified.replace(/(?:\n *\/\/.*\s*)* *lodash\.isPlainObject *= *.+\n/, ''); + } + source = source.replace(snippet, modified); + }()); + + // replace `isArguments` and its fallback + (function() { + var snippet = matchFunction(source, 'isArguments') + .replace(/function isArguments/, 'lodash.isArguments = function'); + + source = removeFunction(source, 'isArguments'); + + source = source.replace(getIsArgumentsFallback(source), function(match) { + return snippet + '\n' + match + .replace(/\bisArguments\b/g, 'lodash.$&') + .replace(/\bnoArgsClass\b/g, '!lodash.isArguments(arguments)'); + }); + }()); + + // remove chainability from `_.forEach` + source = source.replace(matchFunction(source, 'forEach'), function(match) { + return match.replace(/return result([};\s]+)$/, '$1'); + }); + + // unexpose "exit early" feature from `_.forEach`, `_.forIn`, and `_.forOwn` + _.each(['forEach', 'forIn', 'forOwn'], function(methodName) { + source = source.replace(matchFunction(source, methodName), function(match) { + return match.replace(/=== *false\)/g, '=== indicatorObject)'); + }); + }); + + // modify `_.every` and `_.some` to use the private `indicatorObject` + source = source.replace(matchFunction(source, 'every'), function(match) { + return match.replace(/\(result *= *(.+?)\);/, '!(result = $1) && indicatorObject;'); + }); + + source = source.replace(matchFunction(source, 'some'), function(match) { + return match.replace(/!\(result *= *(.+?)\);/, '(result = $1) && indicatorObject;'); + }); + + // replace `_.template` + source = source.replace(/^( *)function template[\s\S]+?\n\1}/m, function() { + return [ + ' function template(text, data, options) {', + " text || (text = '');", + ' options = defaults({}, options, lodash.templateSettings);', + '', + ' var index = 0,', + ' source = "__p += \'",', + ' variable = options.variable;', + '', + ' var reDelimiters = RegExp(', + " (options.escape || reNoMatch).source + '|' +", + " (options.interpolate || reNoMatch).source + '|' +", + " (options.evaluate || reNoMatch).source + '|$'", + " , 'g');", + '', + ' text.replace(reDelimiters, function(match, escapeValue, interpolateValue, evaluateValue, offset) {', + ' source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar);', + ' source +=', + ' escapeValue ? "\' +\\n_.escape(" + escapeValue + ") +\\n\'" :', + ' evaluateValue ? "\';\\n" + evaluateValue + ";\\n__p += \'" :', + ' interpolateValue ? "\' +\\n((__t = (" + interpolateValue + ")) == null ? \'\' : __t) +\\n\'" : \'\';', + '', + ' index = offset + match.length;', + ' });', + '', + ' source += "\';\\n";', + ' if (!variable) {', + " variable = 'obj';", + " source = 'with (' + variable + ' || {}) {\\n' + source + '\\n}\\n';", + ' }', + " source = 'function(' + variable + ') {\\n' +", + " 'var __t, __p = \\'\\', __j = Array.prototype.join;\\n' +", + " 'function print() { __p += __j.call(arguments, \\'\\') }\\n' +", + ' source +', + " 'return __p\\n}';", + '', + ' try {', + " var result = Function('_', 'return ' + source)(lodash);", + ' } catch(e) {', + ' e.source = source;', + ' throw e;', + ' }', + ' if (data) {', + ' return result(data);', + ' }', + ' result.source = source;', + ' return result;', + ' }' + ].join('\n'); + }); + + // remove unneeded template related variables + source = removeVar(source, 'reComplexDelimiter'); + source = removeVar(source, 'reEmptyStringLeading'); + source = removeVar(source, 'reEmptyStringMiddle'); + source = removeVar(source, 'reEmptyStringTrailing'); + source = removeVar(source, 'reInsertVariable'); + } + else { + source = removeIsArgumentsFallback(source); + source = removeVar(source, 'hasObjectSpliceBug'); + + // remove `hasObjectSpliceBug` fix from the mutator Array functions mixin + source = source.replace(/(?:\s*\/\/.*)*\n( *)if *\(hasObjectSpliceBug[\s\S]+?\n\1}/, ''); + } + + // remove `thisArg` from unexposed `forIn` and `forOwn` + _.each([ + { 'methodName': 'forIn', 'flag': exposeForIn }, + { 'methodName': 'forOwn', 'flag': exposeForOwn } + ], function(data) { + if (!data.flag) { + source = source.replace(matchFunction(source, data.methodName), function(match) { + return match.replace(/(callback), *thisArg/g, '$1'); + }); + } + }); + + // remove `hasDontEnumBug`, `iteratesOwnLast`, and `noArgsEnum` declarations and assignments + source = source + .replace(/ *\(function\(\) *{[\s\S]+?}\(1\)\);\n/, '') + .replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *var (?:hasDontEnumBug|iteratesOwnLast|noArgsEnum).+\n/g, ''); + + // remove `iteratesOwnLast` from `isPlainObject` + source = source.replace(/(?:\s*\/\/.*)*\n( *)if *\(iteratesOwnLast[\s\S]+?\n\1}/, ''); + + // remove JScript [[DontEnum]] fix from `_.isEqual` + source = source.replace(/(?:\s*\/\/.*)*\n( *)if *\(hasDontEnumBug[\s\S]+?\n\1}/, ''); + + // remove `noArraySliceOnStrings` from `_.toArray` + source = source.replace(/noArraySliceOnStrings *\?[^:]+: *([^)]+)/g, '$1'); + + // remove `noCharByIndex` from `_.reduceRight` + source = source.replace(/}\s*else if *\(noCharByIndex[^}]+/, ''); + + source = removeVar(source, 'extendIteratorOptions'); + source = removeVar(source, 'iteratorTemplate'); + source = removeVar(source, 'noArraySliceOnStrings'); + source = removeVar(source, 'noCharByIndex'); + source = removeNoArgsClass(source); + source = removeNoNodeClass(source); + } + else { + // inline `iteratorTemplate` template + source = source.replace(/(( *)var iteratorTemplate *= *)[\s\S]+?\n\2.+?;\n/, (function() { + var snippet = getFunctionSource(lodash._iteratorTemplate); + + // prepend data object references to property names to avoid having to + // use a with-statement + iteratorOptions.forEach(function(property) { + snippet = snippet.replace(RegExp('([^\\w.])\\b' + property + '\\b', 'g'), '$1obj.' + property); + }); + + // remove unnecessary code + snippet = snippet + .replace(/var __t.+/, "var __p = '';") + .replace(/function print[^}]+}/, '') + .replace(/'(?:\\n|\s)+'/g, "''") + .replace(/__p *\+= *' *';/g, '') + .replace(/(__p *\+= *)' *' *\+/g, '$1') + .replace(/(\{) *;|; *(\})/g, '$1$2') + .replace(/\(\(__t *= *\( *([^)]+) *\)\) *== *null *\? *'' *: *__t\)/g, '($1)'); + + // remove the with-statement + snippet = snippet.replace(/ *with *\(.+?\) *{/, '\n').replace(/}([^}]*}[^}]*$)/, '$1'); + + // minor cleanup + snippet = snippet + .replace(/obj *\|\| *\(obj *= *\{}\);/, '') + .replace(/var __p = '';\s*__p \+=/, 'var __p ='); + + // remove comments, including sourceURLs + snippet = snippet.replace(/\s*\/\/.*(?:\n|$)/g, ''); + + return '$1' + snippet + ';\n'; + }())); + } + } + + /*------------------------------------------------------------------------*/ + + // customize Lo-Dash's IIFE + (function() { + if (typeof iife == 'string') { + var token = '%output%', + index = iife.indexOf(token); + + source = source.match(/\/\*![\s\S]+?\*\/\n/) + + iife.slice(0, index) + + source.replace(/^[\s\S]+?\(function[^{]+?{|}\(this\)\)[;\s]*$/g, '') + + iife.slice(index + token.length); + } + }()); + + /*------------------------------------------------------------------------*/ + + // customize Lo-Dash's export bootstrap + (function() { + var isAMD = exportsOptions.indexOf('amd') > -1, + isCommonJS = exportsOptions.indexOf('commonjs') > -1, + isGlobal = exportsOptions.indexOf('global') > -1, + isNode = exportsOptions.indexOf('node') > -1; + + if (!isAMD) { + source = source.replace(/(?: *\/\/.*\n)*( *)if *\(typeof +define[\s\S]+?else /, '$1'); + } + if (!isNode) { + source = source.replace(/(?: *\/\/.*\n)*( *)if *\(typeof +module[\s\S]+?else *{([\s\S]+?\n)\1}\n/, '$1$2'); + } + if (!isCommonJS) { + source = source.replace(/(?: *\/\/.*\n)*(?:( *)else *{)?\s*freeExports\.\w+ *=[\s\S]+?(?:\n\1})?\n/, ''); + } + if (!isGlobal) { + source = source.replace(/(?:( *)(})? *else(?: *if *\(_\))? *{)?(?:\s*\/\/.*)*\s*(?:window\._|_\.templates) *=[\s\S]+?(?:\n\1})?\n/g, '$1$2\n'); + } + // remove `if (freeExports) {...}` if it's empty + if (isAMD && isGlobal) { + source = source.replace(/(?: *\/\/.*\n)* *(?:else )?if *\(freeExports\) *{\s*}\n/, ''); + } else { + source = source.replace(/(?: *\/\/.*\n)* *(?:else )?if *\(freeExports\) *{\s*}(?:\s*else *{([\s\S]+?) *})?\n/, '$1\n'); + } + + if ((source.match(/\bfreeExports\b/g) || []).length < 2) { + source = removeVar(source, 'freeExports'); + } + }()); + + /*------------------------------------------------------------------------*/ + + if (isTemplate) { + debugSource = source; + } + else { + // modify/remove references to removed methods/variables + if (isRemoved(source, 'invert')) { + source = replaceVar(source, 'htmlUnescapes', "{'&':'&','<':'<','>':'>','"':'\"',''':\"'\"}"); + } + if (isRemoved(source, 'isArguments')) { + source = replaceVar(source, 'noArgsClass', 'false'); + } + if (isRemoved(source, 'isFunction')) { + source = removeIsFunctionFallback(source); + } + if (isRemoved(source, 'mixin')) { + // remove `lodash.prototype` additions + source = source.replace(/(?:\s*\/\/.*)*\s*mixin\(lodash\)[\s\S]+?\/\*-+\*\//, ''); + source = removeVar(source, 'hasObjectSpliceBug'); + } + + // remove pseudo private properties + source = source.replace(/(?:(?:\s*\/\/.*)*\s*lodash\._[^=]+=.+\n)+/g, '\n'); + + // assign debug source before further modifications that rely on the minifier + // to remove unused variables and other dead code + debugSource = source; + + // remove associated functions, variables, and code snippets that the minifier may miss + if (isRemoved(source, 'clone')) { + source = removeVar(source, 'cloneableClasses'); + } + if (isRemoved(source, 'isArray')) { + source = removeVar(source, 'nativeIsArray'); + } + if (isRemoved(source, 'isPlainObject')) { + source = removeVar(source, 'getPrototypeOf'); + } + if (isRemoved(source, 'keys')) { + source = removeFunction(source, 'shimKeys'); + } + if (isRemoved(source, 'template')) { + // remove `templateSettings` assignment + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *lodash\.templateSettings[\s\S]+?};\n/, ''); + } + if (isRemoved(source, 'toArray')) { + source = removeVar(source, 'noArraySliceOnStrings'); + } + if (isRemoved(source, 'clone', 'isArguments', 'isEmpty', 'isEqual')) { + source = removeNoArgsClass(source); + } + if (isRemoved(source, 'isEqual', 'isPlainObject')) { + source = removeNoNodeClass(source); + } + if ((source.match(/\bcreateIterator\b/g) || []).length < 2) { + source = removeFunction(source, 'createIterator'); + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *var noArgsEnum;|.+?noArgsEnum *=.+/g, ''); + } + if (isRemoved(source, 'createIterator', 'bind')) { + source = removeVar(source, 'isBindFast'); + source = removeVar(source, 'nativeBind'); + } + if (isRemoved(source, 'createIterator', 'bind', 'isArray', 'isPlainObject', 'keys')) { + source = removeVar(source, 'reNative'); + } + if (isRemoved(source, 'createIterator', 'isEqual')) { + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *var hasDontEnumBug;|.+?hasDontEnumBug *=.+/g, ''); + } + if (isRemoved(source, 'createIterator', 'isPlainObject')) { + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *var iteratesOwnLast;|.+?iteratesOwnLast *=.+/g, ''); + } + if (isRemoved(source, 'createIterator', 'keys')) { + source = removeVar(source, 'nativeKeys'); + source = removeKeysOptimization(source); + } + if (!source.match(/var (?:hasDontEnumBug|iteratesOwnLast|noArgsEnum)\b/g)) { + // remove `hasDontEnumBug`, `iteratesOwnLast`, and `noArgsEnum` assignments + source = source.replace(/ *\(function\(\) *{[\s\S]+?}\(1\)\);\n/, ''); + } + } + + /*------------------------------------------------------------------------*/ + + // used to specify creating a custom build + var isCustom = isBackbone || isLegacy || isMobile || isStrict || isUnderscore || + /(?:category|exclude|exports|iife|include|minus|plus)=/.test(options) || + !_.isEqual(exportsOptions, exportsAll); + + // used as the basename of the output path + var basename = outputPath + ? path.basename(outputPath, '.js') + : 'lodash' + (isTemplate ? '.template' : isCustom ? '.custom' : ''); + + // restore `dependencyMap` + dependencyMap = dependencyBackup; + + // output debug build + if (!isMinify && (isCustom || isDebug || isTemplate)) { + if (isDebug && isStdOut) { + stdout.write(debugSource); + callback(debugSource); + } else if (!isStdOut) { + callback(debugSource, (isDebug && outputPath) || path.join(cwd, basename + '.js')); + } + } + // begin the minification process + if (!isDebug) { + outputPath || (outputPath = path.join(cwd, basename + '.min.js')); + + minify(source, { + 'isSilent': isSilent, + 'isTemplate': isTemplate, + 'outputPath': outputPath, + 'onComplete': function(source) { + // inject "use strict" directive + if (isStrict) { + source = source.replace(/^([\s\S]*?function[^{]+{)([^'"])/, '$1"use strict";$2'); + } + if (isStdOut) { + stdout.write(source); + callback(source); + } else { + callback(source, outputPath); + } + } + }); + } + } + + /*--------------------------------------------------------------------------*/ + + // expose `build` + if (module != require.main) { + module.exports = build; + } + else { + // or invoked directly + build(process.argv, function(source, filePath) { + filePath && fs.writeFileSync(filePath, source, 'utf8'); + }); + } +}()); diff --git a/node/node_modules/grunt/node_modules/lodash/build/minify.js b/node/node_modules/grunt/node_modules/lodash/build/minify.js new file mode 100755 index 000000000..904301d08 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/build/minify.js @@ -0,0 +1,575 @@ +#!/usr/bin/env node +;(function() { + 'use strict'; + + /** Load Node modules */ + var fs = require('fs'), + https = require('https'), + path = require('path'), + spawn = require('child_process').spawn, + tar = require('../vendor/tar/tar.js'), + zlib = require('zlib'); + + /** Load other modules */ + var preprocess = require('./pre-compile.js'), + postprocess = require('./post-compile.js'); + + /** The Git object ID of `closure-compiler.tar.gz` */ + var closureId = 'a2787b470c577cee2404d186c562dd9835f779f5'; + + /** The Git object ID of `uglifyjs.tar.gz` */ + var uglifyId = '505f1be36ef60fd25a992a522f116d5179ab317f'; + + /** The path of the directory that is the base of the repository */ + var basePath = fs.realpathSync(path.join(__dirname, '..')); + + /** The path of the `vendor` directory */ + var vendorPath = path.join(basePath, 'vendor'); + + /** The path to the Closure Compiler `.jar` */ + var closurePath = path.join(vendorPath, 'closure-compiler', 'compiler.jar'); + + /** The path to the UglifyJS module */ + var uglifyPath = path.join(vendorPath, 'uglifyjs', 'tools', 'node.js'); + + /** The Closure Compiler command-line options */ + var closureOptions = ['--warning_level=QUIET']; + + /** The media type for raw blob data */ + var mediaType = 'application/vnd.github.v3.raw'; + + /** Used to reference parts of the blob href */ + var location = (function() { + var host = 'api.github.com', + origin = 'https://api.github.com', + pathname = '/repos/bestiejs/lodash/git/blobs'; + + return { + 'host': host, + 'href': origin + pathname, + 'origin': origin, + 'pathname': pathname + }; + }()); + + /** The Closure Compiler optimization modes */ + var optimizationModes = { + 'simple': 'SIMPLE_OPTIMIZATIONS', + 'advanced': 'ADVANCED_OPTIMIZATIONS' + }; + + /** Reassign `existsSync` for older versions of Node */ + fs.existsSync || (fs.existsSync = path.existsSync); + + /*--------------------------------------------------------------------------*/ + + /** + * Minifies a given Lo-Dash `source` and invokes the `options.onComplete` + * callback when finished. The `onComplete` callback is invoked with one + * argument; (outputSource). + * + * @param {Array|String} [source=''] The source to minify or array of commands. + * -o, --output - Write output to a given path/filename. + * -s, --silent - Skip status updates normally logged to the console. + * -t, --template - Applies template specific minifier options. + * + * @param {Object} [options={}] The options object. + * outputPath - Write output to a given path/filename. + * isSilent - Skip status updates normally logged to the console. + * isTemplate - Applies template specific minifier options. + * onComplete - The function called once minification has finished. + */ + function minify(source, options) { + source || (source = ''); + options || (options = {}); + + // juggle arguments + if (Array.isArray(source)) { + // convert commands to an options object + options = source; + + var filePath = options[options.length - 1], + isSilent = options.indexOf('-s') > -1 || options.indexOf('--silent') > -1, + isTemplate = options.indexOf('-t') > -1 || options.indexOf('--template') > -1, + outputPath = path.join(path.dirname(filePath), path.basename(filePath, '.js') + '.min.js'); + + outputPath = options.reduce(function(result, value, index) { + if (/-o|--output/.test(value)) { + result = options[index + 1]; + result = path.join(fs.realpathSync(path.dirname(result)), path.basename(result)); + } + return result; + }, outputPath); + + options = { + 'isSilent': isSilent, + 'isTemplate': isTemplate, + 'outputPath': outputPath + }; + + source = fs.readFileSync(filePath, 'utf8'); + } + // fetch the Closure Compiler + getDependency({ + 'id': 'closure-compiler', + 'hashId': closureId, + 'path': vendorPath, + 'title': 'the Closure Compiler', + 'onComplete': function(exception) { + var error = exception; + + // fetch UglifyJS + getDependency({ + 'id': 'uglifyjs', + 'hashId': uglifyId, + 'title': 'UglifyJS', + 'path': vendorPath, + 'onComplete': function(exception) { + error || (error = exception); + if (!error) { + new Minify(source, options); + } + } + }); + } + }); + } + + /** + * The Minify constructor used to keep state of each `minify` invocation. + * + * @private + * @constructor + * @param {String} source The source to minify. + * @param {Object} options The options object. + * outputPath - Write output to a given path/filename. + * isSilent - Skip status updates normally logged to the console. + * isTemplate - Applies template specific minifier options. + * onComplete - The function called once minification has finished. + */ + function Minify(source, options) { + // juggle arguments + if (typeof source == 'object' && source) { + options = source || options; + source = options.source || ''; + } + this.compiled = { 'simple': {}, 'advanced': {} }; + this.hybrid = { 'simple': {}, 'advanced': {} }; + this.uglified = {}; + + this.isSilent = !!options.isSilent; + this.isTemplate = !!options.isTemplate; + this.outputPath = options.outputPath; + + source = preprocess(source, options); + this.source = source; + + this.onComplete = options.onComplete || function(source) { + fs.writeFileSync(this.outputPath, source, 'utf8'); + }; + + // begin the minification process + closureCompile.call(this, source, 'simple', onClosureSimpleCompile.bind(this)); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Fetches a required `.tar.gz` dependency with the given Git object ID from + * the Lo-Dash repo on GitHub. The object ID may be obtained by running + * `git hash-object path/to/dependency.tar.gz`. + * + * @private + * @param {Object} options The options object. + * id - The Git object ID of the `.tar.gz` file. + * onComplete - The function, invoked with one argument (exception), + * called once the extraction has finished. + * path - The path of the extraction directory. + * title - The dependency's title used in status updates logged to the console. + */ + function getDependency(options) { + options || (options = {}); + + var ran, + destPath = options.path, + hashId = options.hashId, + id = options.id, + onComplete = options.onComplete, + title = options.title; + + // exit early if dependency exists + if (fs.existsSync(path.join(destPath, id))) { + onComplete(); + return; + } + var callback = function(exception) { + if (ran) { + return; + } + if (exception) { + console.error([ + 'There was a problem installing ' + title + '.', + 'Try running the command as root, via `sudo`, or manually install by running:', + '', + "curl -H 'Accept: " + mediaType + "' " + location.href + '/' + hashId + " | tar xvz -C '" + destPath + "'", + '' + ].join('\n')); + } + ran = true; + process.removeListener('uncaughtException', callback); + onComplete(exception); + }; + + console.log('Downloading ' + title + '...'); + process.on('uncaughtException', callback); + + https.get({ + 'host': location.host, + 'path': location.pathname + '/' + hashId, + 'headers': { + // By default, all GitHub blob API endpoints return a JSON document + // containing Base64-encoded blob data. Overriding the `Accept` header + // with the GitHub raw media type returns the blob data directly. + // See http://developer.github.com/v3/media/. + 'Accept': mediaType + } + }, function(response) { + var decompressor = zlib.createUnzip(), + parser = new tar.Extract({ 'path': destPath }); + + parser.on('end', callback); + response.pipe(decompressor).pipe(parser); + }); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Compresses a `source` string using the Closure Compiler. Yields the + * minified result, and any exceptions encountered, to a `callback` function. + * + * @private + * @param {String} source The JavaScript source to minify. + * @param {String} mode The optimization mode. + * @param {Function} callback The function called once the process has completed. + */ + function closureCompile(source, mode, callback) { + // use simple optimizations when minifying template files + var options = closureOptions.slice(); + options.push('--compilation_level=' + optimizationModes[this.isTemplate ? 'simple' : mode]); + + // the standard error stream, standard output stream, and the Closure Compiler process + var error = '', + output = '', + compiler = spawn('java', ['-jar', closurePath].concat(options)); + + if (!this.isSilent) { + console.log('Compressing ' + path.basename(this.outputPath, '.js') + ' using the Closure Compiler (' + mode + ')...'); + } + compiler.stdout.on('data', function(data) { + // append the data to the output stream + output += data; + }); + + compiler.stderr.on('data', function(data) { + // append the error message to the error stream + error += data; + }); + + compiler.on('exit', function(status) { + // `status` contains the process exit code + if (status) { + var exception = new Error(error); + exception.status = status; + } + callback(exception, output); + }); + + // proxy the standard input to the Closure Compiler + compiler.stdin.end(source); + } + + /** + * Compresses a `source` string using UglifyJS. Yields the result to a + * `callback` function. This function is synchronous; the `callback` is used + * for symmetry. + * + * @private + * @param {String} source The JavaScript source to minify. + * @param {String} label The label to log. + * @param {Function} callback The function called once the process has completed. + */ + function uglify(source, label, callback) { + if (!this.isSilent) { + console.log('Compressing ' + path.basename(this.outputPath, '.js') + ' using ' + label + '...'); + } + try { + var uglifyJS = require(uglifyPath); + + // 1. parse + var toplevel = uglifyJS.parse(source); + + // 2. compress + // enable unsafe comparisons + toplevel.figure_out_scope(); + toplevel = toplevel.transform(uglifyJS.Compressor({ + 'comparisons': false, + 'unsafe_comps': true, + 'warnings': false + })); + + // 3. mangle + // excluding the `define` function exposed by AMD loaders + toplevel.figure_out_scope(); + toplevel.compute_char_frequency(); + toplevel.mangle_names({ + 'except': ['define'] + }); + + // 4. output + // restrict lines to 500 characters for consistency with the Closure Compiler + var stream = uglifyJS.OutputStream({ + 'ascii_only': true, + 'comments': true, + 'max_line_len': 500, + }); + + toplevel.print(stream); + } + catch(e) { + var exception = e; + } + callback(exception, stream && String(stream)); + } + + /*--------------------------------------------------------------------------*/ + + /** + * The Closure Compiler callback for simple optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {String} result The resulting minified source. + */ + function onClosureSimpleCompile(exception, result) { + if (exception) { + throw exception; + } + result = postprocess(result); + this.compiled.simple.source = result; + zlib.gzip(result, onClosureSimpleGzip.bind(this)); + } + + /** + * The Closure Compiler `gzip` callback for simple optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {Buffer} result The resulting gzipped source. + */ + function onClosureSimpleGzip(exception, result) { + if (exception) { + throw exception; + } + if (!this.isSilent) { + console.log('Done. Size: %d bytes.', result.length); + } + this.compiled.simple.gzip = result; + + // next, compile the source using advanced optimizations + closureCompile.call(this, this.source, 'advanced', onClosureAdvancedCompile.bind(this)); + } + + /** + * The Closure Compiler callback for advanced optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {String} result The resulting minified source. + */ + function onClosureAdvancedCompile(exception, result) { + if (exception) { + throw exception; + } + result = postprocess(result); + this.compiled.advanced.source = result; + zlib.gzip(result, onClosureAdvancedGzip.bind(this)); + } + + /** + * The Closure Compiler `gzip` callback for advanced optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {Buffer} result The resulting gzipped source. + */ + function onClosureAdvancedGzip(exception, result) { + if (exception) { + throw exception; + } + if (!this.isSilent) { + console.log('Done. Size: %d bytes.', result.length); + } + this.compiled.advanced.gzip = result; + + // next, minify the source using only UglifyJS + uglify.call(this, this.source, 'UglifyJS', onUglify.bind(this)); + } + + /** + * The UglifyJS callback. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {String} result The resulting minified source. + */ + function onUglify(exception, result) { + if (exception) { + throw exception; + } + result = postprocess(result); + this.uglified.source = result; + zlib.gzip(result, onUglifyGzip.bind(this)); + } + + /** + * The UglifyJS `gzip` callback. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {Buffer} result The resulting gzipped source. + */ + function onUglifyGzip(exception, result) { + if (exception) { + throw exception; + } + if (!this.isSilent) { + console.log('Done. Size: %d bytes.', result.length); + } + this.uglified.gzip = result; + + // next, minify the already Closure Compiler simple optimized source using UglifyJS + uglify.call(this, this.compiled.simple.source, 'hybrid (simple)', onSimpleHybrid.bind(this)); + } + + /** + * The hybrid callback for simple optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {String} result The resulting minified source. + */ + function onSimpleHybrid(exception, result) { + if (exception) { + throw exception; + } + result = postprocess(result); + this.hybrid.simple.source = result; + zlib.gzip(result, onSimpleHybridGzip.bind(this)); + } + + /** + * The hybrid `gzip` callback for simple optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {Buffer} result The resulting gzipped source. + */ + function onSimpleHybridGzip(exception, result) { + if (exception) { + throw exception; + } + if (!this.isSilent) { + console.log('Done. Size: %d bytes.', result.length); + } + this.hybrid.simple.gzip = result; + + // next, minify the already Closure Compiler advance optimized source using UglifyJS + uglify.call(this, this.compiled.advanced.source, 'hybrid (advanced)', onAdvancedHybrid.bind(this)); + } + + /** + * The hybrid callback for advanced optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {String} result The resulting minified source. + */ + function onAdvancedHybrid(exception, result) { + if (exception) { + throw exception; + } + result = postprocess(result); + this.hybrid.advanced.source = result; + zlib.gzip(result, onAdvancedHybridGzip.bind(this)); + } + + /** + * The hybrid `gzip` callback for advanced optimizations. + * + * @private + * @param {Object|Undefined} exception The error object. + * @param {Buffer} result The resulting gzipped source. + */ + function onAdvancedHybridGzip(exception, result) { + if (exception) { + throw exception; + } + if (!this.isSilent) { + console.log('Done. Size: %d bytes.', result.length); + } + this.hybrid.advanced.gzip = result; + + // finish by choosing the smallest compressed file + onComplete.call(this); + } + + /** + * The callback executed after the source is minified and gzipped. + * + * @private + */ + function onComplete() { + var compiledSimple = this.compiled.simple, + compiledAdvanced = this.compiled.advanced, + uglified = this.uglified, + hybridSimple = this.hybrid.simple, + hybridAdvanced = this.hybrid.advanced; + + // select the smallest gzipped file and use its minified counterpart as the + // official minified release (ties go to the Closure Compiler) + var min = Math.min( + compiledSimple.gzip.length, + compiledAdvanced.gzip.length, + uglified.gzip.length, + hybridSimple.gzip.length, + hybridAdvanced.gzip.length + ); + + // pass the minified source to the "onComplete" callback + [compiledSimple, compiledAdvanced, uglified, hybridSimple, hybridAdvanced].some(function(data) { + if (data.gzip.length == min) { + this.onComplete(data.source); + } + }, this); + } + + /*--------------------------------------------------------------------------*/ + + // expose `minify` + if (module != require.main) { + module.exports = minify; + } + else { + // read the Lo-Dash source file from the first argument if the script + // was invoked directly (e.g. `node minify.js source.js`) and write to + // `.min.js` + (function() { + var options = process.argv; + if (options.length < 3) { + return; + } + minify(options); + }()); + } +}()); diff --git a/node/node_modules/grunt/node_modules/lodash/build/post-compile.js b/node/node_modules/grunt/node_modules/lodash/build/post-compile.js new file mode 100644 index 000000000..11e855e28 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/build/post-compile.js @@ -0,0 +1,85 @@ +#!/usr/bin/env node +;(function() { + 'use strict'; + + /** The Node filesystem module */ + var fs = require('fs'); + + /** The minimal license/copyright template */ + var licenseTemplate = { + 'lodash': + '/*!\n' + + ' Lo-Dash @VERSION lodash.com/license\n' + + ' Underscore.js 1.4.2 underscorejs.org/LICENSE\n' + + '*/', + 'underscore': + '/*! Underscore.js @VERSION underscorejs.org/LICENSE */' + }; + + /*--------------------------------------------------------------------------*/ + + /** + * Post-process a given minified Lo-Dash `source`, preparing it for + * deployment. + * + * @param {String} source The source to process. + * @returns {String} Returns the processed source. + */ + function postprocess(source) { + // remove old copyright/license header + source = source.replace(/^\/\*![\s\S]+?\*\/\n/, ''); + + // move vars exposed by the Closure Compiler into the IIFE + source = source.replace(/^((?:(['"])use strict\2;)?(?:var (?:[a-z]+=(?:!0|!1|null)[,;])+)?)([\s\S]*?function[^)]+\){)/, '$3$1'); + + // correct overly aggressive Closure Compiler advanced optimizations + source = source.replace(/prototype\s*=\s*{\s*valueOf\s*:\s*1\s*}/, 'prototype={valueOf:1,y:1}'); + + // unescape properties (i.e. foo["bar"] => foo.bar) + source = source.replace(/(\w)\["([^."]+)"\]/g, function(match, left, right) { + return /\W/.test(right) ? match : (left + '.' + right); + }); + + // flip `typeof` expressions to help optimize Safari and + // correct the AMD module definition for AMD build optimizers + // (e.g. from `"number" == typeof x` to `typeof x == "number") + source = source.replace(/(return)?("[^"]+")\s*([!=]=)\s*(typeof(?:\s*\([^)]+\)|\s+[\w.]+))/g, function(match, ret, type, equality, expression) { + return (ret ? ret + ' ' : '') + expression + equality + type; + }); + + // add trailing semicolon + if (source) { + source = source.replace(/[\s;]*$/, ';'); + } + // exit early if version snippet isn't found + var snippet = /VERSION\s*[=:]\s*([\'"])(.*?)\1/.exec(source); + if (!snippet) { + return source; + } + // add license + return licenseTemplate[/call\(this\);?$/.test(source) ? 'underscore' : 'lodash'] + .replace('@VERSION', snippet[2]) + '\n;' + source; + } + + /*--------------------------------------------------------------------------*/ + + // expose `postprocess` + if (module != require.main) { + module.exports = postprocess; + } + else { + // read the Lo-Dash source file from the first argument if the script + // was invoked directly (e.g. `node post-compile.js source.js`) and write to + // the same file + (function() { + var options = process.argv; + if (options.length < 3) { + return; + } + var filePath = options[options.length - 1], + source = fs.readFileSync(filePath, 'utf8'); + + fs.writeFileSync(filePath, postprocess(source), 'utf8'); + }()); + } +}()); diff --git a/node/node_modules/grunt/node_modules/lodash/build/pre-compile.js b/node/node_modules/grunt/node_modules/lodash/build/pre-compile.js new file mode 100644 index 000000000..1c13cef96 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/build/pre-compile.js @@ -0,0 +1,384 @@ +#!/usr/bin/env node +;(function() { + 'use strict'; + + /** The Node filesystem module */ + var fs = require('fs'); + + /** Used to minify variables embedded in compiled strings */ + var compiledVars = [ + 'argsIndex', + 'argsLength', + 'callback', + 'collection', + 'createCallback', + 'ctor', + 'hasOwnProperty', + 'index', + 'isArguments', + 'isString', + 'iteratee', + 'length', + 'nativeKeys', + 'object', + 'objectTypes', + 'ownIndex', + 'ownProps', + 'propertyIsEnumerable', + 'result', + 'skipProto', + 'thisArg', + 'value' + ]; + + /** Used to minify `compileIterator` option properties */ + var iteratorOptions = [ + 'args', + 'arrayLoop', + 'bottom', + 'firstArg', + 'hasDontEnumBug', + 'isKeysFast', + 'objectLoop', + 'noArgsEnum', + 'noCharByIndex', + 'shadowed', + 'top', + 'useHas', + 'useStrict' + ]; + + /** Used to minify variables and string values to a single character */ + var minNames = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); + minNames.push.apply(minNames, minNames.map(function(value) { + return value + value; + })); + + /** Used to protect the specified properties from getting minified */ + var propWhitelist = [ + '_', + '__chain__', + '__wrapped__', + 'after', + 'all', + 'amd', + 'any', + 'attachEvent', + 'bind', + 'bindAll', + 'chain', + 'clone', + 'collect', + 'compact', + 'compose', + 'contains', + 'countBy', + 'criteria', + 'debounce', + 'defaults', + 'defer', + 'delay', + 'detect', + 'difference', + 'drop', + 'each', + 'environment', + 'escape', + 'evaluate', + 'every', + 'exports', + 'extend', + 'filter', + 'find', + 'first', + 'flatten', + 'foldl', + 'foldr', + 'forEach', + 'forIn', + 'forOwn', + 'functions', + 'global', + 'groupBy', + 'has', + 'head', + 'identity', + 'include', + 'index', + 'indexOf', + 'initial', + 'inject', + 'interpolate', + 'intersection', + 'invert', + 'invoke', + 'isArguments', + 'isArray', + 'isBoolean', + 'isDate', + 'isElement', + 'isEmpty', + 'isEqual', + 'isEqual', + 'isFinite', + 'isFinite', + 'isFunction', + 'isNaN', + 'isNull', + 'isNumber', + 'isObject', + 'isPlainObject', + 'isRegExp', + 'isString', + 'isUndefined', + 'keys', + 'last', + 'lastIndexOf', + 'lateBind', + 'map', + 'max', + 'memoize', + 'merge', + 'methods', + 'min', + 'mixin', + 'noConflict', + 'object', + 'omit', + 'once', + 'opera', + 'pairs', + 'partial', + 'pick', + 'pluck', + 'random', + 'range', + 'reduce', + 'reduceRight', + 'reject', + 'rest', + 'result', + 'select', + 'shuffle', + 'size', + 'some', + 'sortBy', + 'sortedIndex', + 'source', + 'tail', + 'take', + 'tap', + 'template', + 'templateSettings', + 'throttle', + 'times', + 'toArray', + 'unescape', + 'union', + 'uniq', + 'unique', + 'uniqueId', + 'value', + 'values', + 'variable', + 'VERSION', + 'where', + 'without', + 'wrap', + 'zip', + + // properties used by underscore.js + '_chain', + '_wrapped' + ]; + + /*--------------------------------------------------------------------------*/ + + /** + * Pre-process a given Lo-Dash `source`, preparing it for minification. + * + * @param {String} [source=''] The source to process. + * @param {Object} [options={}] The options object. + * @returns {String} Returns the processed source. + */ + function preprocess(source, options) { + source || (source = ''); + options || (options = {}); + + // remove unrecognized JSDoc tags so the Closure Compiler won't complain + source = source.replace(/@(?:alias|category)\b.*/g, ''); + + if (options.isTemplate) { + return source; + } + + // remove copyright to add later in post-compile.js + source = source.replace(/\/\*![\s\S]+?\*\//, ''); + + // add brackets to whitelisted properties so the Closure Compiler won't mung them + // http://code.google.com/closure/compiler/docs/api-tutorial3.html#export + source = source.replace(RegExp('\\.(' + propWhitelist.join('|') + ')\\b', 'g'), "['$1']"); + + // remove brackets from `_.escape()` in `_.template` + source = source.replace(/__e *= *_\['escape']/g, '__e=_.escape'); + + // remove brackets from `_.escape()` in underscore.js `_.template` + source = source.replace(/_\['escape'\]\(__t'/g, '_.escape(__t'); + + // remove brackets from `collection.indexOf` in `_.contains` + source = source.replace("collection['indexOf'](target)", 'collection.indexOf(target)'); + + // remove brackets from `result[length].value` in `_.sortBy` + source = source.replace("result[length]['value']", 'result[length].value'); + + // remove whitespace from string literals + source = source.replace(/'(?:(?=(\\?))\1.)*?'/g, function(string) { + // avoids removing the '\n' of the `stringEscapes` object + return string.replace(/\[object |delete |else |function | in |return\s+[\w']|throw |typeof |use strict|var |@ |'\\n'|\\\\n|\\n|\s+/g, function(match) { + return match == false || match == '\\n' ? '' : match; + }); + }); + + // add newline to `+"__p+='"` in underscore.js `_.template` + source = source.replace(/\+"__p\+='"/g, '+"\\n__p+=\'"'); + + // remove whitespace from `_.template` related regexes + source = source.replace(/(?:reEmptyString\w+|reInsertVariable) *=.+/g, function(match) { + return match.replace(/ |\\n/g, ''); + }); + + // remove newline from double-quoted strings in `_.template` + source = source + .replace('"\';\\n__with ("', '"\';__with("') + .replace('"\\n}__\\n__p += \'"', '"}____p+=\'"') + .replace('"__p = \'"', '"__p=\'"') + .replace('"\';\\n"', '"\';"') + .replace("') {\\n'", "'){'") + + // remove `useSourceURL` variable + source = source.replace(/(?:\n +\/\*[^*]*\*+(?:[^\/][^*]*\*+)*\/)?\n *try *\{(?:\s*\/\/.*)*\n *var useSourceURL[\s\S]+?catch[^}]+}\n/, ''); + + // remove debug sourceURL use in `_.template` + source = source.replace(/(?:\s*\/\/.*\n)* *var sourceURL[^;]+;|\+ *sourceURL/g, ''); + + // minify internal properties used by 'compareAscending' and `_.sortBy` + (function() { + var properties = ['criteria', 'index', 'value'], + snippets = source.match(/( +)function (?:compareAscending|sortBy)\b[\s\S]+?\n\1}/g); + + if (!snippets) { + return; + } + snippets.forEach(function(snippet) { + var modified = snippet; + + // minify properties + properties.forEach(function(property, index) { + var reBracketProp = RegExp("\\['(" + property + ")'\\]", 'g'), + reDotProp = RegExp('\\.' + property + '\\b', 'g'), + rePropColon = RegExp("([^?\\s])\\s*([\"'])?\\b" + property + "\\2 *:", 'g'); + + modified = modified + .replace(reBracketProp, "['" + minNames[index] + "']") + .replace(reDotProp, "['" + minNames[index] + "']") + .replace(rePropColon, "$1'" + minNames[index] + "':"); + }); + + // replace with modified snippet + source = source.replace(snippet, modified); + }); + }()); + + // minify all compilable snippets + var snippets = source.match( + RegExp([ + // match the `iteratorTemplate` + '( +)var iteratorTemplate\\b[\\s\\S]+?\\n\\1}', + // match methods created by `createIterator` calls + 'createIterator\\((?:{|[a-zA-Z]+)[\\s\\S]+?\\);\\n', + // match variables storing `createIterator` options + '( +)var [a-zA-Z]+IteratorOptions\\b[\\s\\S]+?\\n\\2}', + // match the the `createIterator` function + '( +)function createIterator\\b[\\s\\S]+?\\n\\3}' + ].join('|'), 'g') + ); + + // exit early if no compilable snippets + if (!snippets) { + return source; + } + + snippets.forEach(function(snippet, index) { + var isCreateIterator = /function createIterator\b/.test(snippet), + isIteratorTemplate = /var iteratorTemplate\b/.test(snippet), + modified = snippet; + + // add brackets to whitelisted properties so the Closure Compiler won't mung them + modified = modified.replace(RegExp('\\.(' + iteratorOptions.join('|') + ')\\b', 'g'), "['$1']"); + + if (isCreateIterator) { + // replace with modified snippet early and clip snippet to the `factory` + // call so other arguments aren't minified + source = source.replace(snippet, modified); + snippet = modified = modified.replace(/factory\([\s\S]+$/, ''); + } + + // minify snippet variables / arguments + compiledVars.forEach(function(variable, index) { + // ensure properties in compiled strings aren't minified + modified = modified.replace(RegExp('([^.]\\b)' + variable + '\\b(?!\' *[\\]:])', 'g'), '$1' + minNames[index]); + + // correct `typeof x == 'object'` + if (variable == 'object') { + modified = modified.replace(RegExp("(typeof [^']+')" + minNames[index] + "'", 'g'), "$1object'"); + } + }); + + // minify `createIterator` option property names + iteratorOptions.forEach(function(property, index) { + if (isIteratorTemplate) { + // minify property names as interpolated template variables + modified = modified.replace(RegExp('\\b' + property + '\\b', 'g'), minNames[index]); + } + else { + // minify property name strings + modified = modified.replace(RegExp("'" + property + "'", 'g'), "'" + minNames[index] + "'"); + // minify property names in accessors + if (isCreateIterator) { + modified = modified.replace(RegExp('\\.' + property + '\\b' , 'g'), '.' + minNames[index]); + } + } + }); + + // replace with modified snippet + source = source.replace(snippet, modified); + }); + + return source; + } + + /*--------------------------------------------------------------------------*/ + + // expose `preprocess` + if (module != require.main) { + module.exports = preprocess; + } + else { + // read the Lo-Dash source file from the first argument if the script + // was invoked directly (e.g. `node pre-compile.js source.js`) and write to + // the same file + (function() { + var options = process.argv; + if (options.length < 3) { + return; + } + var filePath = options[options.length - 1], + isTemplate = options.indexOf('-t') > -1 || options.indexOf('--template') > -1, + source = fs.readFileSync(filePath, 'utf8'); + + fs.writeFileSync(filePath, preprocess(source, { + 'isTemplate': isTemplate + }), 'utf8'); + }()); + } +}()); diff --git a/node/node_modules/grunt/node_modules/lodash/doc/README.md b/node/node_modules/grunt/node_modules/lodash/doc/README.md new file mode 100644 index 000000000..8ad38fb4a --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/doc/README.md @@ -0,0 +1,3095 @@ +# Lo-Dash v0.9.2 + + + + + + +## `Arrays` +* [`_.compact`](#_compactarray) +* [`_.difference`](#_differencearray--array1-array2-) +* [`_.drop`](#_restarray--n1) +* [`_.first`](#_firstarray--n) +* [`_.flatten`](#_flattenarray-shallow) +* [`_.head`](#_firstarray--n) +* [`_.indexOf`](#_indexofarray-value--fromindex0) +* [`_.initial`](#_initialarray--n1) +* [`_.intersection`](#_intersectionarray1-array2-) +* [`_.last`](#_lastarray--n) +* [`_.lastIndexOf`](#_lastindexofarray-value--fromindexarraylength-1) +* [`_.object`](#_objectkeys--values) +* [`_.range`](#_rangestart0-end--step1) +* [`_.rest`](#_restarray--n1) +* [`_.sortedIndex`](#_sortedindexarray-value--callbackidentityproperty-thisarg) +* [`_.tail`](#_restarray--n1) +* [`_.take`](#_firstarray--n) +* [`_.union`](#_unionarray1-array2-) +* [`_.uniq`](#_uniqarray--issortedfalse-callbackidentity-thisarg) +* [`_.unique`](#_uniqarray--issortedfalse-callbackidentity-thisarg) +* [`_.without`](#_withoutarray--value1-value2-) +* [`_.zip`](#_ziparray1-array2-) + + + + + + +## `Chaining` +* [`_`](#_value) +* [`_.chain`](#_chainvalue) +* [`_.tap`](#_tapvalue-interceptor) +* [`_.prototype.chain`](#_prototypechain) +* [`_.prototype.value`](#_prototypevalue) + + + + + + +## `Collections` +* [`_.all`](#_everycollection--callbackidentity-thisarg) +* [`_.any`](#_somecollection--callbackidentity-thisarg) +* [`_.collect`](#_mapcollection--callbackidentity-thisarg) +* [`_.contains`](#_containscollection-target--fromindex0) +* [`_.countBy`](#_countbycollection-callbackproperty--thisarg) +* [`_.detect`](#_findcollection-callback--thisarg) +* [`_.each`](#_foreachcollection-callback--thisarg) +* [`_.every`](#_everycollection--callbackidentity-thisarg) +* [`_.filter`](#_filtercollection--callbackidentity-thisarg) +* [`_.find`](#_findcollection-callback--thisarg) +* [`_.foldl`](#_reducecollection-callback--accumulator-thisarg) +* [`_.foldr`](#_reducerightcollection-callback--accumulator-thisarg) +* [`_.forEach`](#_foreachcollection-callback--thisarg) +* [`_.groupBy`](#_groupbycollection-callbackproperty--thisarg) +* [`_.include`](#_containscollection-target--fromindex0) +* [`_.inject`](#_reducecollection-callback--accumulator-thisarg) +* [`_.invoke`](#_invokecollection-methodname--arg1-arg2-) +* [`_.map`](#_mapcollection--callbackidentity-thisarg) +* [`_.max`](#_maxcollection--callback-thisarg) +* [`_.min`](#_mincollection--callback-thisarg) +* [`_.pluck`](#_pluckcollection-property) +* [`_.reduce`](#_reducecollection-callback--accumulator-thisarg) +* [`_.reduceRight`](#_reducerightcollection-callback--accumulator-thisarg) +* [`_.reject`](#_rejectcollection--callbackidentity-thisarg) +* [`_.select`](#_filtercollection--callbackidentity-thisarg) +* [`_.shuffle`](#_shufflecollection) +* [`_.size`](#_sizecollection) +* [`_.some`](#_somecollection--callbackidentity-thisarg) +* [`_.sortBy`](#_sortbycollection-callbackproperty--thisarg) +* [`_.toArray`](#_toarraycollection) +* [`_.where`](#_wherecollection-properties) + + + + + + +## `Functions` +* [`_.after`](#_aftern-func) +* [`_.bind`](#_bindfunc--thisarg-arg1-arg2-) +* [`_.bindAll`](#_bindallobject--methodname1-methodname2-) +* [`_.compose`](#_composefunc1-func2-) +* [`_.debounce`](#_debouncefunc-wait-immediate) +* [`_.defer`](#_deferfunc--arg1-arg2-) +* [`_.delay`](#_delayfunc-wait--arg1-arg2-) +* [`_.lateBind`](#_latebindobject-methodname--arg1-arg2-) +* [`_.memoize`](#_memoizefunc--resolver) +* [`_.once`](#_oncefunc) +* [`_.partial`](#_partialfunc--arg1-arg2-) +* [`_.throttle`](#_throttlefunc-wait) +* [`_.wrap`](#_wrapvalue-wrapper) + + + + + + +## `Objects` +* [`_.clone`](#_clonevalue-deep) +* [`_.defaults`](#_defaultsobject--default1-default2-) +* [`_.extend`](#_extendobject--source1-source2-) +* [`_.forIn`](#_forinobject-callback--thisarg) +* [`_.forOwn`](#_forownobject-callback--thisarg) +* [`_.functions`](#_functionsobject) +* [`_.has`](#_hasobject-property) +* [`_.invert`](#_invertobject) +* [`_.isArguments`](#_isargumentsvalue) +* [`_.isArray`](#_isarrayvalue) +* [`_.isBoolean`](#_isbooleanvalue) +* [`_.isDate`](#_isdatevalue) +* [`_.isElement`](#_iselementvalue) +* [`_.isEmpty`](#_isemptyvalue) +* [`_.isEqual`](#_isequala-b) +* [`_.isFinite`](#_isfinitevalue) +* [`_.isFunction`](#_isfunctionvalue) +* [`_.isNaN`](#_isnanvalue) +* [`_.isNull`](#_isnullvalue) +* [`_.isNumber`](#_isnumbervalue) +* [`_.isObject`](#_isobjectvalue) +* [`_.isPlainObject`](#_isplainobjectvalue) +* [`_.isRegExp`](#_isregexpvalue) +* [`_.isString`](#_isstringvalue) +* [`_.isUndefined`](#_isundefinedvalue) +* [`_.keys`](#_keysobject) +* [`_.merge`](#_mergeobject--source1-source2-) +* [`_.methods`](#_functionsobject) +* [`_.omit`](#_omitobject-callback-prop1-prop2--thisarg) +* [`_.pairs`](#_pairsobject) +* [`_.pick`](#_pickobject-callback-prop1-prop2--thisarg) +* [`_.values`](#_valuesobject) + + + + + + +## `Utilities` +* [`_.escape`](#_escapestring) +* [`_.identity`](#_identityvalue) +* [`_.mixin`](#_mixinobject) +* [`_.noConflict`](#_noconflict) +* [`_.random`](#_randommin0-max1) +* [`_.result`](#_resultobject-property) +* [`_.template`](#_templatetext-data-options) +* [`_.times`](#_timesn-callback--thisarg) +* [`_.unescape`](#_unescapestring) +* [`_.uniqueId`](#_uniqueidprefix) + + + + + + +## `Properties` +* [`_.VERSION`](#_version) +* [`_.templateSettings`](#_templatesettings) +* [`_.templateSettings.escape`](#_templatesettingsescape) +* [`_.templateSettings.evaluate`](#_templatesettingsevaluate) +* [`_.templateSettings.interpolate`](#_templatesettingsinterpolate) +* [`_.templateSettings.variable`](#_templatesettingsvariable) + + + + + + + + + + + + +## `“Arrays” Methods` + + + +### `_.compact(array)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2554 "View in source") [Ⓣ][1] + +Creates an array with all falsey values of `array` removed. The values `false`, `null`, `0`, `""`, `undefined` and `NaN` are all falsey. + +#### Arguments +1. `array` *(Array)*: The array to compact. + +#### Returns +*(Array)*: Returns a new filtered array. + +#### Example +```js +_.compact([0, 1, false, 2, '', 3]); +// => [1, 2, 3] +``` + +* * * + + + + + + +### `_.difference(array [, array1, array2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2584 "View in source") [Ⓣ][1] + +Creates an array of `array` elements not present in the other arrays using strict equality for comparisons, i.e. `===`. + +#### Arguments +1. `array` *(Array)*: The array to process. +2. `[array1, array2, ...]` *(Array)*: Arrays to check. + +#### Returns +*(Array)*: Returns a new array of `array` elements not present in the other arrays. + +#### Example +```js +_.difference([1, 2, 3, 4, 5], [5, 2, 10]); +// => [1, 3, 4] +``` + +* * * + + + + + + +### `_.first(array [, n])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2619 "View in source") [Ⓣ][1] + +Gets the first element of the `array`. Pass `n` to return the first `n` elements of the `array`. + +#### Aliases +*head, take* + +#### Arguments +1. `array` *(Array)*: The array to query. +2. `[n]` *(Number)*: The number of elements to return. + +#### Returns +*(Mixed)*: Returns the first element or an array of the first `n` elements of `array`. + +#### Example +```js +_.first([5, 4, 3, 2, 1]); +// => 5 +``` + +* * * + + + + + + +### `_.flatten(array, shallow)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2643 "View in source") [Ⓣ][1] + +Flattens a nested array *(the nesting can be to any depth)*. If `shallow` is truthy, `array` will only be flattened a single level. + +#### Arguments +1. `array` *(Array)*: The array to compact. +2. `shallow` *(Boolean)*: A flag to indicate only flattening a single level. + +#### Returns +*(Array)*: Returns a new flattened array. + +#### Example +```js +_.flatten([1, [2], [3, [[4]]]]); +// => [1, 2, 3, 4]; + +_.flatten([1, [2], [3, [[4]]]], true); +// => [1, 2, 3, [[4]]]; +``` + +* * * + + + + + + +### `_.indexOf(array, value [, fromIndex=0])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2685 "View in source") [Ⓣ][1] + +Gets the index at which the first occurrence of `value` is found using strict equality for comparisons, i.e. `===`. If the `array` is already sorted, passing `true` for `fromIndex` will run a faster binary search. + +#### Arguments +1. `array` *(Array)*: The array to search. +2. `value` *(Mixed)*: The value to search for. +3. `[fromIndex=0]` *(Boolean|Number)*: The index to search from or `true` to perform a binary search on a sorted `array`. + +#### Returns +*(Number)*: Returns the index of the matched value or `-1`. + +#### Example +```js +_.indexOf([1, 2, 3, 1, 2, 3], 2); +// => 1 + +_.indexOf([1, 2, 3, 1, 2, 3], 2, 3); +// => 4 + +_.indexOf([1, 1, 2, 2, 3, 3], 2, true); +// => 2 +``` + +* * * + + + + + + +### `_.initial(array [, n=1])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2720 "View in source") [Ⓣ][1] + +Gets all but the last element of `array`. Pass `n` to exclude the last `n` elements from the result. + +#### Arguments +1. `array` *(Array)*: The array to query. +2. `[n=1]` *(Number)*: The number of elements to exclude. + +#### Returns +*(Array)*: Returns all but the last element or `n` elements of `array`. + +#### Example +```js +_.initial([3, 2, 1]); +// => [3, 2] +``` + +* * * + + + + + + +### `_.intersection([array1, array2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2741 "View in source") [Ⓣ][1] + +Computes the intersection of all the passed-in arrays using strict equality for comparisons, i.e. `===`. + +#### Arguments +1. `[array1, array2, ...]` *(Array)*: Arrays to process. + +#### Returns +*(Array)*: Returns a new array of unique elements, in order, that are present in **all** of the arrays. + +#### Example +```js +_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); +// => [1, 2] +``` + +* * * + + + + + + +### `_.last(array [, n])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2779 "View in source") [Ⓣ][1] + +Gets the last element of the `array`. Pass `n` to return the last `n` elements of the `array`. + +#### Arguments +1. `array` *(Array)*: The array to query. +2. `[n]` *(Number)*: The number of elements to return. + +#### Returns +*(Mixed)*: Returns the last element or an array of the last `n` elements of `array`. + +#### Example +```js +_.last([3, 2, 1]); +// => 1 +``` + +* * * + + + + + + +### `_.lastIndexOf(array, value [, fromIndex=array.length-1])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2806 "View in source") [Ⓣ][1] + +Gets the index at which the last occurrence of `value` is found using strict equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the offset from the end of the collection. + +#### Arguments +1. `array` *(Array)*: The array to search. +2. `value` *(Mixed)*: The value to search for. +3. `[fromIndex=array.length-1]` *(Number)*: The index to search from. + +#### Returns +*(Number)*: Returns the index of the matched value or `-1`. + +#### Example +```js +_.lastIndexOf([1, 2, 3, 1, 2, 3], 2); +// => 4 + +_.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); +// => 1 +``` + +* * * + + + + + + +### `_.object(keys [, values=[]])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2836 "View in source") [Ⓣ][1] + +Creates an object composed from arrays of `keys` and `values`. Pass either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]`, or two arrays, one of `keys` and one of corresponding `values`. + +#### Arguments +1. `keys` *(Array)*: The array of keys. +2. `[values=[]]` *(Array)*: The array of values. + +#### Returns +*(Object)*: Returns an object composed of the given keys and corresponding values. + +#### Example +```js +_.object(['moe', 'larry', 'curly'], [30, 40, 50]); +// => { 'moe': 30, 'larry': 40, 'curly': 50 } +``` + +* * * + + + + + + +### `_.range([start=0], end [, step=1])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2881 "View in source") [Ⓣ][1] + +Creates an array of numbers *(positive and/or negative)* progressing from `start` up to but not including `stop`. This method is a port of Python's `range()` function. See http://docs.python.org/library/functions.html#range. + +#### Arguments +1. `[start=0]` *(Number)*: The start of the range. +2. `end` *(Number)*: The end of the range. +3. `[step=1]` *(Number)*: The value to increment or descrement by. + +#### Returns +*(Array)*: Returns a new range array. + +#### Example +```js +_.range(10); +// => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + +_.range(1, 11); +// => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + +_.range(0, 30, 5); +// => [0, 5, 10, 15, 20, 25] + +_.range(0, -10, -1); +// => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] + +_.range(0); +// => [] +``` + +* * * + + + + + + +### `_.rest(array [, n=1])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2920 "View in source") [Ⓣ][1] + +The opposite of `_.initial`, this method gets all but the first value of `array`. Pass `n` to exclude the first `n` values from the result. + +#### Aliases +*drop, tail* + +#### Arguments +1. `array` *(Array)*: The array to query. +2. `[n=1]` *(Number)*: The number of elements to exclude. + +#### Returns +*(Array)*: Returns all but the first value or `n` values of `array`. + +#### Example +```js +_.rest([3, 2, 1]); +// => [2, 1] +``` + +* * * + + + + + + +### `_.sortedIndex(array, value [, callback=identity|property, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2966 "View in source") [Ⓣ][1] + +Uses a binary search to determine the smallest index at which the `value` should be inserted into `array` in order to maintain the sort order of the sorted `array`. If `callback` is passed, it will be executed for `value` and each element in `array` to compute their sort ranking. The `callback` is bound to `thisArg` and invoked with one argument; *(value)*. The `callback` argument may also be the name of a property to order by. + +#### Arguments +1. `array` *(Array)*: The array to iterate over. +2. `value` *(Mixed)*: The value to evaluate. +3. `[callback=identity|property]` *(Function|String)*: The function called per iteration or property name to order by. +4. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Number)*: Returns the index at which the value should be inserted into `array`. + +#### Example +```js +_.sortedIndex([20, 30, 50], 40); +// => 2 + +_.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); +// => 2 + +var dict = { + 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } +}; + +_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + return dict.wordToNumber[word]; +}); +// => 2 + +_.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { + return this.wordToNumber[word]; +}, dict); +// => 2 +``` + +* * * + + + + + + +### `_.union([array1, array2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2997 "View in source") [Ⓣ][1] + +Computes the union of the passed-in arrays using strict equality for comparisons, i.e. `===`. + +#### Arguments +1. `[array1, array2, ...]` *(Array)*: Arrays to process. + +#### Returns +*(Array)*: Returns a new array of unique values, in order, that are present in one or more of the arrays. + +#### Example +```js +_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); +// => [1, 2, 3, 101, 10] +``` + +* * * + + + + + + +### `_.uniq(array [, isSorted=false, callback=identity, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3031 "View in source") [Ⓣ][1] + +Creates a duplicate-value-free version of the `array` using strict equality for comparisons, i.e. `===`. If the `array` is already sorted, passing `true` for `isSorted` will run a faster algorithm. If `callback` is passed, each element of `array` is passed through a callback` before uniqueness is computed. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index, array)*. + +#### Aliases +*unique* + +#### Arguments +1. `array` *(Array)*: The array to process. +2. `[isSorted=false]` *(Boolean)*: A flag to indicate that the `array` is already sorted. +3. `[callback=identity]` *(Function)*: The function called per iteration. +4. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Array)*: Returns a duplicate-value-free array. + +#### Example +```js +_.uniq([1, 2, 1, 3, 1]); +// => [1, 2, 3] + +_.uniq([1, 1, 2, 2, 3], true); +// => [1, 2, 3] + +_.uniq([1, 2, 1.5, 3, 2.5], function(num) { return Math.floor(num); }); +// => [1, 2, 3] + +_.uniq([1, 2, 1.5, 3, 2.5], function(num) { return this.floor(num); }, Math); +// => [1, 2, 3] +``` + +* * * + + + + + + +### `_.without(array [, value1, value2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3089 "View in source") [Ⓣ][1] + +Creates an array with all occurrences of the passed values removed using strict equality for comparisons, i.e. `===`. + +#### Arguments +1. `array` *(Array)*: The array to filter. +2. `[value1, value2, ...]` *(Mixed)*: Values to remove. + +#### Returns +*(Array)*: Returns a new filtered array. + +#### Example +```js +_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); +// => [2, 3, 4] +``` + +* * * + + + + + + +### `_.zip([array1, array2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3120 "View in source") [Ⓣ][1] + +Groups the elements of each array at their corresponding indexes. Useful for separate data sources that are coordinated through matching array indexes. For a matrix of nested arrays, `_.zip.apply(...)` can transpose the matrix in a similar fashion. + +#### Arguments +1. `[array1, array2, ...]` *(Array)*: Arrays to process. + +#### Returns +*(Array)*: Returns a new array of grouped elements. + +#### Example +```js +_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]); +// => [['moe', 30, true], ['larry', 40, false], ['curly', 50, false]] +``` + +* * * + + + + + + + + + +## `“Chaining” Methods` + + + +### `_(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L242 "View in source") [Ⓣ][1] + +The `lodash` function. + +#### Arguments +1. `value` *(Mixed)*: The value to wrap in a `lodash` instance. + +#### Returns +*(Object)*: Returns a `lodash` instance. + +* * * + + + + + + +### `_.chain(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3985 "View in source") [Ⓣ][1] + +Wraps the value in a `lodash` wrapper object. + +#### Arguments +1. `value` *(Mixed)*: The value to wrap. + +#### Returns +*(Object)*: Returns the wrapper object. + +#### Example +```js +var stooges = [ + { 'name': 'moe', 'age': 40 }, + { 'name': 'larry', 'age': 50 }, + { 'name': 'curly', 'age': 60 } +]; + +var youngest = _.chain(stooges) + .sortBy(function(stooge) { return stooge.age; }) + .map(function(stooge) { return stooge.name + ' is ' + stooge.age; }) + .first() + .value(); +// => 'moe is 40' +``` + +* * * + + + + + + +### `_.tap(value, interceptor)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4012 "View in source") [Ⓣ][1] + +Invokes `interceptor` with the `value` as the first argument, and then returns `value`. The purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. + +#### Arguments +1. `value` *(Mixed)*: The value to pass to `interceptor`. +2. `interceptor` *(Function)*: The function to invoke. + +#### Returns +*(Mixed)*: Returns `value`. + +#### Example +```js +_.chain([1, 2, 3, 200]) + .filter(function(num) { return num % 2 == 0; }) + .tap(alert) + .map(function(num) { return num * num }) + .value(); +// => // [2, 200] (alerted) +// => [4, 40000] +``` + +* * * + + + + + + +### `_.prototype.chain()` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4030 "View in source") [Ⓣ][1] + +Enables method chaining on the wrapper object. + +#### Returns +*(Mixed)*: Returns the wrapper object. + +#### Example +```js +_([1, 2, 3]).value(); +// => [1, 2, 3] +``` + +* * * + + + + + + +### `_.prototype.value()` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L4047 "View in source") [Ⓣ][1] + +Extracts the wrapped value. + +#### Returns +*(Mixed)*: Returns the wrapped value. + +#### Example +```js +_([1, 2, 3]).value(); +// => [1, 2, 3] +``` + +* * * + + + + + + + + + +## `“Collections” Methods` + + + +### `_.contains(collection, target [, fromIndex=0])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1837 "View in source") [Ⓣ][1] + +Checks if a given `target` element is present in a `collection` using strict equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the offset from the end of the collection. + +#### Aliases +*include* + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `target` *(Mixed)*: The value to check for. +3. `[fromIndex=0]` *(Number)*: The index to search from. + +#### Returns +*(Boolean)*: Returns `true` if the `target` element is found, else `false`. + +#### Example +```js +_.contains([1, 2, 3], 1); +// => true + +_.contains([1, 2, 3], 1, 2); +// => false + +_.contains({ 'name': 'moe', 'age': 40 }, 'moe'); +// => true + +_.contains('curly', 'ur'); +// => true +``` + +* * * + + + + + + +### `_.countBy(collection, callback|property [, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1879 "View in source") [Ⓣ][1] + +Creates an object composed of keys returned from running each element of `collection` through a `callback`. The corresponding value of each key is the number of times the key was returned by `callback`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. The `callback` argument may also be the name of a property to count by *(e.g. 'length')*. + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `callback|property` *(Function|String)*: The function called per iteration or property name to count by. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Object)*: Returns the composed aggregate object. + +#### Example +```js +_.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); +// => { '4': 1, '6': 2 } + +_.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); +// => { '4': 1, '6': 2 } + +_.countBy(['one', 'two', 'three'], 'length'); +// => { '3': 2, '5': 1 } +``` + +* * * + + + + + + +### `_.every(collection [, callback=identity, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1908 "View in source") [Ⓣ][1] + +Checks if the `callback` returns a truthy value for **all** elements of a `collection`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. + +#### Aliases +*all* + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `[callback=identity]` *(Function)*: The function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Boolean)*: Returns `true` if all elements pass the callback check, else `false`. + +#### Example +```js +_.every([true, 1, null, 'yes'], Boolean); +// => false +``` + +* * * + + + + + + +### `_.filter(collection [, callback=identity, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1947 "View in source") [Ⓣ][1] + +Examines each element in a `collection`, returning an array of all elements the `callback` returns truthy for. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. + +#### Aliases +*select* + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `[callback=identity]` *(Function)*: The function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Array)*: Returns a new array of elements that passed the callback check. + +#### Example +```js +var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); +// => [2, 4, 6] +``` + +* * * + + + + + + +### `_.find(collection, callback [, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1978 "View in source") [Ⓣ][1] + +Examines each element in a `collection`, returning the first one the `callback` returns truthy for. The function returns as soon as it finds an acceptable element, and does not iterate over the entire `collection`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. + +#### Aliases +*detect* + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `callback` *(Function)*: The function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Mixed)*: Returns the element that passed the callback check, else `undefined`. + +#### Example +```js +var even = _.find([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); +// => 2 +``` + +* * * + + + + + + +### `_.forEach(collection, callback [, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2012 "View in source") [Ⓣ][1] + +Iterates over a `collection`, executing the `callback` for each element in the `collection`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. Callbacks may exit iteration early by explicitly returning `false`. + +#### Aliases +*each* + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `callback` *(Function)*: The function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Array, Object, String)*: Returns `collection`. + +#### Example +```js +_([1, 2, 3]).forEach(alert).join(','); +// => alerts each number and returns '1,2,3' + +_.forEach({ 'one': 1, 'two': 2, 'three': 3 }, alert); +// => alerts each number (order is not guaranteed) +``` + +* * * + + + + + + +### `_.groupBy(collection, callback|property [, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2040 "View in source") [Ⓣ][1] + +Creates an object composed of keys returned from running each element of `collection` through a `callback`. The corresponding value of each key is an array of elements passed to `callback` that returned the key. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. The `callback` argument may also be the name of a property to group by *(e.g. 'length')*. + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `callback|property` *(Function|String)*: The function called per iteration or property name to group by. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Object)*: Returns the composed aggregate object. + +#### Example +```js +_.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); +// => { '4': [4.2], '6': [6.1, 6.4] } + +_.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); +// => { '4': [4.2], '6': [6.1, 6.4] } + +_.groupBy(['one', 'two', 'three'], 'length'); +// => { '3': ['one', 'two'], '5': ['three'] } +``` + +* * * + + + + + + +### `_.invoke(collection, methodName [, arg1, arg2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2072 "View in source") [Ⓣ][1] + +Invokes the method named by `methodName` on each element in the `collection`, returning an array of the results of each invoked method. Additional arguments will be passed to each invoked method. If `methodName` is a function it will be invoked for, and `this` bound to, each element in the `collection`. + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `methodName` *(Function|String)*: The name of the method to invoke or the function invoked per iteration. +3. `[arg1, arg2, ...]` *(Mixed)*: Arguments to invoke the method with. + +#### Returns +*(Array)*: Returns a new array of the results of each invoked method. + +#### Example +```js +_.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); +// => [[1, 5, 7], [1, 2, 3]] + +_.invoke([123, 456], String.prototype.split, ''); +// => [['1', '2', '3'], ['4', '5', '6']] +``` + +* * * + + + + + + +### `_.map(collection [, callback=identity, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2104 "View in source") [Ⓣ][1] + +Creates an array of values by running each element in the `collection` through a `callback`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. + +#### Aliases +*collect* + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `[callback=identity]` *(Function)*: The function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Array)*: Returns a new array of the results of each `callback` execution. + +#### Example +```js +_.map([1, 2, 3], function(num) { return num * 3; }); +// => [3, 6, 9] + +_.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); +// => [3, 6, 9] (order is not guaranteed) +``` + +* * * + + + + + + +### `_.max(collection [, callback, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2146 "View in source") [Ⓣ][1] + +Retrieves the maximum value of an `array`. If `callback` is passed, it will be executed for each value in the `array` to generate the criterion by which the value is ranked. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index, collection)*. + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `[callback]` *(Function)*: The function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Mixed)*: Returns the maximum value. + +#### Example +```js +var stooges = [ + { 'name': 'moe', 'age': 40 }, + { 'name': 'larry', 'age': 50 }, + { 'name': 'curly', 'age': 60 } +]; + +_.max(stooges, function(stooge) { return stooge.age; }); +// => { 'name': 'curly', 'age': 60 }; +``` + +* * * + + + + + + +### `_.min(collection [, callback, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2192 "View in source") [Ⓣ][1] + +Retrieves the minimum value of an `array`. If `callback` is passed, it will be executed for each value in the `array` to generate the criterion by which the value is ranked. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index, collection)*. + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `[callback]` *(Function)*: The function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Mixed)*: Returns the minimum value. + +#### Example +```js +_.min([10, 5, 100, 2, 1000]); +// => 2 +``` + +* * * + + + + + + +### `_.pluck(collection, property)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2241 "View in source") [Ⓣ][1] + +Retrieves the value of a specified property from all elements in the `collection`. + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `property` *(String)*: The property to pluck. + +#### Returns +*(Array)*: Returns a new array of property values. + +#### Example +```js +var stooges = [ + { 'name': 'moe', 'age': 40 }, + { 'name': 'larry', 'age': 50 }, + { 'name': 'curly', 'age': 60 } +]; + +_.pluck(stooges, 'name'); +// => ['moe', 'larry', 'curly'] +``` + +* * * + + + + + + +### `_.reduce(collection, callback [, accumulator, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2269 "View in source") [Ⓣ][1] + +Boils down a `collection` to a single value. The initial state of the reduction is `accumulator` and each successive step of it should be returned by the `callback`. The `callback` is bound to `thisArg` and invoked with `4` arguments; for arrays they are *(accumulator, value, index|key, collection)*. + +#### Aliases +*foldl, inject* + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `callback` *(Function)*: The function called per iteration. +3. `[accumulator]` *(Mixed)*: Initial value of the accumulator. +4. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Mixed)*: Returns the accumulated value. + +#### Example +```js +var sum = _.reduce([1, 2, 3], function(memo, num) { return memo + num; }); +// => 6 +``` + +* * * + + + + + + +### `_.reduceRight(collection, callback [, accumulator, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2298 "View in source") [Ⓣ][1] + +The right-associative version of `_.reduce`. + +#### Aliases +*foldr* + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `callback` *(Function)*: The function called per iteration. +3. `[accumulator]` *(Mixed)*: Initial value of the accumulator. +4. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Mixed)*: Returns the accumulated value. + +#### Example +```js +var list = [[0, 1], [2, 3], [4, 5]]; +var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); +// => [4, 5, 2, 3, 0, 1] +``` + +* * * + + + + + + +### `_.reject(collection [, callback=identity, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2335 "View in source") [Ⓣ][1] + +The opposite of `_.filter`, this method returns the values of a `collection` that `callback` does **not** return truthy for. + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `[callback=identity]` *(Function)*: The function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Array)*: Returns a new array of elements that did **not** pass the callback check. + +#### Example +```js +var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); +// => [1, 3, 5] +``` + +* * * + + + + + + +### `_.shuffle(collection)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2356 "View in source") [Ⓣ][1] + +Creates an array of shuffled `array` values, using a version of the Fisher-Yates shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to shuffle. + +#### Returns +*(Array)*: Returns a new shuffled collection. + +#### Example +```js +_.shuffle([1, 2, 3, 4, 5, 6]); +// => [4, 1, 6, 3, 5, 2] +``` + +* * * + + + + + + +### `_.size(collection)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2388 "View in source") [Ⓣ][1] + +Gets the size of the `collection` by returning `collection.length` for arrays and array-like objects or the number of own enumerable properties for objects. + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to inspect. + +#### Returns +*(Number)*: Returns `collection.length` or number of own enumerable properties. + +#### Example +```js +_.size([1, 2]); +// => 2 + +_.size({ 'one': 1, 'two': 2, 'three': 3 }); +// => 3 + +_.size('curly'); +// => 5 +``` + +* * * + + + + + + +### `_.some(collection [, callback=identity, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2413 "View in source") [Ⓣ][1] + +Checks if the `callback` returns a truthy value for **any** element of a `collection`. The function returns as soon as it finds passing value, and does not iterate over the entire `collection`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. + +#### Aliases +*any* + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `[callback=identity]` *(Function)*: The function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Boolean)*: Returns `true` if any element passes the callback check, else `false`. + +#### Example +```js +_.some([null, 0, 'yes', false]); +// => true +``` + +* * * + + + + + + +### `_.sortBy(collection, callback|property [, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2459 "View in source") [Ⓣ][1] + +Creates an array, stable sorted in ascending order by the results of running each element of `collection` through a `callback`. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, index|key, collection)*. The `callback` argument may also be the name of a property to sort by *(e.g. 'length')*. + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `callback|property` *(Function|String)*: The function called per iteration or property name to sort by. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Array)*: Returns a new array of sorted elements. + +#### Example +```js +_.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); +// => [3, 1, 2] + +_.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); +// => [3, 1, 2] + +_.sortBy(['larry', 'brendan', 'moe'], 'length'); +// => ['moe', 'larry', 'brendan'] +``` + +* * * + + + + + + +### `_.toArray(collection)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2491 "View in source") [Ⓣ][1] + +Converts the `collection`, to an array. + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to convert. + +#### Returns +*(Array)*: Returns the new converted array. + +#### Example +```js +(function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); +// => [2, 3, 4] +``` + +* * * + + + + + + +### `_.where(collection, properties)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L2521 "View in source") [Ⓣ][1] + +Examines each element in a `collection`, returning an array of all elements that contain the given `properties`. + +#### Arguments +1. `collection` *(Array|Object|String)*: The collection to iterate over. +2. `properties` *(Object)*: The object of property values to filter by. + +#### Returns +*(Array)*: Returns a new array of elements that contain the given `properties`. + +#### Example +```js +var stooges = [ + { 'name': 'moe', 'age': 40 }, + { 'name': 'larry', 'age': 50 }, + { 'name': 'curly', 'age': 60 } +]; + +_.where(stooges, { 'age': 40 }); +// => [{ 'name': 'moe', 'age': 40 }] +``` + +* * * + + + + + + + + + +## `“Functions” Methods` + + + +### `_.after(n, func)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3153 "View in source") [Ⓣ][1] + +Creates a function that is restricted to executing `func` only after it is called `n` times. The `func` is executed with the `this` binding of the created function. + +#### Arguments +1. `n` *(Number)*: The number of times the function must be called before it is executed. +2. `func` *(Function)*: The function to restrict. + +#### Returns +*(Function)*: Returns the new restricted function. + +#### Example +```js +var renderNotes = _.after(notes.length, render); +_.forEach(notes, function(note) { + note.asyncSave({ 'success': renderNotes }); +}); +// `renderNotes` is run once, after all notes have saved +``` + +* * * + + + + + + +### `_.bind(func [, thisArg, arg1, arg2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3186 "View in source") [Ⓣ][1] + +Creates a function that, when called, invokes `func` with the `this` binding of `thisArg` and prepends any additional `bind` arguments to those passed to the bound function. + +#### Arguments +1. `func` *(Function)*: The function to bind. +2. `[thisArg]` *(Mixed)*: The `this` binding of `func`. +3. `[arg1, arg2, ...]` *(Mixed)*: Arguments to be partially applied. + +#### Returns +*(Function)*: Returns the new bound function. + +#### Example +```js +var func = function(greeting) { + return greeting + ' ' + this.name; +}; + +func = _.bind(func, { 'name': 'moe' }, 'hi'); +func(); +// => 'hi moe' +``` + +* * * + + + + + + +### `_.bindAll(object [, methodName1, methodName2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3216 "View in source") [Ⓣ][1] + +Binds methods on `object` to `object`, overwriting the existing method. If no method names are provided, all the function properties of `object` will be bound. + +#### Arguments +1. `object` *(Object)*: The object to bind and assign the bound methods to. +2. `[methodName1, methodName2, ...]` *(String)*: Method names on the object to bind. + +#### Returns +*(Object)*: Returns `object`. + +#### Example +```js +var buttonView = { + 'label': 'lodash', + 'onClick': function() { alert('clicked: ' + this.label); } +}; + +_.bindAll(buttonView); +jQuery('#lodash_button').on('click', buttonView.onClick); +// => When the button is clicked, `this.label` will have the correct value +``` + +* * * + + + + + + +### `_.compose([func1, func2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3247 "View in source") [Ⓣ][1] + +Creates a function that is the composition of the passed functions, where each function consumes the return value of the function that follows. In math terms, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. Each function is executed with the `this` binding of the composed function. + +#### Arguments +1. `[func1, func2, ...]` *(Function)*: Functions to compose. + +#### Returns +*(Function)*: Returns the new composed function. + +#### Example +```js +var greet = function(name) { return 'hi: ' + name; }; +var exclaim = function(statement) { return statement + '!'; }; +var welcome = _.compose(exclaim, greet); +welcome('moe'); +// => 'hi: moe!' +``` + +* * * + + + + + + +### `_.debounce(func, wait, immediate)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3280 "View in source") [Ⓣ][1] + +Creates a function that will delay the execution of `func` until after `wait` milliseconds have elapsed since the last time it was invoked. Pass `true` for `immediate` to cause debounce to invoke `func` on the leading, instead of the trailing, edge of the `wait` timeout. Subsequent calls to the debounced function will return the result of the last `func` call. + +#### Arguments +1. `func` *(Function)*: The function to debounce. +2. `wait` *(Number)*: The number of milliseconds to delay. +3. `immediate` *(Boolean)*: A flag to indicate execution is on the leading edge of the timeout. + +#### Returns +*(Function)*: Returns the new debounced function. + +#### Example +```js +var lazyLayout = _.debounce(calculateLayout, 300); +jQuery(window).on('resize', lazyLayout); +``` + +* * * + + + + + + +### `_.defer(func [, arg1, arg2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3344 "View in source") [Ⓣ][1] + +Defers executing the `func` function until the current call stack has cleared. Additional arguments will be passed to `func` when it is invoked. + +#### Arguments +1. `func` *(Function)*: The function to defer. +2. `[arg1, arg2, ...]` *(Mixed)*: Arguments to invoke the function with. + +#### Returns +*(Number)*: Returns the `setTimeout` timeout id. + +#### Example +```js +_.defer(function() { alert('deferred'); }); +// returns from the function before `alert` is called +``` + +* * * + + + + + + +### `_.delay(func, wait [, arg1, arg2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3324 "View in source") [Ⓣ][1] + +Executes the `func` function after `wait` milliseconds. Additional arguments will be passed to `func` when it is invoked. + +#### Arguments +1. `func` *(Function)*: The function to delay. +2. `wait` *(Number)*: The number of milliseconds to delay execution. +3. `[arg1, arg2, ...]` *(Mixed)*: Arguments to invoke the function with. + +#### Returns +*(Number)*: Returns the `setTimeout` timeout id. + +#### Example +```js +var log = _.bind(console.log, console); +_.delay(log, 1000, 'logged later'); +// => 'logged later' (Appears after one second.) +``` + +* * * + + + + + + +### `_.lateBind(object, methodName [, arg1, arg2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3382 "View in source") [Ⓣ][1] + +Creates a function that, when called, invokes `object[methodName]` and prepends any additional `lateBind` arguments to those passed to the bound function. This method differs from `_.bind` by allowing bound functions to reference methods that will be redefined or don't yet exist. + +#### Arguments +1. `object` *(Object)*: The object the method belongs to. +2. `methodName` *(String)*: The method name. +3. `[arg1, arg2, ...]` *(Mixed)*: Arguments to be partially applied. + +#### Returns +*(Function)*: Returns the new bound function. + +#### Example +```js +var object = { + 'name': 'moe', + 'greet': function(greeting) { + return greeting + ' ' + this.name; + } +}; + +var func = _.lateBind(object, 'greet', 'hi'); +func(); +// => 'hi moe' + +object.greet = function(greeting) { + return greeting + ', ' + this.name + '!'; +}; + +func(); +// => 'hi, moe!' +``` + +* * * + + + + + + +### `_.memoize(func [, resolver])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3405 "View in source") [Ⓣ][1] + +Creates a function that memoizes the result of `func`. If `resolver` is passed, it will be used to determine the cache key for storing the result based on the arguments passed to the memoized function. By default, the first argument passed to the memoized function is used as the cache key. The `func` is executed with the `this` binding of the memoized function. + +#### Arguments +1. `func` *(Function)*: The function to have its output memoized. +2. `[resolver]` *(Function)*: A function used to resolve the cache key. + +#### Returns +*(Function)*: Returns the new memoizing function. + +#### Example +```js +var fibonacci = _.memoize(function(n) { + return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); +}); +``` + +* * * + + + + + + +### `_.once(func)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3432 "View in source") [Ⓣ][1] + +Creates a function that is restricted to execute `func` once. Repeat calls to the function will return the value of the first call. The `func` is executed with the `this` binding of the created function. + +#### Arguments +1. `func` *(Function)*: The function to restrict. + +#### Returns +*(Function)*: Returns the new restricted function. + +#### Example +```js +var initialize = _.once(createApplication); +initialize(); +initialize(); +// Application is only created once. +``` + +* * * + + + + + + +### `_.partial(func [, arg1, arg2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3467 "View in source") [Ⓣ][1] + +Creates a function that, when called, invokes `func` with any additional `partial` arguments prepended to those passed to the new function. This method is similar to `bind`, except it does **not** alter the `this` binding. + +#### Arguments +1. `func` *(Function)*: The function to partially apply arguments to. +2. `[arg1, arg2, ...]` *(Mixed)*: Arguments to be partially applied. + +#### Returns +*(Function)*: Returns the new partially applied function. + +#### Example +```js +var greet = function(greeting, name) { return greeting + ': ' + name; }; +var hi = _.partial(greet, 'hi'); +hi('moe'); +// => 'hi: moe' +``` + +* * * + + + + + + +### `_.throttle(func, wait)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3489 "View in source") [Ⓣ][1] + +Creates a function that, when executed, will only call the `func` function at most once per every `wait` milliseconds. If the throttled function is invoked more than once during the `wait` timeout, `func` will also be called on the trailing edge of the timeout. Subsequent calls to the throttled function will return the result of the last `func` call. + +#### Arguments +1. `func` *(Function)*: The function to throttle. +2. `wait` *(Number)*: The number of milliseconds to throttle executions to. + +#### Returns +*(Function)*: Returns the new throttled function. + +#### Example +```js +var throttled = _.throttle(updatePosition, 100); +jQuery(window).on('scroll', throttled); +``` + +* * * + + + + + + +### `_.wrap(value, wrapper)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3541 "View in source") [Ⓣ][1] + +Creates a function that passes `value` to the `wrapper` function as its first argument. Additional arguments passed to the function are appended to those passed to the `wrapper` function. The `wrapper` is executed with the `this` binding of the created function. + +#### Arguments +1. `value` *(Mixed)*: The value to wrap. +2. `wrapper` *(Function)*: The wrapper function. + +#### Returns +*(Function)*: Returns the new function. + +#### Example +```js +var hello = function(name) { return 'hello ' + name; }; +hello = _.wrap(hello, function(func) { + return 'before, ' + func('moe') + ', after'; +}); +hello(); +// => 'before, hello moe, after' +``` + +* * * + + + + + + + + + +## `“Objects” Methods` + + + +### `_.clone(value, deep)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L896 "View in source") [Ⓣ][1] + +Creates a clone of `value`. If `deep` is `true`, all nested objects will also be cloned otherwise they will be assigned by reference. Functions, DOM nodes, `arguments` objects, and objects created by constructors other than `Object` are **not** cloned. + +#### Arguments +1. `value` *(Mixed)*: The value to clone. +2. `deep` *(Boolean)*: A flag to indicate a deep clone. + +#### Returns +*(Mixed)*: Returns the cloned `value`. + +#### Example +```js +var stooges = [ + { 'name': 'moe', 'age': 40 }, + { 'name': 'larry', 'age': 50 }, + { 'name': 'curly', 'age': 60 } +]; + +_.clone({ 'name': 'moe' }); +// => { 'name': 'moe' } + +var shallow = _.clone(stooges); +shallow[0] === stooges[0]; +// => true + +var deep = _.clone(stooges, true); +shallow[0] === stooges[0]; +// => false +``` + +* * * + + + + + + +### `_.defaults(object [, default1, default2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L979 "View in source") [Ⓣ][1] + +Assigns enumerable properties of the default object(s) to the `destination` object for all `destination` properties that resolve to `null`/`undefined`. Once a property is set, additional defaults of the same property will be ignored. + +#### Arguments +1. `object` *(Object)*: The destination object. +2. `[default1, default2, ...]` *(Object)*: The default objects. + +#### Returns +*(Object)*: Returns the destination object. + +#### Example +```js +var iceCream = { 'flavor': 'chocolate' }; +_.defaults(iceCream, { 'flavor': 'vanilla', 'sprinkles': 'rainbow' }); +// => { 'flavor': 'chocolate', 'sprinkles': 'rainbow' } +``` + +* * * + + + + + + +### `_.extend(object [, source1, source2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L999 "View in source") [Ⓣ][1] + +Assigns enumerable properties of the source object(s) to the `destination` object. Subsequent sources will overwrite propery assignments of previous sources. + +#### Arguments +1. `object` *(Object)*: The destination object. +2. `[source1, source2, ...]` *(Object)*: The source objects. + +#### Returns +*(Object)*: Returns the destination object. + +#### Example +```js +_.extend({ 'name': 'moe' }, { 'age': 40 }); +// => { 'name': 'moe', 'age': 40 } +``` + +* * * + + + + + + +### `_.forIn(object, callback [, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L754 "View in source") [Ⓣ][1] + +Iterates over `object`'s own and inherited enumerable properties, executing the `callback` for each property. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, key, object)*. Callbacks may exit iteration early by explicitly returning `false`. + +#### Arguments +1. `object` *(Object)*: The object to iterate over. +2. `callback` *(Function)*: The function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Object)*: Returns `object`. + +#### Example +```js +function Dog(name) { + this.name = name; +} + +Dog.prototype.bark = function() { + alert('Woof, woof!'); +}; + +_.forIn(new Dog('Dagny'), function(value, key) { + alert(key); +}); +// => alerts 'name' and 'bark' (order is not guaranteed) +``` + +* * * + + + + + + +### `_.forOwn(object, callback [, thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L778 "View in source") [Ⓣ][1] + +Iterates over `object`'s own enumerable properties, executing the `callback` for each property. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, key, object)*. Callbacks may exit iteration early by explicitly returning `false`. + +#### Arguments +1. `object` *(Object)*: The object to iterate over. +2. `callback` *(Function)*: The function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Object)*: Returns `object`. + +#### Example +```js +_.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { + alert(key); +}); +// => alerts '0', '1', and 'length' (order is not guaranteed) +``` + +* * * + + + + + + +### `_.functions(object)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1016 "View in source") [Ⓣ][1] + +Creates a sorted array of all enumerable properties, own and inherited, of `object` that have function values. + +#### Aliases +*methods* + +#### Arguments +1. `object` *(Object)*: The object to inspect. + +#### Returns +*(Array)*: Returns a new array of property names that have function values. + +#### Example +```js +_.functions(_); +// => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] +``` + +* * * + + + + + + +### `_.has(object, property)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1041 "View in source") [Ⓣ][1] + +Checks if the specified object `property` exists and is a direct property, instead of an inherited property. + +#### Arguments +1. `object` *(Object)*: The object to check. +2. `property` *(String)*: The property to check for. + +#### Returns +*(Boolean)*: Returns `true` if key is a direct property, else `false`. + +#### Example +```js +_.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); +// => true +``` + +* * * + + + + + + +### `_.invert(object)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1058 "View in source") [Ⓣ][1] + +Creates an object composed of the inverted keys and values of the given `object`. + +#### Arguments +1. `object` *(Object)*: The object to invert. + +#### Returns +*(Object)*: Returns the created inverted object. + +#### Example +```js +_.invert({ 'first': 'Moe', 'second': 'Larry', 'third': 'Curly' }); +// => { 'Moe': 'first', 'Larry': 'second', 'Curly': 'third' } (order is not guaranteed) +``` + +* * * + + + + + + +### `_.isArguments(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L716 "View in source") [Ⓣ][1] + +Checks if `value` is an `arguments` object. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is an `arguments` object, else `false`. + +#### Example +```js +(function() { return _.isArguments(arguments); })(1, 2, 3); +// => true + +_.isArguments([1, 2, 3]); +// => false +``` + +* * * + + + + + + +### `_.isArray(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1082 "View in source") [Ⓣ][1] + +Checks if `value` is an array. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is an array, else `false`. + +#### Example +```js +(function() { return _.isArray(arguments); })(); +// => false + +_.isArray([1, 2, 3]); +// => true +``` + +* * * + + + + + + +### `_.isBoolean(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1099 "View in source") [Ⓣ][1] + +Checks if `value` is a boolean *(`true` or `false`)* value. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is a boolean value, else `false`. + +#### Example +```js +_.isBoolean(null); +// => false +``` + +* * * + + + + + + +### `_.isDate(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1116 "View in source") [Ⓣ][1] + +Checks if `value` is a date. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is a date, else `false`. + +#### Example +```js +_.isDate(new Date); +// => true +``` + +* * * + + + + + + +### `_.isElement(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1133 "View in source") [Ⓣ][1] + +Checks if `value` is a DOM element. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is a DOM element, else `false`. + +#### Example +```js +_.isElement(document.body); +// => true +``` + +* * * + + + + + + +### `_.isEmpty(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1158 "View in source") [Ⓣ][1] + +Checks if `value` is empty. Arrays, strings, or `arguments` objects with a length of `0` and objects with no own enumerable properties are considered "empty". + +#### Arguments +1. `value` *(Array|Object|String)*: The value to inspect. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is empty, else `false`. + +#### Example +```js +_.isEmpty([1, 2, 3]); +// => false + +_.isEmpty({}); +// => true + +_.isEmpty(''); +// => true +``` + +* * * + + + + + + +### `_.isEqual(a, b)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1200 "View in source") [Ⓣ][1] + +Performs a deep comparison between two values to determine if they are equivalent to each other. + +#### Arguments +1. `a` *(Mixed)*: The value to compare. +2. `b` *(Mixed)*: The other value to compare. + +#### Returns +*(Boolean)*: Returns `true` if the values are equvalent, else `false`. + +#### Example +```js +var moe = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] }; +var clone = { 'name': 'moe', 'luckyNumbers': [13, 27, 34] }; + +moe == clone; +// => false + +_.isEqual(moe, clone); +// => true +``` + +* * * + + + + + + +### `_.isFinite(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1362 "View in source") [Ⓣ][1] + +Checks if `value` is, or can be coerced to, a finite number. Note: This is not the same as native `isFinite`, which will return true for booleans and empty strings. See http://es5.github.com/#x15.1.2.5. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is a finite number, else `false`. + +#### Example +```js +_.isFinite(-101); +// => true + +_.isFinite('10'); +// => true + +_.isFinite(true); +// => false + +_.isFinite(''); +// => false + +_.isFinite(Infinity); +// => false +``` + +* * * + + + + + + +### `_.isFunction(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1379 "View in source") [Ⓣ][1] + +Checks if `value` is a function. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is a function, else `false`. + +#### Example +```js +_.isFunction(_); +// => true +``` + +* * * + + + + + + +### `_.isNaN(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1443 "View in source") [Ⓣ][1] + +Checks if `value` is `NaN`. Note: This is not the same as native `isNaN`, which will return true for `undefined` and other values. See http://es5.github.com/#x15.1.2.4. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is `NaN`, else `false`. + +#### Example +```js +_.isNaN(NaN); +// => true + +_.isNaN(new Number(NaN)); +// => true + +isNaN(undefined); +// => true + +_.isNaN(undefined); +// => false +``` + +* * * + + + + + + +### `_.isNull(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1466 "View in source") [Ⓣ][1] + +Checks if `value` is `null`. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is `null`, else `false`. + +#### Example +```js +_.isNull(null); +// => true + +_.isNull(undefined); +// => false +``` + +* * * + + + + + + +### `_.isNumber(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1483 "View in source") [Ⓣ][1] + +Checks if `value` is a number. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is a number, else `false`. + +#### Example +```js +_.isNumber(8.4 * 5); +// => true +``` + +* * * + + + + + + +### `_.isObject(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1409 "View in source") [Ⓣ][1] + +Checks if `value` is the language type of Object. *(e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)* + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is an object, else `false`. + +#### Example +```js +_.isObject({}); +// => true + +_.isObject([1, 2, 3]); +// => true + +_.isObject(1); +// => false +``` + +* * * + + + + + + +### `_.isPlainObject(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1511 "View in source") [Ⓣ][1] + +Checks if a given `value` is an object created by the `Object` constructor. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if `value` is a plain object, else `false`. + +#### Example +```js +function Stooge(name, age) { + this.name = name; + this.age = age; +} + +_.isPlainObject(new Stooge('moe', 40)); +// => false + +_.isPlainObject([1, 2, 3]); +// => false + +_.isPlainObject({ 'name': 'moe', 'age': 40 }); +// => true +``` + +* * * + + + + + + +### `_.isRegExp(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1536 "View in source") [Ⓣ][1] + +Checks if `value` is a regular expression. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is a regular expression, else `false`. + +#### Example +```js +_.isRegExp(/moe/); +// => true +``` + +* * * + + + + + + +### `_.isString(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1553 "View in source") [Ⓣ][1] + +Checks if `value` is a string. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is a string, else `false`. + +#### Example +```js +_.isString('moe'); +// => true +``` + +* * * + + + + + + +### `_.isUndefined(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1571 "View in source") [Ⓣ][1] + +Checks if `value` is `undefined`. + +#### Arguments +1. `value` *(Mixed)*: The value to check. + +#### Returns +*(Boolean)*: Returns `true` if the `value` is `undefined`, else `false`. + +#### Example +```js +_.isUndefined(void 0); +// => true +``` + +* * * + + + + + + +### `_.keys(object)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1588 "View in source") [Ⓣ][1] + +Creates an array composed of the own enumerable property names of `object`. + +#### Arguments +1. `object` *(Object)*: The object to inspect. + +#### Returns +*(Array)*: Returns a new array of property names. + +#### Example +```js +_.keys({ 'one': 1, 'two': 2, 'three': 3 }); +// => ['one', 'two', 'three'] (order is not guaranteed) +``` + +* * * + + + + + + +### `_.merge(object [, source1, source2, ...])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1626 "View in source") [Ⓣ][1] + +Merges enumerable properties of the source object(s) into the `destination` object. Subsequent sources will overwrite propery assignments of previous sources. + +#### Arguments +1. `object` *(Object)*: The destination object. +2. `[source1, source2, ...]` *(Object)*: The source objects. + +#### Returns +*(Object)*: Returns the destination object. + +#### Example +```js +var stooges = [ + { 'name': 'moe' }, + { 'name': 'larry' } +]; + +var ages = [ + { 'age': 40 }, + { 'age': 50 } +]; + +_.merge(stooges, ages); +// => [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }] +``` + +* * * + + + + + + +### `_.omit(object, callback|[prop1, prop2, ..., thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1696 "View in source") [Ⓣ][1] + +Creates a shallow clone of `object` excluding the specified properties. Property names may be specified as individual arguments or as arrays of property names. If `callback` is passed, it will be executed for each property in the `object`, omitting the properties `callback` returns truthy for. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, key, object)*. + +#### Arguments +1. `object` *(Object)*: The source object. +2. `callback|[prop1, prop2, ...]` *(Function|String)*: The properties to omit or the function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Object)*: Returns an object without the omitted properties. + +#### Example +```js +_.omit({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'userid'); +// => { 'name': 'moe', 'age': 40 } + +_.omit({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) { + return key.charAt(0) == '_'; +}); +// => { 'name': 'moe' } +``` + +* * * + + + + + + +### `_.pairs(object)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1730 "View in source") [Ⓣ][1] + +Creates a two dimensional array of the given object's key-value pairs, i.e. `[[key1, value1], [key2, value2]]`. + +#### Arguments +1. `object` *(Object)*: The object to inspect. + +#### Returns +*(Array)*: Returns new array of key-value pairs. + +#### Example +```js +_.pairs({ 'moe': 30, 'larry': 40, 'curly': 50 }); +// => [['moe', 30], ['larry', 40], ['curly', 50]] (order is not guaranteed) +``` + +* * * + + + + + + +### `_.pick(object, callback|[prop1, prop2, ..., thisArg])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1763 "View in source") [Ⓣ][1] + +Creates a shallow clone of `object` composed of the specified properties. Property names may be specified as individual arguments or as arrays of property names. If `callback` is passed, it will be executed for each property in the `object`, picking the properties `callback` returns truthy for. The `callback` is bound to `thisArg` and invoked with three arguments; *(value, key, object)*. + +#### Arguments +1. `object` *(Object)*: The source object. +2. `callback|[prop1, prop2, ...]` *(Function|String)*: The properties to pick or the function called per iteration. +3. `[thisArg]` *(Mixed)*: The `this` binding of `callback`. + +#### Returns +*(Object)*: Returns an object composed of the picked properties. + +#### Example +```js +_.pick({ 'name': 'moe', 'age': 40, 'userid': 'moe1' }, 'name', 'age'); +// => { 'name': 'moe', 'age': 40 } + +_.pick({ 'name': 'moe', '_hint': 'knucklehead', '_seed': '96c4eb' }, function(value, key) { + return key.charAt(0) != '_'; +}); +// => { 'name': 'moe' } +``` + +* * * + + + + + + +### `_.values(object)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L1800 "View in source") [Ⓣ][1] + +Creates an array composed of the own enumerable property values of `object`. + +#### Arguments +1. `object` *(Object)*: The object to inspect. + +#### Returns +*(Array)*: Returns a new array of property values. + +#### Example +```js +_.values({ 'one': 1, 'two': 2, 'three': 3 }); +// => [1, 2, 3] +``` + +* * * + + + + + + + + + +## `“Utilities” Methods` + + + +### `_.escape(string)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3565 "View in source") [Ⓣ][1] + +Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their corresponding HTML entities. + +#### Arguments +1. `string` *(String)*: The string to escape. + +#### Returns +*(String)*: Returns the escaped string. + +#### Example +```js +_.escape('Moe, Larry & Curly'); +// => "Moe, Larry & Curly" +``` + +* * * + + + + + + +### `_.identity(value)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3585 "View in source") [Ⓣ][1] + +This function returns the first argument passed to it. Note: It is used throughout Lo-Dash as a default callback. + +#### Arguments +1. `value` *(Mixed)*: Any value. + +#### Returns +*(Mixed)*: Returns `value`. + +#### Example +```js +var moe = { 'name': 'moe' }; +moe === _.identity(moe); +// => true +``` + +* * * + + + + + + +### `_.mixin(object)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3611 "View in source") [Ⓣ][1] + +Adds functions properties of `object` to the `lodash` function and chainable wrapper. + +#### Arguments +1. `object` *(Object)*: The object of function properties to add to `lodash`. + +#### Example +```js +_.mixin({ + 'capitalize': function(string) { + return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); + } +}); + +_.capitalize('larry'); +// => 'Larry' + +_('curly').capitalize(); +// => 'Curly' +``` + +* * * + + + + + + +### `_.noConflict()` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3641 "View in source") [Ⓣ][1] + +Reverts the '_' variable to its previous value and returns a reference to the `lodash` function. + +#### Returns +*(Function)*: Returns the `lodash` function. + +#### Example +```js +var lodash = _.noConflict(); +``` + +* * * + + + + + + +### `_.random([min=0, max=1])` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3664 "View in source") [Ⓣ][1] + +Produces a random number between `min` and `max` *(inclusive)*. If only one argument is passed, a number between `0` and the given number will be returned. + +#### Arguments +1. `[min=0]` *(Number)*: The minimum possible value. +2. `[max=1]` *(Number)*: The maximum possible value. + +#### Returns +*(Number)*: Returns a random number. + +#### Example +```js +_.random(0, 5); +// => a number between 1 and 5 + +_.random(5); +// => also a number between 1 and 5 +``` + +* * * + + + + + + +### `_.result(object, property)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3703 "View in source") [Ⓣ][1] + +Resolves the value of `property` on `object`. If `property` is a function it will be invoked and its result returned, else the property value is returned. If `object` is falsey, then `null` is returned. + +#### Arguments +1. `object` *(Object)*: The object to inspect. +2. `property` *(String)*: The property to get the value of. + +#### Returns +*(Mixed)*: Returns the resolved value. + +#### Example +```js +var object = { + 'cheese': 'crumpets', + 'stuff': function() { + return 'nonsense'; + } +}; + +_.result(object, 'cheese'); +// => 'crumpets' + +_.result(object, 'stuff'); +// => 'nonsense' +``` + +* * * + + + + + + +### `_.template(text, data, options)` +# [Ⓢ](https://github.com/bestiejs/lodash/blob/master/lodash.js#L3788 "View in source") [Ⓣ][1] + +A micro-templating method that handles arbitrary delimiters, preserves whitespace, and correctly escapes quotes within interpolated code. Note: In the development build `_.template` utilizes sourceURLs for easier debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl Note: Lo-Dash may be used in Chrome extensions by either creating a `lodash csp` build and avoiding `_.template` use, or loading Lo-Dash in a sandboxed page. See http://developer.chrome.com/trunk/extensions/sandboxingEval.html + +#### Arguments +1. `text` *(String)*: The template text. +2. `data` *(Obect)*: The data object used to populate the text. +3. `options` *(Object)*: The options object. escape - The "escape" delimiter regexp. evaluate - The "evaluate" delimiter regexp. interpolate - The "interpolate" delimiter regexp. sourceURL - The sourceURL of the template's compiled source. variable - The data object variable name. + +#### Returns +*(Function, String)*: Returns a compiled function when no `data` object is given, else it returns the interpolated text. + +#### Example +```js +// using a compiled template +var compiled = _.template('hello <%= name %>'); +compiled({ 'name': 'moe' }); +// => 'hello moe' + +var list = '<% _.forEach(people, function(name) { %>
    1. <%= name %>
    2. <% }); %>'; +_.template(list, { 'people': ['moe', 'larry', 'curly'] }); +// => '
    3. moe
    4. larry
    5. curly
    6. ' + +// using the "escape" delimiter to escape HTML in data property values +_.template('<%- value %>', { 'value': '\n```\n\nUsing [npm](http://npmjs.org/):\n\n```bash\nnpm install lodash\n\nnpm install -g lodash\nnpm link lodash\n```\n\nIn [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/):\n\n```js\nvar _ = require('lodash');\n```\n\n**Note:** If Lo-Dash is installed globally, [run `npm link lodash`](http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/) in your project’s root directory before requiring it.\n\nIn [RingoJS v0.7.0-](http://ringojs.org/):\n\n```js\nvar _ = require('lodash')._;\n```\n\nIn [Rhino](http://www.mozilla.org/rhino/):\n\n```js\nload('lodash.js');\n```\n\nIn an AMD loader like [RequireJS](http://requirejs.org/):\n\n```js\nrequire({\n 'paths': {\n 'underscore': 'path/to/lodash'\n }\n},\n['underscore'], function(_) {\n console.log(_.VERSION);\n});\n```\n\n## Resolved Underscore.js issues\n\n * Allow iteration of objects with a `length` property [[#799](https://github.com/documentcloud/underscore/pull/799), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L545-551)]\n * Fix cross-browser object iteration bugs [[#60](https://github.com/documentcloud/underscore/issues/60), [#376](https://github.com/documentcloud/underscore/issues/376), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L558-582)]\n * Methods should work on pages with incorrectly shimmed native methods [[#7](https://github.com/documentcloud/underscore/issues/7), [#742](https://github.com/documentcloud/underscore/issues/742), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L140-146)]\n * `_.isEmpty` should support jQuery/MooTools DOM query collections [[#690](https://github.com/documentcloud/underscore/pull/690), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L747-752)]\n * `_.isObject` should avoid V8 bug [#2291](http://code.google.com/p/v8/issues/detail?id=2291) [[#605](https://github.com/documentcloud/underscore/issues/605), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L828-840)]\n * `_.keys` should work with `arguments` objects cross-browser [[#396](https://github.com/documentcloud/underscore/issues/396), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L921-923)]\n * `_.range` should coerce arguments to numbers [[#634](https://github.com/documentcloud/underscore/issues/634), [#683](https://github.com/documentcloud/underscore/issues/683), [test](https://github.com/bestiejs/lodash/blob/v0.9.2/test/test.js#L1337-1340)]\n\n## Release Notes\n\n### v0.9.2\n\n * Added `fromIndex` argument to `_.contains`\n * Added `moduleId` build option\n * Added Closure Compiler *“simple”* optimizations to the build process\n * Added support for strings in `_.max` and `_.min`\n * Added support for ES6 template delimiters to `_.template`\n * Ensured re-minification of Lo-Dash by third parties avoids Closure Compiler bugs\n * Optimized `_.every`, `_.find`, `_.some`, and `_.uniq`\n\nThe full changelog is available [here](https://github.com/bestiejs/lodash/wiki/Changelog).\n\n## BestieJS\n\nLo-Dash is part of the BestieJS *“Best in Class”* module collection. This means we promote solid browser/environment support, ES5 precedents, unit testing, and plenty of documentation.\n\n## Author\n\n* [John-David Dalton](http://allyoucanleet.com/)\n [![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton \"Follow @jdalton on Twitter\")\n\n## Contributors\n\n* [Kit Cambridge](http://kitcambridge.github.com/)\n [![twitter/kitcambridge](http://gravatar.com/avatar/6662a1d02f351b5ef2f8b4d815804661?s=70)](https://twitter.com/kitcambridge \"Follow @kitcambridge on Twitter\")\n* [Mathias Bynens](http://mathiasbynens.be/)\n [![twitter/mathias](http://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias \"Follow @mathias on Twitter\")\n", + "readmeFilename": "README.md", + "_id": "lodash@0.9.2", + "_from": "lodash@~0.9.0" +} diff --git a/node/node_modules/grunt/node_modules/lodash/perf/perf.js b/node/node_modules/grunt/node_modules/lodash/perf/perf.js new file mode 100644 index 000000000..e0d4efd6f --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/perf/perf.js @@ -0,0 +1,1780 @@ +(function(window) { + + /** Use a single load function */ + var load = typeof require == 'function' ? require : window.load; + + /** Load Benchmark.js */ + var Benchmark = + window.Benchmark || ( + Benchmark = load('../vendor/benchmark.js/benchmark.js') || window.Benchmark, + Benchmark.Benchmark || Benchmark + ); + + /** Load Lo-Dash */ + var lodash = + window.lodash || ( + lodash = load('../lodash.js') || window._, + lodash = lodash._ || lodash, + lodash.noConflict() + ); + + /** Load Underscore */ + var _ = + window._ || ( + _ = load('../vendor/underscore/underscore.js') || window._, + _._ || _ + ); + + /** Used to access the Firebug Lite panel (set by `run`) */ + var fbPanel; + + /** Used to score performance */ + var score = { 'a': 0, 'b': 0 }; + + /** Used to queue benchmark suites */ + var suites = []; + + /** The `ui` object */ + var ui = window.ui || {}; + + /** The Lo-Dash build basename */ + var buildName = basename(ui.buildPath || 'lodash', '.js'); + + /** The other library basename */ + var otherName = basename(ui.otherPath || 'underscore', '.js'); + + /** Add `console.log()` support for Narwhal and RingoJS */ + window.console || (window.console = { 'log': window.print }); + + /** Expose functions to the global object */ + window._ = _; + window.Benchmark = Benchmark; + window.lodash = lodash; + + /*--------------------------------------------------------------------------*/ + + /** + * Gets the basename of the given `filePath`. If the file `extension` is passed, + * it will be removed from the basename. + * + * @private + * @param {String} path The file path to inspect. + * @param {String} extension The extension to remove. + * @returns {String} Returns the basename. + */ + function basename(filePath, extension) { + var result = (filePath || '').split(/[\\/]/).pop(); + return arguments.length < 2 + ? result + : result.replace(RegExp(extension.replace(/[.*+?^=!:${}()|[\]\/\\]/g, '\\$&') + '$'), ''); + } + + /** + * Gets the Hz, i.e. operations per second, of `bench` adjusted for the + * margin of error. + * + * @private + * @param {Object} bench The benchmark object. + * @returns {Number} Returns the adjusted Hz. + */ + function getHz(bench) { + return 1 / (bench.stats.mean + bench.stats.moe); + } + + /** + * Logs text to the console. + * + * @private + * @param {String} text The text to log. + */ + function log(text) { + console.log(text + ''); + if (fbPanel) { + // scroll the Firebug Lite panel down + fbPanel.scrollTop = fbPanel.scrollHeight; + } + } + + /** + * Runs all benchmark suites. + * + * @private (@public in the browser) + */ + function run() { + fbPanel = (fbPanel = window.document && document.getElementById('FirebugUI')) && + (fbPanel = (fbPanel = fbPanel.contentWindow || fbPanel.contentDocument).document || fbPanel) && + fbPanel.getElementById('fbPanel1'); + + log('\nSit back and relax, this may take a while.'); + suites[0].run(); + } + + /*--------------------------------------------------------------------------*/ + + lodash.extend(Benchmark.Suite.options, { + 'onStart': function() { + log('\n' + this.name + ':'); + }, + 'onCycle': function(event) { + log(event.target); + }, + 'onComplete': function() { + var formatNumber = Benchmark.formatNumber, + fastest = this.filter('fastest'), + fastestHz = getHz(fastest[0]), + slowest = this.filter('slowest'), + slowestHz = getHz(slowest[0]), + aHz = getHz(this[0]), + bHz = getHz(this[1]); + + if (fastest.length > 1) { + log('It\'s too close to call.'); + aHz = bHz = slowestHz; + } + else { + var percent = ((fastestHz / slowestHz) - 1) * 100; + + log( + fastest[0].name + ' is ' + + formatNumber(percent < 1 ? percent.toFixed(2) : Math.round(percent)) + + '% faster.' + ); + } + // add score adjusted for margin of error + score.a += aHz; + score.b += bHz; + + // remove current suite from queue + suites.shift(); + + if (suites.length) { + // run next suite + suites[0].run(); + } + else { + var fastestTotalHz = Math.max(score.a, score.b), + slowestTotalHz = Math.min(score.a, score.b), + totalPercent = formatNumber(Math.round(((fastestTotalHz / slowestTotalHz) - 1) * 100)), + totalX = fastestTotalHz / slowestTotalHz, + message = 'is ' + totalPercent + '% ' + (totalX == 1 ? '' : '(' + formatNumber(totalX.toFixed(2)) + 'x) ') + 'faster than'; + + // report results + if (score.a >= score.b) { + log('\n' + buildName + ' ' + message + ' ' + otherName + '.'); + } else { + log('\n' + otherName + ' ' + message + ' ' + buildName + '.'); + } + } + } + }); + + /*--------------------------------------------------------------------------*/ + + lodash.extend(Benchmark.options, { + 'async': true, + 'setup': '\ + var window = Function("return this || global")(),\ + _ = window._,\ + lodash = window.lodash,\ + belt = this.name == "Lo-Dash" ? lodash : _;\ + \ + var index,\ + date = new Date,\ + limit = 20,\ + regexp = /x/,\ + object = {},\ + objects = Array(limit),\ + numbers = Array(limit),\ + fourNumbers = [5, 25, 10, 30],\ + nestedNumbers = [1, [2], [3, [[4]]]],\ + twoNumbers = [12, 21];\ + \ + for (index = 0; index < limit; index++) {\ + numbers[index] = index;\ + object["key" + index] = index;\ + objects[index] = { "num": index };\ + }\ + \ + if (typeof bind != "undefined") {\ + var contextObject = { "name": "moe" },\ + ctor = function() {};\ + \ + var func = function(greeting, punctuation) {\ + return greeting + ", " + this.name + (punctuation || ".");\ + };\ + \ + var lodashBoundNormal = lodash.bind(func, contextObject),\ + lodashBoundCtor = lodash.bind(ctor, contextObject),\ + lodashBoundPartial = lodash.bind(func, contextObject, "hi");\ + \ + var _boundNormal = _.bind(func, contextObject),\ + _boundCtor = _.bind(ctor, contextObject),\ + _boundPartial = _.bind(func, contextObject, "hi");\ + }\ + \ + if (typeof bindAll != "undefined") {\ + var bindAllObjects = Array(this.count),\ + funcNames = belt.functions(lodash);\ + \ + // potentially expensive\n\ + for (index = 0; index < this.count; index++) {\ + bindAllObjects[index] = belt.reduce(funcNames, function(object, funcName) {\ + object[funcName] = lodash[funcName];\ + return object;\ + }, {});\ + }\ + }\ + if (typeof compact != "undefined") {\ + var uncompacted = numbers.slice();\ + uncompacted[2] = false;\ + uncompacted[6] = null;\ + uncompacted[18] = "";\ + }\ + \ + if (typeof countBy != "undefined" || typeof omit != "undefined") {\ + var wordToNumber = {\ + "one": 1,\ + "two": 2,\ + "three": 3,\ + "four": 4,\ + "five": 5,\ + "six": 6,\ + "seven": 7,\ + "eight": 8,\ + "nine": 9,\ + "ten": 10,\ + "eleven": 11,\ + "twelve": 12,\ + "thirteen": 13,\ + "fourteen": 14,\ + "fifteen": 15,\ + "sixteen": 16,\ + "seventeen": 17,\ + "eighteen": 18,\ + "nineteen": 19,\ + "twenty": 20,\ + "twenty-one": 21,\ + "twenty-two": 22,\ + "twenty-three": 23,\ + "twenty-four": 24,\ + "twenty-five": 25,\ + "twenty-six": 26,\ + "twenty-seven": 27,\ + "twenty-eight": 28,\ + "twenty-nine": 29,\ + "thirty": 30,\ + "thirty-one": 31,\ + "thirty-two": 32,\ + "thirty-three": 33,\ + "thirty-four": 34,\ + "thirty-five": 35,\ + "thirty-six": 36,\ + "thirty-seven": 37,\ + "thirty-eight": 38,\ + "thirty-nine": 39,\ + "forty": 40\ + };\ + \ + var words = belt.keys(wordToNumber).slice(0, limit);\ + }\ + \ + if (typeof isEqual != "undefined") {\ + var objectOfPrimitives = {\ + "boolean": true,\ + "number": 1,\ + "string": "a"\ + };\ + \ + var objectOfObjects = {\ + "boolean": new Boolean(true),\ + "number": new Number(1),\ + "string": new String("a")\ + };\ + \ + var object2 = {},\ + objects2 = Array(limit),\ + numbers2 = Array(limit),\ + nestedNumbers2 = [1, [2], [3, [[4]]]];\ + \ + for (index = 0; index < limit; index++) {\ + numbers2[index] = index;\ + object2["key" + index] = index;\ + objects2[index] = { "num": index };\ + }\ + }\ + \ + if (typeof multiArrays != "undefined") {\ + var twentyFiveValues = Array(25),\ + twentyFiveValues2 = Array(25),\ + fiftyValues = Array(50),\ + seventyFiveValues = Array(75),\ + seventyFiveValues2 = Array(75),\ + lowerChars = "abcdefghijklmnopqrstuvwxyz".split(""),\ + upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");\ + \ + for (index = 0; index < 75; index++) {\ + if (index < 26) {\ + if (index < 20) {\ + twentyFiveValues[index] = lowerChars[index];\ + twentyFiveValues2[index] = upperChars[index];\ + }\ + else if (index < 25) {\ + twentyFiveValues[index] =\ + twentyFiveValues2[index] = index;\ + }\ + fiftyValues[index] =\ + seventyFiveValues[index] = lowerChars[index];\ + seventyFiveValues2[index] = upperChars[index];\ + }\ + else {\ + if (index < 50) {\ + fiftyValues[index] = index;\ + }\ + seventyFiveValues[index] = index;\ + seventyFiveValues2[index] = index + (index < 60 ? 75 : 0);\ + }\ + }\ + }\ + \ + if (typeof template != "undefined") {\ + var tplData = {\ + "header1": "Header1",\ + "header2": "Header2",\ + "header3": "Header3",\ + "header4": "Header4",\ + "header5": "Header5",\ + "header6": "Header6",\ + "list": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]\ + };\ + \ + var tplBase =\ + "
      " +\ + "

      <%= header1 %>

      " +\ + "

      <%= header2 %>

      " +\ + "

      <%= header3 %>

      " +\ + "

      <%= header4 %>

      " +\ + "
      <%= header5 %>
      " +\ + "
      <%= header6 %>
      ";\ + \ + var tpl =\ + tplBase +\ + "
        " +\ + "
      • <%= list[0] %>
      • " +\ + "
      • <%= list[1] %>
      • " +\ + "
      • <%= list[2] %>
      • " +\ + "
      • <%= list[3] %>
      • " +\ + "
      • <%= list[4] %>
      • " +\ + "
      • <%= list[5] %>
      • " +\ + "
      • <%= list[6] %>
      • " +\ + "
      • <%= list[7] %>
      • " +\ + "
      • <%= list[8] %>
      • " +\ + "
      • <%= list[9] %>
      • " +\ + "
      " +\ + "
      ";\ + \ + var tplWithEvaluate =\ + tplBase +\ + "
        " +\ + "<% for (var index = 0, length = list.length; index < length; index++) { %>" +\ + "
      • <%= list[index] %>
      • " +\ + "<% } %>" +\ + "
      " +\ + "
      ";\ + \ + var tplBaseVerbose =\ + "
      " +\ + "

      <%= data.header1 %>

      " +\ + "

      <%= data.header2 %>

      " +\ + "

      <%= data.header3 %>

      " +\ + "

      <%= data.header4 %>

      " +\ + "
      <%= data.header5 %>
      " +\ + "
      <%= data.header6 %>
      ";\ + \ + var tplVerbose =\ + tplBaseVerbose +\ + "
        " +\ + "
      • <%= data.list[0] %>
      • " +\ + "
      • <%= data.list[1] %>
      • " +\ + "
      • <%= data.list[2] %>
      • " +\ + "
      • <%= data.list[3] %>
      • " +\ + "
      • <%= data.list[4] %>
      • " +\ + "
      • <%= data.list[5] %>
      • " +\ + "
      • <%= data.list[6] %>
      • " +\ + "
      • <%= data.list[7] %>
      • " +\ + "
      • <%= data.list[8] %>
      • " +\ + "
      • <%= data.list[9] %>
      • " +\ + "
      " +\ + "
      ";\ + \ + var tplVerboseWithEvaluate =\ + tplBaseVerbose +\ + "
        " +\ + "<% for (var index = 0, length = data.list.length; index < length; index++) { %>" +\ + "
      • <%= data.list[index] %>
      • " +\ + "<% } %>" +\ + "
      " +\ + "
      ";\ + \ + var settingsObject = { "variable": "data" };\ + \ + var lodashTpl = lodash.template(tpl),\ + lodashTplWithEvaluate = lodash.template(tplWithEvaluate),\ + lodashTplVerbose = lodash.template(tplVerbose, null, settingsObject),\ + lodashTplVerboseWithEvaluate = lodash.template(tplVerboseWithEvaluate, null, settingsObject);\ + \ + var _tpl = _.template(tpl),\ + _tplWithEvaluate = _.template(tplWithEvaluate),\ + _tplVerbose = _.template(tplVerbose, null, settingsObject),\ + _tplVerboseWithEvaluate = _.template(tplVerboseWithEvaluate, null, settingsObject);\ + }' + }); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.bind` (uses native `Function#bind` if available and inferred fast)') + .add(buildName, { + 'fn': 'lodash.bind(func, { "name": "moe" }, "hi")', + 'teardown': 'function bind(){}' + }) + .add(otherName, { + 'fn': '_.bind(func, { "name": "moe" }, "hi")', + 'teardown': 'function bind(){}' + }) + ); + + suites.push( + Benchmark.Suite('bound call') + .add(buildName, { + 'fn': 'lodashBoundNormal()', + 'teardown': 'function bind(){}' + }) + .add(otherName, { + 'fn': '_boundNormal()', + 'teardown': 'function bind(){}' + }) + ); + + suites.push( + Benchmark.Suite('bound call with arguments') + .add(buildName, { + 'fn': 'lodashBoundNormal("hi", "!")', + 'teardown': 'function bind(){}' + }) + .add(otherName, { + 'fn': '_boundNormal("hi", "!")', + 'teardown': 'function bind(){}' + }) + ); + + suites.push( + Benchmark.Suite('bound and partially applied call (uses native `Function#bind` if available)') + .add(buildName, { + 'fn': 'lodashBoundPartial()', + 'teardown': 'function bind(){}' + }) + .add(otherName, { + 'fn': '_boundPartial()', + 'teardown': 'function bind(){}' + }) + ); + + suites.push( + Benchmark.Suite('bound and partially applied call with arguments (uses native `Function#bind` if available)') + .add(buildName, { + 'fn': 'lodashBoundPartial("!")', + 'teardown': 'function bind(){}' + }) + .add(otherName, { + 'fn': '_boundPartial("!")', + 'teardown': 'function bind(){}' + }) + ); + + suites.push( + Benchmark.Suite('bound and called in a `new` expression, i.e. `new bound` (edge case)') + .add(buildName, { + 'fn': 'new lodashBoundCtor()', + 'teardown': 'function bind(){}' + }) + .add(otherName, { + 'fn': 'new _boundCtor()', + 'teardown': 'function bind(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.bindAll` iterating arguments') + .add(buildName, { + 'fn': 'lodash.bindAll.apply(lodash, [bindAllObjects.pop()].concat(funcNames))', + 'teardown': 'function bindAll(){}' + }) + .add(otherName, { + 'fn': '_.bindAll.apply(_, [bindAllObjects.pop()].concat(funcNames))', + 'teardown': 'function bindAll(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.bindAll` iterating the `object`') + .add(buildName, { + 'fn': 'lodash.bindAll(bindAllObjects.pop())', + 'teardown': 'function bindAll(){}' + }) + .add(otherName, { + 'fn': '_.bindAll(bindAllObjects.pop())', + 'teardown': 'function bindAll(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.clone` with an object') + .add(buildName, '\ + lodash.clone(object)' + ) + .add(otherName, '\ + _.clone(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.compact`') + .add(buildName, { + 'fn': 'lodash.compact(uncompacted)', + 'teardown': 'function compact(){}' + }) + .add(otherName, { + 'fn': '_.compact(uncompacted)', + 'teardown': 'function compact(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.contains` iterating an array') + .add(buildName, '\ + lodash.contains(numbers, 19)' + ) + .add(otherName, '\ + _.contains(numbers, 19)' + ) + ); + + suites.push( + Benchmark.Suite('`_.contains` iterating an object') + .add(buildName, '\ + lodash.contains(object, 19)' + ) + .add(otherName, '\ + _.contains(object, 19)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.countBy` with `callback` iterating an array') + .add(buildName, '\ + lodash.countBy(numbers, function(num) { return num >> 1; })' + ) + .add(otherName, '\ + _.countBy(numbers, function(num) { return num >> 1; })' + ) + ); + + suites.push( + Benchmark.Suite('`_.countBy` with `property` name iterating an array') + .add(buildName, { + 'fn': 'lodash.countBy(words, "length")', + 'teardown': 'function countBy(){}' + }) + .add(otherName, { + 'fn': '_.countBy(words, "length")', + 'teardown': 'function countBy(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.countBy` with `callback` iterating an object') + .add(buildName, { + 'fn': 'lodash.countBy(wordToNumber, function(num) { return num >> 1; })', + 'teardown': 'function countBy(){}' + }) + .add(otherName, { + 'fn': '_.countBy(wordToNumber, function(num) { return num >> 1; })', + 'teardown': 'function countBy(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.defaults`') + .add(buildName, '\ + lodash.defaults({ "key2": 2, "key6": 6, "key18": 18 }, object)' + ) + .add(otherName, '\ + _.defaults({ "key2": 2, "key6": 6, "key18": 18 }, object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.difference`') + .add(buildName, '\ + lodash.difference(numbers, fourNumbers, twoNumbers)' + ) + .add(otherName, '\ + _.difference(numbers, fourNumbers, twoNumbers)' + ) + ); + + suites.push( + Benchmark.Suite('`_.difference` iterating 25 elements') + .add(buildName, { + 'fn': 'lodash.difference(twentyFiveValues, twentyFiveValues2)', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.difference(twentyFiveValues, twentyFiveValues2)', + 'teardown': 'function multiArrays(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.difference` iterating 50 and 75 elements') + .add(buildName, { + 'fn': 'lodash.difference(fiftyValues, seventyFiveValues2)', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.difference(fiftyValues, seventyFiveValues2)', + 'teardown': 'function multiArrays(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.difference` iterating 75 elements') + .add(buildName, { + 'fn': 'lodash.difference(seventyFiveValues, seventyFiveValues2)', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.difference(seventyFiveValues, seventyFiveValues2)', + 'teardown': 'function multiArrays(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.each` iterating an array') + .add(buildName, '\ + var result = [];\ + lodash.each(numbers, function(num) {\ + result.push(num * 2);\ + })' + ) + .add(otherName, '\ + var result = [];\ + _.each(numbers, function(num) {\ + result.push(num * 2);\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.each` iterating an array with `thisArg` (slow path)') + .add(buildName, '\ + var result = [];\ + lodash.each(numbers, function(num, index) {\ + result.push(num + this["key" + index]);\ + }, object)' + ) + .add(otherName, '\ + var result = [];\ + _.each(numbers, function(num, index) {\ + result.push(num + this["key" + index]);\ + }, object)' + ) + ); + + suites.push( + Benchmark.Suite('`_.each` iterating an object') + .add(buildName, '\ + var result = [];\ + lodash.each(object, function(num) {\ + result.push(num * 2);\ + })' + ) + .add(otherName, '\ + var result = [];\ + _.each(object, function(num) {\ + result.push(num * 2);\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.every` iterating an array') + .add(buildName, '\ + lodash.every(numbers, function(num) {\ + return num + "";\ + })' + ) + .add(otherName, '\ + _.every(numbers, function(num) {\ + return num + "";\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.every` iterating an object') + .add(buildName, '\ + lodash.every(object, function(num) {\ + return num + "";\ + })' + ) + .add(otherName, '\ + _.every(object, function(num) {\ + return num + "";\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.extend`') + .add(buildName, '\ + lodash.extend({}, object)' + ) + .add(otherName, '\ + _.extend({}, object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.filter` iterating an array') + .add(buildName, '\ + lodash.filter(numbers, function(num) {\ + return num % 2;\ + })' + ) + .add(otherName, '\ + _.filter(numbers, function(num) {\ + return num % 2;\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.filter` iterating an array with `thisArg` (slow path)') + .add(buildName, '\ + lodash.filter(numbers, function(num, index) {\ + return this["key" + index] % 2;\ + }, object)' + ) + .add(otherName, '\ + _.filter(numbers, function(num, index) {\ + return this["key" + index] % 2;\ + }, object)' + ) + ); + + suites.push( + Benchmark.Suite('`_.filter` iterating an object') + .add(buildName, '\ + lodash.filter(object, function(num) {\ + return num % 2\ + })' + ) + .add(otherName, '\ + _.filter(object, function(num) {\ + return num % 2\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.find` iterating an array') + .add(buildName, '\ + lodash.find(numbers, function(num) {\ + return num === 19;\ + })' + ) + .add(otherName, '\ + _.find(numbers, function(num) {\ + return num === 19;\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.find` iterating an object') + .add(buildName, '\ + lodash.find(object, function(value, key) {\ + return /\D9$/.test(key);\ + })' + ) + .add(otherName, '\ + _.find(object, function(value, key) {\ + return /\D9$/.test(key);\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.flatten`') + .add(buildName, '\ + lodash.flatten(nestedNumbers)' + ) + .add(otherName, '\ + _.flatten(nestedNumbers)' + ) + ); + + suites.push( + Benchmark.Suite('`_.flatten` with `shallow`') + .add(buildName, '\ + lodash.flatten(nestedNumbers, true)' + ) + .add(otherName, '\ + _.flatten(nestedNumbers, true)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.functions`') + .add(buildName, '\ + lodash.functions(lodash)' + ) + .add(otherName, '\ + _.functions(lodash)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.groupBy` with `callback` iterating an array') + .add(buildName, '\ + lodash.groupBy(numbers, function(num) { return num >> 1; })' + ) + .add(otherName, '\ + _.groupBy(numbers, function(num) { return num >> 1; })' + ) + ); + + suites.push( + Benchmark.Suite('`_.groupBy` with `property` name iterating an array') + .add(buildName, { + 'fn': 'lodash.groupBy(words, "length")', + 'teardown': 'function countBy(){}' + }) + .add(otherName, { + 'fn': '_.groupBy(words, "length")', + 'teardown': 'function countBy(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.groupBy` with `callback` iterating an object') + .add(buildName, { + 'fn': 'lodash.groupBy(wordToNumber, function(num) { return num >> 1; })', + 'teardown': 'function countBy(){}' + }) + .add(otherName, { + 'fn': '_.groupBy(wordToNumber, function(num) { return num >> 1; })', + 'teardown': 'function countBy(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.indexOf`') + .add(buildName, '\ + lodash.indexOf(numbers, 9)' + ) + .add(otherName, '\ + _.indexOf(numbers, 9)' + ) + ); + + suites.push( + Benchmark.Suite('`_.indexOf` with `isSorted`') + .add(buildName, '\ + lodash.indexOf(numbers, 19, true)' + ) + .add(otherName, '\ + _.indexOf(numbers, 19, true)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.intersection`') + .add(buildName, '\ + lodash.intersection(numbers, fourNumbers, twoNumbers)' + ) + .add(otherName, '\ + _.intersection(numbers, fourNumbers, twoNumbers)' + ) + ); + + suites.push( + Benchmark.Suite('`_.intersection` iterating 25 elements') + .add(buildName, { + 'fn': 'lodash.intersection(twentyFiveValues, twentyFiveValues2)', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.intersection(twentyFiveValues, twentyFiveValues2)', + 'teardown': 'function multiArrays(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.intersection` iterating 50 and 75 elements') + .add(buildName, { + 'fn': 'lodash.intersection(fiftyValues, seventyFiveValues2)', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.intersection(fiftyValues, seventyFiveValues2)', + 'teardown': 'function multiArrays(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.intersection` iterating 75 elements') + .add(buildName, { + 'fn': 'lodash.intersection(seventyFiveValues, seventyFiveValues2)', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.intersection(seventyFiveValues, seventyFiveValues2)', + 'teardown': 'function multiArrays(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.invert`') + .add(buildName, '\ + lodash.invert(object)' + ) + .add(otherName, '\ + _.invert(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.invoke` iterating an array') + .add(buildName, '\ + lodash.invoke(numbers, "toFixed", "2")' + ) + .add(otherName, '\ + _.invoke(numbers, "toFixed", "2")' + ) + ); + + suites.push( + Benchmark.Suite('`_.invoke` with a function for `methodName` iterating an array') + .add(buildName, '\ + lodash.invoke(numbers, String.prototype.split, "")' + ) + .add(otherName, '\ + _.invoke(numbers, String.prototype.split, "")' + ) + ); + + suites.push( + Benchmark.Suite('`_.invoke` iterating an object') + .add(buildName, '\ + lodash.invoke(object, "toFixed", "2")' + ) + .add(otherName, '\ + _.invoke(object, "toFixed", "2")' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.isEqual` comparing primitives and objects (edge case)') + .add(buildName, { + 'fn': 'lodash.isEqual(objectOfPrimitives, objectOfObjects)', + 'teardown': 'function isEqual(){}' + }) + .add(otherName, { + 'fn': '_.isEqual(objectOfPrimitives, objectOfObjects)', + 'teardown': 'function isEqual(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.isEqual` comparing arrays') + .add(buildName, { + 'fn': 'lodash.isEqual(numbers, numbers2)', + 'teardown': 'function isEqual(){}' + }) + .add(otherName, { + 'fn': '_.isEqual(numbers, numbers2)', + 'teardown': 'function isEqual(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.isEqual` comparing nested arrays') + .add(buildName, { + 'fn': 'lodash.isEqual(nestedNumbers, nestedNumbers2)', + 'teardown': 'function isEqual(){}' + }) + .add(otherName, { + 'fn': '_.isEqual(nestedNumbers, nestedNumbers2)', + 'teardown': 'function isEqual(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.isEqual` comparing arrays of objects') + .add(buildName, { + 'fn': 'lodash.isEqual(objects, objects2)', + 'teardown': 'function isEqual(){}' + }) + .add(otherName, { + 'fn': '_.isEqual(objects, objects2)', + 'teardown': 'function isEqual(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.isEqual` comparing objects') + .add(buildName, { + 'fn': 'lodash.isEqual(object, object2)', + 'teardown': 'function isEqual(){}' + }) + .add(otherName, { + 'fn': '_.isEqual(object, object2)', + 'teardown': 'function isEqual(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.isArguments`, `_.isDate`, `_.isFunction`, `_.isNumber`, `_.isRegExp`') + .add(buildName, '\ + lodash.isArguments(arguments);\ + lodash.isArguments(object);\ + lodash.isDate(date);\ + lodash.isDate(object);\ + lodash.isFunction(lodash);\ + lodash.isFunction(object);\ + lodash.isNumber(1);\ + lodash.isNumber(object);\ + lodash.isRegExp(regexp);\ + lodash.isRegExp(object);' + ) + .add(otherName, '\ + _.isArguments(arguments);\ + _.isArguments(object);\ + _.isDate(date);\ + _.isDate(object);\ + _.isFunction(_);\ + _.isFunction(object);\ + _.isNumber(1);\ + _.isNumber(object);\ + _.isRegExp(regexp);\ + _.isRegExp(object);' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.keys` (uses native `Object.keys` if available)') + .add(buildName, '\ + lodash.keys(object)' + ) + .add(otherName, '\ + _.keys(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.lastIndexOf`') + .add(buildName, '\ + lodash.lastIndexOf(numbers, 9)' + ) + .add(otherName, '\ + _.lastIndexOf(numbers, 9)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.map` iterating an array') + .add(buildName, '\ + lodash.map(objects, function(value) {\ + return value.num;\ + })' + ) + .add(otherName, '\ + _.map(objects, function(value) {\ + return value.num;\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.map` with `thisArg` iterating an array (slow path)') + .add(buildName, '\ + lodash.map(objects, function(value, index) {\ + return this["key" + index] + value.num;\ + }, object)' + ) + .add(otherName, '\ + _.map(objects, function(value, index) {\ + return this["key" + index] + value.num;\ + }, object)' + ) + ); + + suites.push( + Benchmark.Suite('`_.map` iterating an object') + .add(buildName, '\ + lodash.map(object, function(value) {\ + return value;\ + })' + ) + .add(otherName, '\ + _.map(object, function(value) {\ + return value;\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.max`') + .add(buildName, '\ + lodash.max(numbers)' + ) + .add(otherName, '\ + _.max(numbers)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.min`') + .add(buildName, '\ + lodash.min(numbers)' + ) + .add(otherName, '\ + _.min(numbers)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.omit` iterating 20 properties, omitting 2 keys') + .add(buildName, '\ + lodash.omit(object, "key6", "key13")' + ) + .add(otherName, '\ + _.omit(object, "key6", "key13")' + ) + ); + + suites.push( + Benchmark.Suite('`_.omit` iterating 40 properties, omitting 20 keys') + .add(buildName, { + 'fn': 'lodash.omit(wordToNumber, words)', + 'teardown': 'function omit(){}' + }) + .add(otherName, { + 'fn': 'result = _.omit(wordToNumber, words)', + 'teardown': 'function omit(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.pairs`') + .add(buildName, '\ + lodash.pairs(object)' + ) + .add(otherName, '\ + _.pairs(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.pick`') + .add(buildName, '\ + lodash.pick(object, "key6", "key13")' + ) + .add(otherName, '\ + _.pick(object, "key6", "key13")' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.pluck`') + .add(buildName, '\ + lodash.pluck(objects, "num")' + ) + .add(otherName, '\ + _.pluck(objects, "num")' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.reduce` iterating an array') + .add(buildName, '\ + lodash.reduce(numbers, function(result, value, index) {\ + result[index] = value;\ + return result;\ + }, {});' + ) + .add(otherName, '\ + _.reduce(numbers, function(result, value, index) {\ + result[index] = value;\ + return result;\ + }, {});' + ) + ); + + suites.push( + Benchmark.Suite('`_.reduce` iterating an object') + .add(buildName, '\ + lodash.reduce(object, function(result, value, key) {\ + result.push([key, value]);\ + return result;\ + }, []);' + ) + .add(otherName, '\ + _.reduce(object, function(result, value, key) {\ + result.push([key, value]);\ + return result;\ + }, []);' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.reduceRight` iterating an array') + .add(buildName, '\ + lodash.reduceRight(numbers, function(result, value, index) {\ + result[index] = value;\ + return result;\ + }, {});' + ) + .add(otherName, '\ + _.reduceRight(numbers, function(result, value, index) {\ + result[index] = value;\ + return result;\ + }, {});' + ) + ); + + suites.push( + Benchmark.Suite('`_.reduceRight` iterating an object') + .add(buildName, '\ + lodash.reduceRight(object, function(result, value, key) {\ + result.push([key, value]);\ + return result;\ + }, []);' + ) + .add(otherName, '\ + _.reduceRight(object, function(result, value, key) {\ + result.push([key, value]);\ + return result;\ + }, []);' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.reject` iterating an array') + .add(buildName, '\ + lodash.reject(numbers, function(num) {\ + return num % 2;\ + })' + ) + .add(otherName, '\ + _.reject(numbers, function(num) {\ + return num % 2;\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.reject` iterating an array with `thisArg` (slow path)') + .add(buildName, '\ + lodash.reject(numbers, function(num, index) {\ + return this["key" + index] % 2;\ + }, object)' + ) + .add(otherName, '\ + _.reject(numbers, function(num, index) {\ + return this["key" + index] % 2;\ + }, object)' + ) + ); + + suites.push( + Benchmark.Suite('`_.reject` iterating an object') + .add(buildName, '\ + lodash.reject(object, function(num) {\ + return num % 2\ + })' + ) + .add(otherName, '\ + _.reject(object, function(num) {\ + return num % 2\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.shuffle`') + .add(buildName, '\ + lodash.shuffle(numbers)' + ) + .add(otherName, '\ + _.shuffle(numbers)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.size` with an object') + .add(buildName, '\ + lodash.size(object)' + ) + .add(otherName, '\ + _.size(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.some` iterating an array') + .add(buildName, '\ + lodash.some(numbers, function(num) {\ + return num == 19;\ + })' + ) + .add(otherName, '\ + _.some(numbers, function(num) {\ + return num == 19;\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.some` iterating an object') + .add(buildName, '\ + lodash.some(object, function(num) {\ + return num == 19;\ + })' + ) + .add(otherName, '\ + _.some(object, function(num) {\ + return num == 19;\ + })' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.sortBy` with `callback`') + .add(buildName, '\ + lodash.sortBy(numbers, function(num) { return Math.sin(num); })' + ) + .add(otherName, '\ + _.sortBy(numbers, function(num) { return Math.sin(num); })' + ) + ); + + suites.push( + Benchmark.Suite('`_.sortBy` with `callback` and `thisArg` (slow path)') + .add(buildName, '\ + lodash.sortBy(numbers, function(num) { return this.sin(num); }, Math)' + ) + .add(otherName, '\ + _.sortBy(numbers, function(num) { return this.sin(num); }, Math)' + ) + ); + + suites.push( + Benchmark.Suite('`_.sortBy` with `property` name') + .add(buildName, { + 'fn': 'lodash.sortBy(words, "length")', + 'teardown': 'function countBy(){}' + }) + .add(otherName, { + 'fn': '_.sortBy(words, "length")', + 'teardown': 'function countBy(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.sortedIndex`') + .add(buildName, '\ + lodash.sortedIndex(numbers, 25)' + ) + .add(otherName, '\ + _.sortedIndex(numbers, 25)' + ) + ); + + suites.push( + Benchmark.Suite('`_.sortedIndex` with `callback`') + .add(buildName, { + 'fn': '\ + lodash.sortedIndex(words, "twenty-five", function(value) {\ + return wordToNumber[value];\ + })', + 'teardown': 'function countBy(){}' + }) + .add(otherName, { + 'fn': '\ + _.sortedIndex(words, "twenty-five", function(value) {\ + return wordToNumber[value];\ + })', + 'teardown': 'function countBy(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.template` without "evaluate" delimiters (slow path)') + .add(buildName, { + 'fn': 'lodash.template(tpl, tplData)', + 'teardown': 'function template(){}' + }) + .add(otherName, { + 'fn': '_.template(tpl, tplData)', + 'teardown': 'function template(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.template` with "evaluate" delimiters (slow path)') + .add(buildName, { + 'fn': 'lodash.template(tplWithEvaluate, tplData)', + 'teardown': 'function template(){}' + }) + .add(otherName, { + 'fn': '_.template(tplWithEvaluate, tplData)', + 'teardown': 'function template(){}' + }) + ); + + suites.push( + Benchmark.Suite('compiled template without "evaluate" delimiters') + .add(buildName, { + 'fn': 'lodashTpl(tplData)', + 'teardown': 'function template(){}' + }) + .add(otherName, { + 'fn': '_tpl(tplData)', + 'teardown': 'function template(){}' + }) + ); + + suites.push( + Benchmark.Suite('compiled template with "evaluate" delimiters') + .add(buildName, { + 'fn': 'lodashTplWithEvaluate(tplData)', + 'teardown': 'function template(){}' + }) + .add(otherName, { + 'fn': '_tplWithEvaluate(tplData)', + 'teardown': 'function template(){}' + }) + ); + + suites.push( + Benchmark.Suite('compiled template without a with-statement or "evaluate" delimiters') + .add(buildName, { + 'fn': 'lodashTplVerbose(tplData)', + 'teardown': 'function template(){}' + }) + .add(otherName, { + 'fn': '_tplVerbose(tplData)', + 'teardown': 'function template(){}' + }) + ); + + suites.push( + Benchmark.Suite('compiled template without a with-statement using "evaluate" delimiters') + .add(buildName, { + 'fn': 'lodashTplVerboseWithEvaluate(tplData)', + 'teardown': 'function template(){}' + }) + .add(otherName, { + 'fn': '_tplVerboseWithEvaluate(tplData)', + 'teardown': 'function template(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.times`') + .add(buildName, '\ + var result = [];\ + lodash.times(limit, function(n) { result.push(n); })' + ) + .add(otherName, '\ + var result = [];\ + _.times(limit, function(n) { result.push(n); })' + ) + ); + + suites.push( + Benchmark.Suite('`_.times` with `thisArg`') + .add(buildName, '\ + var result = [];\ + lodash.times(limit, function(n) { result.push(this.sin(n)); }, Math)' + ) + .add(otherName, '\ + var result = [];\ + _.times(limit, function(n) { result.push(this.sin(n)); }, Math)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.toArray` with an array') + .add(buildName, '\ + lodash.toArray(numbers)' + ) + .add(otherName, '\ + _.toArray(numbers)' + ) + ); + + suites.push( + Benchmark.Suite('`_.toArray` with an object') + .add(buildName, '\ + lodash.toArray(object)' + ) + .add(otherName, '\ + _.toArray(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.union`') + .add(buildName, '\ + lodash.union(numbers, fourNumbers, twoNumbers)' + ) + .add(otherName, '\ + _.union(numbers, fourNumbers, twoNumbers)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.uniq`') + .add(buildName, '\ + lodash.uniq(numbers.concat(fourNumbers, twoNumbers))' + ) + .add(otherName, '\ + _.uniq(numbers.concat(fourNumbers, twoNumbers))' + ) + ); + + suites.push( + Benchmark.Suite('`_.uniq` with `callback`') + .add(buildName, '\ + lodash.uniq(numbers.concat(fourNumbers, twoNumbers), function(num) {\ + return num % 2;\ + });' + ) + .add(otherName, '\ + _.uniq(numbers.concat(fourNumbers, twoNumbers), function(num) {\ + return num % 2;\ + })' + ) + ); + + suites.push( + Benchmark.Suite('`_.uniq` iterating an array of 50 elements') + .add(buildName, { + 'fn': 'lodash.uniq(twentyFiveValues.concat(twentyFiveValues2));', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.uniq(twentyFiveValues.concat(twentyFiveValues2));', + 'teardown': 'function multiArrays(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.uniq` iterating an array of 75 elements') + .add(buildName, { + 'fn': 'lodash.uniq(fiftyValues.concat(twentyFiveValues2));', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.uniq(fiftyValues.concat(twentyFiveValues2));', + 'teardown': 'function multiArrays(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.uniq` iterating an array of 100 elements') + .add(buildName, { + 'fn': 'lodash.uniq(seventyFiveValues.concat(twentyFiveValues2));', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.uniq(seventyFiveValues.concat(twentyFiveValues2));', + 'teardown': 'function multiArrays(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.values`') + .add(buildName, '\ + lodash.values(object)' + ) + .add(otherName, '\ + _.values(object)' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.where`') + .add(buildName, '\ + lodash.where(objects, { "num": 9 });' + ) + .add(otherName, '\ + _.where(objects, { "num": 9 });' + ) + ); + + /*--------------------------------------------------------------------------*/ + + suites.push( + Benchmark.Suite('`_.without`') + .add(buildName, '\ + lodash.without(numbers, 9, 12, 14, 15)' + ) + .add(otherName, '\ + _.without(numbers, 9, 12, 14, 15)' + ) + ); + + suites.push( + Benchmark.Suite('`_.without` iterating an array of 25 elements') + .add(buildName, { + 'fn': 'lodash.without.apply(lodash, [twentyFiveValues].concat(twentyFiveValues2));', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.without.apply(_, [twentyFiveValues].concat(twentyFiveValues2));', + 'teardown': 'function multiArrays(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.without` iterating an array of 75 and 50 elements') + .add(buildName, { + 'fn': 'lodash.without.apply(lodash, [seventyFiveValues2].concat(fiftyValues));', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.without.apply(_, [seventyFiveValues2].concat(fiftyValues));', + 'teardown': 'function multiArrays(){}' + }) + ); + + suites.push( + Benchmark.Suite('`_.without` iterating an array of 75 elements') + .add(buildName, { + 'fn': 'lodash.without.apply(lodash, [seventyFiveValues].concat(seventyFiveValues2));', + 'teardown': 'function multiArrays(){}' + }) + .add(otherName, { + 'fn': '_.without.apply(_, [seventyFiveValues].concat(seventyFiveValues2));', + 'teardown': 'function multiArrays(){}' + }) + ); + + /*--------------------------------------------------------------------------*/ + + if (Benchmark.platform + '') { + log(Benchmark.platform); + } + + // in the browser, expose `run` to be called later + if (window.document) { + window.run = run; + } else { + run(); + } +}(typeof global == 'object' && global || this)); diff --git a/node/node_modules/grunt/node_modules/lodash/test/template/a.jst b/node/node_modules/grunt/node_modules/lodash/test/template/a.jst new file mode 100644 index 000000000..a2a8b6e00 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/test/template/a.jst @@ -0,0 +1,3 @@ +
        +<% _.forEach(people, function(name) { %>
      • <%= name %>
      • <% }); %> +
      \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/lodash/test/template/b.jst b/node/node_modules/grunt/node_modules/lodash/test/template/b.jst new file mode 100644 index 000000000..cad081d19 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/test/template/b.jst @@ -0,0 +1 @@ +<% print("Hello " + epithet); %>. \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/lodash/test/template/c.tpl b/node/node_modules/grunt/node_modules/lodash/test/template/c.tpl new file mode 100644 index 000000000..c7a43bc1f --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/test/template/c.tpl @@ -0,0 +1 @@ +Hello {{ name }}! \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/lodash/test/test-build.js b/node/node_modules/grunt/node_modules/lodash/test/test-build.js new file mode 100644 index 000000000..76ca6aae8 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/test/test-build.js @@ -0,0 +1,1048 @@ +#!/usr/bin/env node +;(function(undefined) { + 'use strict'; + + /** Load modules */ + var fs = require('fs'), + path = require('path'), + vm = require('vm'), + build = require('../build.js'), + minify = require('../build/minify'), + _ = require('../lodash.js'); + + /** The unit testing framework */ + var QUnit = global.QUnit = require('../vendor/qunit/qunit/qunit.js'); + require('../vendor/qunit-clib/qunit-clib.js'); + + /** Used to associate aliases with their real names */ + var aliasToRealMap = { + 'all': 'every', + 'any': 'some', + 'collect': 'map', + 'detect': 'find', + 'drop': 'rest', + 'each': 'forEach', + 'foldl': 'reduce', + 'foldr': 'reduceRight', + 'head': 'first', + 'include': 'contains', + 'inject': 'reduce', + 'methods': 'functions', + 'select': 'filter', + 'tail': 'rest', + 'take': 'first', + 'unique': 'uniq' + }; + + /** Used to associate real names with their aliases */ + var realToAliasMap = { + 'contains': ['include'], + 'every': ['all'], + 'filter': ['select'], + 'find': ['detect'], + 'first': ['head', 'take'], + 'forEach': ['each'], + 'functions': ['methods'], + 'map': ['collect'], + 'reduce': ['foldl', 'inject'], + 'reduceRight': ['foldr'], + 'rest': ['drop', 'tail'], + 'some': ['any'], + 'uniq': ['unique'] + }; + + /** List of all Lo-Dash methods */ + var allMethods = _.functions(_).filter(function(methodName) { + return !/^_/.test(methodName); + }); + + /** List of "Arrays" category methods */ + var arraysMethods = [ + 'compact', + 'difference', + 'drop', + 'first', + 'flatten', + 'head', + 'indexOf', + 'initial', + 'intersection', + 'last', + 'lastIndexOf', + 'object', + 'range', + 'rest', + 'sortedIndex', + 'tail', + 'take', + 'union', + 'uniq', + 'unique', + 'without', + 'zip' + ]; + + /** List of "Chaining" category methods */ + var chainingMethods = [ + 'chain', + 'mixin', + 'tap', + 'value' + ]; + + /** List of "Collections" category methods */ + var collectionsMethods = [ + 'all', + 'any', + 'collect', + 'contains', + 'countBy', + 'detect', + 'each', + 'every', + 'filter', + 'find', + 'foldl', + 'foldr', + 'forEach', + 'groupBy', + 'include', + 'inject', + 'invoke', + 'map', + 'max', + 'min', + 'pluck', + 'reduce', + 'reduceRight', + 'reject', + 'select', + 'shuffle', + 'size', + 'some', + 'sortBy', + 'toArray', + 'where' + ]; + + /** List of "Functions" category methods */ + var functionsMethods = [ + 'after', + 'bind', + 'bindAll', + 'compose', + 'debounce', + 'defer', + 'delay', + 'lateBind', + 'memoize', + 'once', + 'partial', + 'throttle', + 'wrap' + ]; + + /** List of "Objects" category methods */ + var objectsMethods = [ + 'clone', + 'defaults', + 'extend', + 'forIn', + 'forOwn', + 'functions', + 'has', + 'invert', + 'isArguments', + 'isArray', + 'isBoolean', + 'isDate', + 'isElement', + 'isEmpty', + 'isEqual', + 'isFinite', + 'isFunction', + 'isNaN', + 'isNull', + 'isNumber', + 'isObject', + 'isPlainObject', + 'isRegExp', + 'isString', + 'isUndefined', + 'keys', + 'methods', + 'merge', + 'omit', + 'pairs', + 'pick', + 'values' + ]; + + /** List of "Utilities" category methods */ + var utilityMethods = [ + 'escape', + 'identity', + 'noConflict', + 'random', + 'result', + 'template', + 'times', + 'unescape', + 'uniqueId' + ]; + + /** List of Backbone's Lo-Dash dependencies */ + var backboneDependencies = [ + 'bind', + 'bindAll', + 'clone', + 'contains', + 'escape', + 'every', + 'extend', + 'filter', + 'find', + 'first', + 'forEach', + 'groupBy', + 'has', + 'indexOf', + 'initial', + 'invoke', + 'isArray', + 'isEmpty', + 'isEqual', + 'isFunction', + 'isObject', + 'isRegExp', + 'keys', + 'last', + 'lastIndexOf', + 'map', + 'max', + 'min', + 'mixin', + 'reduce', + 'reduceRight', + 'reject', + 'rest', + 'result', + 'shuffle', + 'size', + 'some', + 'sortBy', + 'sortedIndex', + 'toArray', + 'uniqueId', + 'without' + ]; + + /** List of methods used by Underscore */ + var underscoreMethods = _.without.apply(_, [allMethods].concat([ + 'forIn', + 'forOwn', + 'isPlainObject', + 'lateBind', + 'merge', + 'partial' + ])); + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a context object to use with `vm.runInContext`. + * + * @private + * @returns {Object} Returns a new context object. + */ + function createContext() { + return vm.createContext({ + 'clearTimeout': clearTimeout, + 'setTimeout': setTimeout + }); + } + + /** + * Expands a list of method names to include real and alias names. + * + * @private + * @param {Array} methodNames The array of method names to expand. + * @returns {Array} Returns a new array of expanded method names. + */ + function expandMethodNames(methodNames) { + return methodNames.reduce(function(result, methodName) { + var realName = getRealName(methodName); + result.push.apply(result, [realName].concat(getAliases(realName))); + return result; + }, []); + } + + /** + * Gets the aliases associated with a given function name. + * + * @private + * @param {String} funcName The name of the function to get aliases for. + * @returns {Array} Returns an array of aliases. + */ + function getAliases(funcName) { + return realToAliasMap[funcName] || []; + } + + /** + * Gets the names of methods belonging to the given `category`. + * + * @private + * @param {String} category The category to filter by. + * @returns {Array} Returns a new array of method names belonging to the given category. + */ + function getMethodsByCategory(category) { + switch (category) { + case 'Arrays': + return arraysMethods.slice(); + case 'Chaining': + return chainingMethods.slice(); + case 'Collections': + return collectionsMethods.slice(); + case 'Functions': + return functionsMethods.slice(); + case 'Objects': + return objectsMethods.slice(); + case 'Utilities': + return utilityMethods.slice(); + } + return []; + } + + /** + * Gets the real name, not alias, of a given function name. + * + * @private + * @param {String} funcName The name of the function to resolve. + * @returns {String} Returns the real name. + */ + function getRealName(funcName) { + return aliasToRealMap[funcName] || funcName; + } + + /** + * Tests if a given method on the `lodash` object can be called successfully. + * + * @private + * @param {Object} lodash The built Lo-Dash object. + * @param {String} methodName The name of the Lo-Dash method to test. + * @param {String} message The unit test message. + */ + function testMethod(lodash, methodName, message) { + var pass = true, + array = [['a', 1], ['b', 2], ['c', 3]], + object = { 'a': 1, 'b': 2, 'c': 3 }, + noop = function() {}, + string = 'abc', + func = lodash[methodName]; + + try { + if (arraysMethods.indexOf(methodName) > -1) { + if (/(?:indexOf|sortedIndex|without)$/i.test(methodName)) { + func(array, string); + } else if (/^(?:difference|intersection|union|uniq|zip)/.test(methodName)) { + func(array, array); + } else if (methodName == 'range') { + func(2, 4); + } else { + func(array); + } + } + else if (chainingMethods.indexOf(methodName) > -1) { + if (methodName == 'chain') { + lodash.chain(array); + lodash(array).chain(); + } + else if (methodName == 'mixin') { + lodash.mixin({}); + } + else { + lodash(array)[methodName](noop); + } + } + else if (collectionsMethods.indexOf(methodName) > -1) { + if (/^(?:count|group|sort)By$/.test(methodName)) { + func(array, noop); + func(array, string); + func(object, noop); + func(object, string); + } + else if (/^(?:size|toArray)$/.test(methodName)) { + func(array); + func(object); + } + else if (methodName == 'invoke') { + func(array, 'slice'); + func(object, 'toFixed'); + } + else if (methodName == 'where') { + func(array, object); + func(object, object); + } + else { + func(array, noop, object); + func(object, noop, object); + } + } + else if (functionsMethods.indexOf(methodName) > -1) { + if (methodName == 'after') { + func(1, noop); + } else if (methodName == 'bindAll') { + func({ 'noop': noop }); + } else if (methodName == 'lateBind') { + func(lodash, 'identity', array, string); + } else if (/^(?:bind|partial)$/.test(methodName)) { + func(noop, object, array, string); + } else if (/^(?:compose|memoize|wrap)$/.test(methodName)) { + func(noop, noop); + } else if (/^(?:debounce|throttle)$/.test(methodName)) { + func(noop, 100); + } else { + func(noop); + } + } + else if (objectsMethods.indexOf(methodName) > -1) { + if (methodName == 'clone') { + func(object); + func(object, true); + } + else if (/^(?:defaults|extend|merge)$/.test(methodName)) { + func({}, object); + } else if (/^(?:forIn|forOwn)$/.test(methodName)) { + func(object, noop); + } else if (/^(?:omit|pick)$/.test(methodName)) { + func(object, 'b'); + } else if (methodName == 'has') { + func(object, string); + } else { + func(object); + } + } + else if (utilityMethods.indexOf(methodName) > -1) { + if (methodName == 'result') { + func(object, 'b'); + } else if (methodName == 'times') { + func(2, noop, object); + } else { + func(string, object); + } + } + } + catch(e) { + console.log(e); + pass = false; + } + equal(pass, true, '_.' + methodName + ': ' + message); + } + + /*--------------------------------------------------------------------------*/ + + QUnit.module('minified AMD snippet'); + + (function() { + var start = _.once(QUnit.start); + + asyncTest('`lodash`', function() { + build(['-s'], function(source, filePath) { + // used by r.js build optimizer + var defineHasRegExp = /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g, + basename = path.basename(filePath, '.js'); + + ok(!!defineHasRegExp.exec(source), basename); + start(); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('template builds'); + + (function() { + var templatePath = __dirname + '/template'; + + asyncTest('`lodash template=*.jst`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'template=' + templatePath + '/*.jst'], function(source, filePath) { + var basename = path.basename(filePath, '.js'), + context = createContext(); + + var data = { + 'a': { 'people': ['moe', 'larry', 'curly'] }, + 'b': { 'epithet': 'stooge' } + }; + + context._ = _; + vm.runInContext(source, context); + var templates = context._.templates; + + equal(templates.a(data.a).replace(/[\r\n]+/g, ''), '
      • moe
      • larry
      • curly
      ', basename); + equal(templates.b(data.b), 'Hello stooge.', basename); + delete _.templates; + start(); + }); + }); + + ['', 'moduleId=underscore'].forEach(function(command) { + asyncTest('`lodash template=*.jst` exports=amd' + (command ? ' ' + command : ''), function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'template=' + templatePath + '/*.jst', 'exports=amd'].concat(command || []), function(source, filePath) { + var moduleId, + basename = path.basename(filePath, '.js'), + context = createContext(), + pass = false; + + (context.define = function(requires, factory) { + factory(_); + var templates = _.templates; + moduleId = requires + ''; + pass = 'a' in templates && 'b' in templates; + }) + .amd = {}; + + vm.runInContext(source, context); + + equal(moduleId, command ? 'underscore' : 'lodash'); + ok(pass, basename); + delete _.templates; + start(); + }); + }); + }); + + asyncTest('`lodash settings=...`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'template=' + templatePath + '/*.tpl', 'settings={interpolate:/\\{\\{([\\s\\S]+?)\\}\\}/}'], function(source, filePath) { + var basename = path.basename(filePath, '.js'), + context = createContext(); + + var data = { + 'c': { 'name': 'Mustache' } + }; + + context._ = _; + vm.runInContext(source, context); + var templates = context._.templates; + + equal(templates.c(data.c), 'Hello Mustache!', basename); + start(); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('independent builds'); + + (function() { + asyncTest('debug only', function() { + var start = _.once(QUnit.start); + build(['-d', '-s'], function(source, filePath) { + equal(path.basename(filePath, '.js'), 'lodash'); + start(); + }); + }); + + asyncTest('debug custom', function () { + var start = _.once(QUnit.start); + build(['-d', '-s', 'backbone'], function(source, filePath) { + equal(path.basename(filePath, '.js'), 'lodash.custom'); + start(); + }); + }); + + asyncTest('minified only', function() { + var start = _.once(QUnit.start); + build(['-m', '-s'], function(source, filePath) { + equal(path.basename(filePath, '.js'), 'lodash.min'); + start(); + }); + }); + + asyncTest('minified custom', function () { + var start = _.once(QUnit.start); + build(['-m', '-s', 'backbone'], function(source, filePath) { + equal(path.basename(filePath, '.js'), 'lodash.custom.min'); + start(); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('strict modifier'); + + (function() { + var object = Object.freeze({ + 'a': _.identity, + 'b': null + }); + + ['non-strict', 'strict'].forEach(function(strictMode, index) { + asyncTest(strictMode + ' should ' + (index ? 'error': 'silently fail') + ' attempting to overwrite read-only properties', function() { + var commands = ['-s', 'include=bindAll,defaults,extend'], + start = _.after(2, _.once(QUnit.start)); + + if (index) { + commands.push('strict'); + } + build(commands, function(source, filePath) { + var basename = path.basename(filePath, '.js'), + context = createContext(); + + vm.runInContext(source, context); + var lodash = context._; + + var actual = _.every([ + function() { lodash.bindAll(object); }, + function() { lodash.extend(object, { 'a': 1 }); }, + function() { lodash.defaults(object, { 'b': 2 }); } + ], function(fn) { + var pass = !index; + try { + fn(); + } catch(e) { + pass = !!index; + } + return pass; + }); + + equal(actual, true, basename); + start(); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('underscore modifier'); + + (function() { + asyncTest('modified methods should work correctly', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'underscore'], function(source, filePath) { + var last, + array = [{ 'value': 1 }, { 'value': 2 }], + basename = path.basename(filePath, '.js'), + context = createContext(); + + vm.runInContext(source, context); + var lodash = context._; + + var object = { 'fn': lodash.bind(function(foo) { return foo + this.bar; }, { 'bar': 1 }, 1) }; + equal(object.fn(), 2, '_.bind: ' + basename); + + ok(lodash.clone(array, true)[0] === array[0], '_.clone should be shallow: ' + basename); + equal(lodash.contains([1, 2, 3], 1, 2), true, '_.contains should ignore `fromIndex`: ' + basename); + equal(lodash.every([true, false, true]), false, '_.every: ' + basename); + + var actual = lodash.forEach(array, function(value) { + last = value; + return false; + }); + + equal(last.value, 2, '_.forEach should not exit early: ' + basename); + equal(actual, undefined, '_.forEach should return `undefined`: ' + basename); + + object = { 'length': 0, 'splice': Array.prototype.splice }; + equal(lodash.isEmpty(object), false, '_.isEmpty should return `false` for jQuery/MooTools DOM query collections: ' + basename); + + equal(lodash.isFinite('2'), false, '_.isFinite should return `false` for numeric string values: ' + basename); + equal(lodash.max('abc'), -Infinity, '_.max should return `-Infinity` for strings: ' + basename); + equal(lodash.min('abc'), Infinity, '_.min should return `Infinity` for strings: ' + basename); + + // avoid issues comparing objects with `deepEqual` + object = { 'a': 1, 'b': 2, 'c': 3 }; + var actual = lodash.omit(object, function(value) { return value == 3; }); + deepEqual(_.keys(actual).sort(), ['a', 'b', 'c'], '_.omit should not accept a `callback`: ' + basename); + + actual = lodash.pick(object, function(value) { return value != 3; }); + deepEqual(_.keys(actual), [], '_.pick should not accept a `callback`: ' + basename); + + equal(lodash.some([false, true, false]), true, '_.some: ' + basename); + equal(lodash.template('${a}', object), '${a}', '_.template should ignore ES6 delimiters: ' + basename); + start(); + }); + }); + + asyncTest('should not have any Lo-Dash-only methods', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'underscore'], function(source, filePath) { + var basename = path.basename(filePath, '.js'), + context = createContext(); + + vm.runInContext(source, context); + var lodash = context._; + + _.each([ + 'forIn', + 'forOwn', + 'isPlainObject', + 'lateBind', + 'merge', + 'partial' + ], function(methodName) { + equal(lodash[methodName], undefined, '_.' + methodName + ' exists: ' + basename); + }); + + start(); + }); + }); + + asyncTest('`lodash underscore include=partial`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'underscore', 'include=partial'], function(source, filePath) { + var basename = path.basename(filePath, '.js'), + context = createContext(); + + vm.runInContext(source, context); + var lodash = context._; + + equal(lodash.partial(_.identity, 2)(), 2, '_.partial: ' + basename); + start(); + }); + }); + + asyncTest('`lodash underscore plus=clone`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'underscore', 'plus=clone'], function(source, filePath) { + var array = [{ 'value': 1 }], + basename = path.basename(filePath, '.js'), + context = createContext(); + + vm.runInContext(source, context); + var lodash = context._, + clone = lodash.clone(array, true); + + deepEqual(array, clone, basename); + notEqual(array, clone, basename); + start(); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('exports command'); + + (function() { + var commands = [ + 'exports=amd', + 'exports=commonjs', + 'exports=global', + 'exports=node', + 'exports=none' + ]; + + commands.forEach(function(command, index) { + asyncTest('`lodash ' + command +'`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', command], function(source, filePath) { + var basename = path.basename(filePath, '.js'), + context = createContext(), + pass = false; + + switch(index) { + case 0: + context.define = function(fn) { + pass = true; + context._ = fn(); + }; + context.define.amd = {}; + vm.runInContext(source, context); + ok(pass, basename); + break; + + case 1: + context.exports = {}; + vm.runInContext(source, context); + ok(context._ === undefined, basename); + ok(_.isFunction(context.exports._), basename) + break; + + case 2: + vm.runInContext(source, context); + ok(_.isFunction(context._), basename); + break; + + case 3: + context.exports = {}; + context.module = { 'exports': context.exports }; + vm.runInContext(source, context); + ok(context._ === undefined, basename); + ok(_.isFunction(context.module.exports), basename); + break; + + case 4: + vm.runInContext(source, context); + ok(context._ === undefined, basename); + } + start(); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('iife command'); + + (function() { + var commands = [ + 'iife=this["lodash"]=(function(window,undefined){%output%;return lodash}(this))', + 'iife=define(function(window,undefined){return function(){%output%;return lodash}}(this));' + ]; + + commands.forEach(function(command) { + asyncTest('`lodash ' + command +'`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'exports=none', command], function(source, filePath) { + var basename = path.basename(filePath, '.js'), + context = createContext(); + + context.define = function(func) { + context.lodash = func(); + }; + + try { + vm.runInContext(source, context); + } catch(e) { + console.log(e); + } + + var lodash = context.lodash || {}; + ok(_.isString(lodash.VERSION), basename); + start(); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('output options'); + + (function() { + ['-o a.js', '--output a.js'].forEach(function(command, index) { + asyncTest('`lodash ' + command +'`', function() { + var start = _.once(QUnit.start); + + build(['-s'].concat(command.split(' ')), function(source, filePath) { + equal(path.basename(filePath, '.js'), 'a', command); + start(); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('stdout options'); + + (function() { + ['-c', '--stdout'].forEach(function(command, index) { + asyncTest('`lodash ' + command +'`', function() { + var written, + start = _.once(QUnit.start), + write = process.stdout.write; + + process.stdout.write = function(string) { + written = string; + }; + + build([command, 'exports=', 'include='], function(source) { + process.stdout.write = write; + equal(written, source); + equal(arguments.length, 1); + start(); + }); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('minify underscore'); + + (function() { + asyncTest('`node minify underscore.js`', function() { + var source = fs.readFileSync(path.join(__dirname, '..', 'vendor', 'underscore', 'underscore.js'), 'utf8'), + start = _.once(QUnit.start); + + minify(source, { + 'isSilent': true, + 'workingName': 'underscore.min', + 'onComplete': function(result) { + var context = createContext(); + + try { + vm.runInContext(result, context); + } catch(e) { + console.log(e); + } + + var underscore = context._ || {}; + ok(_.isString(underscore.VERSION)); + ok(!/Lo-Dash/.test(result) && result.match(/\n/g).length < source.match(/\n/g).length); + start(); + } + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('mobile build'); + + (function() { + asyncTest('`lodash mobile`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['-s', 'mobile'], function(source, filePath) { + var basename = path.basename(filePath, '.js'), + context = createContext(); + + try { + vm.runInContext(source, context); + } catch(e) { + console.log(e); + } + + var array = [1, 2, 3], + object1 = [{ 'a': 1 }], + object2 = [{ 'b': 2 }], + object3 = [{ 'a': 1, 'b': 2 }], + circular1 = { 'a': 1 }, + circular2 = { 'a': 1 }, + lodash = context._; + + circular1.b = circular1; + circular2.b = circular2; + + deepEqual(lodash.merge(object1, object2), object3, basename); + deepEqual(lodash.sortBy([3, 2, 1], _.identity), array, basename); + equal(lodash.isEqual(circular1, circular2), true, basename); + + var actual = lodash.clone(circular1, true); + ok(actual != circular1 && actual.b == actual, basename); + start(); + }); + }); + }()); + + /*--------------------------------------------------------------------------*/ + + QUnit.module('lodash build'); + + (function() { + var commands = [ + 'backbone', + 'csp', + 'legacy', + 'mobile', + 'strict', + 'underscore', + 'category=arrays', + 'category=chaining', + 'category=collections', + 'category=functions', + 'category=objects', + 'category=utilities', + 'exclude=union,uniq,zip', + 'include=each,filter,map', + 'include=once plus=bind,Chaining', + 'category=collections,functions', + 'underscore backbone', + 'backbone legacy category=utilities minus=first,last', + 'underscore include=debounce,throttle plus=after minus=throttle', + 'underscore mobile strict category=functions exports=amd,global plus=pick,uniq', + ] + .concat( + allMethods.map(function(methodName) { + return 'include=' + methodName; + }) + ); + + commands.forEach(function(command) { + asyncTest('`lodash ' + command +'`', function() { + var start = _.after(2, _.once(QUnit.start)); + + build(['--silent'].concat(command.split(' ')), function(source, filePath) { + var methodNames, + basename = path.basename(filePath, '.js'), + context = createContext(); + + try { + vm.runInContext(source, context); + } catch(e) { + console.log(e); + } + // add method names explicitly + if (/include/.test(command)) { + methodNames = command.match(/include=(\S*)/)[1].split(/, */); + } + // add method names required by Backbone and Underscore builds + if (/backbone/.test(command) && !methodNames) { + methodNames = backboneDependencies.slice(); + } + if (/underscore/.test(command) && !methodNames) { + methodNames = underscoreMethods.slice(); + } + // add method names explicitly by category + if (/category/.test(command)) { + // resolve method names belonging to each category (case-insensitive) + methodNames = command.match(/category=(\S*)/)[1].split(/, */).reduce(function(result, category) { + var capitalized = category[0].toUpperCase() + category.toLowerCase().slice(1); + return result.concat(getMethodsByCategory(capitalized)); + }, methodNames || []); + } + // init `methodNames` if it hasn't been inited + if (!methodNames) { + methodNames = allMethods.slice(); + } + if (/plus/.test(command)) { + methodNames = methodNames.concat(command.match(/plus=(\S*)/)[1].split(/, */)); + } + if (/minus/.test(command)) { + methodNames = _.without.apply(_, [methodNames] + .concat(expandMethodNames(command.match(/minus=(\S*)/)[1].split(/, */)))); + } + if (/exclude/.test(command)) { + methodNames = _.without.apply(_, [methodNames] + .concat(expandMethodNames(command.match(/exclude=(\S*)/)[1].split(/, */)))); + } + + // expand aliases and categories to real method names + methodNames = expandMethodNames(methodNames).reduce(function(result, methodName) { + return result.concat(methodName, getMethodsByCategory(methodName)); + }, []); + + // remove nonexistent and duplicate method names + methodNames = _.uniq(_.intersection(allMethods, expandMethodNames(methodNames))); + + var lodash = context._ || {}; + methodNames.forEach(function(methodName) { + testMethod(lodash, methodName, basename); + }); + + start(); + }); + }); + }); + }()); + +}()); diff --git a/node/node_modules/grunt/node_modules/lodash/test/test.js b/node/node_modules/grunt/node_modules/lodash/test/test.js new file mode 100644 index 000000000..fad3b7caf --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/test/test.js @@ -0,0 +1,2013 @@ +;(function(window, undefined) { + 'use strict'; + + /** Use a single load function */ + var load = typeof require == 'function' ? require : window.load; + + /** The `platform` object to check */ + var platform = + window.platform || + load('../vendor/platform.js/platform.js') || + window.platform; + + /** The unit testing framework */ + var QUnit = + window.QUnit || ( + window.setTimeout || (window.addEventListener = window.setTimeout = / /), + window.QUnit = load('../vendor/qunit/qunit/qunit' + (platform.name == 'Narwhal' ? '-1.8.0' : '') + '.js') || window.QUnit, + load('../vendor/qunit-clib/qunit-clib.js'), + (window.addEventListener || 0).test && delete window.addEventListener, + window.QUnit + ); + + /** The `lodash` function to test */ + var _ = + window._ || ( + _ = load('../lodash.js') || window._, + _._ || _ + ); + + /** Used to pass falsey values to methods */ + var falsey = [ + , + '', + 0, + false, + NaN, + null, + undefined + ]; + + /** Shortcut used to make object properties immutable */ + var freeze = Object.freeze; + + /** Used to set property descriptors */ + var setDescriptor = (function(fn) { + try { + var o = {}; + return fn(o, o, o) && fn; + } catch(e) { } + }(Object.defineProperty)); + + /** Shortcut used to convert array-like objects to arrays */ + var slice = [].slice; + + /** Used to check problem JScript properties (a.k.a. the [[DontEnum]] bug) */ + var shadowed = { + 'constructor': 1, + 'hasOwnProperty': 2, + 'isPrototypeOf': 3, + 'propertyIsEnumerable': 4, + 'toLocaleString': 5, + 'toString': 6, + 'valueOf': 7 + }; + + /** Used to check problem JScript properties too */ + var shadowedKeys = [ + 'constructor', + 'hasOwnProperty', + 'isPrototypeOf', + 'propertyIsEnumerable', + 'toLocaleString', + 'toString', + 'valueOf' + ]; + + /*--------------------------------------------------------------------------*/ + + /** + * Skips a given number of tests with a passing result. + * + * @private + * @param {Number} [count=1] The number of tests to skip. + */ + function skipTest(count) { + count || (count = 1); + while (count--) { + ok(true, 'test skipped'); + } + } + + /*--------------------------------------------------------------------------*/ + + // add object from iframe + (function() { + if (!window.document) { + return; + } + var body = document.body, + iframe = document.createElement('iframe'); + + iframe.frameBorder = iframe.height = iframe.width = 0; + body.appendChild(iframe); + var idoc = (idoc = iframe.contentDocument || iframe.contentWindow).document || idoc; + idoc.write(" +``` + +Optionally, expose Java’s nanosecond timer by adding the `nano` applet to the ``: + +```html + +``` + +Or enable Chrome’s microsecond timer by using the [command line switch](http://peter.sh/experiments/chromium-command-line-switches/#enable-benchmarking): + + --enable-benchmarking + +Via [npm](http://npmjs.org/): + +```bash +npm install benchmark +``` + +In [Node.js](http://nodejs.org/) and [RingoJS v0.8.0+](http://ringojs.org/): + +```js +var Benchmark = require('benchmark'); +``` + +Optionally, use the [microtime module](https://github.com/wadey/node-microtime) by Wade Simmons: + +```bash +npm install microtime +``` + +In [RingoJS v0.7.0-](http://ringojs.org/): + +```js +var Benchmark = require('benchmark').Benchmark; +``` + +In [Rhino](http://www.mozilla.org/rhino/): + +```js +load('benchmark.js'); +``` + +In an AMD loader like [RequireJS](http://requirejs.org/): + +```js +require({ + 'paths': { + 'benchmark': 'path/to/benchmark' + } +}, +['benchmark'], function(Benchmark) { + console.log(Benchmark.version); +}); + +// or with platform.js +// https://github.com/bestiejs/platform.js +require({ + 'paths': { + 'benchmark': 'path/to/benchmark', + 'platform': 'path/to/platform' + } +}, +['benchmark', 'platform'], function(Benchmark, platform) { + Benchmark.platform = platform; + console.log(Benchmark.platform.name); +}); +``` + +Usage example: + +```js +var suite = new Benchmark.Suite; + +// add tests +suite.add('RegExp#test', function() { + /o/.test('Hello World!'); +}) +.add('String#indexOf', function() { + 'Hello World!'.indexOf('o') > -1; +}) +// add listeners +.on('cycle', function(event) { + console.log(String(event.target)); +}) +.on('complete', function() { + console.log('Fastest is ' + this.filter('fastest').pluck('name')); +}) +// run async +.run({ 'async': true }); + +// logs: +// > RegExp#test x 4,161,532 +-0.99% (59 cycles) +// > String#indexOf x 6,139,623 +-1.00% (131 cycles) +// > Fastest is String#indexOf +``` + +## BestieJS + +Benchmark.js is part of the BestieJS *"Best in Class"* module collection. This means we promote solid browser/environment support, ES5 precedents, unit testing, and plenty of documentation. + +## Authors + +* [Mathias Bynens](http://mathiasbynens.be/) + [![twitter/mathias](http://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") +* [John-David Dalton](http://allyoucanleet.com/) + [![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") + +## Contributors + +* [Kit Cambridge](http://kitcambridge.github.com/) + [![twitter/kitcambridge](http://gravatar.com/avatar/6662a1d02f351b5ef2f8b4d815804661?s=70)](https://twitter.com/kitcambridge "Follow @kitcambridge on Twitter") diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/benchmark.js/benchmark.js b/node/node_modules/grunt/node_modules/lodash/vendor/benchmark.js/benchmark.js new file mode 100644 index 000000000..5b63f8baa --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/benchmark.js/benchmark.js @@ -0,0 +1,3954 @@ +/*! + * Benchmark.js v1.0.0 + * Copyright 2010-2012 Mathias Bynens + * Based on JSLitmus.js, copyright Robert Kieffer + * Modified by John-David Dalton + * Available under MIT license + */ +;(function(window, undefined) { + 'use strict'; + + /** Used to assign each benchmark an incrimented id */ + var counter = 0; + + /** Detect DOM document object */ + var doc = isHostType(window, 'document') && document; + + /** Detect free variable `define` */ + var freeDefine = typeof define == 'function' && + typeof define.amd == 'object' && define.amd && define; + + /** Detect free variable `exports` */ + var freeExports = typeof exports == 'object' && exports && + (typeof global == 'object' && global && global == global.global && (window = global), exports); + + /** Detect free variable `require` */ + var freeRequire = typeof require == 'function' && require; + + /** Used to crawl all properties regardless of enumerability */ + var getAllKeys = Object.getOwnPropertyNames; + + /** Used to get property descriptors */ + var getDescriptor = Object.getOwnPropertyDescriptor; + + /** Used in case an object doesn't have its own method */ + var hasOwnProperty = {}.hasOwnProperty; + + /** Used to check if an object is extensible */ + var isExtensible = Object.isExtensible || function() { return true; }; + + /** Used to access Wade Simmons' Node microtime module */ + var microtimeObject = req('microtime'); + + /** Used to access the browser's high resolution timer */ + var perfObject = isHostType(window, 'performance') && performance; + + /** Used to call the browser's high resolution timer */ + var perfName = perfObject && ( + perfObject.now && 'now' || + perfObject.webkitNow && 'webkitNow' + ); + + /** Used to access Node's high resolution timer */ + var processObject = isHostType(window, 'process') && process; + + /** Used to check if an own property is enumerable */ + var propertyIsEnumerable = {}.propertyIsEnumerable; + + /** Used to set property descriptors */ + var setDescriptor = Object.defineProperty; + + /** Used to resolve a value's internal [[Class]] */ + var toString = {}.toString; + + /** Used to prevent a `removeChild` memory leak in IE < 9 */ + var trash = doc && doc.createElement('div'); + + /** Used to integrity check compiled tests */ + var uid = 'uid' + (+new Date); + + /** Used to avoid infinite recursion when methods call each other */ + var calledBy = {}; + + /** Used to avoid hz of Infinity */ + var divisors = { + '1': 4096, + '2': 512, + '3': 64, + '4': 8, + '5': 0 + }; + + /** + * T-Distribution two-tailed critical values for 95% confidence + * http://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm + */ + var tTable = { + '1': 12.706,'2': 4.303, '3': 3.182, '4': 2.776, '5': 2.571, '6': 2.447, + '7': 2.365, '8': 2.306, '9': 2.262, '10': 2.228, '11': 2.201, '12': 2.179, + '13': 2.16, '14': 2.145, '15': 2.131, '16': 2.12, '17': 2.11, '18': 2.101, + '19': 2.093, '20': 2.086, '21': 2.08, '22': 2.074, '23': 2.069, '24': 2.064, + '25': 2.06, '26': 2.056, '27': 2.052, '28': 2.048, '29': 2.045, '30': 2.042, + 'infinity': 1.96 + }; + + /** + * Critical Mann-Whitney U-values for 95% confidence + * http://www.saburchill.com/IBbiology/stats/003.html + */ + var uTable = { + '5': [0, 1, 2], + '6': [1, 2, 3, 5], + '7': [1, 3, 5, 6, 8], + '8': [2, 4, 6, 8, 10, 13], + '9': [2, 4, 7, 10, 12, 15, 17], + '10': [3, 5, 8, 11, 14, 17, 20, 23], + '11': [3, 6, 9, 13, 16, 19, 23, 26, 30], + '12': [4, 7, 11, 14, 18, 22, 26, 29, 33, 37], + '13': [4, 8, 12, 16, 20, 24, 28, 33, 37, 41, 45], + '14': [5, 9, 13, 17, 22, 26, 31, 36, 40, 45, 50, 55], + '15': [5, 10, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59, 64], + '16': [6, 11, 15, 21, 26, 31, 37, 42, 47, 53, 59, 64, 70, 75], + '17': [6, 11, 17, 22, 28, 34, 39, 45, 51, 57, 63, 67, 75, 81, 87], + '18': [7, 12, 18, 24, 30, 36, 42, 48, 55, 61, 67, 74, 80, 86, 93, 99], + '19': [7, 13, 19, 25, 32, 38, 45, 52, 58, 65, 72, 78, 85, 92, 99, 106, 113], + '20': [8, 14, 20, 27, 34, 41, 48, 55, 62, 69, 76, 83, 90, 98, 105, 112, 119, 127], + '21': [8, 15, 22, 29, 36, 43, 50, 58, 65, 73, 80, 88, 96, 103, 111, 119, 126, 134, 142], + '22': [9, 16, 23, 30, 38, 45, 53, 61, 69, 77, 85, 93, 101, 109, 117, 125, 133, 141, 150, 158], + '23': [9, 17, 24, 32, 40, 48, 56, 64, 73, 81, 89, 98, 106, 115, 123, 132, 140, 149, 157, 166, 175], + '24': [10, 17, 25, 33, 42, 50, 59, 67, 76, 85, 94, 102, 111, 120, 129, 138, 147, 156, 165, 174, 183, 192], + '25': [10, 18, 27, 35, 44, 53, 62, 71, 80, 89, 98, 107, 117, 126, 135, 145, 154, 163, 173, 182, 192, 201, 211], + '26': [11, 19, 28, 37, 46, 55, 64, 74, 83, 93, 102, 112, 122, 132, 141, 151, 161, 171, 181, 191, 200, 210, 220, 230], + '27': [11, 20, 29, 38, 48, 57, 67, 77, 87, 97, 107, 118, 125, 138, 147, 158, 168, 178, 188, 199, 209, 219, 230, 240, 250], + '28': [12, 21, 30, 40, 50, 60, 70, 80, 90, 101, 111, 122, 132, 143, 154, 164, 175, 186, 196, 207, 218, 228, 239, 250, 261, 272], + '29': [13, 22, 32, 42, 52, 62, 73, 83, 94, 105, 116, 127, 138, 149, 160, 171, 182, 193, 204, 215, 226, 238, 249, 260, 271, 282, 294], + '30': [13, 23, 33, 43, 54, 65, 76, 87, 98, 109, 120, 131, 143, 154, 166, 177, 189, 200, 212, 223, 235, 247, 258, 270, 282, 293, 305, 317] + }; + + /** + * An object used to flag environments/features. + * + * @static + * @memberOf Benchmark + * @type Object + */ + var support = {}; + + (function() { + + /** + * Detect Adobe AIR. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.air = isClassOf(window.runtime, 'ScriptBridgingProxyObject'); + + /** + * Detect if `arguments` objects have the correct internal [[Class]] value. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.argumentsClass = isClassOf(arguments, 'Arguments'); + + /** + * Detect if in a browser environment. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.browser = doc && isHostType(window, 'navigator'); + + /** + * Detect if strings support accessing characters by index. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.charByIndex = + // IE 8 supports indexes on string literals but not string objects + ('x'[0] + Object('x')[0]) == 'xx'; + + /** + * Detect if strings have indexes as own properties. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.charByOwnIndex = + // Narwhal, Rhino, RingoJS, IE 8, and Opera < 10.52 support indexes on + // strings but don't detect them as own properties + support.charByIndex && hasKey('x', '0'); + + /** + * Detect if Java is enabled/exposed. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.java = isClassOf(window.java, 'JavaPackage'); + + /** + * Detect if the Timers API exists. + * + * @memberOf Benchmark.support + * @type Boolean + */ + support.timeout = isHostType(window, 'setTimeout') && isHostType(window, 'clearTimeout'); + + /** + * Detect if functions support decompilation. + * + * @name decompilation + * @memberOf Benchmark.support + * @type Boolean + */ + try { + // Safari 2.x removes commas in object literals + // from Function#toString results + // http://webk.it/11609 + // Firefox 3.6 and Opera 9.25 strip grouping + // parentheses from Function#toString results + // http://bugzil.la/559438 + support.decompilation = Function( + 'return (' + (function(x) { return { 'x': '' + (1 + x) + '', 'y': 0 }; }) + ')' + )()(0).x === '1'; + } catch(e) { + support.decompilation = false; + } + + /** + * Detect ES5+ property descriptor API. + * + * @name descriptors + * @memberOf Benchmark.support + * @type Boolean + */ + try { + var o = {}; + support.descriptors = (setDescriptor(o, o, o), 'value' in getDescriptor(o, o)); + } catch(e) { + support.descriptors = false; + } + + /** + * Detect ES5+ Object.getOwnPropertyNames(). + * + * @name getAllKeys + * @memberOf Benchmark.support + * @type Boolean + */ + try { + support.getAllKeys = /\bvalueOf\b/.test(getAllKeys(Object.prototype)); + } catch(e) { + support.getAllKeys = false; + } + + /** + * Detect if own properties are iterated before inherited properties (all but IE < 9). + * + * @name iteratesOwnLast + * @memberOf Benchmark.support + * @type Boolean + */ + support.iteratesOwnFirst = (function() { + var props = []; + function ctor() { this.x = 1; } + ctor.prototype = { 'y': 1 }; + for (var prop in new ctor) { props.push(prop); } + return props[0] == 'x'; + }()); + + /** + * Detect if a node's [[Class]] is resolvable (all but IE < 9) + * and that the JS engine errors when attempting to coerce an object to a + * string without a `toString` property value of `typeof` "function". + * + * @name nodeClass + * @memberOf Benchmark.support + * @type Boolean + */ + try { + support.nodeClass = ({ 'toString': 0 } + '', toString.call(doc || 0) != '[object Object]'); + } catch(e) { + support.nodeClass = true; + } + }()); + + /** + * Timer object used by `clock()` and `Deferred#resolve`. + * + * @private + * @type Object + */ + var timer = { + + /** + * The timer namespace object or constructor. + * + * @private + * @memberOf timer + * @type Function|Object + */ + 'ns': Date, + + /** + * Starts the deferred timer. + * + * @private + * @memberOf timer + * @param {Object} deferred The deferred instance. + */ + 'start': null, // lazy defined in `clock()` + + /** + * Stops the deferred timer. + * + * @private + * @memberOf timer + * @param {Object} deferred The deferred instance. + */ + 'stop': null // lazy defined in `clock()` + }; + + /** Shortcut for inverse results */ + var noArgumentsClass = !support.argumentsClass, + noCharByIndex = !support.charByIndex, + noCharByOwnIndex = !support.charByOwnIndex; + + /** Math shortcuts */ + var abs = Math.abs, + floor = Math.floor, + log = Math.log, + max = Math.max, + min = Math.min, + pow = Math.pow, + sqrt = Math.sqrt; + + /*--------------------------------------------------------------------------*/ + + /** + * The Benchmark constructor. + * + * @constructor + * @param {String} name A name to identify the benchmark. + * @param {Function|String} fn The test to benchmark. + * @param {Object} [options={}] Options object. + * @example + * + * // basic usage (the `new` operator is optional) + * var bench = new Benchmark(fn); + * + * // or using a name first + * var bench = new Benchmark('foo', fn); + * + * // or with options + * var bench = new Benchmark('foo', fn, { + * + * // displayed by Benchmark#toString if `name` is not available + * 'id': 'xyz', + * + * // called when the benchmark starts running + * 'onStart': onStart, + * + * // called after each run cycle + * 'onCycle': onCycle, + * + * // called when aborted + * 'onAbort': onAbort, + * + * // called when a test errors + * 'onError': onError, + * + * // called when reset + * 'onReset': onReset, + * + * // called when the benchmark completes running + * 'onComplete': onComplete, + * + * // compiled/called before the test loop + * 'setup': setup, + * + * // compiled/called after the test loop + * 'teardown': teardown + * }); + * + * // or name and options + * var bench = new Benchmark('foo', { + * + * // a flag to indicate the benchmark is deferred + * 'defer': true, + * + * // benchmark test function + * 'fn': function(deferred) { + * // call resolve() when the deferred test is finished + * deferred.resolve(); + * } + * }); + * + * // or options only + * var bench = new Benchmark({ + * + * // benchmark name + * 'name': 'foo', + * + * // benchmark test as a string + * 'fn': '[1,2,3,4].sort()' + * }); + * + * // a test's `this` binding is set to the benchmark instance + * var bench = new Benchmark('foo', function() { + * 'My name is '.concat(this.name); // My name is foo + * }); + */ + function Benchmark(name, fn, options) { + var me = this; + + // allow instance creation without the `new` operator + if (me == null || me.constructor != Benchmark) { + return new Benchmark(name, fn, options); + } + // juggle arguments + if (isClassOf(name, 'Object')) { + // 1 argument (options) + options = name; + } + else if (isClassOf(name, 'Function')) { + // 2 arguments (fn, options) + options = fn; + fn = name; + } + else if (isClassOf(fn, 'Object')) { + // 2 arguments (name, options) + options = fn; + fn = null; + me.name = name; + } + else { + // 3 arguments (name, fn [, options]) + me.name = name; + } + setOptions(me, options); + me.id || (me.id = ++counter); + me.fn == null && (me.fn = fn); + me.stats = deepClone(me.stats); + me.times = deepClone(me.times); + } + + /** + * The Deferred constructor. + * + * @constructor + * @memberOf Benchmark + * @param {Object} clone The cloned benchmark instance. + */ + function Deferred(clone) { + var me = this; + if (me == null || me.constructor != Deferred) { + return new Deferred(clone); + } + me.benchmark = clone; + clock(me); + } + + /** + * The Event constructor. + * + * @constructor + * @memberOf Benchmark + * @param {String|Object} type The event type. + */ + function Event(type) { + var me = this; + return (me == null || me.constructor != Event) + ? new Event(type) + : (type instanceof Event) + ? type + : extend(me, { 'timeStamp': +new Date }, typeof type == 'string' ? { 'type': type } : type); + } + + /** + * The Suite constructor. + * + * @constructor + * @memberOf Benchmark + * @param {String} name A name to identify the suite. + * @param {Object} [options={}] Options object. + * @example + * + * // basic usage (the `new` operator is optional) + * var suite = new Benchmark.Suite; + * + * // or using a name first + * var suite = new Benchmark.Suite('foo'); + * + * // or with options + * var suite = new Benchmark.Suite('foo', { + * + * // called when the suite starts running + * 'onStart': onStart, + * + * // called between running benchmarks + * 'onCycle': onCycle, + * + * // called when aborted + * 'onAbort': onAbort, + * + * // called when a test errors + * 'onError': onError, + * + * // called when reset + * 'onReset': onReset, + * + * // called when the suite completes running + * 'onComplete': onComplete + * }); + */ + function Suite(name, options) { + var me = this; + + // allow instance creation without the `new` operator + if (me == null || me.constructor != Suite) { + return new Suite(name, options); + } + // juggle arguments + if (isClassOf(name, 'Object')) { + // 1 argument (options) + options = name; + } else { + // 2 arguments (name [, options]) + me.name = name; + } + setOptions(me, options); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Note: Some array methods have been implemented in plain JavaScript to avoid + * bugs in IE, Opera, Rhino, and Mobile Safari. + * + * IE compatibility mode and IE < 9 have buggy Array `shift()` and `splice()` + * functions that fail to remove the last element, `object[0]`, of + * array-like-objects even though the `length` property is set to `0`. + * The `shift()` method is buggy in IE 8 compatibility mode, while `splice()` + * is buggy regardless of mode in IE < 9 and buggy in compatibility mode in IE 9. + * + * In Opera < 9.50 and some older/beta Mobile Safari versions using `unshift()` + * generically to augment the `arguments` object will pave the value at index 0 + * without incrimenting the other values's indexes. + * https://github.com/documentcloud/underscore/issues/9 + * + * Rhino and environments it powers, like Narwhal and RingoJS, may have + * buggy Array `concat()`, `reverse()`, `shift()`, `slice()`, `splice()` and + * `unshift()` functions that make sparse arrays non-sparse by assigning the + * undefined indexes a value of undefined. + * https://github.com/mozilla/rhino/commit/702abfed3f8ca043b2636efd31c14ba7552603dd + */ + + /** + * Creates an array containing the elements of the host array followed by the + * elements of each argument in order. + * + * @memberOf Benchmark.Suite + * @returns {Array} The new array. + */ + function concat() { + var value, + j = -1, + length = arguments.length, + result = slice.call(this), + index = result.length; + + while (++j < length) { + value = arguments[j]; + if (isClassOf(value, 'Array')) { + for (var k = 0, l = value.length; k < l; k++, index++) { + if (k in value) { + result[index] = value[k]; + } + } + } else { + result[index++] = value; + } + } + return result; + } + + /** + * Utility function used by `shift()`, `splice()`, and `unshift()`. + * + * @private + * @param {Number} start The index to start inserting elements. + * @param {Number} deleteCount The number of elements to delete from the insert point. + * @param {Array} elements The elements to insert. + * @returns {Array} An array of deleted elements. + */ + function insert(start, deleteCount, elements) { + // `result` should have its length set to the `deleteCount` + // see https://bugs.ecmascript.org/show_bug.cgi?id=332 + var deleteEnd = start + deleteCount, + elementCount = elements ? elements.length : 0, + index = start - 1, + length = start + elementCount, + object = this, + result = Array(deleteCount), + tail = slice.call(object, deleteEnd); + + // delete elements from the array + while (++index < deleteEnd) { + if (index in object) { + result[index - start] = object[index]; + delete object[index]; + } + } + // insert elements + index = start - 1; + while (++index < length) { + object[index] = elements[index - start]; + } + // append tail elements + start = index--; + length = max(0, (object.length >>> 0) - deleteCount + elementCount); + while (++index < length) { + if ((index - start) in tail) { + object[index] = tail[index - start]; + } else if (index in object) { + delete object[index]; + } + } + // delete excess elements + deleteCount = deleteCount > elementCount ? deleteCount - elementCount : 0; + while (deleteCount--) { + index = length + deleteCount; + if (index in object) { + delete object[index]; + } + } + object.length = length; + return result; + } + + /** + * Rearrange the host array's elements in reverse order. + * + * @memberOf Benchmark.Suite + * @returns {Array} The reversed array. + */ + function reverse() { + var upperIndex, + value, + index = -1, + object = Object(this), + length = object.length >>> 0, + middle = floor(length / 2); + + if (length > 1) { + while (++index < middle) { + upperIndex = length - index - 1; + value = upperIndex in object ? object[upperIndex] : uid; + if (index in object) { + object[upperIndex] = object[index]; + } else { + delete object[upperIndex]; + } + if (value != uid) { + object[index] = value; + } else { + delete object[index]; + } + } + } + return object; + } + + /** + * Removes the first element of the host array and returns it. + * + * @memberOf Benchmark.Suite + * @returns {Mixed} The first element of the array. + */ + function shift() { + return insert.call(this, 0, 1)[0]; + } + + /** + * Creates an array of the host array's elements from the start index up to, + * but not including, the end index. + * + * @memberOf Benchmark.Suite + * @param {Number} start The starting index. + * @param {Number} end The end index. + * @returns {Array} The new array. + */ + function slice(start, end) { + var index = -1, + object = Object(this), + length = object.length >>> 0, + result = []; + + start = toInteger(start); + start = start < 0 ? max(length + start, 0) : min(start, length); + start--; + end = end == null ? length : toInteger(end); + end = end < 0 ? max(length + end, 0) : min(end, length); + + while ((++index, ++start) < end) { + if (start in object) { + result[index] = object[start]; + } + } + return result; + } + + /** + * Allows removing a range of elements and/or inserting elements into the + * host array. + * + * @memberOf Benchmark.Suite + * @param {Number} start The start index. + * @param {Number} deleteCount The number of elements to delete. + * @param {Mixed} [val1, val2, ...] values to insert at the `start` index. + * @returns {Array} An array of removed elements. + */ + function splice(start, deleteCount) { + var object = Object(this), + length = object.length >>> 0; + + start = toInteger(start); + start = start < 0 ? max(length + start, 0) : min(start, length); + + // support the de-facto SpiderMonkey extension + // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice#Parameters + // https://bugs.ecmascript.org/show_bug.cgi?id=429 + deleteCount = arguments.length == 1 + ? length - start + : min(max(toInteger(deleteCount), 0), length - start); + + return insert.call(object, start, deleteCount, slice.call(arguments, 2)); + } + + /** + * Converts the specified `value` to an integer. + * + * @private + * @param {Mixed} value The value to convert. + * @returns {Number} The resulting integer. + */ + function toInteger(value) { + value = +value; + return value === 0 || !isFinite(value) ? value || 0 : value - (value % 1); + } + + /** + * Appends arguments to the host array. + * + * @memberOf Benchmark.Suite + * @returns {Number} The new length. + */ + function unshift() { + var object = Object(this); + insert.call(object, 0, 0, arguments); + return object.length; + } + + /*--------------------------------------------------------------------------*/ + + /** + * A generic `Function#bind` like method. + * + * @private + * @param {Function} fn The function to be bound to `thisArg`. + * @param {Mixed} thisArg The `this` binding for the given function. + * @returns {Function} The bound function. + */ + function bind(fn, thisArg) { + return function() { fn.apply(thisArg, arguments); }; + } + + /** + * Creates a function from the given arguments string and body. + * + * @private + * @param {String} args The comma separated function arguments. + * @param {String} body The function body. + * @returns {Function} The new function. + */ + function createFunction() { + // lazy define + createFunction = function(args, body) { + var result, + anchor = freeDefine ? define.amd : Benchmark, + prop = uid + 'createFunction'; + + runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=function(' + args + '){' + body + '}'); + result = anchor[prop]; + delete anchor[prop]; + return result; + }; + // fix JaegerMonkey bug + // http://bugzil.la/639720 + createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || noop)() == uid ? createFunction : Function; + return createFunction.apply(null, arguments); + } + + /** + * Delay the execution of a function based on the benchmark's `delay` property. + * + * @private + * @param {Object} bench The benchmark instance. + * @param {Object} fn The function to execute. + */ + function delay(bench, fn) { + bench._timerId = setTimeout(fn, bench.delay * 1e3); + } + + /** + * Destroys the given element. + * + * @private + * @param {Element} element The element to destroy. + */ + function destroyElement(element) { + trash.appendChild(element); + trash.innerHTML = ''; + } + + /** + * Iterates over an object's properties, executing the `callback` for each. + * Callbacks may terminate the loop by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} callback The function executed per own property. + * @param {Object} options The options object. + * @returns {Object} Returns the object iterated over. + */ + function forProps() { + var forShadowed, + skipSeen, + forArgs = true, + shadowed = ['constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf']; + + (function(enumFlag, key) { + // must use a non-native constructor to catch the Safari 2 issue + function Klass() { this.valueOf = 0; }; + Klass.prototype.valueOf = 0; + // check various for-in bugs + for (key in new Klass) { + enumFlag += key == 'valueOf' ? 1 : 0; + } + // check if `arguments` objects have non-enumerable indexes + for (key in arguments) { + key == '0' && (forArgs = false); + } + // Safari 2 iterates over shadowed properties twice + // http://replay.waybackmachine.org/20090428222941/http://tobielangel.com/2007/1/29/for-in-loop-broken-in-safari/ + skipSeen = enumFlag == 2; + // IE < 9 incorrectly makes an object's properties non-enumerable if they have + // the same name as other non-enumerable properties in its prototype chain. + forShadowed = !enumFlag; + }(0)); + + // lazy define + forProps = function(object, callback, options) { + options || (options = {}); + + var result = object; + object = Object(object); + + var ctor, + key, + keys, + skipCtor, + done = !result, + which = options.which, + allFlag = which == 'all', + index = -1, + iteratee = object, + length = object.length, + ownFlag = allFlag || which == 'own', + seen = {}, + skipProto = isClassOf(object, 'Function'), + thisArg = options.bind; + + if (thisArg !== undefined) { + callback = bind(callback, thisArg); + } + // iterate all properties + if (allFlag && support.getAllKeys) { + for (index = 0, keys = getAllKeys(object), length = keys.length; index < length; index++) { + key = keys[index]; + if (callback(object[key], key, object) === false) { + break; + } + } + } + // else iterate only enumerable properties + else { + for (key in object) { + // Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 + // (if the prototype or a property on the prototype has been set) + // incorrectly set a function's `prototype` property [[Enumerable]] value + // to `true`. Because of this we standardize on skipping the `prototype` + // property of functions regardless of their [[Enumerable]] value. + if ((done = + !(skipProto && key == 'prototype') && + !(skipSeen && (hasKey(seen, key) || !(seen[key] = true))) && + (!ownFlag || ownFlag && hasKey(object, key)) && + callback(object[key], key, object) === false)) { + break; + } + } + // in IE < 9 strings don't support accessing characters by index + if (!done && (forArgs && isArguments(object) || + ((noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String') && + (iteratee = noCharByIndex ? object.split('') : object)))) { + while (++index < length) { + if ((done = + callback(iteratee[index], String(index), object) === false)) { + break; + } + } + } + if (!done && forShadowed) { + // Because IE < 9 can't set the `[[Enumerable]]` attribute of an existing + // property and the `constructor` property of a prototype defaults to + // non-enumerable, we manually skip the `constructor` property when we + // think we are iterating over a `prototype` object. + ctor = object.constructor; + skipCtor = ctor && ctor.prototype && ctor.prototype.constructor === ctor; + for (index = 0; index < 7; index++) { + key = shadowed[index]; + if (!(skipCtor && key == 'constructor') && + hasKey(object, key) && + callback(object[key], key, object) === false) { + break; + } + } + } + } + return result; + }; + return forProps.apply(null, arguments); + } + + /** + * Gets the name of the first argument from a function's source. + * + * @private + * @param {Function} fn The function. + * @returns {String} The argument name. + */ + function getFirstArgument(fn) { + return (!hasKey(fn, 'toString') && + (/^[\s(]*function[^(]*\(([^\s,)]+)/.exec(fn) || 0)[1]) || ''; + } + + /** + * Computes the geometric mean (log-average) of a sample. + * See http://en.wikipedia.org/wiki/Geometric_mean#Relationship_with_arithmetic_mean_of_logarithms. + * + * @private + * @param {Array} sample The sample. + * @returns {Number} The geometric mean. + */ + function getGeometricMean(sample) { + return pow(Math.E, reduce(sample, function(sum, x) { + return sum + log(x); + }) / sample.length) || 0; + } + + /** + * Computes the arithmetic mean of a sample. + * + * @private + * @param {Array} sample The sample. + * @returns {Number} The mean. + */ + function getMean(sample) { + return (reduce(sample, function(sum, x) { + return sum + x; + }) / sample.length) || 0; + } + + /** + * Gets the source code of a function. + * + * @private + * @param {Function} fn The function. + * @param {String} altSource A string used when a function's source code is unretrievable. + * @returns {String} The function's source code. + */ + function getSource(fn, altSource) { + var result = altSource; + if (isStringable(fn)) { + result = String(fn); + } else if (support.decompilation) { + // escape the `{` for Firefox 1 + result = (/^[^{]+\{([\s\S]*)}\s*$/.exec(fn) || 0)[1]; + } + // trim string + result = (result || '').replace(/^\s+|\s+$/g, ''); + + // detect strings containing only the "use strict" directive + return /^(?:\/\*+[\w|\W]*?\*\/|\/\/.*?[\n\r\u2028\u2029]|\s)*(["'])use strict\1;?$/.test(result) + ? '' + : result; + } + + /** + * Checks if a value is an `arguments` object. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the value is an `arguments` object, else `false`. + */ + function isArguments() { + // lazy define + isArguments = function(value) { + return toString.call(value) == '[object Arguments]'; + }; + if (noArgumentsClass) { + isArguments = function(value) { + return hasKey(value, 'callee') && + !(propertyIsEnumerable && propertyIsEnumerable.call(value, 'callee')); + }; + } + return isArguments(arguments[0]); + } + + /** + * Checks if an object is of the specified class. + * + * @private + * @param {Mixed} value The value to check. + * @param {String} name The name of the class. + * @returns {Boolean} Returns `true` if the value is of the specified class, else `false`. + */ + function isClassOf(value, name) { + return value != null && toString.call(value) == '[object ' + name + ']'; + } + + /** + * Host objects can return type values that are different from their actual + * data type. The objects we are concerned with usually return non-primitive + * types of object, function, or unknown. + * + * @private + * @param {Mixed} object The owner of the property. + * @param {String} property The property to check. + * @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`. + */ + function isHostType(object, property) { + var type = object != null ? typeof object[property] : 'number'; + return !/^(?:boolean|number|string|undefined)$/.test(type) && + (type == 'object' ? !!object[property] : true); + } + + /** + * Checks if a given `value` is an object created by the `Object` constructor + * assuming objects created by the `Object` constructor have no inherited + * enumerable properties and that there are no `Object.prototype` extensions. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the `value` is a plain `Object` object, else `false`. + */ + function isPlainObject(value) { + // avoid non-objects and false positives for `arguments` objects in IE < 9 + var result = false; + if (!(value && typeof value == 'object') || isArguments(value)) { + return result; + } + // IE < 9 presents DOM nodes as `Object` objects except they have `toString` + // methods that are `typeof` "string" and still can coerce nodes to strings. + // Also check that the constructor is `Object` (i.e. `Object instanceof Object`) + var ctor = value.constructor; + if ((support.nodeClass || !(typeof value.toString != 'function' && typeof (value + '') == 'string')) && + (!isClassOf(ctor, 'Function') || ctor instanceof ctor)) { + // In most environments an object's own properties are iterated before + // its inherited properties. If the last iterated property is an object's + // own property then there are no inherited enumerable properties. + if (support.iteratesOwnFirst) { + forProps(value, function(subValue, subKey) { + result = subKey; + }); + return result === false || hasKey(value, result); + } + // IE < 9 iterates inherited properties before own properties. If the first + // iterated property is an object's own property then there are no inherited + // enumerable properties. + forProps(value, function(subValue, subKey) { + result = !hasKey(value, subKey); + return false; + }); + return result === false; + } + return result; + } + + /** + * Checks if a value can be safely coerced to a string. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if the value can be coerced, else `false`. + */ + function isStringable(value) { + return hasKey(value, 'toString') || isClassOf(value, 'String'); + } + + /** + * Wraps a function and passes `this` to the original function as the + * first argument. + * + * @private + * @param {Function} fn The function to be wrapped. + * @returns {Function} The new function. + */ + function methodize(fn) { + return function() { + var args = [this]; + args.push.apply(args, arguments); + return fn.apply(null, args); + }; + } + + /** + * A no-operation function. + * + * @private + */ + function noop() { + // no operation performed + } + + /** + * A wrapper around require() to suppress `module missing` errors. + * + * @private + * @param {String} id The module id. + * @returns {Mixed} The exported module or `null`. + */ + function req(id) { + try { + var result = freeExports && freeRequire(id); + } catch(e) { } + return result || null; + } + + /** + * Runs a snippet of JavaScript via script injection. + * + * @private + * @param {String} code The code to run. + */ + function runScript(code) { + var anchor = freeDefine ? define.amd : Benchmark, + script = doc.createElement('script'), + sibling = doc.getElementsByTagName('script')[0], + parent = sibling.parentNode, + prop = uid + 'runScript', + prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();'; + + // Firefox 2.0.0.2 cannot use script injection as intended because it executes + // asynchronously, but that's OK because script injection is only used to avoid + // the previously commented JaegerMonkey bug. + try { + // remove the inserted script *before* running the code to avoid differences + // in the expected script element count/order of the document. + script.appendChild(doc.createTextNode(prefix + code)); + anchor[prop] = function() { destroyElement(script); }; + } catch(e) { + parent = parent.cloneNode(false); + sibling = null; + script.text = code; + } + parent.insertBefore(script, sibling); + delete anchor[prop]; + } + + /** + * A helper function for setting options/event handlers. + * + * @private + * @param {Object} bench The benchmark instance. + * @param {Object} [options={}] Options object. + */ + function setOptions(bench, options) { + options = extend({}, bench.constructor.options, options); + bench.options = forOwn(options, function(value, key) { + if (value != null) { + // add event listeners + if (/^on[A-Z]/.test(key)) { + forEach(key.split(' '), function(key) { + bench.on(key.slice(2).toLowerCase(), value); + }); + } else if (!hasKey(bench, key)) { + bench[key] = deepClone(value); + } + } + }); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Handles cycling/completing the deferred benchmark. + * + * @memberOf Benchmark.Deferred + */ + function resolve() { + var me = this, + clone = me.benchmark, + bench = clone._original; + + if (bench.aborted) { + // cycle() -> clone cycle/complete event -> compute()'s invoked bench.run() cycle/complete + me.teardown(); + clone.running = false; + cycle(me); + } + else if (++me.cycles < clone.count) { + // continue the test loop + if (support.timeout) { + // use setTimeout to avoid a call stack overflow if called recursively + setTimeout(function() { clone.compiled.call(me, timer); }, 0); + } else { + clone.compiled.call(me, timer); + } + } + else { + timer.stop(me); + me.teardown(); + delay(clone, function() { cycle(me); }); + } + } + + /*--------------------------------------------------------------------------*/ + + /** + * A deep clone utility. + * + * @static + * @memberOf Benchmark + * @param {Mixed} value The value to clone. + * @returns {Mixed} The cloned value. + */ + function deepClone(value) { + var accessor, + circular, + clone, + ctor, + descriptor, + extensible, + key, + length, + markerKey, + parent, + result, + source, + subIndex, + data = { 'value': value }, + index = 0, + marked = [], + queue = { 'length': 0 }, + unmarked = []; + + /** + * An easily detectable decorator for cloned values. + */ + function Marker(object) { + this.raw = object; + } + + /** + * The callback used by `forProps()`. + */ + function forPropsCallback(subValue, subKey) { + // exit early to avoid cloning the marker + if (subValue && subValue.constructor == Marker) { + return; + } + // add objects to the queue + if (subValue === Object(subValue)) { + queue[queue.length++] = { 'key': subKey, 'parent': clone, 'source': value }; + } + // assign non-objects + else { + try { + // will throw an error in strict mode if the property is read-only + clone[subKey] = subValue; + } catch(e) { } + } + } + + /** + * Gets an available marker key for the given object. + */ + function getMarkerKey(object) { + // avoid collisions with existing keys + var result = uid; + while (object[result] && object[result].constructor != Marker) { + result += 1; + } + return result; + } + + do { + key = data.key; + parent = data.parent; + source = data.source; + clone = value = source ? source[key] : data.value; + accessor = circular = descriptor = false; + + // create a basic clone to filter out functions, DOM elements, and + // other non `Object` objects + if (value === Object(value)) { + // use custom deep clone function if available + if (isClassOf(value.deepClone, 'Function')) { + clone = value.deepClone(); + } else { + ctor = value.constructor; + switch (toString.call(value)) { + case '[object Array]': + clone = new ctor(value.length); + break; + + case '[object Boolean]': + clone = new ctor(value == true); + break; + + case '[object Date]': + clone = new ctor(+value); + break; + + case '[object Object]': + isPlainObject(value) && (clone = {}); + break; + + case '[object Number]': + case '[object String]': + clone = new ctor(value); + break; + + case '[object RegExp]': + clone = ctor(value.source, + (value.global ? 'g' : '') + + (value.ignoreCase ? 'i' : '') + + (value.multiline ? 'm' : '')); + } + } + // continue clone if `value` doesn't have an accessor descriptor + // http://es5.github.com/#x8.10.1 + if (clone && clone != value && + !(descriptor = source && support.descriptors && getDescriptor(source, key), + accessor = descriptor && (descriptor.get || descriptor.set))) { + // use an existing clone (circular reference) + if ((extensible = isExtensible(value))) { + markerKey = getMarkerKey(value); + if (value[markerKey]) { + circular = clone = value[markerKey].raw; + } + } else { + // for frozen/sealed objects + for (subIndex = 0, length = unmarked.length; subIndex < length; subIndex++) { + data = unmarked[subIndex]; + if (data.object === value) { + circular = clone = data.clone; + break; + } + } + } + if (!circular) { + // mark object to allow quickly detecting circular references and tie it to its clone + if (extensible) { + value[markerKey] = new Marker(clone); + marked.push({ 'key': markerKey, 'object': value }); + } else { + // for frozen/sealed objects + unmarked.push({ 'clone': clone, 'object': value }); + } + // iterate over object properties + forProps(value, forPropsCallback, { 'which': 'all' }); + } + } + } + if (parent) { + // for custom property descriptors + if (accessor || (descriptor && !(descriptor.configurable && descriptor.enumerable && descriptor.writable))) { + if ('value' in descriptor) { + descriptor.value = clone; + } + setDescriptor(parent, key, descriptor); + } + // for default property descriptors + else { + parent[key] = clone; + } + } else { + result = clone; + } + } while ((data = queue[index++])); + + // remove markers + for (index = 0, length = marked.length; index < length; index++) { + data = marked[index]; + delete data.object[data.key]; + } + return result; + } + + /** + * An iteration utility for arrays and objects. + * Callbacks may terminate the loop by explicitly returning `false`. + * + * @static + * @memberOf Benchmark + * @param {Array|Object} object The object to iterate over. + * @param {Function} callback The function called per iteration. + * @param {Mixed} thisArg The `this` binding for the callback. + * @returns {Array|Object} Returns the object iterated over. + */ + function each(object, callback, thisArg) { + var result = object; + object = Object(object); + + var fn = callback, + index = -1, + length = object.length, + isSnapshot = !!(object.snapshotItem && (length = object.snapshotLength)), + isSplittable = (noCharByIndex || noCharByOwnIndex) && isClassOf(object, 'String'), + isConvertable = isSnapshot || isSplittable || 'item' in object, + origObject = object; + + // in Opera < 10.5 `hasKey(object, 'length')` returns `false` for NodeLists + if (length === length >>> 0) { + if (isConvertable) { + // the third argument of the callback is the original non-array object + callback = function(value, index) { + return fn.call(this, value, index, origObject); + }; + // in IE < 9 strings don't support accessing characters by index + if (isSplittable) { + object = object.split(''); + } else { + object = []; + while (++index < length) { + // in Safari 2 `index in object` is always `false` for NodeLists + object[index] = isSnapshot ? result.snapshotItem(index) : result[index]; + } + } + } + forEach(object, callback, thisArg); + } else { + forOwn(object, callback, thisArg); + } + return result; + } + + /** + * Copies enumerable properties from the source(s) object to the destination object. + * + * @static + * @memberOf Benchmark + * @param {Object} destination The destination object. + * @param {Object} [source={}] The source object. + * @returns {Object} The destination object. + */ + function extend(destination, source) { + // Chrome < 14 incorrectly sets `destination` to `undefined` when we `delete arguments[0]` + // http://code.google.com/p/v8/issues/detail?id=839 + var result = destination; + delete arguments[0]; + + forEach(arguments, function(source) { + forProps(source, function(value, key) { + result[key] = value; + }); + }); + return result; + } + + /** + * A generic `Array#filter` like method. + * + * @static + * @memberOf Benchmark + * @param {Array} array The array to iterate over. + * @param {Function|String} callback The function/alias called per iteration. + * @param {Mixed} thisArg The `this` binding for the callback. + * @returns {Array} A new array of values that passed callback filter. + * @example + * + * // get odd numbers + * Benchmark.filter([1, 2, 3, 4, 5], function(n) { + * return n % 2; + * }); // -> [1, 3, 5]; + * + * // get fastest benchmarks + * Benchmark.filter(benches, 'fastest'); + * + * // get slowest benchmarks + * Benchmark.filter(benches, 'slowest'); + * + * // get benchmarks that completed without erroring + * Benchmark.filter(benches, 'successful'); + */ + function filter(array, callback, thisArg) { + var result; + + if (callback == 'successful') { + // callback to exclude those that are errored, unrun, or have hz of Infinity + callback = function(bench) { return bench.cycles && isFinite(bench.hz); }; + } + else if (callback == 'fastest' || callback == 'slowest') { + // get successful, sort by period + margin of error, and filter fastest/slowest + result = filter(array, 'successful').sort(function(a, b) { + a = a.stats; b = b.stats; + return (a.mean + a.moe > b.mean + b.moe ? 1 : -1) * (callback == 'fastest' ? 1 : -1); + }); + result = filter(result, function(bench) { + return result[0].compare(bench) == 0; + }); + } + return result || reduce(array, function(result, value, index) { + return callback.call(thisArg, value, index, array) ? (result.push(value), result) : result; + }, []); + } + + /** + * A generic `Array#forEach` like method. + * Callbacks may terminate the loop by explicitly returning `false`. + * + * @static + * @memberOf Benchmark + * @param {Array} array The array to iterate over. + * @param {Function} callback The function called per iteration. + * @param {Mixed} thisArg The `this` binding for the callback. + * @returns {Array} Returns the array iterated over. + */ + function forEach(array, callback, thisArg) { + var index = -1, + length = (array = Object(array)).length >>> 0; + + if (thisArg !== undefined) { + callback = bind(callback, thisArg); + } + while (++index < length) { + if (index in array && + callback(array[index], index, array) === false) { + break; + } + } + return array; + } + + /** + * Iterates over an object's own properties, executing the `callback` for each. + * Callbacks may terminate the loop by explicitly returning `false`. + * + * @static + * @memberOf Benchmark + * @param {Object} object The object to iterate over. + * @param {Function} callback The function executed per own property. + * @param {Mixed} thisArg The `this` binding for the callback. + * @returns {Object} Returns the object iterated over. + */ + function forOwn(object, callback, thisArg) { + return forProps(object, callback, { 'bind': thisArg, 'which': 'own' }); + } + + /** + * Converts a number to a more readable comma-separated string representation. + * + * @static + * @memberOf Benchmark + * @param {Number} number The number to convert. + * @returns {String} The more readable string representation. + */ + function formatNumber(number) { + number = String(number).split('.'); + return number[0].replace(/(?=(?:\d{3})+$)(?!\b)/g, ',') + + (number[1] ? '.' + number[1] : ''); + } + + /** + * Checks if an object has the specified key as a direct property. + * + * @static + * @memberOf Benchmark + * @param {Object} object The object to check. + * @param {String} key The key to check for. + * @returns {Boolean} Returns `true` if key is a direct property, else `false`. + */ + function hasKey() { + // lazy define for worst case fallback (not as accurate) + hasKey = function(object, key) { + var parent = object != null && (object.constructor || Object).prototype; + return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]); + }; + // for modern browsers + if (isClassOf(hasOwnProperty, 'Function')) { + hasKey = function(object, key) { + return object != null && hasOwnProperty.call(object, key); + }; + } + // for Safari 2 + else if ({}.__proto__ == Object.prototype) { + hasKey = function(object, key) { + var result = false; + if (object != null) { + object = Object(object); + object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0]; + } + return result; + }; + } + return hasKey.apply(this, arguments); + } + + /** + * A generic `Array#indexOf` like method. + * + * @static + * @memberOf Benchmark + * @param {Array} array The array to iterate over. + * @param {Mixed} value The value to search for. + * @param {Number} [fromIndex=0] The index to start searching from. + * @returns {Number} The index of the matched value or `-1`. + */ + function indexOf(array, value, fromIndex) { + var index = toInteger(fromIndex), + length = (array = Object(array)).length >>> 0; + + index = (index < 0 ? max(0, length + index) : index) - 1; + while (++index < length) { + if (index in array && value === array[index]) { + return index; + } + } + return -1; + } + + /** + * Modify a string by replacing named tokens with matching object property values. + * + * @static + * @memberOf Benchmark + * @param {String} string The string to modify. + * @param {Object} object The template object. + * @returns {String} The modified string. + */ + function interpolate(string, object) { + forOwn(object, function(value, key) { + // escape regexp special characters in `key` + string = string.replace(RegExp('#\\{' + key.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1') + '\\}', 'g'), value); + }); + return string; + } + + /** + * Invokes a method on all items in an array. + * + * @static + * @memberOf Benchmark + * @param {Array} benches Array of benchmarks to iterate over. + * @param {String|Object} name The name of the method to invoke OR options object. + * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with. + * @returns {Array} A new array of values returned from each method invoked. + * @example + * + * // invoke `reset` on all benchmarks + * Benchmark.invoke(benches, 'reset'); + * + * // invoke `emit` with arguments + * Benchmark.invoke(benches, 'emit', 'complete', listener); + * + * // invoke `run(true)`, treat benchmarks as a queue, and register invoke callbacks + * Benchmark.invoke(benches, { + * + * // invoke the `run` method + * 'name': 'run', + * + * // pass a single argument + * 'args': true, + * + * // treat as queue, removing benchmarks from front of `benches` until empty + * 'queued': true, + * + * // called before any benchmarks have been invoked. + * 'onStart': onStart, + * + * // called between invoking benchmarks + * 'onCycle': onCycle, + * + * // called after all benchmarks have been invoked. + * 'onComplete': onComplete + * }); + */ + function invoke(benches, name) { + var args, + bench, + queued, + index = -1, + eventProps = { 'currentTarget': benches }, + options = { 'onStart': noop, 'onCycle': noop, 'onComplete': noop }, + result = map(benches, function(bench) { return bench; }); + + /** + * Invokes the method of the current object and if synchronous, fetches the next. + */ + function execute() { + var listeners, + async = isAsync(bench); + + if (async) { + // use `getNext` as the first listener + bench.on('complete', getNext); + listeners = bench.events.complete; + listeners.splice(0, 0, listeners.pop()); + } + // execute method + result[index] = isClassOf(bench && bench[name], 'Function') ? bench[name].apply(bench, args) : undefined; + // if synchronous return true until finished + return !async && getNext(); + } + + /** + * Fetches the next bench or executes `onComplete` callback. + */ + function getNext(event) { + var cycleEvent, + last = bench, + async = isAsync(last); + + if (async) { + last.off('complete', getNext); + last.emit('complete'); + } + // emit "cycle" event + eventProps.type = 'cycle'; + eventProps.target = last; + cycleEvent = Event(eventProps); + options.onCycle.call(benches, cycleEvent); + + // choose next benchmark if not exiting early + if (!cycleEvent.aborted && raiseIndex() !== false) { + bench = queued ? benches[0] : result[index]; + if (isAsync(bench)) { + delay(bench, execute); + } + else if (async) { + // resume execution if previously asynchronous but now synchronous + while (execute()) { } + } + else { + // continue synchronous execution + return true; + } + } else { + // emit "complete" event + eventProps.type = 'complete'; + options.onComplete.call(benches, Event(eventProps)); + } + // When used as a listener `event.aborted = true` will cancel the rest of + // the "complete" listeners because they were already called above and when + // used as part of `getNext` the `return false` will exit the execution while-loop. + if (event) { + event.aborted = true; + } else { + return false; + } + } + + /** + * Checks if invoking `Benchmark#run` with asynchronous cycles. + */ + function isAsync(object) { + // avoid using `instanceof` here because of IE memory leak issues with host objects + var async = args[0] && args[0].async; + return Object(object).constructor == Benchmark && name == 'run' && + ((async == null ? object.options.async : async) && support.timeout || object.defer); + } + + /** + * Raises `index` to the next defined index or returns `false`. + */ + function raiseIndex() { + var length = result.length; + if (queued) { + // if queued remove the previous bench and subsequent skipped non-entries + do { + ++index > 0 && shift.call(benches); + } while ((length = benches.length) && !('0' in benches)); + } + else { + while (++index < length && !(index in result)) { } + } + // if we reached the last index then return `false` + return (queued ? length : index < length) ? index : (index = false); + } + + // juggle arguments + if (isClassOf(name, 'String')) { + // 2 arguments (array, name) + args = slice.call(arguments, 2); + } else { + // 2 arguments (array, options) + options = extend(options, name); + name = options.name; + args = isClassOf(args = 'args' in options ? options.args : [], 'Array') ? args : [args]; + queued = options.queued; + } + + // start iterating over the array + if (raiseIndex() !== false) { + // emit "start" event + bench = result[index]; + eventProps.type = 'start'; + eventProps.target = bench; + options.onStart.call(benches, Event(eventProps)); + + // end early if the suite was aborted in an "onStart" listener + if (benches.aborted && benches.constructor == Suite && name == 'run') { + // emit "cycle" event + eventProps.type = 'cycle'; + options.onCycle.call(benches, Event(eventProps)); + // emit "complete" event + eventProps.type = 'complete'; + options.onComplete.call(benches, Event(eventProps)); + } + // else start + else { + if (isAsync(bench)) { + delay(bench, execute); + } else { + while (execute()) { } + } + } + } + return result; + } + + /** + * Creates a string of joined array values or object key-value pairs. + * + * @static + * @memberOf Benchmark + * @param {Array|Object} object The object to operate on. + * @param {String} [separator1=','] The separator used between key-value pairs. + * @param {String} [separator2=': '] The separator used between keys and values. + * @returns {String} The joined result. + */ + function join(object, separator1, separator2) { + var result = [], + length = (object = Object(object)).length, + arrayLike = length === length >>> 0; + + separator2 || (separator2 = ': '); + each(object, function(value, key) { + result.push(arrayLike ? value : key + separator2 + value); + }); + return result.join(separator1 || ','); + } + + /** + * A generic `Array#map` like method. + * + * @static + * @memberOf Benchmark + * @param {Array} array The array to iterate over. + * @param {Function} callback The function called per iteration. + * @param {Mixed} thisArg The `this` binding for the callback. + * @returns {Array} A new array of values returned by the callback. + */ + function map(array, callback, thisArg) { + return reduce(array, function(result, value, index) { + result[index] = callback.call(thisArg, value, index, array); + return result; + }, Array(Object(array).length >>> 0)); + } + + /** + * Retrieves the value of a specified property from all items in an array. + * + * @static + * @memberOf Benchmark + * @param {Array} array The array to iterate over. + * @param {String} property The property to pluck. + * @returns {Array} A new array of property values. + */ + function pluck(array, property) { + return map(array, function(object) { + return object == null ? undefined : object[property]; + }); + } + + /** + * A generic `Array#reduce` like method. + * + * @static + * @memberOf Benchmark + * @param {Array} array The array to iterate over. + * @param {Function} callback The function called per iteration. + * @param {Mixed} accumulator Initial value of the accumulator. + * @returns {Mixed} The accumulator. + */ + function reduce(array, callback, accumulator) { + var noaccum = arguments.length < 3; + forEach(array, function(value, index) { + accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, array); + }); + return accumulator; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Aborts all benchmarks in the suite. + * + * @name abort + * @memberOf Benchmark.Suite + * @returns {Object} The suite instance. + */ + function abortSuite() { + var event, + me = this, + resetting = calledBy.resetSuite; + + if (me.running) { + event = Event('abort'); + me.emit(event); + if (!event.cancelled || resetting) { + // avoid infinite recursion + calledBy.abortSuite = true; + me.reset(); + delete calledBy.abortSuite; + + if (!resetting) { + me.aborted = true; + invoke(me, 'abort'); + } + } + } + return me; + } + + /** + * Adds a test to the benchmark suite. + * + * @memberOf Benchmark.Suite + * @param {String} name A name to identify the benchmark. + * @param {Function|String} fn The test to benchmark. + * @param {Object} [options={}] Options object. + * @returns {Object} The benchmark instance. + * @example + * + * // basic usage + * suite.add(fn); + * + * // or using a name first + * suite.add('foo', fn); + * + * // or with options + * suite.add('foo', fn, { + * 'onCycle': onCycle, + * 'onComplete': onComplete + * }); + * + * // or name and options + * suite.add('foo', { + * 'fn': fn, + * 'onCycle': onCycle, + * 'onComplete': onComplete + * }); + * + * // or options only + * suite.add({ + * 'name': 'foo', + * 'fn': fn, + * 'onCycle': onCycle, + * 'onComplete': onComplete + * }); + */ + function add(name, fn, options) { + var me = this, + bench = Benchmark(name, fn, options), + event = Event({ 'type': 'add', 'target': bench }); + + if (me.emit(event), !event.cancelled) { + me.push(bench); + } + return me; + } + + /** + * Creates a new suite with cloned benchmarks. + * + * @name clone + * @memberOf Benchmark.Suite + * @param {Object} options Options object to overwrite cloned options. + * @returns {Object} The new suite instance. + */ + function cloneSuite(options) { + var me = this, + result = new me.constructor(extend({}, me.options, options)); + + // copy own properties + forOwn(me, function(value, key) { + if (!hasKey(result, key)) { + result[key] = value && isClassOf(value.clone, 'Function') + ? value.clone() + : deepClone(value); + } + }); + return result; + } + + /** + * An `Array#filter` like method. + * + * @name filter + * @memberOf Benchmark.Suite + * @param {Function|String} callback The function/alias called per iteration. + * @returns {Object} A new suite of benchmarks that passed callback filter. + */ + function filterSuite(callback) { + var me = this, + result = new me.constructor; + + result.push.apply(result, filter(me, callback)); + return result; + } + + /** + * Resets all benchmarks in the suite. + * + * @name reset + * @memberOf Benchmark.Suite + * @returns {Object} The suite instance. + */ + function resetSuite() { + var event, + me = this, + aborting = calledBy.abortSuite; + + if (me.running && !aborting) { + // no worries, `resetSuite()` is called within `abortSuite()` + calledBy.resetSuite = true; + me.abort(); + delete calledBy.resetSuite; + } + // reset if the state has changed + else if ((me.aborted || me.running) && + (me.emit(event = Event('reset')), !event.cancelled)) { + me.running = false; + if (!aborting) { + invoke(me, 'reset'); + } + } + return me; + } + + /** + * Runs the suite. + * + * @name run + * @memberOf Benchmark.Suite + * @param {Object} [options={}] Options object. + * @returns {Object} The suite instance. + * @example + * + * // basic usage + * suite.run(); + * + * // or with options + * suite.run({ 'async': true, 'queued': true }); + */ + function runSuite(options) { + var me = this; + + me.reset(); + me.running = true; + options || (options = {}); + + invoke(me, { + 'name': 'run', + 'args': options, + 'queued': options.queued, + 'onStart': function(event) { + me.emit(event); + }, + 'onCycle': function(event) { + var bench = event.target; + if (bench.error) { + me.emit({ 'type': 'error', 'target': bench }); + } + me.emit(event); + event.aborted = me.aborted; + }, + 'onComplete': function(event) { + me.score = getGeometricMean(map(me, function(bench) { + return bench.reference / (bench.times.period * 1e6); + })) || 0; + + me.running = false; + me.emit(event); + } + }); + return me; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Executes all registered listeners of the specified event type. + * + * @memberOf Benchmark, Benchmark.Suite + * @param {String|Object} type The event type or object. + * @returns {Mixed} Returns the return value of the last listener executed. + */ + function emit(type) { + var listeners, + me = this, + event = Event(type), + events = me.events, + args = (arguments[0] = event, arguments); + + event.currentTarget || (event.currentTarget = me); + event.target || (event.target = me); + delete event.result; + + if (events && (listeners = hasKey(events, event.type) && events[event.type])) { + forEach(listeners.slice(), function(listener) { + if ((event.result = listener.apply(me, args)) === false) { + event.cancelled = true; + } + return !event.aborted; + }); + } + return event.result; + } + + /** + * Returns an array of event listeners for a given type that can be manipulated + * to add or remove listeners. + * + * @memberOf Benchmark, Benchmark.Suite + * @param {String} type The event type. + * @returns {Array} The listeners array. + */ + function listeners(type) { + var me = this, + events = me.events || (me.events = {}); + + return hasKey(events, type) ? events[type] : (events[type] = []); + } + + /** + * Unregisters a listener for the specified event type(s), + * or unregisters all listeners for the specified event type(s), + * or unregisters all listeners for all event types. + * + * @memberOf Benchmark, Benchmark.Suite + * @param {String} [type] The event type. + * @param {Function} [listener] The function to unregister. + * @returns {Object} The benchmark instance. + * @example + * + * // unregister a listener for an event type + * bench.off('cycle', listener); + * + * // unregister a listener for multiple event types + * bench.off('start cycle', listener); + * + * // unregister all listeners for an event type + * bench.off('cycle'); + * + * // unregister all listeners for multiple event types + * bench.off('start cycle complete'); + * + * // unregister all listeners for all event types + * bench.off(); + */ + function off(type, listener) { + var me = this, + events = me.events; + + events && each(type ? type.split(' ') : events, function(listeners, type) { + var index; + if (typeof listeners == 'string') { + type = listeners; + listeners = hasKey(events, type) && events[type]; + } + if (listeners) { + if (listener) { + index = indexOf(listeners, listener); + if (index > -1) { + listeners.splice(index, 1); + } + } else { + listeners.length = 0; + } + } + }); + return me; + } + + /** + * Registers a listener for the specified event type(s). + * + * @memberOf Benchmark, Benchmark.Suite + * @param {String} type The event type. + * @param {Function} listener The function to register. + * @returns {Object} The benchmark instance. + * @example + * + * // register a listener for an event type + * bench.on('cycle', listener); + * + * // register a listener for multiple event types + * bench.on('start cycle', listener); + */ + function on(type, listener) { + var me = this, + events = me.events || (me.events = {}); + + forEach(type.split(' '), function(type) { + (hasKey(events, type) + ? events[type] + : (events[type] = []) + ).push(listener); + }); + return me; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Aborts the benchmark without recording times. + * + * @memberOf Benchmark + * @returns {Object} The benchmark instance. + */ + function abort() { + var event, + me = this, + resetting = calledBy.reset; + + if (me.running) { + event = Event('abort'); + me.emit(event); + if (!event.cancelled || resetting) { + // avoid infinite recursion + calledBy.abort = true; + me.reset(); + delete calledBy.abort; + + if (support.timeout) { + clearTimeout(me._timerId); + delete me._timerId; + } + if (!resetting) { + me.aborted = true; + me.running = false; + } + } + } + return me; + } + + /** + * Creates a new benchmark using the same test and options. + * + * @memberOf Benchmark + * @param {Object} options Options object to overwrite cloned options. + * @returns {Object} The new benchmark instance. + * @example + * + * var bizarro = bench.clone({ + * 'name': 'doppelganger' + * }); + */ + function clone(options) { + var me = this, + result = new me.constructor(extend({}, me, options)); + + // correct the `options` object + result.options = extend({}, me.options, options); + + // copy own custom properties + forOwn(me, function(value, key) { + if (!hasKey(result, key)) { + result[key] = deepClone(value); + } + }); + return result; + } + + /** + * Determines if a benchmark is faster than another. + * + * @memberOf Benchmark + * @param {Object} other The benchmark to compare. + * @returns {Number} Returns `-1` if slower, `1` if faster, and `0` if indeterminate. + */ + function compare(other) { + var critical, + zStat, + me = this, + sample1 = me.stats.sample, + sample2 = other.stats.sample, + size1 = sample1.length, + size2 = sample2.length, + maxSize = max(size1, size2), + minSize = min(size1, size2), + u1 = getU(sample1, sample2), + u2 = getU(sample2, sample1), + u = min(u1, u2); + + function getScore(xA, sampleB) { + return reduce(sampleB, function(total, xB) { + return total + (xB > xA ? 0 : xB < xA ? 1 : 0.5); + }, 0); + } + + function getU(sampleA, sampleB) { + return reduce(sampleA, function(total, xA) { + return total + getScore(xA, sampleB); + }, 0); + } + + function getZ(u) { + return (u - ((size1 * size2) / 2)) / sqrt((size1 * size2 * (size1 + size2 + 1)) / 12); + } + + // exit early if comparing the same benchmark + if (me == other) { + return 0; + } + // reject the null hyphothesis the two samples come from the + // same population (i.e. have the same median) if... + if (size1 + size2 > 30) { + // ...the z-stat is greater than 1.96 or less than -1.96 + // http://www.statisticslectures.com/topics/mannwhitneyu/ + zStat = getZ(u); + return abs(zStat) > 1.96 ? (zStat > 0 ? -1 : 1) : 0; + } + // ...the U value is less than or equal the critical U value + // http://www.geoib.com/mann-whitney-u-test.html + critical = maxSize < 5 || minSize < 3 ? 0 : uTable[maxSize][minSize - 3]; + return u <= critical ? (u == u1 ? 1 : -1) : 0; + } + + /** + * Reset properties and abort if running. + * + * @memberOf Benchmark + * @returns {Object} The benchmark instance. + */ + function reset() { + var data, + event, + me = this, + index = 0, + changes = { 'length': 0 }, + queue = { 'length': 0 }; + + if (me.running && !calledBy.abort) { + // no worries, `reset()` is called within `abort()` + calledBy.reset = true; + me.abort(); + delete calledBy.reset; + } + else { + // a non-recursive solution to check if properties have changed + // http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4 + data = { 'destination': me, 'source': extend({}, me.constructor.prototype, me.options) }; + do { + forOwn(data.source, function(value, key) { + var changed, + destination = data.destination, + currValue = destination[key]; + + if (value && typeof value == 'object') { + if (isClassOf(value, 'Array')) { + // check if an array value has changed to a non-array value + if (!isClassOf(currValue, 'Array')) { + changed = currValue = []; + } + // or has changed its length + if (currValue.length != value.length) { + changed = currValue = currValue.slice(0, value.length); + currValue.length = value.length; + } + } + // check if an object has changed to a non-object value + else if (!currValue || typeof currValue != 'object') { + changed = currValue = {}; + } + // register a changed object + if (changed) { + changes[changes.length++] = { 'destination': destination, 'key': key, 'value': currValue }; + } + queue[queue.length++] = { 'destination': currValue, 'source': value }; + } + // register a changed primitive + else if (value !== currValue && !(value == null || isClassOf(value, 'Function'))) { + changes[changes.length++] = { 'destination': destination, 'key': key, 'value': value }; + } + }); + } + while ((data = queue[index++])); + + // if changed emit the `reset` event and if it isn't cancelled reset the benchmark + if (changes.length && (me.emit(event = Event('reset')), !event.cancelled)) { + forEach(changes, function(data) { + data.destination[data.key] = data.value; + }); + } + } + return me; + } + + /** + * Displays relevant benchmark information when coerced to a string. + * + * @name toString + * @memberOf Benchmark + * @returns {String} A string representation of the benchmark instance. + */ + function toStringBench() { + var me = this, + error = me.error, + hz = me.hz, + id = me.id, + stats = me.stats, + size = stats.sample.length, + pm = support.java ? '+/-' : '\xb1', + result = me.name || (isNaN(id) ? id : ''); + + if (error) { + result += ': ' + join(error); + } else { + result += ' x ' + formatNumber(hz.toFixed(hz < 100 ? 2 : 0)) + ' ops/sec ' + pm + + stats.rme.toFixed(2) + '% (' + size + ' run' + (size == 1 ? '' : 's') + ' sampled)'; + } + return result; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Clocks the time taken to execute a test per cycle (secs). + * + * @private + * @param {Object} bench The benchmark instance. + * @returns {Number} The time taken. + */ + function clock() { + var applet, + options = Benchmark.options, + template = { 'begin': 's$=new n$', 'end': 'r$=(new n$-s$)/1e3', 'uid': uid }, + timers = [{ 'ns': timer.ns, 'res': max(0.0015, getRes('ms')), 'unit': 'ms' }]; + + // lazy define for hi-res timers + clock = function(clone) { + var deferred; + if (clone instanceof Deferred) { + deferred = clone; + clone = deferred.benchmark; + } + + var bench = clone._original, + fn = bench.fn, + fnArg = deferred ? getFirstArgument(fn) || 'deferred' : '', + stringable = isStringable(fn); + + var source = { + 'setup': getSource(bench.setup, preprocess('m$.setup()')), + 'fn': getSource(fn, preprocess('m$.fn(' + fnArg + ')')), + 'fnArg': fnArg, + 'teardown': getSource(bench.teardown, preprocess('m$.teardown()')) + }; + + var count = bench.count = clone.count, + decompilable = support.decompilation || stringable, + id = bench.id, + isEmpty = !(source.fn || stringable), + name = bench.name || (typeof id == 'number' ? '' : id), + ns = timer.ns, + result = 0; + + // init `minTime` if needed + clone.minTime = bench.minTime || (bench.minTime = bench.options.minTime = options.minTime); + + // repair nanosecond timer + // (some Chrome builds erase the `ns` variable after millions of executions) + if (applet) { + try { + ns.nanoTime(); + } catch(e) { + // use non-element to avoid issues with libs that augment them + ns = timer.ns = new applet.Packages.nano; + } + } + + // Compile in setup/teardown functions and the test loop. + // Create a new compiled test, instead of using the cached `bench.compiled`, + // to avoid potential engine optimizations enabled over the life of the test. + var compiled = bench.compiled = createFunction(preprocess('t$'), interpolate( + preprocess(deferred + ? 'var d$=this,#{fnArg}=d$,m$=d$.benchmark._original,f$=m$.fn,su$=m$.setup,td$=m$.teardown;' + + // when `deferred.cycles` is `0` then... + 'if(!d$.cycles){' + + // set `deferred.fn` + 'd$.fn=function(){var #{fnArg}=d$;if(typeof f$=="function"){try{#{fn}\n}catch(e$){f$(d$)}}else{#{fn}\n}};' + + // set `deferred.teardown` + 'd$.teardown=function(){d$.cycles=0;if(typeof td$=="function"){try{#{teardown}\n}catch(e$){td$()}}else{#{teardown}\n}};' + + // execute the benchmark's `setup` + 'if(typeof su$=="function"){try{#{setup}\n}catch(e$){su$()}}else{#{setup}\n};' + + // start timer + 't$.start(d$);' + + // execute `deferred.fn` and return a dummy object + '}d$.fn();return{}' + + : 'var r$,s$,m$=this,f$=m$.fn,i$=m$.count,n$=t$.ns;#{setup}\n#{begin};' + + 'while(i$--){#{fn}\n}#{end};#{teardown}\nreturn{elapsed:r$,uid:"#{uid}"}'), + source + )); + + try { + if (isEmpty) { + // Firefox may remove dead code from Function#toString results + // http://bugzil.la/536085 + throw new Error('The test "' + name + '" is empty. This may be the result of dead code removal.'); + } + else if (!deferred) { + // pretest to determine if compiled code is exits early, usually by a + // rogue `return` statement, by checking for a return object with the uid + bench.count = 1; + compiled = (compiled.call(bench, timer) || {}).uid == uid && compiled; + bench.count = count; + } + } catch(e) { + compiled = null; + clone.error = e || new Error(String(e)); + bench.count = count; + } + // fallback when a test exits early or errors during pretest + if (decompilable && !compiled && !deferred && !isEmpty) { + compiled = createFunction(preprocess('t$'), interpolate( + preprocess( + (clone.error && !stringable + ? 'var r$,s$,m$=this,f$=m$.fn,i$=m$.count' + : 'function f$(){#{fn}\n}var r$,s$,m$=this,i$=m$.count' + ) + + ',n$=t$.ns;#{setup}\n#{begin};m$.f$=f$;while(i$--){m$.f$()}#{end};' + + 'delete m$.f$;#{teardown}\nreturn{elapsed:r$}' + ), + source + )); + + try { + // pretest one more time to check for errors + bench.count = 1; + compiled.call(bench, timer); + bench.compiled = compiled; + bench.count = count; + delete clone.error; + } + catch(e) { + bench.count = count; + if (clone.error) { + compiled = null; + } else { + bench.compiled = compiled; + clone.error = e || new Error(String(e)); + } + } + } + // assign `compiled` to `clone` before calling in case a deferred benchmark + // immediately calls `deferred.resolve()` + clone.compiled = compiled; + // if no errors run the full test loop + if (!clone.error) { + result = compiled.call(deferred || bench, timer).elapsed; + } + return result; + }; + + /*------------------------------------------------------------------------*/ + + /** + * Gets the current timer's minimum resolution (secs). + */ + function getRes(unit) { + var measured, + begin, + count = 30, + divisor = 1e3, + ns = timer.ns, + sample = []; + + // get average smallest measurable time + while (count--) { + if (unit == 'us') { + divisor = 1e6; + if (ns.stop) { + ns.start(); + while (!(measured = ns.microseconds())) { } + } else if (ns[perfName]) { + divisor = 1e3; + measured = Function('n', 'var r,s=n.' + perfName + '();while(!(r=n.' + perfName + '()-s)){};return r')(ns); + } else { + begin = ns(); + while (!(measured = ns() - begin)) { } + } + } + else if (unit == 'ns') { + divisor = 1e9; + if (ns.nanoTime) { + begin = ns.nanoTime(); + while (!(measured = ns.nanoTime() - begin)) { } + } else { + begin = (begin = ns())[0] + (begin[1] / divisor); + while (!(measured = ((measured = ns())[0] + (measured[1] / divisor)) - begin)) { } + divisor = 1; + } + } + else { + begin = new ns; + while (!(measured = new ns - begin)) { } + } + // check for broken timers (nanoTime may have issues) + // http://alivebutsleepy.srnet.cz/unreliable-system-nanotime/ + if (measured > 0) { + sample.push(measured); + } else { + sample.push(Infinity); + break; + } + } + // convert to seconds + return getMean(sample) / divisor; + } + + /** + * Replaces all occurrences of `$` with a unique number and + * template tokens with content. + */ + function preprocess(code) { + return interpolate(code, template).replace(/\$/g, /\d+/.exec(uid)); + } + + /*------------------------------------------------------------------------*/ + + // detect nanosecond support from a Java applet + each(doc && doc.applets || [], function(element) { + return !(timer.ns = applet = 'nanoTime' in element && element); + }); + + // check type in case Safari returns an object instead of a number + try { + if (typeof timer.ns.nanoTime() == 'number') { + timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' }); + } + } catch(e) { } + + // detect Chrome's microsecond timer: + // enable benchmarking via the --enable-benchmarking command + // line switch in at least Chrome 7 to use chrome.Interval + try { + if ((timer.ns = new (window.chrome || window.chromium).Interval)) { + timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' }); + } + } catch(e) { } + + // detect `performance.now` microsecond resolution timer + if ((timer.ns = perfName && perfObject)) { + timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' }); + } + + // detect Node's nanosecond resolution timer available in Node >= 0.8 + if (processObject && typeof (timer.ns = processObject.hrtime) == 'function') { + timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' }); + } + + // detect Wade Simmons' Node microtime module + if (microtimeObject && typeof (timer.ns = microtimeObject.now) == 'function') { + timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' }); + } + + // pick timer with highest resolution + timer = reduce(timers, function(timer, other) { + return other.res < timer.res ? other : timer; + }); + + // remove unused applet + if (timer.unit != 'ns' && applet) { + applet = destroyElement(applet); + } + // error if there are no working timers + if (timer.res == Infinity) { + throw new Error('Benchmark.js was unable to find a working timer.'); + } + // use API of chosen timer + if (timer.unit == 'ns') { + if (timer.ns.nanoTime) { + extend(template, { + 'begin': 's$=n$.nanoTime()', + 'end': 'r$=(n$.nanoTime()-s$)/1e9' + }); + } else { + extend(template, { + 'begin': 's$=n$()', + 'end': 'r$=n$(s$);r$=r$[0]+(r$[1]/1e9)' + }); + } + } + else if (timer.unit == 'us') { + if (timer.ns.stop) { + extend(template, { + 'begin': 's$=n$.start()', + 'end': 'r$=n$.microseconds()/1e6' + }); + } else if (perfName) { + extend(template, { + 'begin': 's$=n$.' + perfName + '()', + 'end': 'r$=(n$.' + perfName + '()-s$)/1e3' + }); + } else { + extend(template, { + 'begin': 's$=n$()', + 'end': 'r$=(n$()-s$)/1e6' + }); + } + } + + // define `timer` methods + timer.start = createFunction(preprocess('o$'), + preprocess('var n$=this.ns,#{begin};o$.elapsed=0;o$.timeStamp=s$')); + + timer.stop = createFunction(preprocess('o$'), + preprocess('var n$=this.ns,s$=o$.timeStamp,#{end};o$.elapsed=r$')); + + // resolve time span required to achieve a percent uncertainty of at most 1% + // http://spiff.rit.edu/classes/phys273/uncert/uncert.html + options.minTime || (options.minTime = max(timer.res / 2 / 0.01, 0.05)); + return clock.apply(null, arguments); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Computes stats on benchmark results. + * + * @private + * @param {Object} bench The benchmark instance. + * @param {Object} options The options object. + */ + function compute(bench, options) { + options || (options = {}); + + var async = options.async, + elapsed = 0, + initCount = bench.initCount, + minSamples = bench.minSamples, + queue = [], + sample = bench.stats.sample; + + /** + * Adds a clone to the queue. + */ + function enqueue() { + queue.push(bench.clone({ + '_original': bench, + 'events': { + 'abort': [update], + 'cycle': [update], + 'error': [update], + 'start': [update] + } + })); + } + + /** + * Updates the clone/original benchmarks to keep their data in sync. + */ + function update(event) { + var clone = this, + type = event.type; + + if (bench.running) { + if (type == 'start') { + // Note: `clone.minTime` prop is inited in `clock()` + clone.count = bench.initCount; + } + else { + if (type == 'error') { + bench.error = clone.error; + } + if (type == 'abort') { + bench.abort(); + bench.emit('cycle'); + } else { + event.currentTarget = event.target = bench; + bench.emit(event); + } + } + } else if (bench.aborted) { + // clear abort listeners to avoid triggering bench's abort/cycle again + clone.events.abort.length = 0; + clone.abort(); + } + } + + /** + * Determines if more clones should be queued or if cycling should stop. + */ + function evaluate(event) { + var critical, + df, + mean, + moe, + rme, + sd, + sem, + variance, + clone = event.target, + done = bench.aborted, + now = +new Date, + size = sample.push(clone.times.period), + maxedOut = size >= minSamples && (elapsed += now - clone.times.timeStamp) / 1e3 > bench.maxTime, + times = bench.times, + varOf = function(sum, x) { return sum + pow(x - mean, 2); }; + + // exit early for aborted or unclockable tests + if (done || clone.hz == Infinity) { + maxedOut = !(size = sample.length = queue.length = 0); + } + + if (!done) { + // sample mean (estimate of the population mean) + mean = getMean(sample); + // sample variance (estimate of the population variance) + variance = reduce(sample, varOf, 0) / (size - 1) || 0; + // sample standard deviation (estimate of the population standard deviation) + sd = sqrt(variance); + // standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean) + sem = sd / sqrt(size); + // degrees of freedom + df = size - 1; + // critical value + critical = tTable[Math.round(df) || 1] || tTable.infinity; + // margin of error + moe = sem * critical; + // relative margin of error + rme = (moe / mean) * 100 || 0; + + extend(bench.stats, { + 'deviation': sd, + 'mean': mean, + 'moe': moe, + 'rme': rme, + 'sem': sem, + 'variance': variance + }); + + // Abort the cycle loop when the minimum sample size has been collected + // and the elapsed time exceeds the maximum time allowed per benchmark. + // We don't count cycle delays toward the max time because delays may be + // increased by browsers that clamp timeouts for inactive tabs. + // https://developer.mozilla.org/en/window.setTimeout#Inactive_tabs + if (maxedOut) { + // reset the `initCount` in case the benchmark is rerun + bench.initCount = initCount; + bench.running = false; + done = true; + times.elapsed = (now - times.timeStamp) / 1e3; + } + if (bench.hz != Infinity) { + bench.hz = 1 / mean; + times.cycle = mean * bench.count; + times.period = mean; + } + } + // if time permits, increase sample size to reduce the margin of error + if (queue.length < 2 && !maxedOut) { + enqueue(); + } + // abort the invoke cycle when done + event.aborted = done; + } + + // init queue and begin + enqueue(); + invoke(queue, { + 'name': 'run', + 'args': { 'async': async }, + 'queued': true, + 'onCycle': evaluate, + 'onComplete': function() { bench.emit('complete'); } + }); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Cycles a benchmark until a run `count` can be established. + * + * @private + * @param {Object} clone The cloned benchmark instance. + * @param {Object} options The options object. + */ + function cycle(clone, options) { + options || (options = {}); + + var deferred; + if (clone instanceof Deferred) { + deferred = clone; + clone = clone.benchmark; + } + + var clocked, + cycles, + divisor, + event, + minTime, + period, + async = options.async, + bench = clone._original, + count = clone.count, + times = clone.times; + + // continue, if not aborted between cycles + if (clone.running) { + // `minTime` is set to `Benchmark.options.minTime` in `clock()` + cycles = ++clone.cycles; + clocked = deferred ? deferred.elapsed : clock(clone); + minTime = clone.minTime; + + if (cycles > bench.cycles) { + bench.cycles = cycles; + } + if (clone.error) { + event = Event('error'); + event.message = clone.error; + clone.emit(event); + if (!event.cancelled) { + clone.abort(); + } + } + } + + // continue, if not errored + if (clone.running) { + // time taken to complete last test cycle + bench.times.cycle = times.cycle = clocked; + // seconds per operation + period = bench.times.period = times.period = clocked / count; + // ops per second + bench.hz = clone.hz = 1 / period; + // avoid working our way up to this next time + bench.initCount = clone.initCount = count; + // do we need to do another cycle? + clone.running = clocked < minTime; + + if (clone.running) { + // tests may clock at `0` when `initCount` is a small number, + // to avoid that we set its count to something a bit higher + if (!clocked && (divisor = divisors[clone.cycles]) != null) { + count = floor(4e6 / divisor); + } + // calculate how many more iterations it will take to achive the `minTime` + if (count <= clone.count) { + count += Math.ceil((minTime - clocked) / period); + } + clone.running = count != Infinity; + } + } + // should we exit early? + event = Event('cycle'); + clone.emit(event); + if (event.aborted) { + clone.abort(); + } + // figure out what to do next + if (clone.running) { + // start a new cycle + clone.count = count; + if (deferred) { + clone.compiled.call(deferred, timer); + } else if (async) { + delay(clone, function() { cycle(clone, options); }); + } else { + cycle(clone); + } + } + else { + // fix TraceMonkey bug associated with clock fallbacks + // http://bugzil.la/509069 + if (support.browser) { + runScript(uid + '=1;delete ' + uid); + } + // done + clone.emit('complete'); + } + } + + /*--------------------------------------------------------------------------*/ + + /** + * Runs the benchmark. + * + * @memberOf Benchmark + * @param {Object} [options={}] Options object. + * @returns {Object} The benchmark instance. + * @example + * + * // basic usage + * bench.run(); + * + * // or with options + * bench.run({ 'async': true }); + */ + function run(options) { + var me = this, + event = Event('start'); + + // set `running` to `false` so `reset()` won't call `abort()` + me.running = false; + me.reset(); + me.running = true; + + me.count = me.initCount; + me.times.timeStamp = +new Date; + me.emit(event); + + if (!event.cancelled) { + options = { 'async': ((options = options && options.async) == null ? me.async : options) && support.timeout }; + + // for clones created within `compute()` + if (me._original) { + if (me.defer) { + Deferred(me); + } else { + cycle(me, options); + } + } + // for original benchmarks + else { + compute(me, options); + } + } + return me; + } + + /*--------------------------------------------------------------------------*/ + + // Firefox 1 erroneously defines variable and argument names of functions on + // the function itself as non-configurable properties with `undefined` values. + // The bugginess continues as the `Benchmark` constructor has an argument + // named `options` and Firefox 1 will not assign a value to `Benchmark.options`, + // making it non-writable in the process, unless it is the first property + // assigned by for-in loop of `extend()`. + extend(Benchmark, { + + /** + * The default options copied by benchmark instances. + * + * @static + * @memberOf Benchmark + * @type Object + */ + 'options': { + + /** + * A flag to indicate that benchmark cycles will execute asynchronously + * by default. + * + * @memberOf Benchmark.options + * @type Boolean + */ + 'async': false, + + /** + * A flag to indicate that the benchmark clock is deferred. + * + * @memberOf Benchmark.options + * @type Boolean + */ + 'defer': false, + + /** + * The delay between test cycles (secs). + * @memberOf Benchmark.options + * @type Number + */ + 'delay': 0.005, + + /** + * Displayed by Benchmark#toString when a `name` is not available + * (auto-generated if absent). + * + * @memberOf Benchmark.options + * @type String + */ + 'id': undefined, + + /** + * The default number of times to execute a test on a benchmark's first cycle. + * + * @memberOf Benchmark.options + * @type Number + */ + 'initCount': 1, + + /** + * The maximum time a benchmark is allowed to run before finishing (secs). + * + * Note: Cycle delays aren't counted toward the maximum time. + * + * @memberOf Benchmark.options + * @type Number + */ + 'maxTime': 5, + + /** + * The minimum sample size required to perform statistical analysis. + * + * @memberOf Benchmark.options + * @type Number + */ + 'minSamples': 5, + + /** + * The time needed to reduce the percent uncertainty of measurement to 1% (secs). + * + * @memberOf Benchmark.options + * @type Number + */ + 'minTime': 0, + + /** + * The name of the benchmark. + * + * @memberOf Benchmark.options + * @type String + */ + 'name': undefined, + + /** + * An event listener called when the benchmark is aborted. + * + * @memberOf Benchmark.options + * @type Function + */ + 'onAbort': undefined, + + /** + * An event listener called when the benchmark completes running. + * + * @memberOf Benchmark.options + * @type Function + */ + 'onComplete': undefined, + + /** + * An event listener called after each run cycle. + * + * @memberOf Benchmark.options + * @type Function + */ + 'onCycle': undefined, + + /** + * An event listener called when a test errors. + * + * @memberOf Benchmark.options + * @type Function + */ + 'onError': undefined, + + /** + * An event listener called when the benchmark is reset. + * + * @memberOf Benchmark.options + * @type Function + */ + 'onReset': undefined, + + /** + * An event listener called when the benchmark starts running. + * + * @memberOf Benchmark.options + * @type Function + */ + 'onStart': undefined, + + /** + * The reference time taken to execute the test once (usecs). + * + * @memberOf Benchmark.options + * @type Number + */ + 'reference': 0 + }, + + /** + * Platform object with properties describing things like browser name, + * version, and operating system. + * + * @static + * @memberOf Benchmark + * @type Object + */ + 'platform': req('platform') || window.platform || { + + /** + * The platform description. + * + * @memberOf Benchmark.platform + * @type String + */ + 'description': window.navigator && navigator.userAgent || null, + + /** + * The name of the browser layout engine. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'layout': null, + + /** + * The name of the product hosting the browser. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'product': null, + + /** + * The name of the browser/environment. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'name': null, + + /** + * The name of the product's manufacturer. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'manufacturer': null, + + /** + * The name of the operating system. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'os': null, + + /** + * The alpha/beta release indicator. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'prerelease': null, + + /** + * The browser/environment version. + * + * @memberOf Benchmark.platform + * @type String|Null + */ + 'version': null, + + /** + * Return platform description when the platform object is coerced to a string. + * + * @memberOf Benchmark.platform + * @type Function + * @returns {String} The platform description. + */ + 'toString': function() { + return this.description || ''; + } + }, + + /** + * The semantic version number. + * + * @static + * @memberOf Benchmark + * @type String + */ + 'version': '1.0.0', + + // an object of environment/feature detection flags + 'support': support, + + // clone objects + 'deepClone': deepClone, + + // iteration utility + 'each': each, + + // augment objects + 'extend': extend, + + // generic Array#filter + 'filter': filter, + + // generic Array#forEach + 'forEach': forEach, + + // generic own property iteration utility + 'forOwn': forOwn, + + // converts a number to a comma-separated string + 'formatNumber': formatNumber, + + // generic Object#hasOwnProperty + // (trigger hasKey's lazy define before assigning it to Benchmark) + 'hasKey': (hasKey(Benchmark, ''), hasKey), + + // generic Array#indexOf + 'indexOf': indexOf, + + // template utility + 'interpolate': interpolate, + + // invokes a method on each item in an array + 'invoke': invoke, + + // generic Array#join for arrays and objects + 'join': join, + + // generic Array#map + 'map': map, + + // retrieves a property value from each item in an array + 'pluck': pluck, + + // generic Array#reduce + 'reduce': reduce + }); + + /*--------------------------------------------------------------------------*/ + + extend(Benchmark.prototype, { + + /** + * The number of times a test was executed. + * + * @memberOf Benchmark + * @type Number + */ + 'count': 0, + + /** + * The number of cycles performed while benchmarking. + * + * @memberOf Benchmark + * @type Number + */ + 'cycles': 0, + + /** + * The number of executions per second. + * + * @memberOf Benchmark + * @type Number + */ + 'hz': 0, + + /** + * The compiled test function. + * + * @memberOf Benchmark + * @type Function|String + */ + 'compiled': undefined, + + /** + * The error object if the test failed. + * + * @memberOf Benchmark + * @type Object + */ + 'error': undefined, + + /** + * The test to benchmark. + * + * @memberOf Benchmark + * @type Function|String + */ + 'fn': undefined, + + /** + * A flag to indicate if the benchmark is aborted. + * + * @memberOf Benchmark + * @type Boolean + */ + 'aborted': false, + + /** + * A flag to indicate if the benchmark is running. + * + * @memberOf Benchmark + * @type Boolean + */ + 'running': false, + + /** + * Compiled into the test and executed immediately **before** the test loop. + * + * @memberOf Benchmark + * @type Function|String + * @example + * + * // basic usage + * var bench = Benchmark({ + * 'setup': function() { + * var c = this.count, + * element = document.getElementById('container'); + * while (c--) { + * element.appendChild(document.createElement('div')); + * } + * }, + * 'fn': function() { + * element.removeChild(element.lastChild); + * } + * }); + * + * // compiles to something like: + * var c = this.count, + * element = document.getElementById('container'); + * while (c--) { + * element.appendChild(document.createElement('div')); + * } + * var start = new Date; + * while (count--) { + * element.removeChild(element.lastChild); + * } + * var end = new Date - start; + * + * // or using strings + * var bench = Benchmark({ + * 'setup': '\ + * var a = 0;\n\ + * (function() {\n\ + * (function() {\n\ + * (function() {', + * 'fn': 'a += 1;', + * 'teardown': '\ + * }())\n\ + * }())\n\ + * }())' + * }); + * + * // compiles to something like: + * var a = 0; + * (function() { + * (function() { + * (function() { + * var start = new Date; + * while (count--) { + * a += 1; + * } + * var end = new Date - start; + * }()) + * }()) + * }()) + */ + 'setup': noop, + + /** + * Compiled into the test and executed immediately **after** the test loop. + * + * @memberOf Benchmark + * @type Function|String + */ + 'teardown': noop, + + /** + * An object of stats including mean, margin or error, and standard deviation. + * + * @memberOf Benchmark + * @type Object + */ + 'stats': { + + /** + * The margin of error. + * + * @memberOf Benchmark#stats + * @type Number + */ + 'moe': 0, + + /** + * The relative margin of error (expressed as a percentage of the mean). + * + * @memberOf Benchmark#stats + * @type Number + */ + 'rme': 0, + + /** + * The standard error of the mean. + * + * @memberOf Benchmark#stats + * @type Number + */ + 'sem': 0, + + /** + * The sample standard deviation. + * + * @memberOf Benchmark#stats + * @type Number + */ + 'deviation': 0, + + /** + * The sample arithmetic mean. + * + * @memberOf Benchmark#stats + * @type Number + */ + 'mean': 0, + + /** + * The array of sampled periods. + * + * @memberOf Benchmark#stats + * @type Array + */ + 'sample': [], + + /** + * The sample variance. + * + * @memberOf Benchmark#stats + * @type Number + */ + 'variance': 0 + }, + + /** + * An object of timing data including cycle, elapsed, period, start, and stop. + * + * @memberOf Benchmark + * @type Object + */ + 'times': { + + /** + * The time taken to complete the last cycle (secs). + * + * @memberOf Benchmark#times + * @type Number + */ + 'cycle': 0, + + /** + * The time taken to complete the benchmark (secs). + * + * @memberOf Benchmark#times + * @type Number + */ + 'elapsed': 0, + + /** + * The time taken to execute the test once (secs). + * + * @memberOf Benchmark#times + * @type Number + */ + 'period': 0, + + /** + * A timestamp of when the benchmark started (ms). + * + * @memberOf Benchmark#times + * @type Number + */ + 'timeStamp': 0 + }, + + // aborts benchmark (does not record times) + 'abort': abort, + + // creates a new benchmark using the same test and options + 'clone': clone, + + // compares benchmark's hertz with another + 'compare': compare, + + // executes listeners + 'emit': emit, + + // get listeners + 'listeners': listeners, + + // unregister listeners + 'off': off, + + // register listeners + 'on': on, + + // reset benchmark properties + 'reset': reset, + + // runs the benchmark + 'run': run, + + // pretty print benchmark info + 'toString': toStringBench + }); + + /*--------------------------------------------------------------------------*/ + + extend(Deferred.prototype, { + + /** + * The deferred benchmark instance. + * + * @memberOf Benchmark.Deferred + * @type Object + */ + 'benchmark': null, + + /** + * The number of deferred cycles performed while benchmarking. + * + * @memberOf Benchmark.Deferred + * @type Number + */ + 'cycles': 0, + + /** + * The time taken to complete the deferred benchmark (secs). + * + * @memberOf Benchmark.Deferred + * @type Number + */ + 'elapsed': 0, + + /** + * A timestamp of when the deferred benchmark started (ms). + * + * @memberOf Benchmark.Deferred + * @type Number + */ + 'timeStamp': 0, + + // cycles/completes the deferred benchmark + 'resolve': resolve + }); + + /*--------------------------------------------------------------------------*/ + + extend(Event.prototype, { + + /** + * A flag to indicate if the emitters listener iteration is aborted. + * + * @memberOf Benchmark.Event + * @type Boolean + */ + 'aborted': false, + + /** + * A flag to indicate if the default action is cancelled. + * + * @memberOf Benchmark.Event + * @type Boolean + */ + 'cancelled': false, + + /** + * The object whose listeners are currently being processed. + * + * @memberOf Benchmark.Event + * @type Object + */ + 'currentTarget': undefined, + + /** + * The return value of the last executed listener. + * + * @memberOf Benchmark.Event + * @type Mixed + */ + 'result': undefined, + + /** + * The object to which the event was originally emitted. + * + * @memberOf Benchmark.Event + * @type Object + */ + 'target': undefined, + + /** + * A timestamp of when the event was created (ms). + * + * @memberOf Benchmark.Event + * @type Number + */ + 'timeStamp': 0, + + /** + * The event type. + * + * @memberOf Benchmark.Event + * @type String + */ + 'type': '' + }); + + /*--------------------------------------------------------------------------*/ + + /** + * The default options copied by suite instances. + * + * @static + * @memberOf Benchmark.Suite + * @type Object + */ + Suite.options = { + + /** + * The name of the suite. + * + * @memberOf Benchmark.Suite.options + * @type String + */ + 'name': undefined + }; + + /*--------------------------------------------------------------------------*/ + + extend(Suite.prototype, { + + /** + * The number of benchmarks in the suite. + * + * @memberOf Benchmark.Suite + * @type Number + */ + 'length': 0, + + /** + * A score computed using the normalized result of each benchmark in the suite. + * + * @memberOf Benchmark.Suite + * @type Number + */ + 'score': 0, + + /** + * A flag to indicate if the suite is aborted. + * + * @memberOf Benchmark.Suite + * @type Boolean + */ + 'aborted': false, + + /** + * A flag to indicate if the suite is running. + * + * @memberOf Benchmark.Suite + * @type Boolean + */ + 'running': false, + + /** + * An `Array#forEach` like method. + * Callbacks may terminate the loop by explicitly returning `false`. + * + * @memberOf Benchmark.Suite + * @param {Function} callback The function called per iteration. + * @returns {Object} The suite iterated over. + */ + 'forEach': methodize(forEach), + + /** + * An `Array#indexOf` like method. + * + * @memberOf Benchmark.Suite + * @param {Mixed} value The value to search for. + * @returns {Number} The index of the matched value or `-1`. + */ + 'indexOf': methodize(indexOf), + + /** + * Invokes a method on all benchmarks in the suite. + * + * @memberOf Benchmark.Suite + * @param {String|Object} name The name of the method to invoke OR options object. + * @param {Mixed} [arg1, arg2, ...] Arguments to invoke the method with. + * @returns {Array} A new array of values returned from each method invoked. + */ + 'invoke': methodize(invoke), + + /** + * Converts the suite of benchmarks to a string. + * + * @memberOf Benchmark.Suite + * @param {String} [separator=','] A string to separate each element of the array. + * @returns {String} The string. + */ + 'join': [].join, + + /** + * An `Array#map` like method. + * + * @memberOf Benchmark.Suite + * @param {Function} callback The function called per iteration. + * @returns {Array} A new array of values returned by the callback. + */ + 'map': methodize(map), + + /** + * Retrieves the value of a specified property from all benchmarks in the suite. + * + * @memberOf Benchmark.Suite + * @param {String} property The property to pluck. + * @returns {Array} A new array of property values. + */ + 'pluck': methodize(pluck), + + /** + * Removes the last benchmark from the suite and returns it. + * + * @memberOf Benchmark.Suite + * @returns {Mixed} The removed benchmark. + */ + 'pop': [].pop, + + /** + * Appends benchmarks to the suite. + * + * @memberOf Benchmark.Suite + * @returns {Number} The suite's new length. + */ + 'push': [].push, + + /** + * Sorts the benchmarks of the suite. + * + * @memberOf Benchmark.Suite + * @param {Function} [compareFn=null] A function that defines the sort order. + * @returns {Object} The sorted suite. + */ + 'sort': [].sort, + + /** + * An `Array#reduce` like method. + * + * @memberOf Benchmark.Suite + * @param {Function} callback The function called per iteration. + * @param {Mixed} accumulator Initial value of the accumulator. + * @returns {Mixed} The accumulator. + */ + 'reduce': methodize(reduce), + + // aborts all benchmarks in the suite + 'abort': abortSuite, + + // adds a benchmark to the suite + 'add': add, + + // creates a new suite with cloned benchmarks + 'clone': cloneSuite, + + // executes listeners of a specified type + 'emit': emit, + + // creates a new suite of filtered benchmarks + 'filter': filterSuite, + + // get listeners + 'listeners': listeners, + + // unregister listeners + 'off': off, + + // register listeners + 'on': on, + + // resets all benchmarks in the suite + 'reset': resetSuite, + + // runs all benchmarks in the suite + 'run': runSuite, + + // array methods + 'concat': concat, + + 'reverse': reverse, + + 'shift': shift, + + 'slice': slice, + + 'splice': splice, + + 'unshift': unshift + }); + + /*--------------------------------------------------------------------------*/ + + // expose Deferred, Event and Suite + extend(Benchmark, { + 'Deferred': Deferred, + 'Event': Event, + 'Suite': Suite + }); + + // expose Benchmark + // some AMD build optimizers, like r.js, check for specific condition patterns like the following: + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + // define as an anonymous module so, through path mapping, it can be aliased + define(function() { + return Benchmark; + }); + } + // check for `exports` after `define` in case a build optimizer adds an `exports` object + else if (freeExports) { + // in Node.js or RingoJS v0.8.0+ + if (typeof module == 'object' && module && module.exports == freeExports) { + (module.exports = Benchmark).Benchmark = Benchmark; + } + // in Narwhal or RingoJS v0.7.0- + else { + freeExports.Benchmark = Benchmark; + } + } + // in a browser or Rhino + else { + // use square bracket notation so Closure Compiler won't munge `Benchmark` + // http://code.google.com/closure/compiler/docs/api-tutorial3.html#export + window['Benchmark'] = Benchmark; + } + + // trigger clock's lazy define early to avoid a security error + if (support.air) { + clock({ '_original': { 'fn': noop, 'count': 1, 'options': {} } }); + } +}(this)); diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/platform.js/LICENSE.txt b/node/node_modules/grunt/node_modules/lodash/vendor/platform.js/LICENSE.txt new file mode 100644 index 000000000..dadad22fa --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/platform.js/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright 2011-2012 John-David Dalton + +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/node_modules/grunt/node_modules/lodash/vendor/platform.js/README.md b/node/node_modules/grunt/node_modules/lodash/vendor/platform.js/README.md new file mode 100644 index 000000000..c2f1cb632 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/platform.js/README.md @@ -0,0 +1,98 @@ +# Platform.js v1.0.0 + +A platform detection library that works on nearly all JavaScript platforms1. + +## Disclaimer + +Platform.js is for informational purposes only and **not** intended as a substitution for [feature detection/inference](http://allyoucanleet.com/post/18087210413/feature-testing-costs#screencast2) checks. + +## BestieJS + +Platform.js is part of the BestieJS *"Best in Class"* module collection. This means we promote solid browser/environment support, ES5 precedents, unit testing, and plenty of documentation. + +## Documentation + +The documentation for Platform.js can be viewed here: [/doc/README.md](https://github.com/bestiejs/platform.js/blob/master/doc/README.md#readme) + +For a list of upcoming features, check out our [roadmap](https://github.com/bestiejs/platform.js/wiki/Roadmap). + +## Support + +Platform.js has been tested in at least Adobe AIR 3.1, Chrome 5-21, Firefox 1-14, IE 6-9, Opera 9.25-12, Safari 3-6, Node.js 0.8.6, Narwhal 0.3.2, RingoJS 0.8, and Rhino 1.7RC5. + +## Installation and usage + +In a browser or Adobe AIR: + +```html + +``` + +Via [npm](http://npmjs.org/): + +```bash +npm install platform +``` + +In [Node.js](http://nodejs.org/) and [RingoJS](http://ringojs.org/): + +```js +var platform = require('platform'); +``` + +In [Rhino](http://www.mozilla.org/rhino/): + +```js +load('platform.js'); +``` + +In an AMD loader like [RequireJS](http://requirejs.org/): + +```js +require({ + 'paths': { + 'platform': 'path/to/platform' + } +}, +['platform'], function(platform) { + console.log(platform.name); +}); +``` + +Usage example: + +```js +// on IE10 x86 platform preview running in IE7 compatibility mode on Windows 7 64 bit edition +platform.name; // 'IE' +platform.version; // '10.0' +platform.layout; // 'Trident' +platform.os; // 'Windows Server 2008 R2 / 7 x64' +platform.description; // 'IE 10.0 x86 (platform preview; running in IE 7 mode) on Windows Server 2008 R2 / 7 x64' + +// or on an iPad +platform.name; // 'Safari' +platform.version; // '5.1' +platform.product; // 'iPad' +platform.manufacturer; // 'Apple' +platform.layout; // 'WebKit' +platform.os; // 'iOS 5.0' +platform.description; // 'Safari 5.1 on Apple iPad (iOS 5.0)' + +// or parsing a given UA string +var info = platform.parse('Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7.2; en; rv:2.0) Gecko/20100101 Firefox/4.0 Opera 11.52'); +info.name; // 'Opera' +info.version; // '11.52' +info.layout; // 'Presto' +info.os; // 'Mac OS X 10.7.2' +info.description; // 'Opera 11.52 (identifying as Firefox 4.0) on Mac OS X 10.7.2' +``` + +## Author + +* [John-David Dalton](http://allyoucanleet.com/) + [![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") + +## Contributors + +* [Mathias Bynens](http://mathiasbynens.be/) + [![twitter/mathias](http://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/platform.js/platform.js b/node/node_modules/grunt/node_modules/lodash/vendor/platform.js/platform.js new file mode 100644 index 000000000..a63ceab25 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/platform.js/platform.js @@ -0,0 +1,996 @@ +/*! + * Platform.js v1.0.0 + * Copyright 2010-2012 John-David Dalton + * Available under MIT license + */ +;(function(window) { + 'use strict'; + + /** Backup possible window/global object */ + var oldWin = window; + + /** Detect free variable `exports` */ + var freeExports = typeof exports == 'object' && exports; + + /** Detect free variable `global` */ + var freeGlobal = typeof global == 'object' && global && + (global == global.global ? (window = global) : global); + + /** Opera regexp */ + var reOpera = /Opera/; + + /** Used to resolve a value's internal [[Class]] */ + var toString = {}.toString; + + /** Detect Java environment */ + var java = /Java/.test(getClassOf(window.java)) && window.java; + + /** A character to represent alpha */ + var alpha = java ? 'a' : '\u03b1'; + + /** A character to represent beta */ + var beta = java ? 'b' : '\u03b2'; + + /** Browser document object */ + var doc = window.document || {}; + + /** Used to check for own properties of an object */ + var hasOwnProperty = {}.hasOwnProperty; + + /** Browser navigator object */ + var nav = window.navigator || {}; + + /** + * Detect Opera browser + * http://www.howtocreate.co.uk/operaStuff/operaObject.html + * http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#operamini + */ + var opera = window.operamini || window.opera; + + /** Opera [[Class]] */ + var operaClass = reOpera.test(operaClass = getClassOf(opera)) ? operaClass : (opera = null); + + /** Possible global object */ + var thisBinding = this; + + /** Browser user agent string */ + var userAgent = nav.userAgent || ''; + + /*--------------------------------------------------------------------------*/ + + /** + * Capitalizes a string value. + * + * @private + * @param {String} string The string to capitalize. + * @returns {String} The capitalized string. + */ + function capitalize(string) { + string = String(string); + return string.charAt(0).toUpperCase() + string.slice(1); + } + + /** + * An iteration utility for arrays and objects. + * + * @private + * @param {Array|Object} object The object to iterate over. + * @param {Function} callback The function called per iteration. + */ + function each(object, callback) { + var index = -1, + length = object.length; + + if (length == length >>> 0) { + while (++index < length) { + callback(object[index], index, object); + } + } else { + forOwn(object, callback); + } + } + + /** + * Trim and conditionally capitalize string values. + * + * @private + * @param {String} string The string to format. + * @returns {String} The formatted string. + */ + function format(string) { + string = trim(string); + return /^(?:webOS|i(?:OS|P))/.test(string) + ? string + : capitalize(string); + } + + /** + * Iterates over an object's own properties, executing the `callback` for each. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} callback The function executed per own property. + */ + function forOwn(object, callback) { + for (var key in object) { + hasKey(object, key) && callback(object[key], key, object); + } + } + + /** + * Gets the internal [[Class]] of a value. + * + * @private + * @param {Mixed} value The value. + * @returns {String} The [[Class]]. + */ + function getClassOf(value) { + return value == null + ? capitalize(value) + : toString.call(value).slice(8, -1); + } + + /** + * Checks if an object has the specified key as a direct property. + * + * @private + * @param {Object} object The object to check. + * @param {String} key The key to check for. + * @returns {Boolean} Returns `true` if key is a direct property, else `false`. + */ + function hasKey() { + // lazy define for others (not as accurate) + hasKey = function(object, key) { + var parent = object != null && (object.constructor || Object).prototype; + return !!parent && key in Object(object) && !(key in parent && object[key] === parent[key]); + }; + // for modern browsers + if (getClassOf(hasOwnProperty) == 'Function') { + hasKey = function(object, key) { + return object != null && hasOwnProperty.call(object, key); + }; + } + // for Safari 2 + else if ({}.__proto__ == Object.prototype) { + hasKey = function(object, key) { + var result = false; + if (object != null) { + object = Object(object); + object.__proto__ = [object.__proto__, object.__proto__ = null, result = key in object][0]; + } + return result; + }; + } + return hasKey.apply(this, arguments); + } + + /** + * Host objects can return type values that are different from their actual + * data type. The objects we are concerned with usually return non-primitive + * types of object, function, or unknown. + * + * @private + * @param {Mixed} object The owner of the property. + * @param {String} property The property to check. + * @returns {Boolean} Returns `true` if the property value is a non-primitive, else `false`. + */ + function isHostType(object, property) { + var type = object != null ? typeof object[property] : 'number'; + return !/^(?:boolean|number|string|undefined)$/.test(type) && + (type == 'object' ? !!object[property] : true); + } + + /** + * Prepares a string for use in a RegExp constructor by making hyphens and + * spaces optional. + * + * @private + * @param {String} string The string to qualify. + * @returns {String} The qualified string. + */ + function qualify(string) { + return String(string).replace(/([ -])(?!$)/g, '$1?'); + } + + /** + * A bare-bones` Array#reduce` like utility function. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function called per iteration. + * @param {Mixed} accumulator Initial value of the accumulator. + * @returns {Mixed} The accumulator. + */ + function reduce(array, callback) { + var accumulator = null; + each(array, function(value, index) { + accumulator = callback(accumulator, value, index, array); + }); + return accumulator; + } + + /** + * Removes leading and trailing whitespace from a string. + * + * @private + * @param {String} string The string to trim. + * @returns {String} The trimmed string. + */ + function trim(string) { + return String(string).replace(/^ +| +$/g, ''); + } + + /*--------------------------------------------------------------------------*/ + + /** + * Creates a new platform object. + * + * @memberOf platform + * @param {String} [ua = navigator.userAgent] The user agent string. + * @returns {Object} A platform object. + */ + function parse(ua) { + + ua || (ua = userAgent); + + /** Temporary variable used over the script's lifetime */ + var data; + + /** The CPU architecture */ + var arch = ua; + + /** Platform description array */ + var description = []; + + /** Platform alpha/beta indicator */ + var prerelease = null; + + /** A flag to indicate that environment features should be used to resolve the platform */ + var useFeatures = ua == userAgent; + + /** The browser/environment version */ + var version = useFeatures && opera && typeof opera.version == 'function' && opera.version(); + + /* Detectable layout engines (order is important) */ + var layout = getLayout([ + { 'label': 'WebKit', 'pattern': 'AppleWebKit' }, + 'iCab', + 'Presto', + 'NetFront', + 'Tasman', + 'Trident', + 'KHTML', + 'Gecko' + ]); + + /* Detectable browser names (order is important) */ + var name = getName([ + 'Adobe AIR', + 'Arora', + 'Avant Browser', + 'Camino', + 'Epiphany', + 'Fennec', + 'Flock', + 'Galeon', + 'GreenBrowser', + 'iCab', + 'Iceweasel', + 'Iron', + 'K-Meleon', + 'Konqueror', + 'Lunascape', + 'Maxthon', + 'Midori', + 'Nook Browser', + 'PhantomJS', + 'Raven', + 'Rekonq', + 'RockMelt', + 'SeaMonkey', + { 'label': 'Silk', 'pattern': '(?:Cloud9|Silk-Accelerated)' }, + 'Sleipnir', + 'SlimBrowser', + 'Sunrise', + 'Swiftfox', + 'WebPositive', + 'Opera Mini', + 'Opera', + 'Chrome', + { 'label': 'Chrome Mobile', 'pattern': '(?:CriOS|CrMo)' }, + { 'label': 'Firefox', 'pattern': '(?:Firefox|Minefield)' }, + { 'label': 'IE', 'pattern': 'MSIE' }, + 'Safari' + ]); + + /* Detectable products (order is important) */ + var product = getProduct([ + 'BlackBerry', + { 'label': 'Galaxy S', 'pattern': 'GT-I9000' }, + { 'label': 'Galaxy S2', 'pattern': 'GT-I9100' }, + 'Google TV', + 'iPad', + 'iPod', + 'iPhone', + 'Kindle', + { 'label': 'Kindle Fire', 'pattern': '(?:Cloud9|Silk-Accelerated)' }, + 'Nook', + 'PlayBook', + 'PlayStation Vita', + 'TouchPad', + 'Transformer', + 'Xoom' + ]); + + /* Detectable manufacturers */ + var manufacturer = getManufacturer({ + 'Apple': { 'iPad': 1, 'iPhone': 1, 'iPod': 1 }, + 'Amazon': { 'Kindle': 1, 'Kindle Fire': 1 }, + 'Asus': { 'Transformer': 1 }, + 'Barnes & Noble': { 'Nook': 1 }, + 'BlackBerry': { 'PlayBook': 1 }, + 'Google': { 'Google TV': 1 }, + 'HP': { 'TouchPad': 1 }, + 'LG': { }, + 'Motorola': { 'Xoom': 1 }, + 'Nokia': { }, + 'Samsung': { 'Galaxy S': 1, 'Galaxy S2': 1 }, + 'Sony': { 'PlayStation Vita': 1 } + }); + + /* Detectable OSes (order is important) */ + var os = getOS([ + 'Android', + 'CentOS', + 'Debian', + 'Fedora', + 'FreeBSD', + 'Gentoo', + 'Haiku', + 'Kubuntu', + 'Linux Mint', + 'Red Hat', + 'SuSE', + 'Ubuntu', + 'Xubuntu', + 'Cygwin', + 'Symbian OS', + 'hpwOS', + 'webOS ', + 'webOS', + 'Tablet OS', + 'Linux', + 'Mac OS X', + 'Macintosh', + 'Mac', + 'Windows 98;', + 'Windows ' + ]); + + /*------------------------------------------------------------------------*/ + + /** + * Picks the layout engine from an array of guesses. + * + * @private + * @param {Array} guesses An array of guesses. + * @returns {String|Null} The detected layout engine. + */ + function getLayout(guesses) { + return reduce(guesses, function(result, guess) { + return result || RegExp('\\b' + ( + guess.pattern || qualify(guess) + ) + '\\b', 'i').exec(ua) && (guess.label || guess); + }); + } + + /** + * Picks the manufacturer from an array of guesses. + * + * @private + * @param {Array} guesses An array of guesses. + * @returns {String|Null} The detected manufacturer. + */ + function getManufacturer(guesses) { + return reduce(guesses, function(result, value, key) { + // lookup the manufacturer by product or scan the UA for the manufacturer + return result || ( + value[product] || + value[0/*Opera 9.25 fix*/, /^[a-z]+(?: +[a-z]+\b)*/i.exec(product)] || + RegExp('\\b' + (key.pattern || qualify(key)) + '(?:\\b|\\w*\\d)', 'i').exec(ua) + ) && (key.label || key); + }); + } + + /** + * Picks the browser name from an array of guesses. + * + * @private + * @param {Array} guesses An array of guesses. + * @returns {String|Null} The detected browser name. + */ + function getName(guesses) { + return reduce(guesses, function(result, guess) { + return result || RegExp('\\b' + ( + guess.pattern || qualify(guess) + ) + '\\b', 'i').exec(ua) && (guess.label || guess); + }); + } + + /** + * Picks the OS name from an array of guesses. + * + * @private + * @param {Array} guesses An array of guesses. + * @returns {String|Null} The detected OS name. + */ + function getOS(guesses) { + return reduce(guesses, function(result, guess) { + var pattern = guess.pattern || qualify(guess); + if (!result && (result = + RegExp('\\b' + pattern + '(?:/[\\d.]+|[ \\w.]*)', 'i').exec(ua))) { + // platform tokens defined at + // http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx + // http://web.archive.org/web/20081122053950/http://msdn.microsoft.com/en-us/library/ms537503(VS.85).aspx + data = { + '6.2': '8', + '6.1': 'Server 2008 R2 / 7', + '6.0': 'Server 2008 / Vista', + '5.2': 'Server 2003 / XP 64-bit', + '5.1': 'XP', + '5.01': '2000 SP1', + '5.0': '2000', + '4.0': 'NT', + '4.90': 'ME' + }; + // detect Windows version from platform tokens + if (/^Win/i.test(result) && + (data = data[0/*Opera 9.25 fix*/, /[\d.]+$/.exec(result)])) { + result = 'Windows ' + data; + } + // correct character case and cleanup + result = format(String(result) + .replace(RegExp(pattern, 'i'), guess.label || guess) + .replace(/ ce$/i, ' CE') + .replace(/hpw/i, 'web') + .replace(/Macintosh/, 'Mac OS') + .replace(/_PowerPC/i, ' OS') + .replace(/(OS X) [^ \d]+/i, '$1') + .replace(/\/(\d)/, ' $1') + .replace(/_/g, '.') + .replace(/(?: BePC|[ .]*fc[ \d.]+)$/i, '') + .replace(/x86\.64/gi, 'x86_64') + .split(' on ')[0]); + } + return result; + }); + } + + /** + * Picks the product name from an array of guesses. + * + * @private + * @param {Array} guesses An array of guesses. + * @returns {String|Null} The detected product name. + */ + function getProduct(guesses) { + return reduce(guesses, function(result, guess) { + var pattern = guess.pattern || qualify(guess); + if (!result && (result = + RegExp('\\b' + pattern + ' *\\d+[.\\w_]*', 'i').exec(ua) || + RegExp('\\b' + pattern + '(?:; *(?:[a-z]+[_-])?[a-z]+\\d+|[^ ();-]*)', 'i').exec(ua) + )) { + // split by forward slash and append product version if needed + if ((result = String(guess.label || result).split('/'))[1] && !/[\d.]+/.test(result[0])) { + result[0] += ' ' + result[1]; + } + // correct character case and cleanup + guess = guess.label || guess; + result = format(result[0] + .replace(RegExp(pattern, 'i'), guess) + .replace(RegExp('; *(?:' + guess + '[_-])?', 'i'), ' ') + .replace(RegExp('(' + guess + ')(\\w)', 'i'), '$1 $2')); + } + return result; + }); + } + + /** + * Resolves the version using an array of UA patterns. + * + * @private + * @param {Array} patterns An array of UA patterns. + * @returns {String|Null} The detected version. + */ + function getVersion(patterns) { + return reduce(patterns, function(result, pattern) { + return result || (RegExp(pattern + + '(?:-[\\d.]+/|(?: for [\\w-]+)?[ /-])([\\d.]+[^ ();/_-]*)', 'i').exec(ua) || 0)[1] || null; + }); + } + + /*------------------------------------------------------------------------*/ + + /** + * Returns `platform.description` when the platform object is coerced to a string. + * + * @name toString + * @memberOf platform + * @returns {String} Returns `platform.description` if available, else an empty string. + */ + function toStringPlatform() { + return this.description || ''; + } + + /*------------------------------------------------------------------------*/ + + // convert layout to an array so we can add extra details + layout && (layout = [layout]); + + // detect product names that contain their manufacturer's name + if (manufacturer && !product) { + product = getProduct([manufacturer]); + } + // clean up Google TV + if ((data = /Google TV/.exec(product))) { + product = data[0]; + } + // detect simulators + if (/\bSimulator\b/i.test(ua)) { + product = (product ? product + ' ' : '') + 'Simulator'; + } + // detect iOS + if (/^iP/.test(product)) { + name || (name = 'Safari'); + os = 'iOS' + ((data = / OS ([\d_]+)/i.exec(ua)) + ? ' ' + data[1].replace(/_/g, '.') + : ''); + } + // detect Kubuntu + else if (name == 'Konqueror' && !/buntu/i.test(os)) { + os = 'Kubuntu'; + } + // detect Android browsers + else if (manufacturer && manufacturer != 'Google' && + /Chrome|Vita/.test(name + ';' + product)) { + name = 'Android Browser'; + os = /Android/.test(os) ? os : 'Android'; + } + // detect false positives for Firefox/Safari + else if (!name || (data = !/\bMinefield\b/i.test(ua) && /Firefox|Safari/.exec(name))) { + // escape the `/` for Firefox 1 + if (name && !product && /[\/,]|^[^(]+?\)/.test(ua.slice(ua.indexOf(data + '/') + 8))) { + // clear name of false positives + name = null; + } + // reassign a generic name + if ((data = product || manufacturer || os) && + (product || manufacturer || /Android|Symbian OS|Tablet OS|webOS/.test(os))) { + name = /[a-z]+(?: Hat)?/i.exec(/Android/.test(os) ? os : data) + ' Browser'; + } + } + // detect non-Opera versions (order is important) + if (!version) { + version = getVersion([ + '(?:Cloud9|CriOS|CrMo|Opera ?Mini|Raven|Silk(?!/[\\d.]+$))', + 'Version', + qualify(name), + '(?:Firefox|Minefield|NetFront)' + ]); + } + // detect stubborn layout engines + if (layout == 'iCab' && parseFloat(version) > 3) { + layout = ['WebKit']; + } else if (data = + /Opera/.test(name) && 'Presto' || + /\b(?:Midori|Nook|Safari)\b/i.test(ua) && 'WebKit' || + !layout && /\bMSIE\b/i.test(ua) && (/^Mac/.test(os) ? 'Tasman' : 'Trident')) { + layout = [data]; + } + // leverage environment features + if (useFeatures) { + // detect server-side environments + // Rhino has a global function while others have a global object + if (isHostType(window, 'global')) { + if (java) { + data = java.lang.System; + arch = data.getProperty('os.arch'); + os = os || data.getProperty('os.name') + ' ' + data.getProperty('os.version'); + } + if (typeof exports == 'object' && exports) { + // if `thisBinding` is the [ModuleScope] + if (thisBinding == oldWin && typeof system == 'object' && (data = [system])[0]) { + os || (os = data[0].os || null); + try { + data[1] = require('ringo/engine').version; + version = data[1].join('.'); + name = 'RingoJS'; + } catch(e) { + if (data[0].global == freeGlobal) { + name = 'Narwhal'; + } + } + } else if (typeof process == 'object' && (data = process)) { + name = 'Node.js'; + arch = data.arch; + os = data.platform; + version = /[\d.]+/.exec(data.version)[0]; + } + } else if (getClassOf(window.environment) == 'Environment') { + name = 'Rhino'; + } + } + // detect Adobe AIR + else if (getClassOf(data = window.runtime) == 'ScriptBridgingProxyObject') { + name = 'Adobe AIR'; + os = data.flash.system.Capabilities.os; + } + // detect PhantomJS + else if (getClassOf(data = window.phantom) == 'RuntimeObject') { + name = 'PhantomJS'; + version = (data = data.version || null) && (data.major + '.' + data.minor + '.' + data.patch); + } + // detect IE compatibility modes + else if (typeof doc.documentMode == 'number' && (data = /\bTrident\/(\d+)/i.exec(ua))) { + // we're in compatibility mode when the Trident version + 4 doesn't + // equal the document mode + version = [version, doc.documentMode]; + if ((data = +data[1] + 4) != version[1]) { + description.push('IE ' + version[1] + ' mode'); + layout[1] = ''; + version[1] = data; + } + version = name == 'IE' ? String(version[1].toFixed(1)) : version[0]; + } + os = os && format(os); + } + // detect prerelease phases + if (version && (data = + /(?:[ab]|dp|pre|[ab]\d+pre)(?:\d+\+?)?$/i.exec(version) || + /(?:alpha|beta)(?: ?\d)?/i.exec(ua + ';' + (useFeatures && nav.appMinorVersion)) || + /\bMinefield\b/i.test(ua) && 'a')) { + prerelease = /b/i.test(data) ? 'beta' : 'alpha'; + version = version.replace(RegExp(data + '\\+?$'), '') + + (prerelease == 'beta' ? beta : alpha) + (/\d+\+?/.exec(data) || ''); + } + // rename code name "Fennec" + if (name == 'Fennec') { + name = 'Firefox Mobile'; + } + // obscure Maxthon's unreliable version + else if (name == 'Maxthon' && version) { + version = version.replace(/\.[\d.]+/, '.x'); + } + // detect Silk desktop/accelerated modes + else if (name == 'Silk') { + if (!/Mobi/i.test(ua)) { + os = 'Android'; + description.unshift('desktop mode'); + } + if (/Accelerated *= *true/i.test(ua)) { + description.unshift('accelerated'); + } + } + // detect Windows Phone desktop mode + else if (name == 'IE' && (data = (/; *(?:XBLWP|ZuneWP)(\d+)/i.exec(ua) || 0)[1])) { + name += ' Mobile'; + os = 'Windows Phone OS ' + data + '.x'; + description.unshift('desktop mode'); + } + // add mobile postfix + else if ((name == 'IE' || name && !product && !/Browser|Mobi/.test(name)) && + (os == 'Windows CE' || /Mobi/i.test(ua))) { + name += ' Mobile'; + } + // detect IE platform preview + else if (name == 'IE' && useFeatures && typeof external == 'object' && !external) { + description.unshift('platform preview'); + } + // detect BlackBerry OS version + // http://docs.blackberry.com/en/developers/deliverables/18169/HTTP_headers_sent_by_BB_Browser_1234911_11.jsp + else if (/BlackBerry/.test(product) && (data = + (RegExp(product.replace(/ +/g, ' *') + '/([.\\d]+)', 'i').exec(ua) || 0)[1] || + version)) { + os = 'Device Software ' + data; + version = null; + } + // detect Opera identifying/masking itself as another browser + // http://www.opera.com/support/kb/view/843/ + else if (this != forOwn && ( + (useFeatures && opera) || + (/Opera/.test(name) && /\b(?:MSIE|Firefox)\b/i.test(ua)) || + (name == 'Firefox' && /OS X (?:\d+\.){2,}/.test(os)) || + (name == 'IE' && ( + (os && !/^Win/.test(os) && version > 5.5) || + /Windows XP/.test(os) && version > 8 || + version == 8 && !/Trident/.test(ua) + )) + ) && !reOpera.test(data = parse.call(forOwn, ua.replace(reOpera, '') + ';')) && data.name) { + + // when "indentifying", the UA contains both Opera and the other browser's name + data = 'ing as ' + data.name + ((data = data.version) ? ' ' + data : ''); + if (reOpera.test(name)) { + if (/IE/.test(data) && os == 'Mac OS') { + os = null; + } + data = 'identify' + data; + } + // when "masking", the UA contains only the other browser's name + else { + data = 'mask' + data; + if (operaClass) { + name = format(operaClass.replace(/([a-z])([A-Z])/g, '$1 $2')); + } else { + name = 'Opera'; + } + if (/IE/.test(data)) { + os = null; + } + if (!useFeatures) { + version = null; + } + } + layout = ['Presto']; + description.push(data); + } + // detect WebKit Nightly and approximate Chrome/Safari versions + if ((data = (/\bAppleWebKit\/([\d.]+\+?)/i.exec(ua) || 0)[1])) { + // correct build for numeric comparison + // (e.g. "532.5" becomes "532.05") + data = [parseFloat(data.replace(/\.(\d)$/, '.0$1')), data]; + // nightly builds are postfixed with a `+` + if (name == 'Safari' && data[1].slice(-1) == '+') { + name = 'WebKit Nightly'; + prerelease = 'alpha'; + version = data[1].slice(0, -1); + } + // clear incorrect browser versions + else if (version == data[1] || + version == (/\bSafari\/([\d.]+\+?)/i.exec(ua) || 0)[1]) { + version = null; + } + // use the full Chrome version when available + data = [data[0], (/\bChrome\/([\d.]+)/i.exec(ua) || 0)[1]]; + + // detect JavaScriptCore + // http://stackoverflow.com/questions/6768474/how-can-i-detect-which-javascript-engine-v8-or-jsc-is-used-at-runtime-in-androi + if (!useFeatures || (/internal|\n/i.test(toString.toString()) && !data[1])) { + layout[1] = 'like Safari'; + data = (data = data[0], data < 400 ? 1 : data < 500 ? 2 : data < 526 ? 3 : data < 533 ? 4 : data < 534 ? '4+' : data < 535 ? 5 : '5'); + } else { + layout[1] = 'like Chrome'; + data = data[1] || (data = data[0], data < 530 ? 1 : data < 532 ? 2 : data < 532.05 ? 3 : data < 533 ? 4 : data < 534.03 ? 5 : data < 534.07 ? 6 : data < 534.10 ? 7 : data < 534.13 ? 8 : data < 534.16 ? 9 : data < 534.24 ? 10 : data < 534.30 ? 11 : data < 535.01 ? 12 : data < 535.02 ? '13+' : data < 535.07 ? 15 : data < 535.11 ? 16 : data < 535.19 ? 17 : data < 536.05 ? 18 : data < 536.10 ? 19 : data < 537.01 ? 20 : '21'); + } + // add the postfix of ".x" or "+" for approximate versions + layout[1] += ' ' + (data += typeof data == 'number' ? '.x' : /[.+]/.test(data) ? '' : '+'); + // obscure version for some Safari 1-2 releases + if (name == 'Safari' && (!version || parseInt(version) > 45)) { + version = data; + } + } + // detect Opera desktop modes + if (name == 'Opera' && (data = /(?:zbov|zvav)$/.exec(os))) { + name += ' '; + description.unshift('desktop mode'); + if (data == 'zvav') { + name += 'Mini'; + version = null; + } else { + name += 'Mobile'; + } + } + // detect Chrome desktop mode + else if (name == 'Safari' && /Chrome/.exec(layout[1])) { + description.unshift('desktop mode'); + name = 'Chrome Mobile'; + version = null; + + if (/Mac OS X/.test(os)) { + manufacturer = 'Apple'; + os = 'iOS 4.3+'; + } else { + os = null; + } + } + // strip incorrect OS versions + if (version && version.indexOf(data = /[\d.]+$/.exec(os)) == 0 && + ua.indexOf('/' + data + '-') > -1) { + os = trim(os.replace(data, '')); + } + // add layout engine + if (layout && !/Avant|Nook/.test(name) && ( + /Browser|Lunascape|Maxthon/.test(name) || + /^(?:Adobe|Arora|Midori|Phantom|Rekonq|Rock|Sleipnir|Web)/.test(name) && layout[1])) { + // don't add layout details to description if they are falsey + (data = layout[layout.length - 1]) && description.push(data); + } + // combine contextual information + if (description.length) { + description = ['(' + description.join('; ') + ')']; + } + // append manufacturer + if (manufacturer && product && product.indexOf(manufacturer) < 0) { + description.push('on ' + manufacturer); + } + // append product + if (product) { + description.push((/^on /.test(description[description.length -1]) ? '' : 'on ') + product); + } + // parse OS into an object + if (os) { + data = / ([\d.+]+)$/.exec(os); + os = { + 'architecture': 32, + 'family': data ? os.replace(data[0], '') : os, + 'version': data ? data[1] : null, + 'toString': function() { + var version = this.version; + return this.family + (version ? ' ' + version : '') + (this.architecture == 64 ? ' 64-bit' : ''); + } + }; + } + // add browser/OS architecture + if ((data = /\b(?:AMD|IA|Win|WOW|x86_|x)64\b/i.exec(arch)) && !/\bi686\b/i.test(arch)) { + if (os) { + os.architecture = 64; + os.family = os.family.replace(RegExp(' *' + data), ''); + } + if (name && (/WOW64/i.test(ua) || + (useFeatures && /\w(?:86|32)$/.test(nav.cpuClass || nav.platform)))) { + description.unshift('32-bit'); + } + } + + ua || (ua = null); + + /*------------------------------------------------------------------------*/ + + /** + * The platform object. + * + * @name platform + * @type Object + */ + return { + + /** + * The browser/environment version. + * + * @memberOf platform + * @type String|Null + */ + 'version': name && version && (description.unshift(version), version), + + /** + * The name of the browser/environment. + * + * @memberOf platform + * @type String|Null + */ + 'name': name && (description.unshift(name), name), + + /** + * The name of the operating system. + * + * @memberOf platform + * @type Object + */ + 'os': os + ? (name && + !(os == String(os).split(' ')[0] && (os == name.split(' ')[0] || product)) && + description.push(product ? '(' + os + ')' : 'on ' + os), os) + : { + + /** + * The CPU architecture the OS is built for. + * + * @memberOf platform.os + * @type String|Null + */ + 'architecture': null, + + /** + * The family of the OS. + * + * @memberOf platform.os + * @type String|Null + */ + 'family': null, + + /** + * The version of the OS. + * + * @memberOf platform.os + * @type String|Null + */ + 'version': null, + + /** + * Returns the OS string. + * + * @memberOf platform.os + * @returns {String} The OS string. + */ + 'toString': function() { return 'null'; } + }, + + /** + * The platform description. + * + * @memberOf platform + * @type String|Null + */ + 'description': description.length ? description.join(' ') : ua, + + /** + * The name of the browser layout engine. + * + * @memberOf platform + * @type String|Null + */ + 'layout': layout && layout[0], + + /** + * The name of the product's manufacturer. + * + * @memberOf platform + * @type String|Null + */ + 'manufacturer': manufacturer, + + /** + * The alpha/beta release indicator. + * + * @memberOf platform + * @type String|Null + */ + 'prerelease': prerelease, + + /** + * The name of the product hosting the browser. + * + * @memberOf platform + * @type String|Null + */ + 'product': product, + + /** + * The browser's user agent string. + * + * @memberOf platform + * @type String|Null + */ + 'ua': ua, + + // parses a user agent string into a platform object + 'parse': parse, + + // returns the platform description + 'toString': toStringPlatform + }; + } + + /*--------------------------------------------------------------------------*/ + + // expose platform + // some AMD build optimizers, like r.js, check for specific condition patterns like the following: + if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { + // define as an anonymous module so, through path mapping, it can be aliased + define(function() { + return parse(); + }); + } + // check for `exports` after `define` in case a build optimizer adds an `exports` object + else if (freeExports) { + // in Narwhal, Node.js, or RingoJS + forOwn(parse(), function(value, key) { + freeExports[key] = value; + }); + } + // in a browser or Rhino + else { + // use square bracket notation so Closure Compiler won't munge `platform` + // http://code.google.com/closure/compiler/docs/api-tutorial3.html#export + window['platform'] = parse(); + } +}(this)); diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/qunit-clib/LICENSE.txt b/node/node_modules/grunt/node_modules/lodash/vendor/qunit-clib/LICENSE.txt new file mode 100644 index 000000000..dadad22fa --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/qunit-clib/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright 2011-2012 John-David Dalton + +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/node_modules/grunt/node_modules/lodash/vendor/qunit-clib/README.md b/node/node_modules/grunt/node_modules/lodash/vendor/qunit-clib/README.md new file mode 100644 index 000000000..b84a21c98 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/qunit-clib/README.md @@ -0,0 +1,57 @@ +# QUnit CLIB v1.0.0 +## command-line interface boilerplate + +QUnit CLIB helps extend QUnit's CLI support to many common CLI environments. + +## Screenshot + +![QUnit CLIB brings QUnit to your favorite shell.](http://i.imgur.com/jpu9l.png) + +## Support + +QUnit CLIB has been tested in at least Node.js 0.4.8-0.8.6, Narwhal v0.3.2, RingoJS v0.8.0, and Rhino v1.7RC3-RC5. + +## Usage + +```js +(function(window) { + + // use a single load function + var load = typeof require == 'function' ? require : window.load; + + // load QUnit and CLIB if needed + var QUnit = + window.QUnit || ( + window.setTimeout || (window.addEventListener = window.setTimeout = / /), + window.QUnit = load('path/to/qunit.js') || window.QUnit, + load('path/to/qunit-clib.js'), + (window.addEventListener || 0).test && delete window.addEventListener, + window.QUnit + ); + + // explicitly call `QUnit.module()` instead of `module()` + // in case we are in a CLI environment + QUnit.module('A Test Module'); + + test('A Test', function() { + // ... + }); + + // must call `QUnit.start()` if using QUnit < 1.3.0 with Node.js or any + // version of QUnit with Narwhal, Rhino, or RingoJS + if (!window.document) { + QUnit.start(); + } +}(typeof global == 'object' && global || this)); +``` + +## Footnotes + + 1. QUnit v1.3.0 does not work with Narwhal or Ringo < v0.8.0 + + 2. Rhino v1.7RC4 does not support timeout fallbacks `clearTimeout` and `setTimeout` + +## Author + +* [John-David Dalton](http://allyoucanleet.com/) + [![twitter/jdalton](http://gravatar.com/avatar/299a3d891ff1920b69c364d061007043?s=70)](https://twitter.com/jdalton "Follow @jdalton on Twitter") diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/qunit-clib/qunit-clib.js b/node/node_modules/grunt/node_modules/lodash/vendor/qunit-clib/qunit-clib.js new file mode 100644 index 000000000..14a3da825 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/qunit-clib/qunit-clib.js @@ -0,0 +1,324 @@ +/*! + * QUnit CLI Boilerplate v1.0.0 + * Copyright 2011-2012 John-David Dalton + * Based on a gist by Jörn Zaefferer + * Available under MIT license + */ +;(function(global) { + 'use strict'; + + /** Add `console.log()` support for Narwhal, Rhino, and RingoJS */ + global.console || (global.console = { 'log': global.print }); + + /** Reduce global.QUnit.QUnit -> global.QUnit */ + global.QUnit && (QUnit = QUnit.QUnit || QUnit); + + /*--------------------------------------------------------------------------*/ + + /** Used as a horizontal rule in console output */ + var hr = '----------------------------------------'; + + /** Shortcut used to convert array-like objects to arrays */ + var slice = [].slice; + + /** Used to resolve a value's internal [[Class]] */ + var toString = {}.toString; + + /** Used by timer methods */ + var doneCalled, + timer, + counter = 0, + ids = {}; + + /*--------------------------------------------------------------------------*/ + + /** + * An iteration utility for arrays. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function called per iteration. + */ + function each(array, callback) { + var index = -1, + length = array.length; + + while (++index < length) { + callback(array[index], index, array); + } + } + + /** + * Checks if the specified `value` is a function. + * + * @private + * @param {Mixed} value The value to check. + * @returns {Boolean} Returns `true` if `value` is a function, else `false`. + */ + function isFunction(value) { + return toString.call(value) == '[object Function]'; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Timeout fallbacks based on the work of Andrea Giammarchi and Weston C. + * https://github.com/WebReflection/wru/blob/master/src/rhinoTimers.js + * http://stackoverflow.com/questions/2261705/how-to-run-a-javascript-function-asynchronously-without-using-settimeout + */ + + /** + * Clears the delay set by `setInterval` or `setTimeout`. + * + * @memberOf global + * @param {Number} id The ID of the timeout to be cleared. + */ + function clearTimer(id) { + if (ids[id]) { + ids[id].cancel(); + timer.purge(); + delete ids[id]; + } + } + + /** + * Schedules timer-based callbacks. + * + * @private + * @param {Function} fn The function to call. + * @oaram {Number} delay The number of milliseconds to delay the `fn` call. + * @param [arg1, arg2, ...] Arguments to invoke `fn` with. + * @param {Boolean} repeated A flag to specify whether `fn` is called repeatedly. + * @returns {Number} The the ID of the timeout. + */ + function schedule(fn, delay, args, repeated) { + // Rhino 1.7RC4 will error assigning `task` below + // https://bugzilla.mozilla.org/show_bug.cgi?id=775566 + var task = ids[++counter] = new JavaAdapter(java.util.TimerTask, { + 'run': function() { + fn.apply(global, args); + } + }); + // support non-functions + if (!isFunction(fn)) { + fn = (function(code) { + code = String(code); + return function() { eval(code); }; + }(fn)); + } + // used by setInterval + if (repeated) { + timer.schedule(task, delay, delay); + } + // used by setTimeout + else { + timer.schedule(task, delay); + } + return counter; + } + + /** + * Executes a code snippet or function repeatedly, with a delay between each call. + * + * @memberOf global + * @param {Function|String} fn The function to call or string to evaluate. + * @oaram {Number} delay The number of milliseconds to delay each `fn` call. + * @param [arg1, arg2, ...] Arguments to invoke `fn` with. + * @returns {Number} The the ID of the timeout. + */ + function setInterval(fn, delay) { + return schedule(fn, delay, slice.call(arguments, 2), true); + } + + /** + * Executes a code snippet or a function after specified delay. + * + * @memberOf global + * @param {Function|String} fn The function to call or string to evaluate. + * @oaram {Number} delay The number of milliseconds to delay the `fn` call. + * @param [arg1, arg2, ...] Arguments to invoke `fn` with. + * @returns {Number} The the ID of the timeout. + */ + function setTimeout(fn, delay) { + return schedule(fn, delay, slice.call(arguments, 2)); + } + + /*--------------------------------------------------------------------------*/ + + /** + * A logging callback triggered when all testing is completed. + * + * @memberOf QUnit + * @param {Object} details An object with properties `failed`, `passed`, + * `runtime`, and `total`. + */ + function done(details) { + // stop `asyncTest()` from erroneously calling `done()` twice in + // environments w/o timeouts + if (doneCalled) { + return; + } + doneCalled = true; + console.log(hr); + console.log(' PASS: ' + details.passed + ' FAIL: ' + details.failed + ' TOTAL: ' + details.total); + console.log(' Finished in ' + details.runtime + ' milliseconds.'); + console.log(hr); + + // exit out of Rhino + try { + quit(); + } catch(e) { } + + // exit out of Node.js + try { + if (details.failed) { + console.error('Error: ' + details.failed + ' of ' + details.total + ' tests failed.'); + process.exit(1); + } else { + process.exit(0); + } + } catch(e) { } + } + + /** + * A logging callback triggered after every assertion. + * + * @memberOf QUnit + * @param {Object} details An object with properties `actual`, `expected`, + * `message`, and `result`. + */ + function log(details) { + var expected = details.expected, + result = details.result, + type = typeof expected != 'undefined' ? 'EQ' : 'OK'; + + var assertion = [ + result ? 'PASS' : 'FAIL', + type, + details.message || 'ok' + ]; + + if (!result && type == 'EQ') { + assertion.push('Expected: ' + expected + ', Actual: ' + details.actual); + } + QUnit.config.testStats.assertions.push(assertion.join(' | ')); + } + + /** + * A logging callback triggered at the start of every test module. + * + * @memberOf QUnit + * @param {Object} details An object with property `name`. + */ + function moduleStart(details) { + console.log(hr); + console.log(details.name); + console.log(hr); + } + + /** + * Converts an object into a string representation. + * + * @memberOf QUnit + * @type Function + * @param {Object} object The object to stringify. + * @returns {String} The result string. + */ + var parseObject = (function() { + var func = QUnit.jsDump.parsers.object; + return function(object) { + // fork to support Rhino's error objects + if (typeof object.rhinoException == 'object') { + return object.name + + ' { message: "' + object.message + + '", fileName: "' + object.fileName + + '", lineNumber: ' + object.lineNumber + ' }'; + } + return func(object); + }; + }()); + + /** + * A logging callback triggered after a test is completed. + * + * @memberOf QUnit + * @param {Object} details An object with properties `failed`, `name`, + * `passed`, and `total`. + */ + function testDone(details) { + var assertions = QUnit.config.testStats.assertions, + testName = details.name; + + if (details.failed > 0) { + console.log(' FAIL - '+ testName); + each(assertions, function(value) { + console.log(' ' + value); + }); + } + else { + console.log(' PASS - ' + testName); + } + assertions.length = 0; + } + + /*--------------------------------------------------------------------------*/ + + /** + * An object used to hold information about the current running test. + * + * @memberOf QUnit.config + * @type Object + */ + QUnit.config.testStats = { + + /** + * An array of test summaries (pipe separated). + * + * @memberOf QUnit.config.testStats + * @type Array + */ + 'assertions': [] + }; + + // add shortcuts to the global + // exclude `module` because some environments have it as a built-in object + each(['asyncTest', 'deepEqual', 'equal', 'equals', 'expect', 'notDeepEqual', + 'notEqual', 'notStrictEqual', 'ok', 'raises', 'same', 'start', 'stop', + 'strictEqual', 'test', 'throws'], function(funcName) { + var func = QUnit[funcName]; + if (func) { + global[funcName] = func; + } + }); + + // expose timer methods to global + try { + timer = new java.util.Timer; + if (!isFunction(global.clearInterval)) { + global.clearInterval = clearTimer; + } + if (!isFunction(global.clearTimeout)) { + global.clearTimeout = clearTimer; + } + if (!isFunction(global.setInterval)) { + global.setInterval = setInterval; + } + if (!isFunction(global.setTimeout)) { + global.setTimeout = setTimeout; + } + } catch(e) { } + + // add callbacks + QUnit.done(done); + QUnit.log(log); + QUnit.moduleStart(moduleStart); + QUnit.testDone(testDone); + + // add wrapped function + QUnit.jsDump.parsers.object = parseObject; + + // must call `QUnit.start()` in the test file if using QUnit < 1.3.0 with + // Node.js or any version of QUnit with Narwhal, Rhino, or RingoJS + QUnit.init(); + +}(typeof global == 'object' && global || this)); diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/qunit/README.md b/node/node_modules/grunt/node_modules/lodash/vendor/qunit/README.md new file mode 100644 index 000000000..57ff29e1f --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/qunit/README.md @@ -0,0 +1,59 @@ +[QUnit](http://qunitjs.com) - A JavaScript Unit Testing framework. +================================ + +QUnit is a powerful, easy-to-use, JavaScript test suite. It's used by the jQuery +project to test its code and plugins but is capable of testing any generic +JavaScript code (and even capable of testing JavaScript code on the server-side). + +QUnit is especially useful for regression testing: Whenever a bug is reported, +write a test that asserts the existence of that particular bug. Then fix it and +commit both. Every time you work on the code again, run the tests. If the bug +comes up again - a regression - you'll spot it immediately and know how to fix +it, because you know what code you just changed. + +Having good unit test coverage makes safe refactoring easy and cheap. You can +run the tests after each small refactoring step and always know what change +broke something. + +QUnit is similar to other unit testing frameworks like JUnit, but makes use of +the features JavaScript provides and helps with testing code in the browser, e.g. +with its stop/start facilities for testing asynchronous code. + +If you are interested in helping developing QUnit, you are in the right place. +For related discussions, visit the +[QUnit and Testing forum](http://forum.jquery.com/qunit-and-testing). + +Planning for a qunitjs.com site and other testing tools related work now happens +on the [jQuery Testing Team planning wiki](http://jquerytesting.pbworks.com/w/page/41556026/FrontPage). + +Development +----------- + +To submit patches, fork the repository, create a branch for the change. Then implement +the change, run `grunt` to lint and test it, then commit, push and create a pull request. + +Include some background for the change in the commit message and `Fixes #nnn`, referring +to the issue number you're addressing. + +To run `grunt`, you need `node` and `npm`, then `npm install grunt -g`. That gives you a global +grunt binary. For additional grunt tasks, also run `npm install`. + +Releases +-------- + +Install git-extras and run `git changelog` to update History.md. +Update qunit/qunit.js|css and package.json to the release version, commit and +tag, update them again to the next version, commit and push commits and tags +(`git push --tags origin master`). + +Put the 'v' in front of the tag, e.g. `v1.8.0`. Clean up the changelog, removing merge commits +or whitespace cleanups. + +To upload to code.jquery.com (replace $version accordingly): + + scp -q qunit/qunit.js jqadmin@code.origin.jquery.com:/var/www/html/code.jquery.com/qunit/qunit-$version.js + scp -q qunit/qunit.css jqadmin@code.origin.jquery.com:/var/www/html/code.jquery.com/qunit/qunit-$version.css + +Then update /var/www/html/code.jquery.com/index.html and purge it with: + + curl -s http://code.origin.jquery.com/?reload \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/qunit/qunit/qunit.js b/node/node_modules/grunt/node_modules/lodash/vendor/qunit/qunit/qunit.js new file mode 100644 index 000000000..d4f17b5ae --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/qunit/qunit/qunit.js @@ -0,0 +1,1977 @@ +/** + * QUnit v1.10.0 - A JavaScript Unit Testing Framework + * + * http://qunitjs.com + * + * Copyright 2012 jQuery Foundation and other contributors + * Released under the MIT license. + * http://jquery.org/license + */ + +(function( window ) { + +var QUnit, + config, + onErrorFnPrev, + testId = 0, + fileName = (sourceFromStacktrace( 0 ) || "" ).replace(/(:\d+)+\)?/, "").replace(/.+\//, ""), + toString = Object.prototype.toString, + hasOwn = Object.prototype.hasOwnProperty, + // Keep a local reference to Date (GH-283) + Date = window.Date, + defined = { + setTimeout: typeof window.setTimeout !== "undefined", + sessionStorage: (function() { + var x = "qunit-test-string"; + try { + sessionStorage.setItem( x, x ); + sessionStorage.removeItem( x ); + return true; + } catch( e ) { + return false; + } + }()) +}; + +function Test( settings ) { + extend( this, settings ); + this.assertions = []; + this.testNumber = ++Test.count; +} + +Test.count = 0; + +Test.prototype = { + init: function() { + var a, b, li, + tests = id( "qunit-tests" ); + + if ( tests ) { + b = document.createElement( "strong" ); + b.innerHTML = this.name; + + // `a` initialized at top of scope + a = document.createElement( "a" ); + a.innerHTML = "Rerun"; + a.href = QUnit.url({ testNumber: this.testNumber }); + + li = document.createElement( "li" ); + li.appendChild( b ); + li.appendChild( a ); + li.className = "running"; + li.id = this.id = "qunit-test-output" + testId++; + + tests.appendChild( li ); + } + }, + setup: function() { + if ( this.module !== config.previousModule ) { + if ( config.previousModule ) { + runLoggingCallbacks( "moduleDone", QUnit, { + name: config.previousModule, + failed: config.moduleStats.bad, + passed: config.moduleStats.all - config.moduleStats.bad, + total: config.moduleStats.all + }); + } + config.previousModule = this.module; + config.moduleStats = { all: 0, bad: 0 }; + runLoggingCallbacks( "moduleStart", QUnit, { + name: this.module + }); + } else if ( config.autorun ) { + runLoggingCallbacks( "moduleStart", QUnit, { + name: this.module + }); + } + + config.current = this; + + this.testEnvironment = extend({ + setup: function() {}, + teardown: function() {} + }, this.moduleTestEnvironment ); + + runLoggingCallbacks( "testStart", QUnit, { + name: this.testName, + module: this.module + }); + + // allow utility functions to access the current test environment + // TODO why?? + QUnit.current_testEnvironment = this.testEnvironment; + + if ( !config.pollution ) { + saveGlobal(); + } + if ( config.notrycatch ) { + this.testEnvironment.setup.call( this.testEnvironment ); + return; + } + try { + this.testEnvironment.setup.call( this.testEnvironment ); + } catch( e ) { + QUnit.pushFailure( "Setup failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) ); + } + }, + run: function() { + config.current = this; + + var running = id( "qunit-testresult" ); + + if ( running ) { + running.innerHTML = "Running:
      " + this.name; + } + + if ( this.async ) { + QUnit.stop(); + } + + if ( config.notrycatch ) { + this.callback.call( this.testEnvironment, QUnit.assert ); + return; + } + + try { + this.callback.call( this.testEnvironment, QUnit.assert ); + } catch( e ) { + QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + " " + this.stack + ": " + e.message, extractStacktrace( e, 0 ) ); + // else next test will carry the responsibility + saveGlobal(); + + // Restart the tests if they're blocking + if ( config.blocking ) { + QUnit.start(); + } + } + }, + teardown: function() { + config.current = this; + if ( config.notrycatch ) { + this.testEnvironment.teardown.call( this.testEnvironment ); + return; + } else { + try { + this.testEnvironment.teardown.call( this.testEnvironment ); + } catch( e ) { + QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) ); + } + } + checkPollution(); + }, + finish: function() { + config.current = this; + if ( config.requireExpects && this.expected == null ) { + QUnit.pushFailure( "Expected number of assertions to be defined, but expect() was not called.", this.stack ); + } else if ( this.expected != null && this.expected != this.assertions.length ) { + QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run", this.stack ); + } else if ( this.expected == null && !this.assertions.length ) { + QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions.", this.stack ); + } + + var assertion, a, b, i, li, ol, + test = this, + good = 0, + bad = 0, + tests = id( "qunit-tests" ); + + config.stats.all += this.assertions.length; + config.moduleStats.all += this.assertions.length; + + if ( tests ) { + ol = document.createElement( "ol" ); + + for ( i = 0; i < this.assertions.length; i++ ) { + assertion = this.assertions[i]; + + li = document.createElement( "li" ); + li.className = assertion.result ? "pass" : "fail"; + li.innerHTML = assertion.message || ( assertion.result ? "okay" : "failed" ); + ol.appendChild( li ); + + if ( assertion.result ) { + good++; + } else { + bad++; + config.stats.bad++; + config.moduleStats.bad++; + } + } + + // store result when possible + if ( QUnit.config.reorder && defined.sessionStorage ) { + if ( bad ) { + sessionStorage.setItem( "qunit-test-" + this.module + "-" + this.testName, bad ); + } else { + sessionStorage.removeItem( "qunit-test-" + this.module + "-" + this.testName ); + } + } + + if ( bad === 0 ) { + ol.style.display = "none"; + } + + // `b` initialized at top of scope + b = document.createElement( "strong" ); + b.innerHTML = this.name + " (" + bad + ", " + good + ", " + this.assertions.length + ")"; + + addEvent(b, "click", function() { + var next = b.nextSibling.nextSibling, + display = next.style.display; + next.style.display = display === "none" ? "block" : "none"; + }); + + addEvent(b, "dblclick", function( e ) { + var target = e && e.target ? e.target : window.event.srcElement; + if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { + target = target.parentNode; + } + if ( window.location && target.nodeName.toLowerCase() === "strong" ) { + window.location = QUnit.url({ testNumber: test.testNumber }); + } + }); + + // `li` initialized at top of scope + li = id( this.id ); + li.className = bad ? "fail" : "pass"; + li.removeChild( li.firstChild ); + a = li.firstChild; + li.appendChild( b ); + li.appendChild ( a ); + li.appendChild( ol ); + + } else { + for ( i = 0; i < this.assertions.length; i++ ) { + if ( !this.assertions[i].result ) { + bad++; + config.stats.bad++; + config.moduleStats.bad++; + } + } + } + + runLoggingCallbacks( "testDone", QUnit, { + name: this.testName, + module: this.module, + failed: bad, + passed: this.assertions.length - bad, + total: this.assertions.length + }); + + QUnit.reset(); + + config.current = undefined; + }, + + queue: function() { + var bad, + test = this; + + synchronize(function() { + test.init(); + }); + function run() { + // each of these can by async + synchronize(function() { + test.setup(); + }); + synchronize(function() { + test.run(); + }); + synchronize(function() { + test.teardown(); + }); + synchronize(function() { + test.finish(); + }); + } + + // `bad` initialized at top of scope + // defer when previous test run passed, if storage is available + bad = QUnit.config.reorder && defined.sessionStorage && + +sessionStorage.getItem( "qunit-test-" + this.module + "-" + this.testName ); + + if ( bad ) { + run(); + } else { + synchronize( run, true ); + } + } +}; + +// Root QUnit object. +// `QUnit` initialized at top of scope +QUnit = { + + // call on start of module test to prepend name to all tests + module: function( name, testEnvironment ) { + config.currentModule = name; + config.currentModuleTestEnvironment = testEnvironment; + config.modules[name] = true; + }, + + asyncTest: function( testName, expected, callback ) { + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + + QUnit.test( testName, expected, callback, true ); + }, + + test: function( testName, expected, callback, async ) { + var test, + name = "" + escapeInnerText( testName ) + ""; + + if ( arguments.length === 2 ) { + callback = expected; + expected = null; + } + + if ( config.currentModule ) { + name = "" + config.currentModule + ": " + name; + } + + test = new Test({ + name: name, + testName: testName, + expected: expected, + async: async, + callback: callback, + module: config.currentModule, + moduleTestEnvironment: config.currentModuleTestEnvironment, + stack: sourceFromStacktrace( 2 ) + }); + + if ( !validTest( test ) ) { + return; + } + + test.queue(); + }, + + // Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. + expect: function( asserts ) { + if (arguments.length === 1) { + config.current.expected = asserts; + } else { + return config.current.expected; + } + }, + + start: function( count ) { + config.semaphore -= count || 1; + // don't start until equal number of stop-calls + if ( config.semaphore > 0 ) { + return; + } + // ignore if start is called more often then stop + if ( config.semaphore < 0 ) { + config.semaphore = 0; + } + // A slight delay, to avoid any current callbacks + if ( defined.setTimeout ) { + window.setTimeout(function() { + if ( config.semaphore > 0 ) { + return; + } + if ( config.timeout ) { + clearTimeout( config.timeout ); + } + + config.blocking = false; + process( true ); + }, 13); + } else { + config.blocking = false; + process( true ); + } + }, + + stop: function( count ) { + config.semaphore += count || 1; + config.blocking = true; + + if ( config.testTimeout && defined.setTimeout ) { + clearTimeout( config.timeout ); + config.timeout = window.setTimeout(function() { + QUnit.ok( false, "Test timed out" ); + config.semaphore = 1; + QUnit.start(); + }, config.testTimeout ); + } + } +}; + +// Asssert helpers +// All of these must call either QUnit.push() or manually do: +// - runLoggingCallbacks( "log", .. ); +// - config.current.assertions.push({ .. }); +QUnit.assert = { + /** + * Asserts rough true-ish result. + * @name ok + * @function + * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); + */ + ok: function( result, msg ) { + if ( !config.current ) { + throw new Error( "ok() assertion outside test context, was " + sourceFromStacktrace(2) ); + } + result = !!result; + + var source, + details = { + module: config.current.module, + name: config.current.testName, + result: result, + message: msg + }; + + msg = escapeInnerText( msg || (result ? "okay" : "failed" ) ); + msg = "" + msg + ""; + + if ( !result ) { + source = sourceFromStacktrace( 2 ); + if ( source ) { + details.source = source; + msg += "
      Source:
      " + escapeInnerText( source ) + "
      "; + } + } + runLoggingCallbacks( "log", QUnit, details ); + config.current.assertions.push({ + result: result, + message: msg + }); + }, + + /** + * Assert that the first two arguments are equal, with an optional message. + * Prints out both actual and expected values. + * @name equal + * @function + * @example equal( format( "Received {0} bytes.", 2), "Received 2 bytes.", "format() replaces {0} with next argument" ); + */ + equal: function( actual, expected, message ) { + QUnit.push( expected == actual, actual, expected, message ); + }, + + /** + * @name notEqual + * @function + */ + notEqual: function( actual, expected, message ) { + QUnit.push( expected != actual, actual, expected, message ); + }, + + /** + * @name deepEqual + * @function + */ + deepEqual: function( actual, expected, message ) { + QUnit.push( QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name notDeepEqual + * @function + */ + notDeepEqual: function( actual, expected, message ) { + QUnit.push( !QUnit.equiv(actual, expected), actual, expected, message ); + }, + + /** + * @name strictEqual + * @function + */ + strictEqual: function( actual, expected, message ) { + QUnit.push( expected === actual, actual, expected, message ); + }, + + /** + * @name notStrictEqual + * @function + */ + notStrictEqual: function( actual, expected, message ) { + QUnit.push( expected !== actual, actual, expected, message ); + }, + + throws: function( block, expected, message ) { + var actual, + ok = false; + + // 'expected' is optional + if ( typeof expected === "string" ) { + message = expected; + expected = null; + } + + config.current.ignoreGlobalErrors = true; + try { + block.call( config.current.testEnvironment ); + } catch (e) { + actual = e; + } + config.current.ignoreGlobalErrors = false; + + if ( actual ) { + // we don't want to validate thrown error + if ( !expected ) { + ok = true; + // expected is a regexp + } else if ( QUnit.objectType( expected ) === "regexp" ) { + ok = expected.test( actual ); + // expected is a constructor + } else if ( actual instanceof expected ) { + ok = true; + // expected is a validation function which returns true is validation passed + } else if ( expected.call( {}, actual ) === true ) { + ok = true; + } + + QUnit.push( ok, actual, null, message ); + } else { + QUnit.pushFailure( message, null, 'No exception was thrown.' ); + } + } +}; + +/** + * @deprecate since 1.8.0 + * Kept assertion helpers in root for backwards compatibility + */ +extend( QUnit, QUnit.assert ); + +/** + * @deprecated since 1.9.0 + * Kept global "raises()" for backwards compatibility + */ +QUnit.raises = QUnit.assert.throws; + +/** + * @deprecated since 1.0.0, replaced with error pushes since 1.3.0 + * Kept to avoid TypeErrors for undefined methods. + */ +QUnit.equals = function() { + QUnit.push( false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead" ); +}; +QUnit.same = function() { + QUnit.push( false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead" ); +}; + +// We want access to the constructor's prototype +(function() { + function F() {} + F.prototype = QUnit; + QUnit = new F(); + // Make F QUnit's constructor so that we can add to the prototype later + QUnit.constructor = F; +}()); + +/** + * Config object: Maintain internal state + * Later exposed as QUnit.config + * `config` initialized at top of scope + */ +config = { + // The queue of tests to run + queue: [], + + // block until document ready + blocking: true, + + // when enabled, show only failing tests + // gets persisted through sessionStorage and can be changed in UI via checkbox + hidepassed: false, + + // by default, run previously failed tests first + // very useful in combination with "Hide passed tests" checked + reorder: true, + + // by default, modify document.title when suite is done + altertitle: true, + + // when enabled, all tests must call expect() + requireExpects: false, + + // add checkboxes that are persisted in the query-string + // when enabled, the id is set to `true` as a `QUnit.config` property + urlConfig: [ + { + id: "noglobals", + label: "Check for Globals", + tooltip: "Enabling this will test if any test introduces new properties on the `window` object. Stored as query-strings." + }, + { + id: "notrycatch", + label: "No try-catch", + tooltip: "Enabling this will run tests outside of a try-catch block. Makes debugging exceptions in IE reasonable. Stored as query-strings." + } + ], + + // Set of all modules. + modules: {}, + + // logging callback queues + begin: [], + done: [], + log: [], + testStart: [], + testDone: [], + moduleStart: [], + moduleDone: [] +}; + +// Initialize more QUnit.config and QUnit.urlParams +(function() { + var i, + location = window.location || { search: "", protocol: "file:" }, + params = location.search.slice( 1 ).split( "&" ), + length = params.length, + urlParams = {}, + current; + + if ( params[ 0 ] ) { + for ( i = 0; i < length; i++ ) { + current = params[ i ].split( "=" ); + current[ 0 ] = decodeURIComponent( current[ 0 ] ); + // allow just a key to turn on a flag, e.g., test.html?noglobals + current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; + urlParams[ current[ 0 ] ] = current[ 1 ]; + } + } + + QUnit.urlParams = urlParams; + + // String search anywhere in moduleName+testName + config.filter = urlParams.filter; + + // Exact match of the module name + config.module = urlParams.module; + + config.testNumber = parseInt( urlParams.testNumber, 10 ) || null; + + // Figure out if we're running the tests from a server or not + QUnit.isLocal = location.protocol === "file:"; +}()); + +// Export global variables, unless an 'exports' object exists, +// in that case we assume we're in CommonJS (dealt with on the bottom of the script) +if ( typeof exports === "undefined" ) { + extend( window, QUnit ); + + // Expose QUnit object + window.QUnit = QUnit; +} + +// Extend QUnit object, +// these after set here because they should not be exposed as global functions +extend( QUnit, { + config: config, + + // Initialize the configuration options + init: function() { + extend( config, { + stats: { all: 0, bad: 0 }, + moduleStats: { all: 0, bad: 0 }, + started: +new Date(), + updateRate: 1000, + blocking: false, + autostart: true, + autorun: false, + filter: "", + queue: [], + semaphore: 0 + }); + + var tests, banner, result, + qunit = id( "qunit" ); + + if ( qunit ) { + qunit.innerHTML = + "

      " + escapeInnerText( document.title ) + "

      " + + "

      " + + "
      " + + "

      " + + "
        "; + } + + tests = id( "qunit-tests" ); + banner = id( "qunit-banner" ); + result = id( "qunit-testresult" ); + + if ( tests ) { + tests.innerHTML = ""; + } + + if ( banner ) { + banner.className = ""; + } + + if ( result ) { + result.parentNode.removeChild( result ); + } + + if ( tests ) { + result = document.createElement( "p" ); + result.id = "qunit-testresult"; + result.className = "result"; + tests.parentNode.insertBefore( result, tests ); + result.innerHTML = "Running...
         "; + } + }, + + // Resets the test setup. Useful for tests that modify the DOM. + reset: function() { + var fixture = id( "qunit-fixture" ); + if ( fixture ) { + fixture.innerHTML = config.fixture; + } + }, + + // Trigger an event on an element. + // @example triggerEvent( document.body, "click" ); + triggerEvent: function( elem, type, event ) { + if ( document.createEvent ) { + event = document.createEvent( "MouseEvents" ); + event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, + 0, 0, 0, 0, 0, false, false, false, false, 0, null); + + elem.dispatchEvent( event ); + } else if ( elem.fireEvent ) { + elem.fireEvent( "on" + type ); + } + }, + + // Safe object type checking + is: function( type, obj ) { + return QUnit.objectType( obj ) == type; + }, + + objectType: function( obj ) { + if ( typeof obj === "undefined" ) { + return "undefined"; + // consider: typeof null === object + } + if ( obj === null ) { + return "null"; + } + + var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || ""; + + switch ( type ) { + case "Number": + if ( isNaN(obj) ) { + return "nan"; + } + return "number"; + case "String": + case "Boolean": + case "Array": + case "Date": + case "RegExp": + case "Function": + return type.toLowerCase(); + } + if ( typeof obj === "object" ) { + return "object"; + } + return undefined; + }, + + push: function( result, actual, expected, message ) { + if ( !config.current ) { + throw new Error( "assertion outside test context, was " + sourceFromStacktrace() ); + } + + var output, source, + details = { + module: config.current.module, + name: config.current.testName, + result: result, + message: message, + actual: actual, + expected: expected + }; + + message = escapeInnerText( message ) || ( result ? "okay" : "failed" ); + message = "" + message + ""; + output = message; + + if ( !result ) { + expected = escapeInnerText( QUnit.jsDump.parse(expected) ); + actual = escapeInnerText( QUnit.jsDump.parse(actual) ); + output += ""; + + if ( actual != expected ) { + output += ""; + output += ""; + } + + source = sourceFromStacktrace(); + + if ( source ) { + details.source = source; + output += ""; + } + + output += "
        Expected:
        " + expected + "
        Result:
        " + actual + "
        Diff:
        " + QUnit.diff( expected, actual ) + "
        Source:
        " + escapeInnerText( source ) + "
        "; + } + + runLoggingCallbacks( "log", QUnit, details ); + + config.current.assertions.push({ + result: !!result, + message: output + }); + }, + + pushFailure: function( message, source, actual ) { + if ( !config.current ) { + throw new Error( "pushFailure() assertion outside test context, was " + sourceFromStacktrace(2) ); + } + + var output, + details = { + module: config.current.module, + name: config.current.testName, + result: false, + message: message + }; + + message = escapeInnerText( message ) || "error"; + message = "" + message + ""; + output = message; + + output += ""; + + if ( actual ) { + output += ""; + } + + if ( source ) { + details.source = source; + output += ""; + } + + output += "
        Result:
        " + escapeInnerText( actual ) + "
        Source:
        " + escapeInnerText( source ) + "
        "; + + runLoggingCallbacks( "log", QUnit, details ); + + config.current.assertions.push({ + result: false, + message: output + }); + }, + + url: function( params ) { + params = extend( extend( {}, QUnit.urlParams ), params ); + var key, + querystring = "?"; + + for ( key in params ) { + if ( !hasOwn.call( params, key ) ) { + continue; + } + querystring += encodeURIComponent( key ) + "=" + + encodeURIComponent( params[ key ] ) + "&"; + } + return window.location.pathname + querystring.slice( 0, -1 ); + }, + + extend: extend, + id: id, + addEvent: addEvent + // load, equiv, jsDump, diff: Attached later +}); + +/** + * @deprecated: Created for backwards compatibility with test runner that set the hook function + * into QUnit.{hook}, instead of invoking it and passing the hook function. + * QUnit.constructor is set to the empty F() above so that we can add to it's prototype here. + * Doing this allows us to tell if the following methods have been overwritten on the actual + * QUnit object. + */ +extend( QUnit.constructor.prototype, { + + // Logging callbacks; all receive a single argument with the listed properties + // run test/logs.html for any related changes + begin: registerLoggingCallback( "begin" ), + + // done: { failed, passed, total, runtime } + done: registerLoggingCallback( "done" ), + + // log: { result, actual, expected, message } + log: registerLoggingCallback( "log" ), + + // testStart: { name } + testStart: registerLoggingCallback( "testStart" ), + + // testDone: { name, failed, passed, total } + testDone: registerLoggingCallback( "testDone" ), + + // moduleStart: { name } + moduleStart: registerLoggingCallback( "moduleStart" ), + + // moduleDone: { name, failed, passed, total } + moduleDone: registerLoggingCallback( "moduleDone" ) +}); + +if ( typeof document === "undefined" || document.readyState === "complete" ) { + config.autorun = true; +} + +QUnit.load = function() { + runLoggingCallbacks( "begin", QUnit, {} ); + + // Initialize the config, saving the execution queue + var banner, filter, i, label, len, main, ol, toolbar, userAgent, val, urlConfigCheckboxes, moduleFilter, + numModules = 0, + moduleFilterHtml = "", + urlConfigHtml = "", + oldconfig = extend( {}, config ); + + QUnit.init(); + extend(config, oldconfig); + + config.blocking = false; + + len = config.urlConfig.length; + + for ( i = 0; i < len; i++ ) { + val = config.urlConfig[i]; + if ( typeof val === "string" ) { + val = { + id: val, + label: val, + tooltip: "[no tooltip available]" + }; + } + config[ val.id ] = QUnit.urlParams[ val.id ]; + urlConfigHtml += ""; + } + + moduleFilterHtml += ""; + + // `userAgent` initialized at top of scope + userAgent = id( "qunit-userAgent" ); + if ( userAgent ) { + userAgent.innerHTML = navigator.userAgent; + } + + // `banner` initialized at top of scope + banner = id( "qunit-header" ); + if ( banner ) { + banner.innerHTML = "" + banner.innerHTML + " "; + } + + // `toolbar` initialized at top of scope + toolbar = id( "qunit-testrunner-toolbar" ); + if ( toolbar ) { + // `filter` initialized at top of scope + filter = document.createElement( "input" ); + filter.type = "checkbox"; + filter.id = "qunit-filter-pass"; + + addEvent( filter, "click", function() { + var tmp, + ol = document.getElementById( "qunit-tests" ); + + if ( filter.checked ) { + ol.className = ol.className + " hidepass"; + } else { + tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; + ol.className = tmp.replace( / hidepass /, " " ); + } + if ( defined.sessionStorage ) { + if (filter.checked) { + sessionStorage.setItem( "qunit-filter-passed-tests", "true" ); + } else { + sessionStorage.removeItem( "qunit-filter-passed-tests" ); + } + } + }); + + if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem( "qunit-filter-passed-tests" ) ) { + filter.checked = true; + // `ol` initialized at top of scope + ol = document.getElementById( "qunit-tests" ); + ol.className = ol.className + " hidepass"; + } + toolbar.appendChild( filter ); + + // `label` initialized at top of scope + label = document.createElement( "label" ); + label.setAttribute( "for", "qunit-filter-pass" ); + label.setAttribute( "title", "Only show tests and assertons that fail. Stored in sessionStorage." ); + label.innerHTML = "Hide passed tests"; + toolbar.appendChild( label ); + + urlConfigCheckboxes = document.createElement( 'span' ); + urlConfigCheckboxes.innerHTML = urlConfigHtml; + addEvent( urlConfigCheckboxes, "change", function( event ) { + var params = {}; + params[ event.target.name ] = event.target.checked ? true : undefined; + window.location = QUnit.url( params ); + }); + toolbar.appendChild( urlConfigCheckboxes ); + + if (numModules > 1) { + moduleFilter = document.createElement( 'span' ); + moduleFilter.setAttribute( 'id', 'qunit-modulefilter-container' ); + moduleFilter.innerHTML = moduleFilterHtml; + addEvent( moduleFilter, "change", function() { + var selectBox = moduleFilter.getElementsByTagName("select")[0], + selectedModule = decodeURIComponent(selectBox.options[selectBox.selectedIndex].value); + + window.location = QUnit.url( { module: ( selectedModule === "" ) ? undefined : selectedModule } ); + }); + toolbar.appendChild(moduleFilter); + } + } + + // `main` initialized at top of scope + main = id( "qunit-fixture" ); + if ( main ) { + config.fixture = main.innerHTML; + } + + if ( config.autostart ) { + QUnit.start(); + } +}; + +addEvent( window, "load", QUnit.load ); + +// `onErrorFnPrev` initialized at top of scope +// Preserve other handlers +onErrorFnPrev = window.onerror; + +// Cover uncaught exceptions +// Returning true will surpress the default browser handler, +// returning false will let it run. +window.onerror = function ( error, filePath, linerNr ) { + var ret = false; + if ( onErrorFnPrev ) { + ret = onErrorFnPrev( error, filePath, linerNr ); + } + + // Treat return value as window.onerror itself does, + // Only do our handling if not surpressed. + if ( ret !== true ) { + if ( QUnit.config.current ) { + if ( QUnit.config.current.ignoreGlobalErrors ) { + return true; + } + QUnit.pushFailure( error, filePath + ":" + linerNr ); + } else { + QUnit.test( "global failure", extend( function() { + QUnit.pushFailure( error, filePath + ":" + linerNr ); + }, { validTest: validTest } ) ); + } + return false; + } + + return ret; +}; + +function done() { + config.autorun = true; + + // Log the last module results + if ( config.currentModule ) { + runLoggingCallbacks( "moduleDone", QUnit, { + name: config.currentModule, + failed: config.moduleStats.bad, + passed: config.moduleStats.all - config.moduleStats.bad, + total: config.moduleStats.all + }); + } + + var i, key, + banner = id( "qunit-banner" ), + tests = id( "qunit-tests" ), + runtime = +new Date() - config.started, + passed = config.stats.all - config.stats.bad, + html = [ + "Tests completed in ", + runtime, + " milliseconds.
        ", + "", + passed, + " tests of ", + config.stats.all, + " passed, ", + config.stats.bad, + " failed." + ].join( "" ); + + if ( banner ) { + banner.className = ( config.stats.bad ? "qunit-fail" : "qunit-pass" ); + } + + if ( tests ) { + id( "qunit-testresult" ).innerHTML = html; + } + + if ( config.altertitle && typeof document !== "undefined" && document.title ) { + // show ✖ for good, ✔ for bad suite result in title + // use escape sequences in case file gets loaded with non-utf-8-charset + document.title = [ + ( config.stats.bad ? "\u2716" : "\u2714" ), + document.title.replace( /^[\u2714\u2716] /i, "" ) + ].join( " " ); + } + + // clear own sessionStorage items if all tests passed + if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) { + // `key` & `i` initialized at top of scope + for ( i = 0; i < sessionStorage.length; i++ ) { + key = sessionStorage.key( i++ ); + if ( key.indexOf( "qunit-test-" ) === 0 ) { + sessionStorage.removeItem( key ); + } + } + } + + // scroll back to top to show results + if ( window.scrollTo ) { + window.scrollTo(0, 0); + } + + runLoggingCallbacks( "done", QUnit, { + failed: config.stats.bad, + passed: passed, + total: config.stats.all, + runtime: runtime + }); +} + +/** @return Boolean: true if this test should be ran */ +function validTest( test ) { + var include, + filter = config.filter && config.filter.toLowerCase(), + module = config.module && config.module.toLowerCase(), + fullName = (test.module + ": " + test.testName).toLowerCase(); + + // Internally-generated tests are always valid + if ( test.callback && test.callback.validTest === validTest ) { + delete test.callback.validTest; + return true; + } + + if ( config.testNumber ) { + return test.testNumber === config.testNumber; + } + + if ( module && ( !test.module || test.module.toLowerCase() !== module ) ) { + return false; + } + + if ( !filter ) { + return true; + } + + include = filter.charAt( 0 ) !== "!"; + if ( !include ) { + filter = filter.slice( 1 ); + } + + // If the filter matches, we need to honour include + if ( fullName.indexOf( filter ) !== -1 ) { + return include; + } + + // Otherwise, do the opposite + return !include; +} + +// so far supports only Firefox, Chrome and Opera (buggy), Safari (for real exceptions) +// Later Safari and IE10 are supposed to support error.stack as well +// See also https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error/Stack +function extractStacktrace( e, offset ) { + offset = offset === undefined ? 3 : offset; + + var stack, include, i, regex; + + if ( e.stacktrace ) { + // Opera + return e.stacktrace.split( "\n" )[ offset + 3 ]; + } else if ( e.stack ) { + // Firefox, Chrome + stack = e.stack.split( "\n" ); + if (/^error$/i.test( stack[0] ) ) { + stack.shift(); + } + if ( fileName ) { + include = []; + for ( i = offset; i < stack.length; i++ ) { + if ( stack[ i ].indexOf( fileName ) != -1 ) { + break; + } + include.push( stack[ i ] ); + } + if ( include.length ) { + return include.join( "\n" ); + } + } + return stack[ offset ]; + } else if ( e.sourceURL ) { + // Safari, PhantomJS + // hopefully one day Safari provides actual stacktraces + // exclude useless self-reference for generated Error objects + if ( /qunit.js$/.test( e.sourceURL ) ) { + return; + } + // for actual exceptions, this is useful + return e.sourceURL + ":" + e.line; + } +} +function sourceFromStacktrace( offset ) { + try { + throw new Error(); + } catch ( e ) { + return extractStacktrace( e, offset ); + } +} + +function escapeInnerText( s ) { + if ( !s ) { + return ""; + } + s = s + ""; + return s.replace( /[\&<>]/g, function( s ) { + switch( s ) { + case "&": return "&"; + case "<": return "<"; + case ">": return ">"; + default: return s; + } + }); +} + +function synchronize( callback, last ) { + config.queue.push( callback ); + + if ( config.autorun && !config.blocking ) { + process( last ); + } +} + +function process( last ) { + function next() { + process( last ); + } + var start = new Date().getTime(); + config.depth = config.depth ? config.depth + 1 : 1; + + while ( config.queue.length && !config.blocking ) { + if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { + config.queue.shift()(); + } else { + window.setTimeout( next, 13 ); + break; + } + } + config.depth--; + if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { + done(); + } +} + +function saveGlobal() { + config.pollution = []; + + if ( config.noglobals ) { + for ( var key in window ) { + // in Opera sometimes DOM element ids show up here, ignore them + if ( !hasOwn.call( window, key ) || /^qunit-test-output/.test( key ) ) { + continue; + } + config.pollution.push( key ); + } + } +} + +function checkPollution( name ) { + var newGlobals, + deletedGlobals, + old = config.pollution; + + saveGlobal(); + + newGlobals = diff( config.pollution, old ); + if ( newGlobals.length > 0 ) { + QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") ); + } + + deletedGlobals = diff( old, config.pollution ); + if ( deletedGlobals.length > 0 ) { + QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") ); + } +} + +// returns a new Array with the elements that are in a but not in b +function diff( a, b ) { + var i, j, + result = a.slice(); + + for ( i = 0; i < result.length; i++ ) { + for ( j = 0; j < b.length; j++ ) { + if ( result[i] === b[j] ) { + result.splice( i, 1 ); + i--; + break; + } + } + } + return result; +} + +function extend( a, b ) { + for ( var prop in b ) { + if ( b[ prop ] === undefined ) { + delete a[ prop ]; + + // Avoid "Member not found" error in IE8 caused by setting window.constructor + } else if ( prop !== "constructor" || a !== window ) { + a[ prop ] = b[ prop ]; + } + } + + return a; +} + +function addEvent( elem, type, fn ) { + if ( elem.addEventListener ) { + elem.addEventListener( type, fn, false ); + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, fn ); + } else { + fn(); + } +} + +function id( name ) { + return !!( typeof document !== "undefined" && document && document.getElementById ) && + document.getElementById( name ); +} + +function registerLoggingCallback( key ) { + return function( callback ) { + config[key].push( callback ); + }; +} + +// Supports deprecated method of completely overwriting logging callbacks +function runLoggingCallbacks( key, scope, args ) { + //debugger; + var i, callbacks; + if ( QUnit.hasOwnProperty( key ) ) { + QUnit[ key ].call(scope, args ); + } else { + callbacks = config[ key ]; + for ( i = 0; i < callbacks.length; i++ ) { + callbacks[ i ].call( scope, args ); + } + } +} + +// Test for equality any JavaScript type. +// Author: Philippe Rathé +QUnit.equiv = (function() { + + // Call the o related callback with the given arguments. + function bindCallbacks( o, callbacks, args ) { + var prop = QUnit.objectType( o ); + if ( prop ) { + if ( QUnit.objectType( callbacks[ prop ] ) === "function" ) { + return callbacks[ prop ].apply( callbacks, args ); + } else { + return callbacks[ prop ]; // or undefined + } + } + } + + // the real equiv function + var innerEquiv, + // stack to decide between skip/abort functions + callers = [], + // stack to avoiding loops from circular referencing + parents = [], + + getProto = Object.getPrototypeOf || function ( obj ) { + return obj.__proto__; + }, + callbacks = (function () { + + // for string, boolean, number and null + function useStrictEquality( b, a ) { + if ( b instanceof a.constructor || a instanceof b.constructor ) { + // to catch short annotaion VS 'new' annotation of a + // declaration + // e.g. var i = 1; + // var j = new Number(1); + return a == b; + } else { + return a === b; + } + } + + return { + "string": useStrictEquality, + "boolean": useStrictEquality, + "number": useStrictEquality, + "null": useStrictEquality, + "undefined": useStrictEquality, + + "nan": function( b ) { + return isNaN( b ); + }, + + "date": function( b, a ) { + return QUnit.objectType( b ) === "date" && a.valueOf() === b.valueOf(); + }, + + "regexp": function( b, a ) { + return QUnit.objectType( b ) === "regexp" && + // the regex itself + a.source === b.source && + // and its modifers + a.global === b.global && + // (gmi) ... + a.ignoreCase === b.ignoreCase && + a.multiline === b.multiline && + a.sticky === b.sticky; + }, + + // - skip when the property is a method of an instance (OOP) + // - abort otherwise, + // initial === would have catch identical references anyway + "function": function() { + var caller = callers[callers.length - 1]; + return caller !== Object && typeof caller !== "undefined"; + }, + + "array": function( b, a ) { + var i, j, len, loop; + + // b could be an object literal here + if ( QUnit.objectType( b ) !== "array" ) { + return false; + } + + len = a.length; + if ( len !== b.length ) { + // safe and faster + return false; + } + + // track reference to avoid circular references + parents.push( a ); + for ( i = 0; i < len; i++ ) { + loop = false; + for ( j = 0; j < parents.length; j++ ) { + if ( parents[j] === a[i] ) { + loop = true;// dont rewalk array + } + } + if ( !loop && !innerEquiv(a[i], b[i]) ) { + parents.pop(); + return false; + } + } + parents.pop(); + return true; + }, + + "object": function( b, a ) { + var i, j, loop, + // Default to true + eq = true, + aProperties = [], + bProperties = []; + + // comparing constructors is more strict than using + // instanceof + if ( a.constructor !== b.constructor ) { + // Allow objects with no prototype to be equivalent to + // objects with Object as their constructor. + if ( !(( getProto(a) === null && getProto(b) === Object.prototype ) || + ( getProto(b) === null && getProto(a) === Object.prototype ) ) ) { + return false; + } + } + + // stack constructor before traversing properties + callers.push( a.constructor ); + // track reference to avoid circular references + parents.push( a ); + + for ( i in a ) { // be strict: don't ensures hasOwnProperty + // and go deep + loop = false; + for ( j = 0; j < parents.length; j++ ) { + if ( parents[j] === a[i] ) { + // don't go down the same path twice + loop = true; + } + } + aProperties.push(i); // collect a's properties + + if (!loop && !innerEquiv( a[i], b[i] ) ) { + eq = false; + break; + } + } + + callers.pop(); // unstack, we are done + parents.pop(); + + for ( i in b ) { + bProperties.push( i ); // collect b's properties + } + + // Ensures identical properties name + return eq && innerEquiv( aProperties.sort(), bProperties.sort() ); + } + }; + }()); + + innerEquiv = function() { // can take multiple arguments + var args = [].slice.apply( arguments ); + if ( args.length < 2 ) { + return true; // end transition + } + + return (function( a, b ) { + if ( a === b ) { + return true; // catch the most you can + } else if ( a === null || b === null || typeof a === "undefined" || + typeof b === "undefined" || + QUnit.objectType(a) !== QUnit.objectType(b) ) { + return false; // don't lose time with error prone cases + } else { + return bindCallbacks(a, callbacks, [ b, a ]); + } + + // apply transition with (1..n) arguments + }( args[0], args[1] ) && arguments.callee.apply( this, args.splice(1, args.length - 1 )) ); + }; + + return innerEquiv; +}()); + +/** + * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | + * http://flesler.blogspot.com Licensed under BSD + * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 + * + * @projectDescription Advanced and extensible data dumping for Javascript. + * @version 1.0.0 + * @author Ariel Flesler + * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} + */ +QUnit.jsDump = (function() { + function quote( str ) { + return '"' + str.toString().replace( /"/g, '\\"' ) + '"'; + } + function literal( o ) { + return o + ""; + } + function join( pre, arr, post ) { + var s = jsDump.separator(), + base = jsDump.indent(), + inner = jsDump.indent(1); + if ( arr.join ) { + arr = arr.join( "," + s + inner ); + } + if ( !arr ) { + return pre + post; + } + return [ pre, inner + arr, base + post ].join(s); + } + function array( arr, stack ) { + var i = arr.length, ret = new Array(i); + this.up(); + while ( i-- ) { + ret[i] = this.parse( arr[i] , undefined , stack); + } + this.down(); + return join( "[", ret, "]" ); + } + + var reName = /^function (\w+)/, + jsDump = { + parse: function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance + stack = stack || [ ]; + var inStack, res, + parser = this.parsers[ type || this.typeOf(obj) ]; + + type = typeof parser; + inStack = inArray( obj, stack ); + + if ( inStack != -1 ) { + return "recursion(" + (inStack - stack.length) + ")"; + } + //else + if ( type == "function" ) { + stack.push( obj ); + res = parser.call( this, obj, stack ); + stack.pop(); + return res; + } + // else + return ( type == "string" ) ? parser : this.parsers.error; + }, + typeOf: function( obj ) { + var type; + if ( obj === null ) { + type = "null"; + } else if ( typeof obj === "undefined" ) { + type = "undefined"; + } else if ( QUnit.is( "regexp", obj) ) { + type = "regexp"; + } else if ( QUnit.is( "date", obj) ) { + type = "date"; + } else if ( QUnit.is( "function", obj) ) { + type = "function"; + } else if ( typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined" ) { + type = "window"; + } else if ( obj.nodeType === 9 ) { + type = "document"; + } else if ( obj.nodeType ) { + type = "node"; + } else if ( + // native arrays + toString.call( obj ) === "[object Array]" || + // NodeList objects + ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) + ) { + type = "array"; + } else { + type = typeof obj; + } + return type; + }, + separator: function() { + return this.multiline ? this.HTML ? "
        " : "\n" : this.HTML ? " " : " "; + }, + indent: function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing + if ( !this.multiline ) { + return ""; + } + var chr = this.indentChar; + if ( this.HTML ) { + chr = chr.replace( /\t/g, " " ).replace( / /g, " " ); + } + return new Array( this._depth_ + (extra||0) ).join(chr); + }, + up: function( a ) { + this._depth_ += a || 1; + }, + down: function( a ) { + this._depth_ -= a || 1; + }, + setParser: function( name, parser ) { + this.parsers[name] = parser; + }, + // The next 3 are exposed so you can use them + quote: quote, + literal: literal, + join: join, + // + _depth_: 1, + // This is the list of parsers, to modify them, use jsDump.setParser + parsers: { + window: "[Window]", + document: "[Document]", + error: "[ERROR]", //when no parser is found, shouldn"t happen + unknown: "[Unknown]", + "null": "null", + "undefined": "undefined", + "function": function( fn ) { + var ret = "function", + name = "name" in fn ? fn.name : (reName.exec(fn) || [])[1];//functions never have name in IE + + if ( name ) { + ret += " " + name; + } + ret += "( "; + + ret = [ ret, QUnit.jsDump.parse( fn, "functionArgs" ), "){" ].join( "" ); + return join( ret, QUnit.jsDump.parse(fn,"functionCode" ), "}" ); + }, + array: array, + nodelist: array, + "arguments": array, + object: function( map, stack ) { + var ret = [ ], keys, key, val, i; + QUnit.jsDump.up(); + if ( Object.keys ) { + keys = Object.keys( map ); + } else { + keys = []; + for ( key in map ) { + keys.push( key ); + } + } + keys.sort(); + for ( i = 0; i < keys.length; i++ ) { + key = keys[ i ]; + val = map[ key ]; + ret.push( QUnit.jsDump.parse( key, "key" ) + ": " + QUnit.jsDump.parse( val, undefined, stack ) ); + } + QUnit.jsDump.down(); + return join( "{", ret, "}" ); + }, + node: function( node ) { + var a, val, + open = QUnit.jsDump.HTML ? "<" : "<", + close = QUnit.jsDump.HTML ? ">" : ">", + tag = node.nodeName.toLowerCase(), + ret = open + tag; + + for ( a in QUnit.jsDump.DOMAttrs ) { + val = node[ QUnit.jsDump.DOMAttrs[a] ]; + if ( val ) { + ret += " " + a + "=" + QUnit.jsDump.parse( val, "attribute" ); + } + } + return ret + close + open + "/" + tag + close; + }, + functionArgs: function( fn ) {//function calls it internally, it's the arguments part of the function + var args, + l = fn.length; + + if ( !l ) { + return ""; + } + + args = new Array(l); + while ( l-- ) { + args[l] = String.fromCharCode(97+l);//97 is 'a' + } + return " " + args.join( ", " ) + " "; + }, + key: quote, //object calls it internally, the key part of an item in a map + functionCode: "[code]", //function calls it internally, it's the content of the function + attribute: quote, //node calls it internally, it's an html attribute value + string: quote, + date: quote, + regexp: literal, //regex + number: literal, + "boolean": literal + }, + DOMAttrs: { + //attributes to dump from nodes, name=>realName + id: "id", + name: "name", + "class": "className" + }, + HTML: false,//if true, entities are escaped ( <, >, \t, space and \n ) + indentChar: " ",//indentation unit + multiline: true //if true, items in a collection, are separated by a \n, else just a space. + }; + + return jsDump; +}()); + +// from Sizzle.js +function getText( elems ) { + var i, elem, + ret = ""; + + for ( i = 0; elems[i]; i++ ) { + elem = elems[i]; + + // Get the text from text nodes and CDATA nodes + if ( elem.nodeType === 3 || elem.nodeType === 4 ) { + ret += elem.nodeValue; + + // Traverse everything else, except comment nodes + } else if ( elem.nodeType !== 8 ) { + ret += getText( elem.childNodes ); + } + } + + return ret; +} + +// from jquery.js +function inArray( elem, array ) { + if ( array.indexOf ) { + return array.indexOf( elem ); + } + + for ( var i = 0, length = array.length; i < length; i++ ) { + if ( array[ i ] === elem ) { + return i; + } + } + + return -1; +} + +/* + * Javascript Diff Algorithm + * By John Resig (http://ejohn.org/) + * Modified by Chu Alan "sprite" + * + * Released under the MIT license. + * + * More Info: + * http://ejohn.org/projects/javascript-diff-algorithm/ + * + * Usage: QUnit.diff(expected, actual) + * + * QUnit.diff( "the quick brown fox jumped over", "the quick fox jumps over" ) == "the quick brown fox jumped jumps over" + */ +QUnit.diff = (function() { + function diff( o, n ) { + var i, + ns = {}, + os = {}; + + for ( i = 0; i < n.length; i++ ) { + if ( ns[ n[i] ] == null ) { + ns[ n[i] ] = { + rows: [], + o: null + }; + } + ns[ n[i] ].rows.push( i ); + } + + for ( i = 0; i < o.length; i++ ) { + if ( os[ o[i] ] == null ) { + os[ o[i] ] = { + rows: [], + n: null + }; + } + os[ o[i] ].rows.push( i ); + } + + for ( i in ns ) { + if ( !hasOwn.call( ns, i ) ) { + continue; + } + if ( ns[i].rows.length == 1 && typeof os[i] != "undefined" && os[i].rows.length == 1 ) { + n[ ns[i].rows[0] ] = { + text: n[ ns[i].rows[0] ], + row: os[i].rows[0] + }; + o[ os[i].rows[0] ] = { + text: o[ os[i].rows[0] ], + row: ns[i].rows[0] + }; + } + } + + for ( i = 0; i < n.length - 1; i++ ) { + if ( n[i].text != null && n[ i + 1 ].text == null && n[i].row + 1 < o.length && o[ n[i].row + 1 ].text == null && + n[ i + 1 ] == o[ n[i].row + 1 ] ) { + + n[ i + 1 ] = { + text: n[ i + 1 ], + row: n[i].row + 1 + }; + o[ n[i].row + 1 ] = { + text: o[ n[i].row + 1 ], + row: i + 1 + }; + } + } + + for ( i = n.length - 1; i > 0; i-- ) { + if ( n[i].text != null && n[ i - 1 ].text == null && n[i].row > 0 && o[ n[i].row - 1 ].text == null && + n[ i - 1 ] == o[ n[i].row - 1 ]) { + + n[ i - 1 ] = { + text: n[ i - 1 ], + row: n[i].row - 1 + }; + o[ n[i].row - 1 ] = { + text: o[ n[i].row - 1 ], + row: i - 1 + }; + } + } + + return { + o: o, + n: n + }; + } + + return function( o, n ) { + o = o.replace( /\s+$/, "" ); + n = n.replace( /\s+$/, "" ); + + var i, pre, + str = "", + out = diff( o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/) ), + oSpace = o.match(/\s+/g), + nSpace = n.match(/\s+/g); + + if ( oSpace == null ) { + oSpace = [ " " ]; + } + else { + oSpace.push( " " ); + } + + if ( nSpace == null ) { + nSpace = [ " " ]; + } + else { + nSpace.push( " " ); + } + + if ( out.n.length === 0 ) { + for ( i = 0; i < out.o.length; i++ ) { + str += "" + out.o[i] + oSpace[i] + ""; + } + } + else { + if ( out.n[0].text == null ) { + for ( n = 0; n < out.o.length && out.o[n].text == null; n++ ) { + str += "" + out.o[n] + oSpace[n] + ""; + } + } + + for ( i = 0; i < out.n.length; i++ ) { + if (out.n[i].text == null) { + str += "" + out.n[i] + nSpace[i] + ""; + } + else { + // `pre` initialized at top of scope + pre = ""; + + for ( n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++ ) { + pre += "" + out.o[n] + oSpace[n] + ""; + } + str += " " + out.n[i].text + nSpace[i] + pre; + } + } + } + + return str; + }; +}()); + +// for CommonJS enviroments, export everything +if ( typeof exports !== "undefined" ) { + extend(exports, QUnit); +} + +// get at whatever the global object is, like window in browsers +}( (function() {return this;}.call()) )); diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/LICENCE b/node/node_modules/grunt/node_modules/lodash/vendor/tar/LICENCE new file mode 100644 index 000000000..74489e2e2 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/LICENCE @@ -0,0 +1,25 @@ +Copyright (c) Isaac Z. Schlueter +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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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/node_modules/grunt/node_modules/lodash/vendor/tar/README.md b/node/node_modules/grunt/node_modules/lodash/vendor/tar/README.md new file mode 100644 index 000000000..7cfe3bbca --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/README.md @@ -0,0 +1,50 @@ +# node-tar + +Tar for Node.js. + +## Goals of this project + +1. Be able to parse and reasonably extract the contents of any tar file + created by any program that creates tar files, period. + + At least, this includes every version of: + + * bsdtar + * gnutar + * solaris posix tar + * Joerg Schilling's star ("Schilly tar") + +2. Create tar files that can be extracted by any of the following tar + programs: + + * bsdtar/libarchive version 2.6.2 + * gnutar 1.15 and above + * SunOS Posix tar + * Joerg Schilling's star ("Schilly tar") + +3. 100% test coverage. Speed is important. Correctness is slightly + more important. + +4. Create the kind of tar interface that Node users would want to use. + +5. Satisfy npm's needs for a portable tar implementation with a + JavaScript interface. + +6. No excuses. No complaining. No tolerance for failure. + +## But isn't there already a tar.js? + +Yes, there are a few. This one is going to be better, and it will be +fanatically maintained, because npm will depend on it. + +That's why I need to write it from scratch. Creating and extracting +tarballs is such a large part of what npm does, I simply can't have it +be a black box any longer. + +## Didn't you have something already? Where'd it go? + +It's in the "old" folder. It's not functional. Don't use it. + +It was a useful exploration to learn the issues involved, but like most +software of any reasonable complexity, node-tar won't be useful until +it's been written at least 3 times. diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/buffer-entry.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/buffer-entry.js new file mode 100644 index 000000000..c7b5a6e04 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/buffer-entry.js @@ -0,0 +1,30 @@ +// just like the Entry class, but it buffers the contents +// +// XXX It would be good to set a maximum BufferEntry filesize, +// since it eats up memory. In normal operation, +// these are only for long filenames or link names, which are +// rarely very big. + +module.exports = BufferEntry + +var inherits = require("../vendor/inherits/inherits.js") + , Entry = require("./entry.js") + +function BufferEntry () { + Entry.apply(this, arguments) + this._buffer = new Buffer(this.props.size) + this._offset = 0 + this.body = "" + this.on("end", function () { + this.body = this._buffer.toString().slice(0, -1) + }) +} + +// collect the bytes as they come in. +BufferEntry.prototype.write = function (c) { + c.copy(this._buffer, this._offset) + this._offset += c.length + Entry.prototype.write.call(this, c) +} + +inherits(BufferEntry, Entry) diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/entry-writer.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/entry-writer.js new file mode 100644 index 000000000..9d6a9b78b --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/entry-writer.js @@ -0,0 +1,169 @@ +module.exports = EntryWriter + +var tar = require("../tar.js") + , TarHeader = require("./header.js") + , Entry = require("./entry.js") + , inherits = require("../vendor/inherits/inherits.js") + , BlockStream = require("../vendor/block-stream/block-stream.js") + , ExtendedHeaderWriter + , Stream = require("stream").Stream + , EOF = {} + +inherits(EntryWriter, Stream) + +function EntryWriter (props) { + var me = this + + if (!(me instanceof EntryWriter)) { + return new EntryWriter(props) + } + + Stream.apply(this) + + me.writable = true + me.readable = true + + me._stream = new BlockStream(512) + + me._stream.on("data", function (c) { + me.emit("data", c) + }) + + me._stream.on("drain", function () { + me.emit("drain") + }) + + me._stream.on("end", function () { + me.emit("end") + me.emit("close") + }) + + me.props = props + if (props.type === "Directory") { + props.size = 0 + } + props.ustar = "ustar\0" + props.ustarver = "00" + me.path = props.path + + me._buffer = [] + me._didHeader = false + me._meta = false + + me.on("pipe", function () { + me._process() + }) +} + +EntryWriter.prototype.write = function (c) { + // console.error(".. ew write") + if (this._ended) return this.emit("error", new Error("write after end")) + this._buffer.push(c) + this._process() + this._needDrain = this._buffer.length > 0 + return !this._needDrain +} + +EntryWriter.prototype.end = function (c) { + // console.error(".. ew end") + if (c) this._buffer.push(c) + this._buffer.push(EOF) + this._ended = true + this._process() + this._needDrain = this._buffer.length > 0 +} + +EntryWriter.prototype.pause = function () { + // console.error(".. ew pause") + this._paused = true + this.emit("pause") +} + +EntryWriter.prototype.resume = function () { + // console.error(".. ew resume") + this._paused = false + this.emit("resume") + this._process() +} + +EntryWriter.prototype.add = function (entry) { + // console.error(".. ew add") + if (!this.parent) return this.emit("error", new Error("no parent")) + + // make sure that the _header and such is emitted, and clear out + // the _currentEntry link on the parent. + if (!this._ended) this.end() + + return this.parent.add(entry) +} + +EntryWriter.prototype._header = function () { + // console.error(".. ew header") + if (this._didHeader) return + this._didHeader = true + + var headerBlock = TarHeader.encode(this.props) + + if (this.props.needExtended && !this._meta) { + var me = this + + ExtendedHeaderWriter = ExtendedHeaderWriter || + require("./extended-header-writer.js") + + ExtendedHeaderWriter(this.props) + .on("data", function (c) { + me.emit("data", c) + }) + .on("error", function (er) { + me.emit("error", er) + }) + .end() + } + + // console.error(".. .. ew headerBlock emitting") + this.emit("data", headerBlock) + this.emit("header") +} + +EntryWriter.prototype._process = function () { + // console.error(".. .. ew process") + if (!this._didHeader && !this._meta) { + this._header() + } + + if (this._paused || this._processing) { + // console.error(".. .. .. paused=%j, processing=%j", this._paused, this._processing) + return + } + + this._processing = true + + var buf = this._buffer + for (var i = 0; i < buf.length; i ++) { + // console.error(".. .. .. i=%d", i) + + var c = buf[i] + + if (c === EOF) this._stream.end() + else this._stream.write(c) + + if (this._paused) { + // console.error(".. .. .. paused mid-emission") + this._processing = false + if (i < buf.length) { + this._needDrain = true + this._buffer = buf.slice(i + 1) + } + return + } + } + + // console.error(".. .. .. emitted") + this._buffer.length = 0 + this._processing = false + + // console.error(".. .. .. emitting drain") + this.emit("drain") +} + +EntryWriter.prototype.destroy = function () {} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/entry.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/entry.js new file mode 100644 index 000000000..6221ffd2c --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/entry.js @@ -0,0 +1,212 @@ +// A passthrough read/write stream that sets its properties +// based on a header, extendedHeader, and globalHeader +// +// Can be either a file system object of some sort, or +// a pax/ustar metadata entry. + +module.exports = Entry + +var TarHeader = require("./header.js") + , tar = require("../tar") + , assert = require("assert").ok + , Stream = require("stream").Stream + , inherits = require("../vendor/inherits/inherits.js") + , fstream = require("../vendor/fstream/fstream.js").Abstract + +function Entry (header, extended, global) { + Stream.call(this) + this.readable = true + this.writable = true + + this._needDrain = false + this._paused = false + this._reading = false + this._ending = false + this._ended = false + this._remaining = 0 + this._queue = [] + this._index = 0 + this._queueLen = 0 + + this._read = this._read.bind(this) + + this.props = {} + this._header = header + this._extended = extended || {} + + // globals can change throughout the course of + // a file parse operation. Freeze it at its current state. + this._global = {} + var me = this + Object.keys(global || {}).forEach(function (g) { + me._global[g] = global[g] + }) + + this._setProps() +} + +inherits(Entry, Stream, +{ write: function (c) { + if (this._ending) this.error("write() after end()", null, true) + if (this._remaining === 0) { + this.error("invalid bytes past eof") + } + + // often we'll get a bunch of \0 at the end of the last write, + // since chunks will always be 512 bytes when reading a tarball. + if (c.length > this._remaining) { + c = c.slice(0, this._remaining) + } + this._remaining -= c.length + + // put it on the stack. + var ql = this._queueLen + this._queue.push(c) + this._queueLen ++ + + this._read() + + // either paused, or buffered + if (this._paused || ql > 0) { + this._needDrain = true + return false + } + + return true + } + +, end: function (c) { + if (c) this.write(c) + this._ending = true + this._read() + } + +, pause: function () { + this._paused = true + this.emit("pause") + } + +, resume: function () { + // console.error(" Tar Entry resume", this.path) + this.emit("resume") + this._paused = false + this._read() + return this._queueLen - this._index > 1 + } + + // This is bound to the instance +, _read: function () { + // console.error(" Tar Entry _read", this.path) + + if (this._paused || this._reading || this._ended) return + + // set this flag so that event handlers don't inadvertently + // get multiple _read() calls running. + this._reading = true + + // have any data to emit? + while (this._index < this._queueLen && !this._paused) { + var chunk = this._queue[this._index ++] + this.emit("data", chunk) + } + + // check if we're drained + if (this._index >= this._queueLen) { + this._queue.length = this._queueLen = this._index = 0 + if (this._needDrain) { + this._needDrain = false + this.emit("drain") + } + if (this._ending) { + this._ended = true + this.emit("end") + } + } + + // if the queue gets too big, then pluck off whatever we can. + // this should be fairly rare. + var mql = this._maxQueueLen + if (this._queueLen > mql && this._index > 0) { + mql = Math.min(this._index, mql) + this._index -= mql + this._queueLen -= mql + this._queue = this._queue.slice(mql) + } + + this._reading = false + } + +, _setProps: function () { + // props = extended->global->header->{} + var header = this._header + , extended = this._extended + , global = this._global + , props = this.props + + // first get the values from the normal header. + var fields = tar.fields + for (var f = 0; fields[f] !== null; f ++) { + var field = fields[f] + , val = header[field] + if (typeof val !== "undefined") props[field] = val + } + + // next, the global header for this file. + // numeric values, etc, will have already been parsed. + ;[global, extended].forEach(function (p) { + Object.keys(p).forEach(function (f) { + if (typeof p[f] !== "undefined") props[f] = p[f] + }) + }) + + // no nulls allowed in path or linkpath + ;["path", "linkpath"].forEach(function (p) { + if (props.hasOwnProperty(p)) { + props[p] = props[p].split("\0")[0] + } + }) + + + // set date fields to be a proper date + ;["mtime", "ctime", "atime"].forEach(function (p) { + if (props.hasOwnProperty(p)) { + props[p] = new Date(props[p] * 1000) + } + }) + + // set the type so that we know what kind of file to create + var type + switch (tar.types[props.type]) { + case "OldFile": + case "ContiguousFile": + type = "File" + break + + case "GNUDumpDir": + type = "Directory" + break + + case undefined: + type = "Unknown" + break + + case "Link": + case "SymbolicLink": + case "CharacterDevice": + case "BlockDevice": + case "Directory": + case "FIFO": + default: + type = tar.types[props.type] + } + + this.type = type + this.path = props.path + this.size = props.size + + // size is special, since it signals when the file needs to end. + this._remaining = props.size + } +, warn: fstream.warn +, error: fstream.error +}) diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/extended-header-writer.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/extended-header-writer.js new file mode 100644 index 000000000..10a7d8fe2 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/extended-header-writer.js @@ -0,0 +1,192 @@ + +module.exports = ExtendedHeaderWriter + +var inherits = require("../vendor/inherits/inherits.js") + , EntryWriter = require("./entry-writer.js") + +inherits(ExtendedHeaderWriter, EntryWriter) + +var tar = require("../tar.js") + , path = require("path") + , inherits = require("../vendor/inherits/inherits.js") + , TarHeader = require("./header.js") + +// props is the props of the thing we need to write an +// extended header for. +// Don't be shy with it. Just encode everything. +function ExtendedHeaderWriter (props) { + // console.error(">> ehw ctor") + var me = this + + if (!(me instanceof ExtendedHeaderWriter)) { + return new ExtendedHeaderWriter(props) + } + + me.fields = props + + var p = + { path : ("PaxHeader" + path.join("/", props.path || "")) + .replace(/\\/g, "/").substr(0, 100) + , mode : props.mode || 0666 + , uid : props.uid || 0 + , gid : props.gid || 0 + , size : 0 // will be set later + , mtime : props.mtime || Date.now() / 1000 + , type : "x" + , linkpath : "" + , ustar : "ustar\0" + , ustarver : "00" + , uname : props.uname || "" + , gname : props.gname || "" + , devmaj : props.devmaj || 0 + , devmin : props.devmin || 0 + } + + + EntryWriter.call(me, p) + // console.error(">> ehw props", me.props) + me.props = p + + me._meta = true +} + +ExtendedHeaderWriter.prototype.end = function () { + // console.error(">> ehw end") + var me = this + + if (me._ended) return + me._ended = true + + me._encodeFields() + + if (me.props.size === 0) { + // nothing to write! + me._ready = true + me._stream.end() + return + } + + me._stream.write(TarHeader.encode(me.props)) + me.body.forEach(function (l) { + me._stream.write(l) + }) + me._ready = true + + // console.error(">> ehw _process calling end()", me.props) + this._stream.end() +} + +ExtendedHeaderWriter.prototype._encodeFields = function () { + // console.error(">> ehw _encodeFields") + this.body = [] + if (this.fields.prefix) { + this.fields.path = this.fields.prefix + "/" + this.fields.path + this.fields.prefix = "" + } + encodeFields(this.fields, "", this.body, this.fields.noProprietary) + var me = this + this.body.forEach(function (l) { + me.props.size += l.length + }) +} + +function encodeFields (fields, prefix, body, nop) { + // console.error(">> >> ehw encodeFields") + // "%d %s=%s\n", , , + // The length is a decimal number, and includes itself and the \n + // Numeric values are decimal strings. + + Object.keys(fields).forEach(function (k) { + var val = fields[k] + , numeric = tar.numeric[k] + + if (prefix) k = prefix + "." + k + + // already including NODETAR.type, don't need File=true also + if (k === fields.type && val === true) return + + switch (k) { + // don't include anything that's always handled just fine + // in the normal header, or only meaningful in the context + // of nodetar + case "mode": + case "cksum": + case "ustar": + case "ustarver": + case "prefix": + case "basename": + case "dirname": + case "needExtended": + case "block": + case "filter": + return + + case "rdev": + if (val === 0) return + break + + case "nlink": + case "dev": // Truly a hero among men, Creator of Star! + case "ino": // Speak his name with reverent awe! It is: + k = "SCHILY." + k + break + + default: break + } + + if (val && typeof val === "object" && + !Buffer.isBuffer(val)) encodeFields(val, k, body, nop) + else if (val === null || val === undefined) return + else body.push.apply(body, encodeField(k, val, nop)) + }) + + return body +} + +function encodeField (k, v, nop) { + // lowercase keys must be valid, otherwise prefix with + // "NODETAR." + if (k.charAt(0) === k.charAt(0).toLowerCase()) { + var m = k.split(".")[0] + if (!tar.knownExtended[m]) k = "NODETAR." + k + } + + // no proprietary + if (nop && k.charAt(0) !== k.charAt(0).toLowerCase()) { + return [] + } + + if (typeof val === "number") val = val.toString(10) + + var s = new Buffer(" " + k + "=" + v + "\n") + , digits = Math.floor(Math.log(s.length) / Math.log(10)) + 1 + + // console.error("1 s=%j digits=%j s.length=%d", s.toString(), digits, s.length) + + // if adding that many digits will make it go over that length, + // then add one to it. For example, if the string is: + // " foo=bar\n" + // then that's 9 characters. With the "9", that bumps the length + // up to 10. However, this is invalid: + // "10 foo=bar\n" + // but, since that's actually 11 characters, since 10 adds another + // character to the length, and the length includes the number + // itself. In that case, just bump it up again. + if (s.length + digits >= Math.pow(10, digits)) digits += 1 + // console.error("2 s=%j digits=%j s.length=%d", s.toString(), digits, s.length) + + var len = digits + s.length + // console.error("3 s=%j digits=%j s.length=%d len=%d", s.toString(), digits, s.length, len) + var lenBuf = new Buffer("" + len) + if (lenBuf.length + s.length !== len) { + throw new Error("Bad length calculation\n"+ + "len="+len+"\n"+ + "lenBuf="+JSON.stringify(lenBuf.toString())+"\n"+ + "lenBuf.length="+lenBuf.length+"\n"+ + "digits="+digits+"\n"+ + "s="+JSON.stringify(s.toString())+"\n"+ + "s.length="+s.length) + } + + return [lenBuf, s] +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/extended-header.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/extended-header.js new file mode 100644 index 000000000..63b79eca9 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/extended-header.js @@ -0,0 +1,139 @@ +// An Entry consisting of: +// +// "%d %s=%s\n", , , +// +// The length is a decimal number, and includes itself and the \n +// \0 does not terminate anything. Only the length terminates the string. +// Numeric values are decimal strings. + +module.exports = ExtendedHeader + +var Entry = require("./entry.js") + , inherits = require("../vendor/inherits/inherits.js") + , tar = require("../tar.js") + , numeric = tar.numeric + , keyTrans = { "SCHILY.dev": "dev" + , "SCHILY.ino": "ino" + , "SCHILY.nlink": "nlink" } + +function ExtendedHeader () { + Entry.apply(this, arguments) + this.on("data", this._parse) + this.fields = {} + this._position = 0 + this._fieldPos = 0 + this._state = SIZE + this._sizeBuf = [] + this._keyBuf = [] + this._valBuf = [] + this._size = -1 + this._key = "" +} + +inherits(ExtendedHeader, Entry, { _parse: parse }) + +var s = 0 + , states = ExtendedHeader.states = {} + , SIZE = states.SIZE = s++ + , KEY = states.KEY = s++ + , VAL = states.VAL = s++ + , ERR = states.ERR = s++ + +Object.keys(states).forEach(function (s) { + states[states[s]] = states[s] +}) + +states[s] = null + +// char code values for comparison +var _0 = "0".charCodeAt(0) + , _9 = "9".charCodeAt(0) + , point = ".".charCodeAt(0) + , a = "a".charCodeAt(0) + , Z = "Z".charCodeAt(0) + , a = "a".charCodeAt(0) + , z = "z".charCodeAt(0) + , space = " ".charCodeAt(0) + , eq = "=".charCodeAt(0) + , cr = "\n".charCodeAt(0) + +function parse (c) { + if (this._state === ERR) return + + for ( var i = 0, l = c.length + ; i < l + ; this._position++, this._fieldPos++, i++) { + // console.error("top of loop, size="+this._size) + + var b = c[i] + + if (this._size >= 0 && this._fieldPos > this._size) { + error(this, "field exceeds length="+this._size) + return + } + + switch (this._state) { + case ERR: return + + case SIZE: + // console.error("parsing size, b=%d, rest=%j", b, c.slice(i).toString()) + if (b === space) { + this._state = KEY + // this._fieldPos = this._sizeBuf.length + this._size = parseInt(new Buffer(this._sizeBuf).toString(), 10) + this._sizeBuf.length = 0 + continue + } + if (b < _0 || b > _9) { + error(this, "expected [" + _0 + ".." + _9 + "], got " + b) + return + } + this._sizeBuf.push(b) + continue + + case KEY: + // can be any char except =, not > size. + if (b === eq) { + this._state = VAL + this._key = new Buffer(this._keyBuf).toString() + if (keyTrans[this._key]) this._key = keyTrans[this._key] + this._keyBuf.length = 0 + continue + } + this._keyBuf.push(b) + continue + + case VAL: + // field must end with cr + if (this._fieldPos === this._size - 1) { + // console.error("finished with "+this._key) + if (b !== cr) { + error(this, "expected \\n at end of field") + return + } + var val = new Buffer(this._valBuf).toString() + if (numeric[this._key]) { + val = parseFloat(val) + } + this.fields[this._key] = val + + this._valBuf.length = 0 + this._state = SIZE + this._size = -1 + this._fieldPos = -1 + continue + } + this._valBuf.push(b) + continue + } + } +} + +function error (me, msg) { + msg = "invalid header: " + msg + + "\nposition=" + me._position + + "\nfield position=" + me._fieldPos + + me.error(msg) + me.state = ERR +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/extract.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/extract.js new file mode 100644 index 000000000..bffc03380 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/extract.js @@ -0,0 +1,78 @@ +// give it a tarball and a path, and it'll dump the contents + +module.exports = Extract + +var tar = require("../tar.js") + , fstream = require("../vendor/fstream/fstream.js") + , inherits = require("../vendor/inherits/inherits.js") + , path = require("path") + +function Extract (opts) { + if (!(this instanceof Extract)) return new Extract(opts) + tar.Parse.apply(this) + + // have to dump into a directory + opts.type = "Directory" + opts.Directory = true + + if (typeof opts !== "object") { + opts = { path: opts } + } + + // better to drop in cwd? seems more standard. + opts.path = opts.path || path.resolve("node-tar-extract") + opts.type = "Directory" + opts.Directory = true + + // similar to --strip or --strip-components + opts.strip = +opts.strip + if (!opts.strip || opts.strip <= 0) opts.strip = 0 + + this._fst = fstream.Writer(opts) + + this.pause() + var me = this + + // Hardlinks in tarballs are relative to the root + // of the tarball. So, they need to be resolved against + // the target directory in order to be created properly. + me.on("entry", function (entry) { + // if there's a "strip" argument, then strip off that many + // path components. + if (opts.strip) { + var p = entry.path.split("/").slice(opts.strip).join("/") + entry.path = entry.props.path = p + if (entry.linkpath) { + var lp = entry.linkpath.split("/").slice(opts.strip).join("/") + entry.linkpath = entry.props.linkpath = lp + } + } + if (entry.type !== "Link") return + entry.linkpath = entry.props.linkpath = + path.join(opts.path, path.join("/", entry.props.linkpath)) + }) + + this._fst.on("ready", function () { + me.pipe(me._fst, { end: false }) + me.resume() + }) + + // this._fst.on("end", function () { + // console.error("\nEEEE Extract End", me._fst.path) + // }) + + this._fst.on("close", function () { + // console.error("\nEEEE Extract End", me._fst.path) + me.emit("end") + me.emit("close") + }) +} + +inherits(Extract, tar.Parse) + +Extract.prototype._streamEnd = function () { + var me = this + if (!me._ended) me.error("unexpected eof") + me._fst.end() + // my .end() is coming later. +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/global-header-writer.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/global-header-writer.js new file mode 100644 index 000000000..99ff25779 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/global-header-writer.js @@ -0,0 +1,14 @@ +module.exports = GlobalHeaderWriter + +var ExtendedHeaderWriter = require("./extended-header-writer.js") + , inherits = require("../vendor/inherits/inherits.js") + +inherits(GlobalHeaderWriter, ExtendedHeaderWriter) + +function GlobalHeaderWriter (props) { + if (!(this instanceof GlobalHeaderWriter)) { + return new GlobalHeaderWriter(props) + } + ExtendedHeaderWriter.call(this, props) + this.props.type = "g" +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/header.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/header.js new file mode 100644 index 000000000..05b237c0c --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/header.js @@ -0,0 +1,385 @@ +// parse a 512-byte header block to a data object, or vice-versa +// If the data won't fit nicely in a simple header, then generate +// the appropriate extended header file, and return that. + +module.exports = TarHeader + +var tar = require("../tar.js") + , fields = tar.fields + , fieldOffs = tar.fieldOffs + , fieldEnds = tar.fieldEnds + , fieldSize = tar.fieldSize + , numeric = tar.numeric + , assert = require("assert").ok + , space = " ".charCodeAt(0) + , slash = "/".charCodeAt(0) + , bslash = process.platform === "win32" ? "\\".charCodeAt(0) : null + +function TarHeader (block) { + if (!(this instanceof TarHeader)) return new TarHeader(block) + if (block) this.decode(block) +} + +TarHeader.prototype = + { decode : decode + , encode: encode + , calcSum: calcSum + , checkSum: checkSum + } + +TarHeader.parseNumeric = parseNumeric +TarHeader.encode = encode +TarHeader.decode = decode + +// note that this will only do the normal ustar header, not any kind +// of extended posix header file. If something doesn't fit comfortably, +// then it will set obj.needExtended = true, and set the block to +// the closest approximation. +function encode (obj) { + if (!obj && !(this instanceof TarHeader)) throw new Error( + "encode must be called on a TarHeader, or supplied an object") + + obj = obj || this + var block = obj.block = new Buffer(512) + + // if the object has a "prefix", then that's actually an extension of + // the path field. + if (obj.prefix) { + // console.error("%% header encoding, got a prefix", obj.prefix) + obj.path = obj.prefix + "/" + obj.path + // console.error("%% header encoding, prefixed path", obj.path) + obj.prefix = "" + } + + obj.needExtended = false + + if (obj.mode) { + if (typeof obj.mode === "string") obj.mode = parseInt(obj.mode, 8) + obj.mode = obj.mode & 0777 + } + + for (var f = 0; fields[f] !== null; f ++) { + var field = fields[f] + , off = fieldOffs[f] + , end = fieldEnds[f] + , ret + + switch (field) { + case "cksum": + // special, done below, after all the others + break + + case "prefix": + // special, this is an extension of the "path" field. + // console.error("%% header encoding, skip prefix later") + break + + case "type": + // convert from long name to a single char. + var type = obj.type || "0" + if (type.length > 1) { + type = tar.types[obj.type] + if (!type) type = "0" + } + writeText(block, off, end, type) + break + + case "path": + // uses the "prefix" field if > 100 bytes, but <= 255 + var pathLen = Buffer.byteLength(obj.path) + , pathFSize = fieldSize[fields.path] + , prefFSize = fieldSize[fields.prefix] + + // paths between 100 and 255 should use the prefix field. + // longer than 255 + if (pathLen > pathFSize && + pathLen <= pathFSize + prefFSize) { + // need to find a slash somewhere in the middle so that + // path and prefix both fit in their respective fields + var searchStart = pathLen - 1 - pathFSize + , searchEnd = prefFSize + , found = false + , pathBuf = new Buffer(obj.path) + + for ( var s = searchStart + ; (s <= searchEnd) + ; s ++ ) { + if (pathBuf[s] === slash || pathBuf[s] === bslash) { + found = s + break + } + } + + if (found !== false) { + prefix = pathBuf.slice(0, found).toString("utf8") + path = pathBuf.slice(found + 1).toString("utf8") + + ret = writeText(block, off, end, path) + off = fieldOffs[fields.prefix] + end = fieldEnds[fields.prefix] + // console.error("%% header writing prefix", off, end, prefix) + ret = writeText(block, off, end, prefix) || ret + break + } + } + + // paths less than 100 chars don't need a prefix + // and paths longer than 255 need an extended header and will fail + // on old implementations no matter what we do here. + // Null out the prefix, and fallthrough to default. + // console.error("%% header writing no prefix") + var poff = fieldOffs[fields.prefix] + , pend = fieldEnds[fields.prefix] + writeText(block, poff, pend, "") + // fallthrough + + // all other fields are numeric or text + default: + ret = numeric[field] + ? writeNumeric(block, off, end, obj[field]) + : writeText(block, off, end, obj[field] || "") + break + } + obj.needExtended = obj.needExtended || ret + } + + var off = fieldOffs[fields.cksum] + , end = fieldEnds[fields.cksum] + + writeNumeric(block, off, end, calcSum.call(this, block)) + + return block +} + +// if it's a negative number, or greater than will fit, +// then use write256. +var MAXNUM = { 12: 077777777777 + , 11: 07777777777 + , 8 : 07777777 + , 7 : 0777777 } +function writeNumeric (block, off, end, num) { + var writeLen = end - off + , maxNum = MAXNUM[writeLen] || 0 + + num = num || 0 + // console.error(" numeric", num) + + if (num instanceof Date || + Object.prototype.toString.call(num) === "[object Date]") { + num = num.getTime() / 1000 + } + + if (num > maxNum || num < 0) { + write256(block, off, end, num) + // need an extended header if negative or too big. + return true + } + + // god, tar is so annoying + // if the string is small enough, you should put a space + // between the octal string and the \0, but if it doesn't + // fit, then don't. + var numStr = Math.floor(num).toString(8) + if (num < MAXNUM[writeLen - 1]) numStr += " " + + // pad with "0" chars + if (numStr.length < writeLen) { + numStr = (new Array(writeLen - numStr.length).join("0")) + numStr + } + + if (numStr.length !== writeLen - 1) { + throw new Error("invalid length: " + JSON.stringify(numStr) + "\n" + + "expected: "+writeLen) + } + block.write(numStr, off, writeLen, "utf8") + block[end - 1] = 0 +} + +function write256 (block, off, end, num) { + var buf = block.slice(off, end) + var positive = num >= 0 + buf[0] = positive ? 0x80 : 0xFF + + // get the number as a base-256 tuple + if (!positive) num *= -1 + var tuple = [] + do { + var n = num % 256 + tuple.push(n) + num = (num - n) / 256 + } while (num) + + var bytes = tuple.length + + var fill = buf.length - bytes + for (var i = 1; i < fill; i ++) { + buf[i] = positive ? 0 : 0xFF + } + + // tuple is a base256 number, with [0] as the *least* significant byte + // if it's negative, then we need to flip all the bits once we hit the + // first non-zero bit. The 2's-complement is (0x100 - n), and the 1's- + // complement is (0xFF - n). + var zero = true + for (i = bytes; i > 0; i --) { + var byte = tuple[bytes - i] + if (positive) buf[fill + i] = byte + else if (zero && byte === 0) buf[fill + i] = 0 + else if (zero) { + zero = false + buf[fill + i] = 0x100 - byte + } else buf[fill + i] = 0xFF - byte + } +} + +function writeText (block, off, end, str) { + // strings are written as utf8, then padded with \0 + var strLen = Buffer.byteLength(str) + , writeLen = Math.min(strLen, end - off) + // non-ascii fields need extended headers + // long fields get truncated + , needExtended = strLen !== str.length || strLen > writeLen + + // write the string, and null-pad + if (writeLen > 0) block.write(str, off, writeLen, "utf8") + for (var i = off + writeLen; i < end; i ++) block[i] = 0 + + return needExtended +} + +function calcSum (block) { + block = block || this.block + assert(Buffer.isBuffer(block) && block.length === 512) + + if (!block) throw new Error("Need block to checksum") + + // now figure out what it would be if the cksum was " " + var sum = 0 + , start = fieldOffs[fields.cksum] + , end = fieldEnds[fields.cksum] + + for (var i = 0; i < fieldOffs[fields.cksum]; i ++) { + sum += block[i] + } + + for (var i = start; i < end; i ++) { + sum += space + } + + for (var i = end; i < 512; i ++) { + sum += block[i] + } + + return sum +} + + +function checkSum (block) { + var sum = calcSum.call(this, block) + block = block || this.block + + var cksum = block.slice(fieldOffs[fields.cksum], fieldEnds[fields.cksum]) + cksum = parseNumeric(cksum) + + return cksum === sum +} + +function decode (block) { + block = block || this.block + assert(Buffer.isBuffer(block) && block.length === 512) + + this.block = block + this.cksumValid = this.checkSum() + + var prefix = null + + // slice off each field. + for (var f = 0; fields[f] !== null; f ++) { + var field = fields[f] + , val = block.slice(fieldOffs[f], fieldEnds[f]) + + switch (field) { + case "ustar": + // if not ustar, then everything after that is just padding. + if (val.toString() !== "ustar\0") { + this.ustar = false + return + } else { + // console.error("ustar:", val, val.toString()) + this.ustar = val.toString() + } + break + + // prefix is special, since it might signal the xstar header + case "prefix": + var atime = parseNumeric(val.slice(131, 131 + 12)) + , ctime = parseNumeric(val.slice(131 + 12, 131 + 12 + 12)) + if ((val[130] === 0 || val[130] === space) && + typeof atime === "number" && + typeof ctime === "number" && + val[131 + 12] === space && + val[131 + 12 + 12] === space) { + this.atime = atime + this.ctime = ctime + val = val.slice(0, 130) + } + prefix = val.toString("utf8").replace(/\0+$/, "") + // console.error("%% header reading prefix", prefix) + break + + // all other fields are null-padding text + // or a number. + default: + if (numeric[field]) { + this[field] = parseNumeric(val) + } else { + this[field] = val.toString("utf8").replace(/\0+$/, "") + } + break + } + } + + // if we got a prefix, then prepend it to the path. + if (prefix) { + this.path = prefix + "/" + this.path + // console.error("%% header got a prefix", this.path) + } +} + +function parse256 (buf) { + // first byte MUST be either 80 or FF + // 80 for positive, FF for 2's comp + var positive + if (buf[0] === 0x80) positive = true + else if (buf[0] === 0xFF) positive = false + else return null + + // build up a base-256 tuple from the least sig to the highest + var zero = false + , tuple = [] + for (var i = buf.length - 1; i > 0; i --) { + var byte = buf[i] + if (positive) tuple.push(byte) + else if (zero && byte === 0) tuple.push(0) + else if (zero) { + zero = false + tuple.push(0x100 - byte) + } else tuple.push(0xFF - byte) + } + + for (var sum = 0, i = 0, l = tuple.length; i < l; i ++) { + sum += tuple[i] * Math.pow(256, i) + } + + return positive ? sum : -1 * sum +} + +function parseNumeric (f) { + if (f[0] & 0x80) return parse256(f) + + var str = f.toString("utf8").split("\0")[0].trim() + , res = parseInt(str, 8) + + return isNaN(res) ? null : res +} + diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/pack.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/pack.js new file mode 100644 index 000000000..c436ec19d --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/pack.js @@ -0,0 +1,231 @@ +// pipe in an fstream, and it'll make a tarball. +// key-value pair argument is global extended header props. + +module.exports = Pack + +var EntryWriter = require("./entry-writer.js") + , Stream = require("stream").Stream + , path = require("path") + , inherits = require("../vendor/inherits/inherits.js") + , GlobalHeaderWriter = require("./global-header-writer.js") + , collect = require("../vendor/fstream/fstream.js").collect + , eof = new Buffer(512) + +for (var i = 0; i < 512; i ++) eof[i] = 0 + +inherits(Pack, Stream) + +function Pack (props) { + // console.error("-- p ctor") + var me = this + if (!(me instanceof Pack)) return new Pack(props) + + if (props) me._noProprietary = props.noProprietary + else me._noProprietary = false + + me._global = props + + me.readable = true + me.writable = true + me._buffer = [] + // console.error("-- -- set current to null in ctor") + me._currentEntry = null + me._processing = false + + me._pipeRoot = null + me.on("pipe", function (src) { + if (src.root === me._pipeRoot) return + me._pipeRoot = src + src.on("end", function () { + me._pipeRoot = null + }) + me.add(src) + }) +} + +Pack.prototype.addGlobal = function (props) { + // console.error("-- p addGlobal") + if (this._didGlobal) return + this._didGlobal = true + + var me = this + GlobalHeaderWriter(props) + .on("data", function (c) { + me.emit("data", c) + }) + .end() +} + +Pack.prototype.add = function (stream) { + if (this._global && !this._didGlobal) this.addGlobal(this._global) + + if (this._ended) return this.emit("error", new Error("add after end")) + + collect(stream) + this._buffer.push(stream) + this._process() + this._needDrain = this._buffer.length > 0 + return !this._needDrain +} + +Pack.prototype.pause = function () { + this._paused = true + if (this._currentEntry) this._currentEntry.pause() + this.emit("pause") +} + +Pack.prototype.resume = function () { + this._paused = false + if (this._currentEntry) this._currentEntry.resume() + this.emit("resume") + this._process() +} + +Pack.prototype.end = function () { + this._ended = true + this._buffer.push(eof) + this._process() +} + +Pack.prototype._process = function () { + var me = this + if (me._paused || me._processing) { + return + } + + var entry = me._buffer.shift() + + if (!entry) { + if (me._needDrain) { + me.emit("drain") + } + return + } + + if (entry.ready === false) { + // console.error("-- entry is not ready", entry) + me._buffer.unshift(entry) + entry.on("ready", function () { + // console.error("-- -- ready!", entry) + me._process() + }) + return + } + + me._processing = true + + if (entry === eof) { + // need 2 ending null blocks. + me.emit("data", eof) + me.emit("data", eof) + me.emit("end") + me.emit("close") + return + } + + // Change the path to be relative to the root dir that was + // added to the tarball. + // + // XXX This should be more like how -C works, so you can + // explicitly set a root dir, and also explicitly set a pathname + // in the tarball to use. That way we can skip a lot of extra + // work when resolving symlinks for bundled dependencies in npm. + + var root = path.dirname((entry.root || entry).path) + var wprops = {} + + Object.keys(entry.props || {}).forEach(function (k) { + wprops[k] = entry.props[k] + }) + + if (me._noProprietary) wprops.noProprietary = true + + wprops.path = path.relative(root, entry.path || '') + + // actually not a matter of opinion or taste. + if (process.platform === "win32") { + wprops.path = wprops.path.replace(/\\/g, "/") + } + + if (!wprops.type) + wprops.type = 'Directory' + + switch (wprops.type) { + // sockets not supported + case "Socket": + return + + case "Directory": + wprops.path += "/" + wprops.size = 0 + break + + case "Link": + var lp = path.resolve(path.dirname(entry.path), entry.linkpath) + wprops.linkpath = path.relative(root, lp) || "." + wprops.size = 0 + break + + case "SymbolicLink": + var lp = path.resolve(path.dirname(entry.path), entry.linkpath) + wprops.linkpath = path.relative(path.dirname(entry.path), lp) || "." + wprops.size = 0 + break + } + + // console.error("-- new writer", wprops) + // if (!wprops.type) { + // // console.error("-- no type?", entry.constructor.name, entry) + // } + + // console.error("-- -- set current to new writer", wprops.path) + var writer = me._currentEntry = EntryWriter(wprops) + + writer.parent = me + + // writer.on("end", function () { + // // console.error("-- -- writer end", writer.path) + // }) + + writer.on("data", function (c) { + me.emit("data", c) + }) + + writer.on("header", function () { + Buffer.prototype.toJSON = function () { + return this.toString().split(/\0/).join(".") + } + // console.error("-- -- writer header %j", writer.props) + if (writer.props.size === 0) nextEntry() + }) + writer.on("close", nextEntry) + + var ended = false + function nextEntry () { + if (ended) return + ended = true + + // console.error("-- -- writer close", writer.path) + // console.error("-- -- set current to null", wprops.path) + me._currentEntry = null + me._processing = false + me._process() + } + + writer.on("error", function (er) { + // console.error("-- -- writer error", writer.path) + me.emit("error", er) + }) + + // if it's the root, then there's no need to add its entries, + // or data, since they'll be added directly. + if (entry === me._pipeRoot) { + // console.error("-- is the root, don't auto-add") + writer.add = null + } + + entry.pipe(writer) +} + +Pack.prototype.destroy = function () {} +Pack.prototype.write = function () {} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/parse.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/parse.js new file mode 100644 index 000000000..3f71a92d5 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/lib/parse.js @@ -0,0 +1,270 @@ + +// A writable stream. +// It emits "entry" events, which provide a readable stream that has +// header info attached. + +module.exports = Parse.create = Parse + +var stream = require("stream") + , Stream = stream.Stream + , BlockStream = require("../vendor/block-stream/block-stream.js") + , tar = require("../tar.js") + , TarHeader = require("./header.js") + , Entry = require("./entry.js") + , BufferEntry = require("./buffer-entry.js") + , ExtendedHeader = require("./extended-header.js") + , assert = require("assert").ok + , inherits = require("../vendor/inherits/inherits.js") + , fstream = require("../vendor/fstream/fstream.js") + +// reading a tar is a lot like reading a directory +// However, we're actually not going to run the ctor, +// since it does a stat and various other stuff. +// This inheritance gives us the pause/resume/pipe +// behavior that is desired. +inherits(Parse, fstream.Reader) + +function Parse () { + var me = this + if (!(me instanceof Parse)) return new Parse() + + // doesn't apply fstream.Reader ctor? + // no, becasue we don't want to stat/etc, we just + // want to get the entry/add logic from .pipe() + Stream.apply(me) + + me.writable = true + me.readable = true + me._stream = new BlockStream(512) + me.position = 0 + + me._stream.on("error", function (e) { + me.emit("error", e) + }) + + me._stream.on("data", function (c) { + me._process(c) + }) + + me._stream.on("end", function () { + me._streamEnd() + }) + + me._stream.on("drain", function () { + me.emit("drain") + }) +} + +// overridden in Extract class, since it needs to +// wait for its DirWriter part to finish before +// emitting "end" +Parse.prototype._streamEnd = function () { + var me = this + if (!me._ended) me.error("unexpected eof") + me.emit("end") +} + +// a tar reader is actually a filter, not just a readable stream. +// So, you should pipe a tarball stream into it, and it needs these +// write/end methods to do that. +Parse.prototype.write = function (c) { + if (this._ended) { + // gnutar puts a LOT of nulls at the end. + // you can keep writing these things forever. + // Just ignore them. + for (var i = 0, l = c.length; i > l; i ++) { + if (c[i] !== 0) return this.error("write() after end()") + } + return + } + return this._stream.write(c) +} + +Parse.prototype.end = function (c) { + this._ended = true + return this._stream.end(c) +} + +// don't need to do anything, since we're just +// proxying the data up from the _stream. +// Just need to override the parent's "Not Implemented" +// error-thrower. +Parse.prototype._read = function () {} + +Parse.prototype._process = function (c) { + assert(c && c.length === 512, "block size should be 512") + + // one of three cases. + // 1. A new header + // 2. A part of a file/extended header + // 3. One of two or more EOF null blocks + + if (this._entry) { + var entry = this._entry + entry.write(c) + if (entry._remaining === 0) { + entry.end() + this._entry = null + } + } else { + // either zeroes or a header + var zero = true + for (var i = 0; i < 512 && zero; i ++) { + zero = c[i] === 0 + } + + // eof is *at least* 2 blocks of nulls, and then the end of the + // file. you can put blocks of nulls between entries anywhere, + // so appending one tarball to another is technically valid. + // ending without the eof null blocks is not allowed, however. + if (zero) { + this._ended = this._eofStarted + this._eofStarted = true + } else { + this._ended = this._eofStarted = false + this._startEntry(c) + } + + } + + this.position += 512 +} + +// take a header chunk, start the right kind of entry. +Parse.prototype._startEntry = function (c) { + var header = new TarHeader(c) + , self = this + , entry + , ev + , EntryType + , onend + , meta = false + + if (null === header.size || !header.cksumValid) { + var e = new Error("invalid tar file") + e.header = header + e.tar_file_offset = this.position + e.tar_block = this.position / 512 + this.emit("error", e) + } + + switch (tar.types[header.type]) { + case "File": + case "OldFile": + case "Link": + case "SymbolicLink": + case "CharacterDevice": + case "BlockDevice": + case "Directory": + case "FIFO": + case "ContiguousFile": + case "GNUDumpDir": + // start a file. + // pass in any extended headers + // These ones consumers are typically most interested in. + EntryType = Entry + ev = "entry" + break + + case "GlobalExtendedHeader": + // extended headers that apply to the rest of the tarball + EntryType = ExtendedHeader + onend = function () { + self._global = self._global || {} + Object.keys(entry.fields).forEach(function (k) { + self._global[k] = entry.fields[k] + }) + } + ev = "globalExtendedHeader" + meta = true + break + + case "ExtendedHeader": + case "OldExtendedHeader": + // extended headers that apply to the next entry + EntryType = ExtendedHeader + onend = function () { + self._extended = entry.fields + } + ev = "extendedHeader" + meta = true + break + + case "NextFileHasLongLinkpath": + // set linkpath= in extended header + EntryType = BufferEntry + onend = function () { + self._extended = self._extended || {} + self._extended.linkpath = entry.body + } + ev = "longLinkpath" + meta = true + break + + case "NextFileHasLongPath": + case "OldGnuLongPath": + // set path= in file-extended header + EntryType = BufferEntry + onend = function () { + self._extended = self._extended || {} + self._extended.path = entry.body + } + ev = "longPath" + meta = true + break + + default: + // all the rest we skip, but still set the _entry + // member, so that we can skip over their data appropriately. + // emit an event to say that this is an ignored entry type? + EntryType = Entry + ev = "ignoredEntry" + break + } + + var global, extended + if (meta) { + global = extended = null + } else { + var global = this._global + var extended = this._extended + + // extendedHeader only applies to one entry, so once we start + // an entry, it's over. + this._extended = null + } + entry = new EntryType(header, extended, global) + entry.meta = meta + + // only proxy data events of normal files. + if (!meta) { + entry.on("data", function (c) { + me.emit("data", c) + }) + } + + if (onend) entry.on("end", onend) + + this._entry = entry + var me = this + + entry.on("pause", function () { + me.pause() + }) + + entry.on("resume", function () { + me.resume() + }) + + if (this.listeners("*").length) { + this.emit("*", ev, entry) + } + + this.emit(ev, entry) + + // Zero-byte entry. End immediately. + if (entry.props.size === 0) { + entry.end() + this._entry = null + } +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/tar.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/tar.js new file mode 100644 index 000000000..a81298b9a --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/tar.js @@ -0,0 +1,173 @@ +// field paths that every tar file must have. +// header is padded to 512 bytes. +var f = 0 + , fields = {} + , path = fields.path = f++ + , mode = fields.mode = f++ + , uid = fields.uid = f++ + , gid = fields.gid = f++ + , size = fields.size = f++ + , mtime = fields.mtime = f++ + , cksum = fields.cksum = f++ + , type = fields.type = f++ + , linkpath = fields.linkpath = f++ + , headerSize = 512 + , blockSize = 512 + , fieldSize = [] + +fieldSize[path] = 100 +fieldSize[mode] = 8 +fieldSize[uid] = 8 +fieldSize[gid] = 8 +fieldSize[size] = 12 +fieldSize[mtime] = 12 +fieldSize[cksum] = 8 +fieldSize[type] = 1 +fieldSize[linkpath] = 100 + +// "ustar\0" may introduce another bunch of headers. +// these are optional, and will be nulled out if not present. + +var ustar = fields.ustar = f++ + , ustarver = fields.ustarver = f++ + , uname = fields.uname = f++ + , gname = fields.gname = f++ + , devmaj = fields.devmaj = f++ + , devmin = fields.devmin = f++ + , prefix = fields.prefix = f++ + , fill = fields.fill = f++ + +// terminate fields. +fields[f] = null + +fieldSize[ustar] = 6 +fieldSize[ustarver] = 2 +fieldSize[uname] = 32 +fieldSize[gname] = 32 +fieldSize[devmaj] = 8 +fieldSize[devmin] = 8 +fieldSize[prefix] = 155 +fieldSize[fill] = 12 + +// nb: prefix field may in fact be 130 bytes of prefix, +// a null char, 12 bytes for atime, 12 bytes for ctime. +// +// To recognize this format: +// 1. prefix[130] === ' ' or '\0' +// 2. atime and ctime are octal numeric values +// 3. atime and ctime have ' ' in their last byte + +var fieldEnds = {} + , fieldOffs = {} + , fe = 0 +for (var i = 0; i < f; i ++) { + fieldOffs[i] = fe + fieldEnds[i] = (fe += fieldSize[i]) +} + +// build a translation table of field paths. +Object.keys(fields).forEach(function (f) { + if (fields[f] !== null) fields[fields[f]] = f +}) + +// different values of the 'type' field +// paths match the values of Stats.isX() functions, where appropriate +var types = + { 0: "File" + , "\0": "OldFile" // like 0 + , "": "OldFile" + , 1: "Link" + , 2: "SymbolicLink" + , 3: "CharacterDevice" + , 4: "BlockDevice" + , 5: "Directory" + , 6: "FIFO" + , 7: "ContiguousFile" // like 0 + // posix headers + , g: "GlobalExtendedHeader" // k=v for the rest of the archive + , x: "ExtendedHeader" // k=v for the next file + // vendor-specific stuff + , A: "SolarisACL" // skip + , D: "GNUDumpDir" // like 5, but with data, which should be skipped + , I: "Inode" // metadata only, skip + , K: "NextFileHasLongLinkpath" // data = link path of next file + , L: "NextFileHasLongPath" // data = path of next file + , M: "ContinuationFile" // skip + , N: "OldGnuLongPath" // like L + , S: "SparseFile" // skip + , V: "TapeVolumeHeader" // skip + , X: "OldExtendedHeader" // like x + } + +Object.keys(types).forEach(function (t) { + types[types[t]] = types[types[t]] || t +}) + +// values for the mode field +var modes = + { suid: 04000 // set uid on extraction + , sgid: 02000 // set gid on extraction + , svtx: 01000 // set restricted deletion flag on dirs on extraction + , uread: 0400 + , uwrite: 0200 + , uexec: 0100 + , gread: 040 + , gwrite: 020 + , gexec: 010 + , oread: 4 + , owrite: 2 + , oexec: 1 + , all: 07777 + } + +var numeric = + { mode: true + , uid: true + , gid: true + , size: true + , mtime: true + , devmaj: true + , devmin: true + , cksum: true + , atime: true + , ctime: true + , dev: true + , ino: true + , nlink: true + } + +Object.keys(modes).forEach(function (t) { + modes[modes[t]] = modes[modes[t]] || t +}) + +var knownExtended = + { atime: true + , charset: true + , comment: true + , ctime: true + , gid: true + , gname: true + , linkpath: true + , mtime: true + , path: true + , realtime: true + , security: true + , size: true + , uid: true + , uname: true } + + +exports.fields = fields +exports.fieldSize = fieldSize +exports.fieldOffs = fieldOffs +exports.fieldEnds = fieldEnds +exports.types = types +exports.modes = modes +exports.numeric = numeric +exports.headerSize = headerSize +exports.blockSize = blockSize +exports.knownExtended = knownExtended + +exports.Pack = require("./lib/pack.js") +exports.Parse = require("./lib/parse.js") +exports.Extract = require("./lib/extract.js") diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/block-stream/LICENCE b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/block-stream/LICENCE new file mode 100644 index 000000000..74489e2e2 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/block-stream/LICENCE @@ -0,0 +1,25 @@ +Copyright (c) Isaac Z. Schlueter +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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/block-stream/README.md b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/block-stream/README.md new file mode 100644 index 000000000..c16e9c468 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/block-stream/README.md @@ -0,0 +1,14 @@ +# block-stream + +A stream of blocks. + +Write data into it, and it'll output data in buffer blocks the size you +specify, padding with zeroes if necessary. + +```javascript +var block = new BlockStream(512) +fs.createReadStream("some-file").pipe(block) +block.pipe(fs.createWriteStream("block-file")) +``` + +When `.end()` or `.flush()` is called, it'll pad the block with zeroes. diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/block-stream/block-stream.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/block-stream/block-stream.js new file mode 100644 index 000000000..af63e5f72 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/block-stream/block-stream.js @@ -0,0 +1,209 @@ +// write data to it, and it'll emit data in 512 byte blocks. +// if you .end() or .flush(), it'll emit whatever it's got, +// padded with nulls to 512 bytes. + +module.exports = BlockStream + +var Stream = require("stream").Stream + , inherits = require("../inherits/inherits.js") + , assert = require("assert").ok + , debug = process.env.DEBUG ? console.error : function () {} + +function BlockStream (size, opt) { + this.writable = this.readable = true + this._opt = opt || {} + this._chunkSize = size || 512 + this._offset = 0 + this._buffer = [] + this._bufferLength = 0 + if (this._opt.nopad) this._zeroes = false + else { + this._zeroes = new Buffer(this._chunkSize) + for (var i = 0; i < this._chunkSize; i ++) { + this._zeroes[i] = 0 + } + } +} + +inherits(BlockStream, Stream) + +BlockStream.prototype.write = function (c) { + // debug(" BS write", c) + if (this._ended) throw new Error("BlockStream: write after end") + if (c && !Buffer.isBuffer(c)) c = new Buffer(c + "") + if (c.length) { + this._buffer.push(c) + this._bufferLength += c.length + } + // debug("pushed onto buffer", this._bufferLength) + if (this._bufferLength >= this._chunkSize) { + if (this._paused) { + // debug(" BS paused, return false, need drain") + this._needDrain = true + return false + } + this._emitChunk() + } + return true +} + +BlockStream.prototype.pause = function () { + // debug(" BS pausing") + this._paused = true +} + +BlockStream.prototype.resume = function () { + // debug(" BS resume") + this._paused = false + return this._emitChunk() +} + +BlockStream.prototype.end = function (chunk) { + // debug("end", chunk) + if (typeof chunk === "function") cb = chunk, chunk = null + if (chunk) this.write(chunk) + this._ended = true + this.flush() +} + +BlockStream.prototype.flush = function () { + this._emitChunk(true) +} + +BlockStream.prototype._emitChunk = function (flush) { + // debug("emitChunk flush=%j emitting=%j paused=%j", flush, this._emitting, this._paused) + + // emit a chunk + if (flush && this._zeroes) { + // debug(" BS push zeroes", this._bufferLength) + // push a chunk of zeroes + var padBytes = (this._bufferLength % this._chunkSize) + if (padBytes !== 0) padBytes = this._chunkSize - padBytes + if (padBytes > 0) { + // debug("padBytes", padBytes, this._zeroes.slice(0, padBytes)) + this._buffer.push(this._zeroes.slice(0, padBytes)) + this._bufferLength += padBytes + // debug(this._buffer[this._buffer.length - 1].length, this._bufferLength) + } + } + + if (this._emitting || this._paused) return + this._emitting = true + + // debug(" BS entering loops") + var bufferIndex = 0 + while (this._bufferLength >= this._chunkSize && + (flush || !this._paused)) { + // debug(" BS data emission loop", this._bufferLength) + + var out + , outOffset = 0 + , outHas = this._chunkSize + + while (outHas > 0 && (flush || !this._paused) ) { + // debug(" BS data inner emit loop", this._bufferLength) + var cur = this._buffer[bufferIndex] + , curHas = cur.length - this._offset + // debug("cur=", cur) + // debug("curHas=%j", curHas) + // If it's not big enough to fill the whole thing, then we'll need + // to copy multiple buffers into one. However, if it is big enough, + // then just slice out the part we want, to save unnecessary copying. + // Also, need to copy if we've already done some copying, since buffers + // can't be joined like cons strings. + if (out || curHas < outHas) { + out = out || new Buffer(this._chunkSize) + cur.copy(out, outOffset, + this._offset, this._offset + Math.min(curHas, outHas)) + } else if (cur.length === outHas && this._offset === 0) { + // shortcut -- cur is exactly long enough, and no offset. + out = cur + } else { + // slice out the piece of cur that we need. + out = cur.slice(this._offset, this._offset + outHas) + } + + if (curHas > outHas) { + // means that the current buffer couldn't be completely output + // update this._offset to reflect how much WAS written + this._offset += outHas + outHas = 0 + } else { + // output the entire current chunk. + // toss it away + outHas -= curHas + outOffset += curHas + bufferIndex ++ + this._offset = 0 + } + } + + this._bufferLength -= this._chunkSize + assert(out.length === this._chunkSize) + // debug("emitting data", out) + // debug(" BS emitting, paused=%j", this._paused, this._bufferLength) + this.emit("data", out) + out = null + } + // debug(" BS out of loops", this._bufferLength) + + // whatever is left, it's not enough to fill up a block, or we're paused + this._buffer = this._buffer.slice(bufferIndex) + if (this._paused) { + // debug(" BS paused, leaving", this._bufferLength) + this._needsDrain = true + this._emitting = false + return + } + + // if flushing, and not using null-padding, then need to emit the last + // chunk(s) sitting in the queue. We know that it's not enough to + // fill up a whole block, because otherwise it would have been emitted + // above, but there may be some offset. + var l = this._buffer.length + if (flush && !this._zeroes && l) { + if (l === 1) { + if (this._offset) { + this.emit("data", this._buffer[0].slice(this._offset)) + } else { + this.emit("data", this._buffer[0]) + } + } else { + var outHas = this._bufferLength + , out = new Buffer(outHas) + , outOffset = 0 + for (var i = 0; i < l; i ++) { + var cur = this._buffer[i] + , curHas = cur.length - this._offset + cur.copy(out, outOffset, this._offset) + this._offset = 0 + outOffset += curHas + this._bufferLength -= curHas + } + this.emit("data", out) + } + // truncate + this._buffer.length = 0 + this._bufferLength = 0 + this._offset = 0 + } + + // now either drained or ended + // debug("either draining, or ended", this._bufferLength, this._ended) + // means that we've flushed out all that we can so far. + if (this._needDrain) { + // debug("emitting drain", this._bufferLength) + this._needDrain = false + this.emit("drain") + } + + if ((this._bufferLength === 0) && this._ended && !this._endEmitted) { + // debug("emitting end", this._bufferLength) + this._endEmitted = true + this.emit("end") + } + + this._emitting = false + + // debug(" BS no longer emitting", flush, this._paused, this._emitting, this._bufferLength, this._chunkSize) +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/LICENSE b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/LICENSE new file mode 100644 index 000000000..0c44ae716 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/LICENSE @@ -0,0 +1,27 @@ +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/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/README.md b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/README.md new file mode 100644 index 000000000..9d8cb77e5 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/README.md @@ -0,0 +1,76 @@ +Like FS streams, but with stat on them, and supporting directories and +symbolic links, as well as normal files. Also, you can use this to set +the stats on a file, even if you don't change its contents, or to create +a symlink, etc. + +So, for example, you can "write" a directory, and it'll call `mkdir`. You +can specify a uid and gid, and it'll call `chown`. You can specify a +`mtime` and `atime`, and it'll call `utimes`. You can call it a symlink +and provide a `linkpath` and it'll call `symlink`. + +Note that it won't automatically resolve symbolic links. So, if you +call `fstream.Reader('/some/symlink')` then you'll get an object +that stats and then ends immediately (since it has no data). To follow +symbolic links, do this: `fstream.Reader({path:'/some/symlink', follow: +true })`. + +There are various checks to make sure that the bytes emitted are the +same as the intended size, if the size is set. + +## Examples + +```javascript +fstream + .Writer({ path: "path/to/file" + , mode: 0755 + , size: 6 + }) + .write("hello\n") + .end() +``` + +This will create the directories if they're missing, and then write +`hello\n` into the file, chmod it to 0755, and assert that 6 bytes have +been written when it's done. + +```javascript +fstream + .Writer({ path: "path/to/file" + , mode: 0755 + , size: 6 + , flags: "a" + }) + .write("hello\n") + .end() +``` + +You can pass flags in, if you want to append to a file. + +```javascript +fstream + .Writer({ path: "path/to/symlink" + , linkpath: "./file" + , SymbolicLink: true + , mode: "0755" // octal strings supported + }) + .end() +``` + +If isSymbolicLink is a function, it'll be called, and if it returns +true, then it'll treat it as a symlink. If it's not a function, then +any truish value will make a symlink, or you can set `type: +'SymbolicLink'`, which does the same thing. + +Note that the linkpath is relative to the symbolic link location, not +the parent dir or cwd. + +```javascript +fstream + .Reader("path/to/dir") + .pipe(fstream.Writer("path/to/other/dir")) +``` + +This will do like `cp -Rp path/to/dir path/to/other/dir`. If the other +dir exists and isn't a directory, then it'll emit an error. It'll also +set the uid, gid, mode, etc. to be identical. In this way, it's more +like `rsync -a` than simply a copy. diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/fstream.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/fstream.js new file mode 100644 index 000000000..c66d26f51 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/fstream.js @@ -0,0 +1,31 @@ +exports.Abstract = require("./lib/abstract.js") +exports.Reader = require("./lib/reader.js") +exports.Writer = require("./lib/writer.js") + +exports.File = + { Reader: require("./lib/file-reader.js") + , Writer: require("./lib/file-writer.js") } + +exports.Dir = + { Reader : require("./lib/dir-reader.js") + , Writer : require("./lib/dir-writer.js") } + +exports.Link = + { Reader : require("./lib/link-reader.js") + , Writer : require("./lib/link-writer.js") } + +exports.Proxy = + { Reader : require("./lib/proxy-reader.js") + , Writer : require("./lib/proxy-writer.js") } + +exports.Reader.Dir = exports.DirReader = exports.Dir.Reader +exports.Reader.File = exports.FileReader = exports.File.Reader +exports.Reader.Link = exports.LinkReader = exports.Link.Reader +exports.Reader.Proxy = exports.ProxyReader = exports.Proxy.Reader + +exports.Writer.Dir = exports.DirWriter = exports.Dir.Writer +exports.Writer.File = exports.FileWriter = exports.File.Writer +exports.Writer.Link = exports.LinkWriter = exports.Link.Writer +exports.Writer.Proxy = exports.ProxyWriter = exports.Proxy.Writer + +exports.collect = require("./lib/collect.js") diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/abstract.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/abstract.js new file mode 100644 index 000000000..6161f3bef --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/abstract.js @@ -0,0 +1,85 @@ +// the parent class for all fstreams. + +module.exports = Abstract + +var Stream = require("stream").Stream + , inherits = require("../../inherits/inherits.js") + +function Abstract () { + Stream.call(this) +} + +inherits(Abstract, Stream) + +Abstract.prototype.on = function (ev, fn) { + if (ev === "ready" && this.ready) { + process.nextTick(fn.bind(this)) + } else { + Stream.prototype.on.call(this, ev, fn) + } + return this +} + +Abstract.prototype.abort = function () { + this._aborted = true + this.emit("abort") +} + +Abstract.prototype.destroy = function () {} + +Abstract.prototype.warn = function (msg, code) { + var me = this + , er = decorate(msg, code, me) + if (!me.listeners("warn")) { + console.error("%s %s\n" + + "path = %s\n" + + "syscall = %s\n" + + "fstream_type = %s\n" + + "fstream_path = %s\n" + + "fstream_unc_path = %s\n" + + "fstream_class = %s\n" + + "fstream_stack =\n%s\n", + code || "UNKNOWN", + er.stack, + er.path, + er.syscall, + er.fstream_type, + er.fstream_path, + er.fstream_unc_path, + er.fstream_class, + er.fstream_stack.join("\n")) + } else { + me.emit("warn", er) + } +} + +Abstract.prototype.info = function (msg, code) { + this.emit("info", msg, code) +} + +Abstract.prototype.error = function (msg, code, th) { + var er = decorate(msg, code, this) + if (th) throw er + else this.emit("error", er) +} + +function decorate (er, code, me) { + if (!(er instanceof Error)) er = new Error(er) + er.code = er.code || code + er.path = er.path || me.path + er.fstream_type = er.fstream_type || me.type + er.fstream_path = er.fstream_path || me.path + if (me._path !== me.path) { + er.fstream_unc_path = er.fstream_unc_path || me._path + } + if (me.linkpath) { + er.fstream_linkpath = er.fstream_linkpath || me.linkpath + } + er.fstream_class = er.fstream_class || me.constructor.name + er.fstream_stack = er.fstream_stack || + new Error().stack.split(/\n/).slice(3).map(function (s) { + return s.replace(/^ at /, "") + }) + + return er +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/collect.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/collect.js new file mode 100644 index 000000000..a36f780eb --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/collect.js @@ -0,0 +1,67 @@ +module.exports = collect + +function collect (stream) { + if (stream._collected) return + + stream._collected = true + stream.pause() + + stream.on("data", save) + stream.on("end", save) + var buf = [] + function save (b) { + if (typeof b === "string") b = new Buffer(b) + if (Buffer.isBuffer(b) && !b.length) return + buf.push(b) + } + + stream.on("entry", saveEntry) + var entryBuffer = [] + function saveEntry (e) { + collect(e) + entryBuffer.push(e) + } + + stream.on("proxy", proxyPause) + function proxyPause (p) { + p.pause() + } + + + // replace the pipe method with a new version that will + // unlock the buffered stuff. if you just call .pipe() + // without a destination, then it'll re-play the events. + stream.pipe = (function (orig) { return function (dest) { + // console.error(" === open the pipes", dest && dest.path) + + // let the entries flow through one at a time. + // Once they're all done, then we can resume completely. + var e = 0 + ;(function unblockEntry () { + var entry = entryBuffer[e++] + // console.error(" ==== unblock entry", entry && entry.path) + if (!entry) return resume() + entry.on("end", unblockEntry) + if (dest) dest.add(entry) + else stream.emit("entry", entry) + })() + + function resume () { + stream.removeListener("entry", saveEntry) + stream.removeListener("data", save) + stream.removeListener("end", save) + + stream.pipe = orig + if (dest) stream.pipe(dest) + + buf.forEach(function (b) { + if (b) stream.emit("data", b) + else stream.emit("end") + }) + + stream.resume() + } + + return dest + }})(stream.pipe) +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/dir-reader.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/dir-reader.js new file mode 100644 index 000000000..e655b0d98 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/dir-reader.js @@ -0,0 +1,250 @@ +// A thing that emits "entry" events with Reader objects +// Pausing it causes it to stop emitting entry events, and also +// pauses the current entry if there is one. + +module.exports = DirReader + +var fs = require("../../graceful-fs/graceful-fs.js") + , fstream = require("../fstream.js") + , Reader = fstream.Reader + , inherits = require("../../inherits/inherits.js") + , mkdir = require("../../mkdirp") + , path = require("path") + , Reader = require("./reader.js") + , assert = require("assert").ok + +inherits(DirReader, Reader) + +function DirReader (props) { + var me = this + if (!(me instanceof DirReader)) throw new Error( + "DirReader must be called as constructor.") + + // should already be established as a Directory type + if (props.type !== "Directory" || !props.Directory) { + throw new Error("Non-directory type "+ props.type) + } + + me.entries = null + me._index = -1 + me._paused = false + me._length = -1 + + if (props.sort) { + this.sort = props.sort + } + + Reader.call(this, props) +} + +DirReader.prototype._getEntries = function () { + var me = this + + // race condition. might pause() before calling _getEntries, + // and then resume, and try to get them a second time. + if (me._gotEntries) return + me._gotEntries = true + + fs.readdir(me._path, function (er, entries) { + if (er) return me.error(er) + + me.entries = entries + + me.emit("entries", entries) + if (me._paused) me.once("resume", processEntries) + else processEntries() + + function processEntries () { + me._length = me.entries.length + if (typeof me.sort === "function") { + me.entries = me.entries.sort(me.sort.bind(me)) + } + me._read() + } + }) +} + +// start walking the dir, and emit an "entry" event for each one. +DirReader.prototype._read = function () { + var me = this + + if (!me.entries) return me._getEntries() + + if (me._paused || me._currentEntry || me._aborted) { + // console.error("DR paused=%j, current=%j, aborted=%j", me._paused, !!me._currentEntry, me._aborted) + return + } + + me._index ++ + if (me._index >= me.entries.length) { + if (!me._ended) { + me._ended = true + me.emit("end") + me.emit("close") + } + return + } + + // ok, handle this one, then. + + // save creating a proxy, by stat'ing the thing now. + var p = path.resolve(me._path, me.entries[me._index]) + assert(p !== me._path) + assert(me.entries[me._index]) + + // set this to prevent trying to _read() again in the stat time. + me._currentEntry = p + fs[ me.props.follow ? "stat" : "lstat" ](p, function (er, stat) { + if (er) return me.error(er) + + var who = me._proxy || me + + stat.path = p + stat.basename = path.basename(p) + stat.dirname = path.dirname(p) + var childProps = me.getChildProps.call(who, stat) + childProps.path = p + childProps.basename = path.basename(p) + childProps.dirname = path.dirname(p) + + var entry = Reader(childProps, stat) + + // console.error("DR Entry", p, stat.size) + + me._currentEntry = entry + + // "entry" events are for direct entries in a specific dir. + // "child" events are for any and all children at all levels. + // This nomenclature is not completely final. + + entry.on("pause", function (who) { + if (!me._paused && !entry._disowned) { + me.pause(who) + } + }) + + entry.on("resume", function (who) { + if (me._paused && !entry._disowned) { + me.resume(who) + } + }) + + entry.on("stat", function (props) { + me.emit("_entryStat", entry, props) + if (entry._aborted) return + if (entry._paused) entry.once("resume", function () { + me.emit("entryStat", entry, props) + }) + else me.emit("entryStat", entry, props) + }) + + entry.on("ready", function EMITCHILD () { + // console.error("DR emit child", entry._path) + if (me._paused) { + // console.error(" DR emit child - try again later") + // pause the child, and emit the "entry" event once we drain. + // console.error("DR pausing child entry") + entry.pause(me) + return me.once("resume", EMITCHILD) + } + + // skip over sockets. they can't be piped around properly, + // so there's really no sense even acknowledging them. + // if someone really wants to see them, they can listen to + // the "socket" events. + if (entry.type === "Socket") { + me.emit("socket", entry) + } else { + me.emitEntry(entry) + } + }) + + var ended = false + entry.on("close", onend) + entry.on("disown", onend) + function onend () { + if (ended) return + ended = true + me.emit("childEnd", entry) + me.emit("entryEnd", entry) + me._currentEntry = null + if (!me._paused) { + me._read() + } + } + + // XXX Remove this. Works in node as of 0.6.2 or so. + // Long filenames should not break stuff. + entry.on("error", function (er) { + if (entry._swallowErrors) { + me.warn(er) + entry.emit("end") + entry.emit("close") + } else { + me.emit("error", er) + } + }) + + // proxy up some events. + ; [ "child" + , "childEnd" + , "warn" + ].forEach(function (ev) { + entry.on(ev, me.emit.bind(me, ev)) + }) + }) +} + +DirReader.prototype.disown = function (entry) { + entry.emit("beforeDisown") + entry._disowned = true + entry.parent = entry.root = null + if (entry === this._currentEntry) { + this._currentEntry = null + } + entry.emit("disown") +} + +DirReader.prototype.getChildProps = function (stat) { + return { depth: this.depth + 1 + , root: this.root || this + , parent: this + , follow: this.follow + , filter: this.filter + , sort: this.props.sort + } +} + +DirReader.prototype.pause = function (who) { + var me = this + if (me._paused) return + who = who || me + me._paused = true + if (me._currentEntry && me._currentEntry.pause) { + me._currentEntry.pause(who) + } + me.emit("pause", who) +} + +DirReader.prototype.resume = function (who) { + var me = this + if (!me._paused) return + who = who || me + + me._paused = false + // console.error("DR Emit Resume", me._path) + me.emit("resume", who) + if (me._paused) { + // console.error("DR Re-paused", me._path) + return + } + + if (me._currentEntry) { + if (me._currentEntry.resume) me._currentEntry.resume(who) + } else me._read() +} + +DirReader.prototype.emitEntry = function (entry) { + this.emit("entry", entry) + this.emit("child", entry) +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/dir-writer.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/dir-writer.js new file mode 100644 index 000000000..71eb3584e --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/dir-writer.js @@ -0,0 +1,171 @@ +// It is expected that, when .add() returns false, the consumer +// of the DirWriter will pause until a "drain" event occurs. Note +// that this is *almost always going to be the case*, unless the +// thing being written is some sort of unsupported type, and thus +// skipped over. + +module.exports = DirWriter + +var fs = require("../../graceful-fs/graceful-fs.js") + , fstream = require("../fstream.js") + , Writer = require("./writer.js") + , inherits = require("../../inherits/inherits.js") + , mkdir = require("../../mkdirp") + , path = require("path") + , collect = require("./collect.js") + +inherits(DirWriter, Writer) + +function DirWriter (props) { + var me = this + if (!(me instanceof DirWriter)) me.error( + "DirWriter must be called as constructor.", null, true) + + // should already be established as a Directory type + if (props.type !== "Directory" || !props.Directory) { + me.error("Non-directory type "+ props.type + " " + + JSON.stringify(props), null, true) + } + + Writer.call(this, props) +} + +DirWriter.prototype._create = function () { + var me = this + mkdir(me._path, Writer.dirmode, function (er) { + if (er) return me.error(er) + // ready to start getting entries! + me.ready = true + me.emit("ready") + me._process() + }) +} + +// a DirWriter has an add(entry) method, but its .write() doesn't +// do anything. Why a no-op rather than a throw? Because this +// leaves open the door for writing directory metadata for +// gnu/solaris style dumpdirs. +DirWriter.prototype.write = function () { + return true +} + +DirWriter.prototype.end = function () { + this._ended = true + this._process() +} + +DirWriter.prototype.add = function (entry) { + var me = this + + // console.error("\tadd", entry._path, "->", me._path) + collect(entry) + if (!me.ready || me._currentEntry) { + me._buffer.push(entry) + return false + } + + // create a new writer, and pipe the incoming entry into it. + if (me._ended) { + return me.error("add after end") + } + + me._buffer.push(entry) + me._process() + + return 0 === this._buffer.length +} + +DirWriter.prototype._process = function () { + var me = this + + // console.error("DW Process p=%j", me._processing, me.basename) + + if (me._processing) return + + var entry = me._buffer.shift() + if (!entry) { + // console.error("DW Drain") + me.emit("drain") + if (me._ended) me._finish() + return + } + + me._processing = true + // console.error("DW Entry", entry._path) + + me.emit("entry", entry) + + // ok, add this entry + // + // don't allow recursive copying + var p = entry + do { + var pp = p._path || p.path + if (pp === me.root._path || pp === me._path || + (pp && pp.indexOf(me._path) === 0)) { + // console.error("DW Exit (recursive)", entry.basename, me._path) + me._processing = false + if (entry._collected) entry.pipe() + return me._process() + } + } while (p = p.parent) + + // console.error("DW not recursive") + + // chop off the entry's root dir, replace with ours + var props = { parent: me + , root: me.root || me + , type: entry.type + , depth: me.depth + 1 } + + var p = entry._path || entry.path || entry.props.path + if (entry.parent) { + p = p.substr(entry.parent._path.length + 1) + } + // get rid of any ../../ shenanigans + props.path = path.join(me.path, path.join("/", p)) + + // if i have a filter, the child should inherit it. + props.filter = me.filter + + // all the rest of the stuff, copy over from the source. + Object.keys(entry.props).forEach(function (k) { + if (!props.hasOwnProperty(k)) { + props[k] = entry.props[k] + } + }) + + // not sure at this point what kind of writer this is. + var child = me._currentChild = new Writer(props) + child.on("ready", function () { + // console.error("DW Child Ready", child.type, child._path) + // console.error(" resuming", entry._path) + entry.pipe(child) + entry.resume() + }) + + // XXX Make this work in node. + // Long filenames should not break stuff. + child.on("error", function (er) { + if (child._swallowErrors) { + me.warn(er) + child.emit("end") + child.emit("close") + } else { + me.emit("error", er) + } + }) + + // we fire _end internally *after* end, so that we don't move on + // until any "end" listeners have had their chance to do stuff. + child.on("close", onend) + var ended = false + function onend () { + if (ended) return + ended = true + // console.error("* DW Child end", child.basename) + me._currentChild = null + me._processing = false + me._process() + } +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/file-reader.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/file-reader.js new file mode 100644 index 000000000..e53718ad6 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/file-reader.js @@ -0,0 +1,147 @@ +// Basically just a wrapper around an fs.ReadStream + +module.exports = FileReader + +var fs = require("../../graceful-fs/graceful-fs.js") + , fstream = require("../fstream.js") + , Reader = fstream.Reader + , inherits = require("../../inherits/inherits.js") + , mkdir = require("../../mkdirp") + , Reader = require("./reader.js") + , EOF = {EOF: true} + , CLOSE = {CLOSE: true} + +inherits(FileReader, Reader) + +function FileReader (props) { + // console.error(" FR create", props.path, props.size, new Error().stack) + var me = this + if (!(me instanceof FileReader)) throw new Error( + "FileReader must be called as constructor.") + + // should already be established as a File type + // XXX Todo: preserve hardlinks by tracking dev+inode+nlink, + // with a HardLinkReader class. + if (!((props.type === "Link" && props.Link) || + (props.type === "File" && props.File))) { + throw new Error("Non-file type "+ props.type) + } + + me._buffer = [] + me._bytesEmitted = 0 + Reader.call(me, props) +} + +FileReader.prototype._getStream = function () { + var me = this + , stream = me._stream = fs.createReadStream(me._path, me.props) + + if (me.props.blksize) { + stream.bufferSize = me.props.blksize + } + + stream.on("open", me.emit.bind(me, "open")) + + stream.on("data", function (c) { + // console.error("\t\t%d %s", c.length, me.basename) + me._bytesEmitted += c.length + // no point saving empty chunks + if (!c.length) return + else if (me._paused || me._buffer.length) { + me._buffer.push(c) + me._read() + } else me.emit("data", c) + }) + + stream.on("end", function () { + if (me._paused || me._buffer.length) { + // console.error("FR Buffering End", me._path) + me._buffer.push(EOF) + me._read() + } else { + me.emit("end") + } + + if (me._bytesEmitted !== me.props.size) { + me.error("Didn't get expected byte count\n"+ + "expect: "+me.props.size + "\n" + + "actual: "+me._bytesEmitted) + } + }) + + stream.on("close", function () { + if (me._paused || me._buffer.length) { + // console.error("FR Buffering Close", me._path) + me._buffer.push(CLOSE) + me._read() + } else { + // console.error("FR close 1", me._path) + me.emit("close") + } + }) + + me._read() +} + +FileReader.prototype._read = function () { + var me = this + // console.error("FR _read", me._path) + if (me._paused) { + // console.error("FR _read paused", me._path) + return + } + + if (!me._stream) { + // console.error("FR _getStream calling", me._path) + return me._getStream() + } + + // clear out the buffer, if there is one. + if (me._buffer.length) { + // console.error("FR _read has buffer", me._buffer.length, me._path) + var buf = me._buffer + for (var i = 0, l = buf.length; i < l; i ++) { + var c = buf[i] + if (c === EOF) { + // console.error("FR Read emitting buffered end", me._path) + me.emit("end") + } else if (c === CLOSE) { + // console.error("FR Read emitting buffered close", me._path) + me.emit("close") + } else { + // console.error("FR Read emitting buffered data", me._path) + me.emit("data", c) + } + + if (me._paused) { + // console.error("FR Read Re-pausing at "+i, me._path) + me._buffer = buf.slice(i) + return + } + } + me._buffer.length = 0 + } + // console.error("FR _read done") + // that's about all there is to it. +} + +FileReader.prototype.pause = function (who) { + var me = this + // console.error("FR Pause", me._path) + if (me._paused) return + who = who || me + me._paused = true + if (me._stream) me._stream.pause() + me.emit("pause", who) +} + +FileReader.prototype.resume = function (who) { + var me = this + // console.error("FR Resume", me._path) + if (!me._paused) return + who = who || me + me.emit("resume", who) + me._paused = false + if (me._stream) me._stream.resume() + me._read() +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/file-writer.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/file-writer.js new file mode 100644 index 000000000..00e078da4 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/file-writer.js @@ -0,0 +1,100 @@ +module.exports = FileWriter + +var fs = require("../../graceful-fs/graceful-fs.js") + , mkdir = require("../../mkdirp") + , Writer = require("./writer.js") + , inherits = require("../../inherits/inherits.js") + , EOF = {} + +inherits(FileWriter, Writer) + +function FileWriter (props) { + var me = this + if (!(me instanceof FileWriter)) throw new Error( + "FileWriter must be called as constructor.") + + // should already be established as a File type + if (props.type !== "File" || !props.File) { + throw new Error("Non-file type "+ props.type) + } + + me._buffer = [] + me._bytesWritten = 0 + + Writer.call(this, props) +} + +FileWriter.prototype._create = function () { + var me = this + if (me._stream) return + + var so = {} + if (me.props.flags) so.flags = me.props.flags + so.mode = Writer.filemode + if (me._old && me._old.blksize) so.bufferSize = me._old.blksize + + me._stream = fs.createWriteStream(me._path, so) + + me._stream.on("open", function (fd) { + // console.error("FW open", me._buffer, me._path) + me.ready = true + me._buffer.forEach(function (c) { + if (c === EOF) me._stream.end() + else me._stream.write(c) + }) + me.emit("ready") + // give this a kick just in case it needs it. + me.emit("drain") + }) + + me._stream.on("drain", function () { me.emit("drain") }) + + me._stream.on("close", function () { + // console.error("\n\nFW Stream Close", me._path, me.size) + me._finish() + }) +} + +FileWriter.prototype.write = function (c) { + var me = this + + me._bytesWritten += c.length + + if (!me.ready) { + if (!Buffer.isBuffer(c) && typeof c !== 'string') + throw new Error('invalid write data') + me._buffer.push(c) + return false + } + + var ret = me._stream.write(c) + // console.error("\t-- fw wrote, _stream says", ret, me._stream._queue.length) + + // allow 2 buffered writes, because otherwise there's just too + // much stop and go bs. + return ret || (me._stream._queue && me._stream._queue.length <= 2) +} + +FileWriter.prototype.end = function (c) { + var me = this + + if (c) me.write(c) + + if (!me.ready) { + me._buffer.push(EOF) + return false + } + + return me._stream.end() +} + +FileWriter.prototype._finish = function () { + var me = this + if (typeof me.size === "number" && me._bytesWritten != me.size) { + me.error( + "Did not get expected byte count.\n" + + "expect: " + me.size + "\n" + + "actual: " + me._bytesWritten) + } + Writer.prototype._finish.call(me) +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/get-type.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/get-type.js new file mode 100644 index 000000000..cd65c41d8 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/get-type.js @@ -0,0 +1,32 @@ +module.exports = getType + +function getType (st) { + var types = + [ "Directory" + , "File" + , "SymbolicLink" + , "Link" // special for hardlinks from tarballs + , "BlockDevice" + , "CharacterDevice" + , "FIFO" + , "Socket" ] + , type + + if (st.type && -1 !== types.indexOf(st.type)) { + st[st.type] = true + return st.type + } + + for (var i = 0, l = types.length; i < l; i ++) { + type = types[i] + var is = st[type] || st["is" + type] + if (typeof is === "function") is = is.call(st) + if (is) { + st[type] = true + st.type = type + return type + } + } + + return null +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/link-reader.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/link-reader.js new file mode 100644 index 000000000..1d07e2fc7 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/link-reader.js @@ -0,0 +1,54 @@ +// Basically just a wrapper around an fs.readlink +// +// XXX: Enhance this to support the Link type, by keeping +// a lookup table of {:}, so that hardlinks +// can be preserved in tarballs. + +module.exports = LinkReader + +var fs = require("../../graceful-fs/graceful-fs.js") + , fstream = require("../fstream.js") + , inherits = require("../../inherits/inherits.js") + , mkdir = require("../../mkdirp") + , Reader = require("./reader.js") + +inherits(LinkReader, Reader) + +function LinkReader (props) { + var me = this + if (!(me instanceof LinkReader)) throw new Error( + "LinkReader must be called as constructor.") + + if (!((props.type === "Link" && props.Link) || + (props.type === "SymbolicLink" && props.SymbolicLink))) { + throw new Error("Non-link type "+ props.type) + } + + Reader.call(me, props) +} + +// When piping a LinkReader into a LinkWriter, we have to +// already have the linkpath property set, so that has to +// happen *before* the "ready" event, which means we need to +// override the _stat method. +LinkReader.prototype._stat = function (currentStat) { + var me = this + fs.readlink(me._path, function (er, linkpath) { + if (er) return me.error(er) + me.linkpath = me.props.linkpath = linkpath + me.emit("linkpath", linkpath) + Reader.prototype._stat.call(me, currentStat) + }) +} + +LinkReader.prototype._read = function () { + var me = this + if (me._paused) return + // basically just a no-op, since we got all the info we need + // from the _stat method + if (!me._ended) { + me.emit("end") + me.emit("close") + me._ended = true + } +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/link-writer.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/link-writer.js new file mode 100644 index 000000000..c652eb312 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/link-writer.js @@ -0,0 +1,95 @@ + +module.exports = LinkWriter + +var fs = require("../../graceful-fs/graceful-fs.js") + , Writer = require("./writer.js") + , inherits = require("../../inherits/inherits.js") + , path = require("path") + , rimraf = require("../../rimraf/rimraf.js") + +inherits(LinkWriter, Writer) + +function LinkWriter (props) { + var me = this + if (!(me instanceof LinkWriter)) throw new Error( + "LinkWriter must be called as constructor.") + + // should already be established as a Link type + if (!((props.type === "Link" && props.Link) || + (props.type === "SymbolicLink" && props.SymbolicLink))) { + throw new Error("Non-link type "+ props.type) + } + + if (props.linkpath === "") props.linkpath = "." + if (!props.linkpath) { + me.error("Need linkpath property to create " + props.type) + } + + Writer.call(this, props) +} + +LinkWriter.prototype._create = function () { + // console.error(" LW _create") + var me = this + , hard = me.type === "Link" || process.platform === "win32" + , link = hard ? "link" : "symlink" + , lp = hard ? path.resolve(me.dirname, me.linkpath) : me.linkpath + + // can only change the link path by clobbering + // For hard links, let's just assume that's always the case, since + // there's no good way to read them if we don't already know. + if (hard) return clobber(me, lp, link) + + fs.readlink(me._path, function (er, p) { + // only skip creation if it's exactly the same link + if (p && p === lp) return finish(me) + clobber(me, lp, link) + }) +} + +function clobber (me, lp, link) { + rimraf(me._path, function (er) { + if (er) return me.error(er) + create(me, lp, link) + }) +} + +function create (me, lp, link) { + fs[link](lp, me._path, function (er) { + // if this is a hard link, and we're in the process of writing out a + // directory, it's very possible that the thing we're linking to + // doesn't exist yet (especially if it was intended as a symlink), + // so swallow ENOENT errors here and just soldier in. + // Additionally, an EPERM or EACCES can happen on win32 if it's trying + // to make a link to a directory. Again, just skip it. + // A better solution would be to have fs.symlink be supported on + // windows in some nice fashion. + if (er) { + if ((er.code === "ENOENT" || + er.code === "EACCES" || + er.code === "EPERM" ) && process.platform === "win32") { + me.ready = true + me.emit("ready") + me.emit("end") + me.emit("close") + me.end = me._finish = function () {} + } else return me.error(er) + } + finish(me) + }) +} + +function finish (me) { + me.ready = true + me.emit("ready") + if (me._ended && !me._finished) me._finish() +} + +LinkWriter.prototype.end = function () { + // console.error("LW finish in end") + this._ended = true + if (this.ready) { + this._finished = true + this._finish() + } +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/proxy-reader.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/proxy-reader.js new file mode 100644 index 000000000..a51ebdf72 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/proxy-reader.js @@ -0,0 +1,93 @@ +// A reader for when we don't yet know what kind of thing +// the thing is. + +module.exports = ProxyReader + +var Reader = require("./reader.js") + , getType = require("./get-type.js") + , inherits = require("../../inherits/inherits.js") + , fs = require("../../graceful-fs/graceful-fs.js") + +inherits(ProxyReader, Reader) + +function ProxyReader (props) { + var me = this + if (!(me instanceof ProxyReader)) throw new Error( + "ProxyReader must be called as constructor.") + + me.props = props + me._buffer = [] + me.ready = false + + Reader.call(me, props) +} + +ProxyReader.prototype._stat = function () { + var me = this + , props = me.props + // stat the thing to see what the proxy should be. + , stat = props.follow ? "stat" : "lstat" + + fs[stat](props.path, function (er, current) { + var type + if (er || !current) { + type = "File" + } else { + type = getType(current) + } + + props[type] = true + props.type = me.type = type + + me._old = current + me._addProxy(Reader(props, current)) + }) +} + +ProxyReader.prototype._addProxy = function (proxy) { + var me = this + if (me._proxyTarget) { + return me.error("proxy already set") + } + + me._proxyTarget = proxy + proxy._proxy = me + + ; [ "error" + , "data" + , "end" + , "close" + , "linkpath" + , "entry" + , "entryEnd" + , "child" + , "childEnd" + , "warn" + , "stat" + ].forEach(function (ev) { + // console.error("~~ proxy event", ev, me.path) + proxy.on(ev, me.emit.bind(me, ev)) + }) + + me.emit("proxy", proxy) + + proxy.on("ready", function () { + // console.error("~~ proxy is ready!", me.path) + me.ready = true + me.emit("ready") + }) + + var calls = me._buffer + me._buffer.length = 0 + calls.forEach(function (c) { + proxy[c[0]].apply(proxy, c[1]) + }) +} + +ProxyReader.prototype.pause = function () { + return this._proxyTarget ? this._proxyTarget.pause() : false +} + +ProxyReader.prototype.resume = function () { + return this._proxyTarget ? this._proxyTarget.resume() : false +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/proxy-writer.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/proxy-writer.js new file mode 100644 index 000000000..ea2b560b2 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/proxy-writer.js @@ -0,0 +1,109 @@ +// A writer for when we don't know what kind of thing +// the thing is. That is, it's not explicitly set, +// so we're going to make it whatever the thing already +// is, or "File" +// +// Until then, collect all events. + +module.exports = ProxyWriter + +var Writer = require("./writer.js") + , getType = require("./get-type.js") + , inherits = require("../../inherits/inherits.js") + , collect = require("./collect.js") + , fs = require("fs") + +inherits(ProxyWriter, Writer) + +function ProxyWriter (props) { + var me = this + if (!(me instanceof ProxyWriter)) throw new Error( + "ProxyWriter must be called as constructor.") + + me.props = props + me._needDrain = false + + Writer.call(me, props) +} + +ProxyWriter.prototype._stat = function () { + var me = this + , props = me.props + // stat the thing to see what the proxy should be. + , stat = props.follow ? "stat" : "lstat" + + fs[stat](props.path, function (er, current) { + var type + if (er || !current) { + type = "File" + } else { + type = getType(current) + } + + props[type] = true + props.type = me.type = type + + me._old = current + me._addProxy(Writer(props, current)) + }) +} + +ProxyWriter.prototype._addProxy = function (proxy) { + // console.error("~~ set proxy", this.path) + var me = this + if (me._proxy) { + return me.error("proxy already set") + } + + me._proxy = proxy + ; [ "ready" + , "error" + , "close" + , "pipe" + , "drain" + , "warn" + ].forEach(function (ev) { + proxy.on(ev, me.emit.bind(me, ev)) + }) + + me.emit("proxy", proxy) + + var calls = me._buffer + calls.forEach(function (c) { + // console.error("~~ ~~ proxy buffered call", c[0], c[1]) + proxy[c[0]].apply(proxy, c[1]) + }) + me._buffer.length = 0 + if (me._needsDrain) me.emit("drain") +} + +ProxyWriter.prototype.add = function (entry) { + // console.error("~~ proxy add") + collect(entry) + + if (!this._proxy) { + this._buffer.push(["add", [entry]]) + this._needDrain = true + return false + } + return this._proxy.add(entry) +} + +ProxyWriter.prototype.write = function (c) { + // console.error("~~ proxy write") + if (!this._proxy) { + this._buffer.push(["write", [c]]) + this._needDrain = true + return false + } + return this._proxy.write(c) +} + +ProxyWriter.prototype.end = function (c) { + // console.error("~~ proxy end") + if (!this._proxy) { + this._buffer.push(["end", [c]]) + return false + } + return this._proxy.end(c) +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/reader.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/reader.js new file mode 100644 index 000000000..4ae98eb4f --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/reader.js @@ -0,0 +1,259 @@ + +module.exports = Reader + +var fs = require("../../graceful-fs/graceful-fs.js") + , Stream = require("stream").Stream + , inherits = require("../../inherits/inherits.js") + , path = require("path") + , getType = require("./get-type.js") + , hardLinks = Reader.hardLinks = {} + , Abstract = require("./abstract.js") + +// Must do this *before* loading the child classes +inherits(Reader, Abstract) + +var DirReader = require("./dir-reader.js") + , FileReader = require("./file-reader.js") + , LinkReader = require("./link-reader.js") + , SocketReader = require("./socket-reader.js") + , ProxyReader = require("./proxy-reader.js") + +function Reader (props, currentStat) { + var me = this + if (!(me instanceof Reader)) return new Reader(props, currentStat) + + if (typeof props === "string") { + props = { path: props } + } + + if (!props.path) { + me.error("Must provide a path", null, true) + } + + // polymorphism. + // call fstream.Reader(dir) to get a DirReader object, etc. + // Note that, unlike in the Writer case, ProxyReader is going + // to be the *normal* state of affairs, since we rarely know + // the type of a file prior to reading it. + + + var type + , ClassType + + if (props.type && typeof props.type === "function") { + type = props.type + ClassType = type + } else { + type = getType(props) + ClassType = Reader + } + + if (currentStat && !type) { + type = getType(currentStat) + props[type] = true + props.type = type + } + + switch (type) { + case "Directory": + ClassType = DirReader + break + + case "Link": + // XXX hard links are just files. + // However, it would be good to keep track of files' dev+inode + // and nlink values, and create a HardLinkReader that emits + // a linkpath value of the original copy, so that the tar + // writer can preserve them. + // ClassType = HardLinkReader + // break + + case "File": + ClassType = FileReader + break + + case "SymbolicLink": + ClassType = LinkReader + break + + case "Socket": + ClassType = SocketReader + break + + case null: + ClassType = ProxyReader + break + } + + if (!(me instanceof ClassType)) { + return new ClassType(props) + } + + Abstract.call(me) + + me.readable = true + me.writable = false + + me.type = type + me.props = props + me.depth = props.depth = props.depth || 0 + me.parent = props.parent || null + me.root = props.root || (props.parent && props.parent.root) || me + + me._path = me.path = path.resolve(props.path) + if (process.platform === "win32") { + me.path = me._path = me.path.replace(/\?/g, "_") + if (me._path.length >= 260) { + // how DOES one create files on the moon? + // if the path has spaces in it, then UNC will fail. + me._swallowErrors = true + //if (me._path.indexOf(" ") === -1) { + me._path = "\\\\?\\" + me.path.replace(/\//g, "\\") + //} + } + } + me.basename = props.basename = path.basename(me.path) + me.dirname = props.dirname = path.dirname(me.path) + + // these have served their purpose, and are now just noisy clutter + props.parent = props.root = null + + // console.error("\n\n\n%s setting size to", props.path, props.size) + me.size = props.size + me.filter = typeof props.filter === "function" ? props.filter : null + if (props.sort === "alpha") props.sort = alphasort + + // start the ball rolling. + // this will stat the thing, and then call me._read() + // to start reading whatever it is. + // console.error("calling stat", props.path, currentStat) + me._stat(currentStat) +} + +function alphasort (a, b) { + return a === b ? 0 + : a.toLowerCase() > b.toLowerCase() ? 1 + : a.toLowerCase() < b.toLowerCase() ? -1 + : a > b ? 1 + : -1 +} + +Reader.prototype._stat = function (currentStat) { + var me = this + , props = me.props + , stat = props.follow ? "stat" : "lstat" + + // console.error("Reader._stat", me._path, currentStat) + if (currentStat) process.nextTick(statCb.bind(null, null, currentStat)) + else fs[stat](me._path, statCb) + + + function statCb (er, props_) { + // console.error("Reader._stat, statCb", me._path, props_, props_.nlink) + if (er) return me.error(er) + + Object.keys(props_).forEach(function (k) { + props[k] = props_[k] + }) + + // if it's not the expected size, then abort here. + if (undefined !== me.size && props.size !== me.size) { + return me.error("incorrect size") + } + me.size = props.size + + var type = getType(props) + // special little thing for handling hardlinks. + if (type !== "Directory" && props.nlink && props.nlink > 1) { + var k = props.dev + ":" + props.ino + // console.error("Reader has nlink", me._path, k) + if (hardLinks[k] === me._path || !hardLinks[k]) hardLinks[k] = me._path + else { + // switch into hardlink mode. + type = me.type = me.props.type = "Link" + me.Link = me.props.Link = true + me.linkpath = me.props.linkpath = hardLinks[k] + // console.error("Hardlink detected, switching mode", me._path, me.linkpath) + // Setting __proto__ would arguably be the "correct" + // approach here, but that just seems too wrong. + me._stat = me._read = LinkReader.prototype._read + } + } + + if (me.type && me.type !== type) { + me.error("Unexpected type: " + type) + } + + // if the filter doesn't pass, then just skip over this one. + // still have to emit end so that dir-walking can move on. + if (me.filter) { + var who = me._proxy || me + // special handling for ProxyReaders + if (!me.filter.call(who, who, props)) { + if (!me._disowned) { + me.abort() + me.emit("end") + me.emit("close") + } + return + } + } + + // last chance to abort or disown before the flow starts! + var events = ["_stat", "stat", "ready"] + var e = 0 + ;(function go () { + if (me._aborted) { + me.emit("end") + me.emit("close") + return + } + + if (me._paused) { + me.once("resume", go) + return + } + + var ev = events[e ++] + if (!ev) return me._read() + me.emit(ev, props) + go() + })() + } +} + +Reader.prototype.pipe = function (dest, opts) { + var me = this + if (typeof dest.add === "function") { + // piping to a multi-compatible, and we've got directory entries. + me.on("entry", function (entry) { + var ret = dest.add(entry) + if (false === ret) { + me.pause() + } + }) + } + + // console.error("R Pipe apply Stream Pipe") + return Stream.prototype.pipe.apply(this, arguments) +} + +Reader.prototype.pause = function (who) { + this._paused = true + who = who || this + this.emit("pause", who) + if (this._stream) this._stream.pause(who) +} + +Reader.prototype.resume = function (who) { + this._paused = false + who = who || this + this.emit("resume", who) + if (this._stream) this._stream.resume(who) + this._read() +} + +Reader.prototype._read = function () { + this.error("Cannot read unknown type: "+this.type) +} + diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/socket-reader.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/socket-reader.js new file mode 100644 index 000000000..1de8ce9a1 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/socket-reader.js @@ -0,0 +1,38 @@ +// Just get the stats, and then don't do anything. +// You can't really "read" from a socket. You "connect" to it. +// Mostly, this is here so that reading a dir with a socket in it +// doesn't blow up. + +module.exports = SocketReader + +var fs = require("../../graceful-fs/graceful-fs.js") + , fstream = require("../fstream.js") + , inherits = require("../../inherits/inherits.js") + , mkdir = require("../../mkdirp") + , Reader = require("./reader.js") + +inherits(SocketReader, Reader) + +function SocketReader (props) { + var me = this + if (!(me instanceof SocketReader)) throw new Error( + "SocketReader must be called as constructor.") + + if (!(props.type === "Socket" && props.Socket)) { + throw new Error("Non-socket type "+ props.type) + } + + Reader.call(me, props) +} + +SocketReader.prototype._read = function () { + var me = this + if (me._paused) return + // basically just a no-op, since we got all the info we have + // from the _stat method + if (!me._ended) { + me.emit("end") + me.emit("close") + me._ended = true + } +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/writer.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/writer.js new file mode 100644 index 000000000..f689baff6 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/fstream/lib/writer.js @@ -0,0 +1,389 @@ + +module.exports = Writer + +var fs = require("../../graceful-fs/graceful-fs.js") + , inherits = require("../../inherits/inherits.js") + , rimraf = require("../../rimraf/rimraf.js") + , mkdir = require("../../mkdirp") + , path = require("path") + , umask = process.platform === "win32" ? 0 : process.umask() + , getType = require("./get-type.js") + , Abstract = require("./abstract.js") + +// Must do this *before* loading the child classes +inherits(Writer, Abstract) + +Writer.dirmode = 0777 & (~umask) +Writer.filemode = 0666 & (~umask) + +var DirWriter = require("./dir-writer.js") + , LinkWriter = require("./link-writer.js") + , FileWriter = require("./file-writer.js") + , ProxyWriter = require("./proxy-writer.js") + +// props is the desired state. current is optionally the current stat, +// provided here so that subclasses can avoid statting the target +// more than necessary. +function Writer (props, current) { + var me = this + + if (typeof props === "string") { + props = { path: props } + } + + if (!props.path) me.error("Must provide a path", null, true) + + // polymorphism. + // call fstream.Writer(dir) to get a DirWriter object, etc. + var type = getType(props) + , ClassType = Writer + + switch (type) { + case "Directory": + ClassType = DirWriter + break + case "File": + ClassType = FileWriter + break + case "Link": + case "SymbolicLink": + ClassType = LinkWriter + break + case null: + // Don't know yet what type to create, so we wrap in a proxy. + ClassType = ProxyWriter + break + } + + if (!(me instanceof ClassType)) return new ClassType(props) + + // now get down to business. + + Abstract.call(me) + + // props is what we want to set. + // set some convenience properties as well. + me.type = props.type + me.props = props + me.depth = props.depth || 0 + me.clobber = false === props.clobber ? props.clobber : true + me.parent = props.parent || null + me.root = props.root || (props.parent && props.parent.root) || me + + me._path = me.path = path.resolve(props.path) + if (process.platform === "win32") { + me.path = me._path = me.path.replace(/\?/g, "_") + if (me._path.length >= 260) { + me._swallowErrors = true + me._path = "\\\\?\\" + me.path.replace(/\//g, "\\") + } + } + me.basename = path.basename(props.path) + me.dirname = path.dirname(props.path) + me.linkpath = props.linkpath || null + + props.parent = props.root = null + + // console.error("\n\n\n%s setting size to", props.path, props.size) + me.size = props.size + + if (typeof props.mode === "string") { + props.mode = parseInt(props.mode, 8) + } + + me.readable = false + me.writable = true + + // buffer until ready, or while handling another entry + me._buffer = [] + me.ready = false + + me.filter = typeof props.filter === "function" ? props.filter: null + + // start the ball rolling. + // this checks what's there already, and then calls + // me._create() to call the impl-specific creation stuff. + me._stat(current) +} + +// Calling this means that it's something we can't create. +// Just assert that it's already there, otherwise raise a warning. +Writer.prototype._create = function () { + var me = this + fs[me.props.follow ? "stat" : "lstat"](me._path, function (er, current) { + if (er) { + return me.warn("Cannot create " + me._path + "\n" + + "Unsupported type: "+me.type, "ENOTSUP") + } + me._finish() + }) +} + +Writer.prototype._stat = function (current) { + var me = this + , props = me.props + , stat = props.follow ? "stat" : "lstat" + , who = me._proxy || me + + if (current) statCb(null, current) + else fs[stat](me._path, statCb) + + function statCb (er, current) { + if (me.filter && !me.filter.call(who, who, current)) { + me._aborted = true + me.emit("end") + me.emit("close") + return + } + + // if it's not there, great. We'll just create it. + // if it is there, then we'll need to change whatever differs + if (er || !current) { + return create(me) + } + + me._old = current + var currentType = getType(current) + + // if it's a type change, then we need to clobber or error. + // if it's not a type change, then let the impl take care of it. + if (currentType !== me.type) { + return rimraf(me._path, function (er) { + if (er) return me.error(er) + me._old = null + create(me) + }) + } + + // otherwise, just handle in the app-specific way + // this creates a fs.WriteStream, or mkdir's, or whatever + create(me) + } +} + +function create (me) { + // console.error("W create", me._path, Writer.dirmode) + + // XXX Need to clobber non-dirs that are in the way, + // unless { clobber: false } in the props. + mkdir(path.dirname(me._path), Writer.dirmode, function (er, made) { + // console.error("W created", path.dirname(me._path), er) + if (er) return me.error(er) + + // later on, we have to set the mode and owner for these + me._madeDir = made + return me._create() + }) +} + +function endChmod (me, want, current, path, cb) { + var wantMode = want.mode + , chmod = want.follow || me.type !== "SymbolicLink" + ? "chmod" : "lchmod" + + if (!fs[chmod]) return cb() + if (typeof wantMode !== "number") return cb() + + var curMode = current.mode & 0777 + wantMode = wantMode & 0777 + if (wantMode === curMode) return cb() + + fs[chmod](path, wantMode, cb) +} + + +function endChown (me, want, current, path, cb) { + // Don't even try it unless root. Too easy to EPERM. + if (process.platform === "win32") return cb() + if (!process.getuid || !process.getuid() === 0) return cb() + if (typeof want.uid !== "number" && + typeof want.gid !== "number" ) return cb() + + if (current.uid === want.uid && + current.gid === want.gid) return cb() + + var chown = (me.props.follow || me.type !== "SymbolicLink") + ? "chown" : "lchown" + if (!fs[chown]) return cb() + + if (typeof want.uid !== "number") want.uid = current.uid + if (typeof want.gid !== "number") want.gid = current.gid + + fs[chown](path, want.uid, want.gid, cb) +} + +function endUtimes (me, want, current, path, cb) { + if (!fs.utimes || process.platform === "win32") return cb() + + var utimes = (want.follow || me.type !== "SymbolicLink") + ? "utimes" : "lutimes" + + if (utimes === "lutimes" && !fs[utimes]) { + utimes = "utimes" + } + + if (!fs[utimes]) return cb() + + var curA = current.atime + , curM = current.mtime + , meA = want.atime + , meM = want.mtime + + if (meA === undefined) meA = curA + if (meM === undefined) meM = curM + + if (!isDate(meA)) meA = new Date(meA) + if (!isDate(meM)) meA = new Date(meM) + + if (meA.getTime() === curA.getTime() && + meM.getTime() === curM.getTime()) return cb() + + fs[utimes](path, meA, meM, cb) +} + + +// XXX This function is beastly. Break it up! +Writer.prototype._finish = function () { + var me = this + + // console.error(" W Finish", me._path, me.size) + + // set up all the things. + // At this point, we're already done writing whatever we've gotta write, + // adding files to the dir, etc. + var todo = 0 + var errState = null + var done = false + + if (me._old) { + // the times will almost *certainly* have changed. + // adds the utimes syscall, but remove another stat. + me._old.atime = new Date(0) + me._old.mtime = new Date(0) + // console.error(" W Finish Stale Stat", me._path, me.size) + setProps(me._old) + } else { + var stat = me.props.follow ? "stat" : "lstat" + // console.error(" W Finish Stating", me._path, me.size) + fs[stat](me._path, function (er, current) { + // console.error(" W Finish Stated", me._path, me.size, current) + if (er) { + // if we're in the process of writing out a + // directory, it's very possible that the thing we're linking to + // doesn't exist yet (especially if it was intended as a symlink), + // so swallow ENOENT errors here and just soldier on. + if (er.code === "ENOENT" && + (me.type === "Link" || me.type === "SymbolicLink") && + process.platform === "win32") { + me.ready = true + me.emit("ready") + me.emit("end") + me.emit("close") + me.end = me._finish = function () {} + return + } else return me.error(er) + } + setProps(me._old = current) + }) + } + + return + + function setProps (current) { + todo += 3 + endChmod(me, me.props, current, me._path, next("chmod")) + endChown(me, me.props, current, me._path, next("chown")) + endUtimes(me, me.props, current, me._path, next("utimes")) + } + + function next (what) { + return function (er) { + // console.error(" W Finish", what, todo) + if (errState) return + if (er) { + er.fstream_finish_call = what + return me.error(errState = er) + } + if (--todo > 0) return + if (done) return + done = true + + // we may still need to set the mode/etc. on some parent dirs + // that were created previously. delay end/close until then. + if (!me._madeDir) return end() + else endMadeDir(me, me._path, end) + + function end (er) { + if (er) { + er.fstream_finish_call = "setupMadeDir" + return me.error(er) + } + // all the props have been set, so we're completely done. + me.emit("end") + me.emit("close") + } + } + } +} + +function endMadeDir (me, p, cb) { + var made = me._madeDir + // everything *between* made and path.dirname(me._path) + // needs to be set up. Note that this may just be one dir. + var d = path.dirname(p) + + endMadeDir_(me, d, function (er) { + if (er) return cb(er) + if (d === made) { + return cb() + } + endMadeDir(me, d, cb) + }) +} + +function endMadeDir_ (me, p, cb) { + var dirProps = {} + Object.keys(me.props).forEach(function (k) { + dirProps[k] = me.props[k] + + // only make non-readable dirs if explicitly requested. + if (k === "mode" && me.type !== "Directory") { + dirProps[k] = dirProps[k] | 0111 + } + }) + + var todo = 3 + , errState = null + fs.stat(p, function (er, current) { + if (er) return cb(errState = er) + endChmod(me, dirProps, current, p, next) + endChown(me, dirProps, current, p, next) + endUtimes(me, dirProps, current, p, next) + }) + + function next (er) { + if (errState) return + if (er) return cb(errState = er) + if (-- todo === 0) return cb() + } +} + +Writer.prototype.pipe = function () { + this.error("Can't pipe from writable stream") +} + +Writer.prototype.add = function () { + this.error("Cannot add to non-Directory type") +} + +Writer.prototype.write = function () { + return true +} + +function objectToString (d) { + return Object.prototype.toString.call(d) +} + +function isDate(d) { + return typeof d === 'object' && objectToString(d) === '[object Date]'; +} diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/graceful-fs/LICENSE b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/graceful-fs/LICENSE new file mode 100644 index 000000000..05a401094 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/graceful-fs/LICENSE @@ -0,0 +1,23 @@ +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/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/graceful-fs/README.md b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/graceful-fs/README.md new file mode 100644 index 000000000..7d2e681e3 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/graceful-fs/README.md @@ -0,0 +1,5 @@ +Just like node's `fs` module, but it does an incremental back-off when +EMFILE is encountered. + +Useful in asynchronous situations where one needs to try to open lots +and lots of files. diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/graceful-fs/graceful-fs.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/graceful-fs/graceful-fs.js new file mode 100644 index 000000000..fe9c3f4ca --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/graceful-fs/graceful-fs.js @@ -0,0 +1,316 @@ +// this keeps a queue of opened file descriptors, and will make +// fs operations wait until some have closed before trying to open more. + +var fs_ = require("fs") + +var fs = module.exports = {} + +Object.getOwnPropertyNames(fs_).forEach(function(prop) { + var desc = Object.getOwnPropertyDescriptor(fs_, prop) + Object.defineProperty(fs, prop, desc) +}) + +var queue = [] + , constants = require("constants") + +exports = module.exports = fs +fs._curOpen = 0 + +fs.MIN_MAX_OPEN = 64 +fs.MAX_OPEN = 1024 + +var originalOpen = fs.open + , originalOpenSync = fs.openSync + , originalClose = fs.close + , originalCloseSync = fs.closeSync + + +// prevent EMFILE errors +function OpenReq (path, flags, mode, cb) { + this.path = path + this.flags = flags + this.mode = mode + this.cb = cb +} + +function noop () {} + +fs.open = gracefulOpen + +function gracefulOpen (path, flags, mode, cb) { + if (typeof mode === "function") cb = mode, mode = null + if (typeof cb !== "function") cb = noop + + if (fs._curOpen >= fs.MAX_OPEN) { + queue.push(new OpenReq(path, flags, mode, cb)) + setTimeout(flush) + return + } + open(path, flags, mode, function (er, fd) { + if (er && er.code === "EMFILE" && fs._curOpen > fs.MIN_MAX_OPEN) { + // that was too many. reduce max, get back in queue. + // this should only happen once in a great while, and only + // if the ulimit -n is set lower than 1024. + fs.MAX_OPEN = fs._curOpen - 1 + return fs.open(path, flags, mode, cb) + } + cb(er, fd) + }) +} + +function open (path, flags, mode, cb) { + cb = cb || noop + fs._curOpen ++ + originalOpen.call(fs, path, flags, mode, function (er, fd) { + if (er) onclose() + cb(er, fd) + }) +} + +fs.openSync = function (path, flags, mode) { + var ret + ret = originalOpenSync.call(fs, path, flags, mode) + fs._curOpen ++ + return ret +} + +function onclose () { + fs._curOpen -- + flush() +} + +function flush () { + while (fs._curOpen < fs.MAX_OPEN) { + var req = queue.shift() + if (!req) return + open(req.path, req.flags || "r", req.mode || 0777, req.cb) + } +} + +fs.close = function (fd, cb) { + cb = cb || noop + originalClose.call(fs, fd, function (er) { + onclose() + cb(er) + }) +} + +fs.closeSync = function (fd) { + onclose() + return originalCloseSync.call(fs, fd) +} + + +// (re-)implement some things that are known busted or missing. + +var constants = require("constants") + +// 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/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/inherits/README.md b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/inherits/README.md new file mode 100644 index 000000000..b2beaed93 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/inherits/README.md @@ -0,0 +1,51 @@ +A dead simple way to do inheritance in JS. + + var inherits = require("inherits") + + function Animal () { + this.alive = true + } + Animal.prototype.say = function (what) { + console.log(what) + } + + inherits(Dog, Animal) + function Dog () { + Dog.super.apply(this) + } + Dog.prototype.sniff = function () { + this.say("sniff sniff") + } + Dog.prototype.bark = function () { + this.say("woof woof") + } + + inherits(Chihuahua, Dog) + function Chihuahua () { + Chihuahua.super.apply(this) + } + Chihuahua.prototype.bark = function () { + this.say("yip yip") + } + + // also works + function Cat () { + Cat.super.apply(this) + } + Cat.prototype.hiss = function () { + this.say("CHSKKSS!!") + } + inherits(Cat, Animal, { + meow: function () { this.say("miao miao") } + }) + Cat.prototype.purr = function () { + this.say("purr purr") + } + + + var c = new Chihuahua + assert(c instanceof Chihuahua) + assert(c instanceof Dog) + assert(c instanceof Animal) + +The actual function is laughably small. 10-lines small. diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/inherits/inherits.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/inherits/inherits.js new file mode 100644 index 000000000..061b39620 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/inherits/inherits.js @@ -0,0 +1,29 @@ +module.exports = inherits + +function inherits (c, p, proto) { + proto = proto || {} + var e = {} + ;[c.prototype, proto].forEach(function (s) { + Object.getOwnPropertyNames(s).forEach(function (k) { + e[k] = Object.getOwnPropertyDescriptor(s, k) + }) + }) + c.prototype = Object.create(p.prototype, e) + c.super = p +} + +//function Child () { +// Child.super.call(this) +// console.error([this +// ,this.constructor +// ,this.constructor === Child +// ,this.constructor.super === Parent +// ,Object.getPrototypeOf(this) === Child.prototype +// ,Object.getPrototypeOf(Object.getPrototypeOf(this)) +// === Parent.prototype +// ,this instanceof Child +// ,this instanceof Parent]) +//} +//function Parent () {} +//inherits(Child, Parent) +//new Child diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/mkdirp/LICENSE b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/mkdirp/LICENSE new file mode 100644 index 000000000..432d1aeb0 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/mkdirp/LICENSE @@ -0,0 +1,21 @@ +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/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/mkdirp/index.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/mkdirp/index.js new file mode 100644 index 000000000..fda6de8a2 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/mkdirp/index.js @@ -0,0 +1,82 @@ +var path = require('path'); +var fs = require('fs'); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, mode, f, made) { + if (typeof mode === 'function' || mode === undefined) { + f = mode; + mode = 0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + if (typeof mode === 'string') mode = parseInt(mode, 8); + p = path.resolve(p); + + fs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), mode, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, mode, 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: + fs.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, mode, made) { + if (mode === undefined) { + mode = 0777 & (~process.umask()); + } + if (!made) made = null; + + if (typeof mode === 'string') mode = parseInt(mode, 8); + p = path.resolve(p); + + try { + fs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), mode, made); + sync(p, mode, 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 = fs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/mkdirp/readme.markdown b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/mkdirp/readme.markdown new file mode 100644 index 000000000..83b0216ab --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/mkdirp/readme.markdown @@ -0,0 +1,63 @@ +# 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, 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())`. + +`cb(err, made)` fires with the error or the first directory `made` +that had to be created, if any. + +## 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())`. + +Returns the first directory that had to be created, if any. + +# install + +With [npm](http://npmjs.org) do: + +``` +npm install mkdirp +``` + +# license + +MIT diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/rimraf/AUTHORS b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/rimraf/AUTHORS new file mode 100644 index 000000000..247b75437 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/rimraf/AUTHORS @@ -0,0 +1,6 @@ +# Authors sorted by whether or not they're me. +Isaac Z. Schlueter (http://blog.izs.me) +Wayne Larsen (http://github.com/wvl) +ritch +Marcel Laverdet +Yosef Dinerstein diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/rimraf/LICENSE b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/rimraf/LICENSE new file mode 100644 index 000000000..05a401094 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/rimraf/LICENSE @@ -0,0 +1,23 @@ +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/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/rimraf/README.md b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/rimraf/README.md new file mode 100644 index 000000000..96ce9b2a0 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/rimraf/README.md @@ -0,0 +1,21 @@ +A `rm -rf` for node. + +Install with `npm install rimraf`, or just drop rimraf.js somewhere. + +## API + +`rimraf(f, callback)` + +The callback will be called with an error if there is one. Certain +errors are handled for you: + +* `EBUSY` - rimraf will back off a maximum of opts.maxBusyTries times + before giving up. +* `EMFILE` - If too many file descriptors get opened, rimraf will + patiently wait until more become available. + + +## rimraf.sync + +It can remove stuff synchronously, too. But that's not so good. Use +the async API. It's better. diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/rimraf/rimraf.js b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/rimraf/rimraf.js new file mode 100644 index 000000000..2d3ae41b2 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/tar/vendor/rimraf/rimraf.js @@ -0,0 +1,132 @@ +module.exports = rimraf +rimraf.sync = rimrafSync + +var path = require("path") + , fs + +try { + // optional dependency + fs = require("../../graceful-fs/graceful-fs.js") +} catch (er) { + fs = require("fs") +} + +// for EMFILE handling +var timeout = 0 +exports.EMFILE_MAX = 1000 +exports.BUSYTRIES_MAX = 3 + +function rimraf (p, cb) { + if (!cb) throw new Error("No callback passed to rimraf()") + + var busyTries = 0 + rimraf_(p, function CB (er) { + if (er) { + if (er.code === "EBUSY" && busyTries < exports.BUSYTRIES_MAX) { + busyTries ++ + var time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(function () { + rimraf_(p, CB) + }, time) + } + + // this one won't happen if graceful-fs is used. + if (er.code === "EMFILE" && timeout < exports.EMFILE_MAX) { + return setTimeout(function () { + rimraf_(p, CB) + }, timeout ++) + } + + // already gone + if (er.code === "ENOENT") er = null + } + + timeout = 0 + cb(er) + }) +} + +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +function rimraf_ (p, cb) { + fs.unlink(p, function (er) { + if (er && er.code === "ENOENT") + return cb() + if (er && (er.code === "EPERM" || er.code === "EISDIR")) + return rmdir(p, er, cb) + return cb(er) + }) +} + +function rmdir (p, originalEr, cb) { + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + fs.rmdir(p, function (er) { + if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST")) + rmkids(p, cb) + else if (er && er.code === "ENOTDIR") + cb(originalEr) + else + cb(er) + }) +} + +function rmkids(p, cb) { + fs.readdir(p, function (er, files) { + if (er) + return cb(er) + var n = files.length + if (n === 0) + return fs.rmdir(p, cb) + var errState + files.forEach(function (f) { + rimraf(path.join(p, f), function (er) { + if (errState) + return + if (er) + return cb(errState = er) + if (--n === 0) + fs.rmdir(p, cb) + }) + }) + }) +} + +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +function rimrafSync (p) { + try { + fs.unlinkSync(p) + } catch (er) { + if (er.code === "ENOENT") + return + if (er.code !== "EPERM" && er.code !== "EISDIR") + throw er + try { + fs.rmdirSync(p) + } catch (er2) { + if (er2.code === "ENOENT") + return + if (er2.code === "ENOTDIR") + throw er + if (er2.code === "ENOTEMPTY") { + fs.readdirSync(p).forEach(function (f) { + rimrafSync(path.join(p, f)) + }) + fs.rmdirSync(p) + } + } + } +} diff --git a/node/node_modules/grunt/node_modules/underscore/LICENSE b/node/node_modules/grunt/node_modules/lodash/vendor/underscore/LICENSE similarity index 100% rename from node/node_modules/grunt/node_modules/underscore/LICENSE rename to node/node_modules/grunt/node_modules/lodash/vendor/underscore/LICENSE diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/underscore/README.md b/node/node_modules/grunt/node_modules/lodash/vendor/underscore/README.md new file mode 100644 index 000000000..b1f3e50a8 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/underscore/README.md @@ -0,0 +1,19 @@ + __ + /\ \ __ + __ __ ___ \_\ \ __ _ __ ____ ___ ___ _ __ __ /\_\ ____ + /\ \/\ \ /' _ `\ /'_ \ /'__`\/\ __\/ ,__\ / ___\ / __`\/\ __\/'__`\ \/\ \ /',__\ + \ \ \_\ \/\ \/\ \/\ \ \ \/\ __/\ \ \//\__, `\/\ \__//\ \ \ \ \ \//\ __/ __ \ \ \/\__, `\ + \ \____/\ \_\ \_\ \___,_\ \____\\ \_\\/\____/\ \____\ \____/\ \_\\ \____\/\_\ _\ \ \/\____/ + \/___/ \/_/\/_/\/__,_ /\/____/ \/_/ \/___/ \/____/\/___/ \/_/ \/____/\/_//\ \_\ \/___/ + \ \____/ + \/___/ + +Underscore.js is a utility-belt library for JavaScript that provides +support for the usual functional suspects (each, map, reduce, filter...) +without extending any core JavaScript objects. + +For Docs, License, Tests, and pre-packed downloads, see: +http://underscorejs.org + +Many thanks to our contributors: +https://github.com/documentcloud/underscore/contributors diff --git a/node/node_modules/grunt/node_modules/lodash/vendor/underscore/underscore.js b/node/node_modules/grunt/node_modules/lodash/vendor/underscore/underscore.js new file mode 100644 index 000000000..5a4907b00 --- /dev/null +++ b/node/node_modules/grunt/node_modules/lodash/vendor/underscore/underscore.js @@ -0,0 +1,1204 @@ +// Underscore.js 1.4.2 +// http://underscorejs.org +// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. +// Underscore may be freely distributed under the MIT license. + +(function() { + + // Baseline setup + // -------------- + + // Establish the root object, `window` in the browser, or `global` on the server. + var root = this; + + // Save the previous value of the `_` variable. + var previousUnderscore = root._; + + // Establish the object that gets returned to break out of a loop iteration. + var breaker = {}; + + // Save bytes in the minified (but not gzipped) version: + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; + + // Create quick reference variables for speed access to core prototypes. + var push = ArrayProto.push, + slice = ArrayProto.slice, + concat = ArrayProto.concat, + unshift = ArrayProto.unshift, + toString = ObjProto.toString, + hasOwnProperty = ObjProto.hasOwnProperty; + + // All **ECMAScript 5** native function implementations that we hope to use + // are declared here. + var + nativeForEach = ArrayProto.forEach, + nativeMap = ArrayProto.map, + nativeReduce = ArrayProto.reduce, + nativeReduceRight = ArrayProto.reduceRight, + nativeFilter = ArrayProto.filter, + nativeEvery = ArrayProto.every, + nativeSome = ArrayProto.some, + nativeIndexOf = ArrayProto.indexOf, + nativeLastIndexOf = ArrayProto.lastIndexOf, + nativeIsArray = Array.isArray, + nativeKeys = Object.keys, + nativeBind = FuncProto.bind; + + // Create a safe reference to the Underscore object for use below. + var _ = function(obj) { + if (obj instanceof _) return obj; + if (!(this instanceof _)) return new _(obj); + this._wrapped = obj; + }; + + // Export the Underscore object for **Node.js**, with + // backwards-compatibility for the old `require()` API. If we're in + // the browser, add `_` as a global object via a string identifier, + // for Closure Compiler "advanced" mode. + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = _; + } + exports._ = _; + } else { + root['_'] = _; + } + + // Current version. + _.VERSION = '1.4.2'; + + // Collection Functions + // -------------------- + + // The cornerstone, an `each` implementation, aka `forEach`. + // Handles objects with the built-in `forEach`, arrays, and raw objects. + // Delegates to **ECMAScript 5**'s native `forEach` if available. + var each = _.each = _.forEach = function(obj, iterator, context) { + if (obj == null) return; + if (nativeForEach && obj.forEach === nativeForEach) { + obj.forEach(iterator, context); + } else if (obj.length === +obj.length) { + for (var i = 0, l = obj.length; i < l; i++) { + if (iterator.call(context, obj[i], i, obj) === breaker) return; + } + } else { + for (var key in obj) { + if (_.has(obj, key)) { + if (iterator.call(context, obj[key], key, obj) === breaker) return; + } + } + } + }; + + // Return the results of applying the iterator to each element. + // Delegates to **ECMAScript 5**'s native `map` if available. + _.map = _.collect = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); + each(obj, function(value, index, list) { + results[results.length] = iterator.call(context, value, index, list); + }); + return results; + }; + + // **Reduce** builds up a single result from a list of values, aka `inject`, + // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. + _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { + var initial = arguments.length > 2; + if (obj == null) obj = []; + if (nativeReduce && obj.reduce === nativeReduce) { + if (context) iterator = _.bind(iterator, context); + return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); + } + each(obj, function(value, index, list) { + if (!initial) { + memo = value; + initial = true; + } else { + memo = iterator.call(context, memo, value, index, list); + } + }); + if (!initial) throw new TypeError('Reduce of empty array with no initial value'); + return memo; + }; + + // The right-associative version of reduce, also known as `foldr`. + // Delegates to **ECMAScript 5**'s native `reduceRight` if available. + _.reduceRight = _.foldr = function(obj, iterator, memo, context) { + var initial = arguments.length > 2; + if (obj == null) obj = []; + if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { + if (context) iterator = _.bind(iterator, context); + return arguments.length > 2 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); + } + var length = obj.length; + if (length !== +length) { + var keys = _.keys(obj); + length = keys.length; + } + each(obj, function(value, index, list) { + index = keys ? keys[--length] : --length; + if (!initial) { + memo = obj[index]; + initial = true; + } else { + memo = iterator.call(context, memo, obj[index], index, list); + } + }); + if (!initial) throw new TypeError('Reduce of empty array with no initial value'); + return memo; + }; + + // Return the first value which passes a truth test. Aliased as `detect`. + _.find = _.detect = function(obj, iterator, context) { + var result; + any(obj, function(value, index, list) { + if (iterator.call(context, value, index, list)) { + result = value; + return true; + } + }); + return result; + }; + + // Return all the elements that pass a truth test. + // Delegates to **ECMAScript 5**'s native `filter` if available. + // Aliased as `select`. + _.filter = _.select = function(obj, iterator, context) { + var results = []; + if (obj == null) return results; + if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); + each(obj, function(value, index, list) { + if (iterator.call(context, value, index, list)) results[results.length] = value; + }); + return results; + }; + + // Return all the elements for which a truth test fails. + _.reject = function(obj, iterator, context) { + return _.filter(obj, function(value, index, list) { + return !iterator.call(context, value, index, list); + }, context); + }; + + // Determine whether all of the elements match a truth test. + // Delegates to **ECMAScript 5**'s native `every` if available. + // Aliased as `all`. + _.every = _.all = function(obj, iterator, context) { + iterator || (iterator = _.identity); + var result = true; + if (obj == null) return result; + if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); + each(obj, function(value, index, list) { + if (!(result = result && iterator.call(context, value, index, list))) return breaker; + }); + return !!result; + }; + + // Determine if at least one element in the object matches a truth test. + // Delegates to **ECMAScript 5**'s native `some` if available. + // Aliased as `any`. + var any = _.some = _.any = function(obj, iterator, context) { + iterator || (iterator = _.identity); + var result = false; + if (obj == null) return result; + if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); + each(obj, function(value, index, list) { + if (result || (result = iterator.call(context, value, index, list))) return breaker; + }); + return !!result; + }; + + // Determine if the array or object contains a given value (using `===`). + // Aliased as `include`. + _.contains = _.include = function(obj, target) { + if (obj == null) return false; + if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; + return any(obj, function(value) { + return value === target; + }); + }; + + // Invoke a method (with arguments) on every item in a collection. + _.invoke = function(obj, method) { + var args = slice.call(arguments, 2); + return _.map(obj, function(value) { + return (_.isFunction(method) ? method : value[method]).apply(value, args); + }); + }; + + // Convenience version of a common use case of `map`: fetching a property. + _.pluck = function(obj, key) { + return _.map(obj, function(value){ return value[key]; }); + }; + + // Convenience version of a common use case of `filter`: selecting only objects + // with specific `key:value` pairs. + _.where = function(obj, attrs) { + if (_.isEmpty(attrs)) return []; + return _.filter(obj, function(value) { + for (var key in attrs) { + if (attrs[key] !== value[key]) return false; + } + return true; + }); + }; + + // Return the maximum element or (element-based computation). + // Can't optimize arrays of integers longer than 65,535 elements. + // See: https://bugs.webkit.org/show_bug.cgi?id=80797 + _.max = function(obj, iterator, context) { + if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { + return Math.max.apply(Math, obj); + } + if (!iterator && _.isEmpty(obj)) return -Infinity; + var result = {computed : -Infinity}; + each(obj, function(value, index, list) { + var computed = iterator ? iterator.call(context, value, index, list) : value; + computed >= result.computed && (result = {value : value, computed : computed}); + }); + return result.value; + }; + + // Return the minimum element (or element-based computation). + _.min = function(obj, iterator, context) { + if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { + return Math.min.apply(Math, obj); + } + if (!iterator && _.isEmpty(obj)) return Infinity; + var result = {computed : Infinity}; + each(obj, function(value, index, list) { + var computed = iterator ? iterator.call(context, value, index, list) : value; + computed < result.computed && (result = {value : value, computed : computed}); + }); + return result.value; + }; + + // Shuffle an array. + _.shuffle = function(obj) { + var rand; + var index = 0; + var shuffled = []; + each(obj, function(value) { + rand = _.random(index++); + shuffled[index - 1] = shuffled[rand]; + shuffled[rand] = value; + }); + return shuffled; + }; + + // An internal function to generate lookup iterators. + var lookupIterator = function(value) { + return _.isFunction(value) ? value : function(obj){ return obj[value]; }; + }; + + // Sort the object's values by a criterion produced by an iterator. + _.sortBy = function(obj, value, context) { + var iterator = lookupIterator(value); + return _.pluck(_.map(obj, function(value, index, list) { + return { + value : value, + index : index, + criteria : iterator.call(context, value, index, list) + }; + }).sort(function(left, right) { + var a = left.criteria; + var b = right.criteria; + if (a !== b) { + if (a > b || a === void 0) return 1; + if (a < b || b === void 0) return -1; + } + return left.index < right.index ? -1 : 1; + }), 'value'); + }; + + // An internal function used for aggregate "group by" operations. + var group = function(obj, value, context, behavior) { + var result = {}; + var iterator = lookupIterator(value); + each(obj, function(value, index) { + var key = iterator.call(context, value, index, obj); + behavior(result, key, value); + }); + return result; + }; + + // Groups the object's values by a criterion. Pass either a string attribute + // to group by, or a function that returns the criterion. + _.groupBy = function(obj, value, context) { + return group(obj, value, context, function(result, key, value) { + (_.has(result, key) ? result[key] : (result[key] = [])).push(value); + }); + }; + + // Counts instances of an object that group by a certain criterion. Pass + // either a string attribute to count by, or a function that returns the + // criterion. + _.countBy = function(obj, value, context) { + return group(obj, value, context, function(result, key, value) { + if (!_.has(result, key)) result[key] = 0; + result[key]++; + }); + }; + + // Use a comparator function to figure out the smallest index at which + // an object should be inserted so as to maintain order. Uses binary search. + _.sortedIndex = function(array, obj, iterator, context) { + iterator = iterator == null ? _.identity : lookupIterator(iterator); + var value = iterator.call(context, obj); + var low = 0, high = array.length; + while (low < high) { + var mid = (low + high) >>> 1; + iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; + } + return low; + }; + + // Safely convert anything iterable into a real, live array. + _.toArray = function(obj) { + if (!obj) return []; + if (obj.length === +obj.length) return slice.call(obj); + return _.values(obj); + }; + + // Return the number of elements in an object. + _.size = function(obj) { + if (obj == null) return 0; + return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; + }; + + // Array Functions + // --------------- + + // Get the first element of an array. Passing **n** will return the first N + // values in the array. Aliased as `head` and `take`. The **guard** check + // allows it to work with `_.map`. + _.first = _.head = _.take = function(array, n, guard) { + if (array == null) return void 0; + return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; + }; + + // Returns everything but the last entry of the array. Especially useful on + // the arguments object. Passing **n** will return all the values in + // the array, excluding the last N. The **guard** check allows it to work with + // `_.map`. + _.initial = function(array, n, guard) { + return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); + }; + + // Get the last element of an array. Passing **n** will return the last N + // values in the array. The **guard** check allows it to work with `_.map`. + _.last = function(array, n, guard) { + if (array == null) return void 0; + if ((n != null) && !guard) { + return slice.call(array, Math.max(array.length - n, 0)); + } else { + return array[array.length - 1]; + } + }; + + // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. + // Especially useful on the arguments object. Passing an **n** will return + // the rest N values in the array. The **guard** + // check allows it to work with `_.map`. + _.rest = _.tail = _.drop = function(array, n, guard) { + return slice.call(array, (n == null) || guard ? 1 : n); + }; + + // Trim out all falsy values from an array. + _.compact = function(array) { + return _.filter(array, function(value){ return !!value; }); + }; + + // Internal implementation of a recursive `flatten` function. + var flatten = function(input, shallow, output) { + each(input, function(value) { + if (_.isArray(value)) { + shallow ? push.apply(output, value) : flatten(value, shallow, output); + } else { + output.push(value); + } + }); + return output; + }; + + // Return a completely flattened version of an array. + _.flatten = function(array, shallow) { + return flatten(array, shallow, []); + }; + + // Return a version of the array that does not contain the specified value(s). + _.without = function(array) { + return _.difference(array, slice.call(arguments, 1)); + }; + + // Produce a duplicate-free version of the array. If the array has already + // been sorted, you have the option of using a faster algorithm. + // Aliased as `unique`. + _.uniq = _.unique = function(array, isSorted, iterator, context) { + if (_.isFunction(isSorted)) { + context = iterator; + iterator = isSorted; + isSorted = false; + } + var initial = iterator ? _.map(array, iterator, context) : array; + var results = []; + var seen = []; + each(initial, function(value, index) { + if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { + seen.push(value); + results.push(array[index]); + } + }); + return results; + }; + + // Produce an array that contains the union: each distinct element from all of + // the passed-in arrays. + _.union = function() { + return _.uniq(concat.apply(ArrayProto, arguments)); + }; + + // Produce an array that contains every item shared between all the + // passed-in arrays. + _.intersection = function(array) { + var rest = slice.call(arguments, 1); + return _.filter(_.uniq(array), function(item) { + return _.every(rest, function(other) { + return _.indexOf(other, item) >= 0; + }); + }); + }; + + // Take the difference between one array and a number of other arrays. + // Only the elements present in just the first array will remain. + _.difference = function(array) { + var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); + return _.filter(array, function(value){ return !_.contains(rest, value); }); + }; + + // Zip together multiple lists into a single array -- elements that share + // an index go together. + _.zip = function() { + var args = slice.call(arguments); + var length = _.max(_.pluck(args, 'length')); + var results = new Array(length); + for (var i = 0; i < length; i++) { + results[i] = _.pluck(args, "" + i); + } + return results; + }; + + // Converts lists into objects. Pass either a single array of `[key, value]` + // pairs, or two parallel arrays of the same length -- one of keys, and one of + // the corresponding values. + _.object = function(list, values) { + if (list == null) return {}; + var result = {}; + for (var i = 0, l = list.length; i < l; i++) { + if (values) { + result[list[i]] = values[i]; + } else { + result[list[i][0]] = list[i][1]; + } + } + return result; + }; + + // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), + // we need this function. Return the position of the first occurrence of an + // item in an array, or -1 if the item is not included in the array. + // Delegates to **ECMAScript 5**'s native `indexOf` if available. + // If the array is large and already in sort order, pass `true` + // for **isSorted** to use binary search. + _.indexOf = function(array, item, isSorted) { + if (array == null) return -1; + var i = 0, l = array.length; + if (isSorted) { + if (typeof isSorted == 'number') { + i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted); + } else { + i = _.sortedIndex(array, item); + return array[i] === item ? i : -1; + } + } + if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); + for (; i < l; i++) if (array[i] === item) return i; + return -1; + }; + + // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. + _.lastIndexOf = function(array, item, from) { + if (array == null) return -1; + var hasIndex = from != null; + if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { + return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); + } + var i = (hasIndex ? from : array.length); + while (i--) if (array[i] === item) return i; + return -1; + }; + + // Generate an integer Array containing an arithmetic progression. A port of + // the native Python `range()` function. See + // [the Python documentation](http://docs.python.org/library/functions.html#range). + _.range = function(start, stop, step) { + if (arguments.length <= 1) { + stop = start || 0; + start = 0; + } + step = arguments[2] || 1; + + var len = Math.max(Math.ceil((stop - start) / step), 0); + var idx = 0; + var range = new Array(len); + + while(idx < len) { + range[idx++] = start; + start += step; + } + + return range; + }; + + // Function (ahem) Functions + // ------------------ + + // Reusable constructor function for prototype setting. + var ctor = function(){}; + + // Create a function bound to a given object (assigning `this`, and arguments, + // optionally). Binding with arguments is also known as `curry`. + // Delegates to **ECMAScript 5**'s native `Function.bind` if available. + // We check for `func.bind` first, to fail fast when `func` is undefined. + _.bind = function bind(func, context) { + var bound, args; + if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); + if (!_.isFunction(func)) throw new TypeError; + args = slice.call(arguments, 2); + return bound = function() { + if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); + ctor.prototype = func.prototype; + var self = new ctor; + var result = func.apply(self, args.concat(slice.call(arguments))); + if (Object(result) === result) return result; + return self; + }; + }; + + // Bind all of an object's methods to that object. Useful for ensuring that + // all callbacks defined on an object belong to it. + _.bindAll = function(obj) { + var funcs = slice.call(arguments, 1); + if (funcs.length == 0) funcs = _.functions(obj); + each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); + return obj; + }; + + // Memoize an expensive function by storing its results. + _.memoize = function(func, hasher) { + var memo = {}; + hasher || (hasher = _.identity); + return function() { + var key = hasher.apply(this, arguments); + return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); + }; + }; + + // Delays a function for the given number of milliseconds, and then calls + // it with the arguments supplied. + _.delay = function(func, wait) { + var args = slice.call(arguments, 2); + return setTimeout(function(){ return func.apply(null, args); }, wait); + }; + + // Defers a function, scheduling it to run after the current call stack has + // cleared. + _.defer = function(func) { + return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); + }; + + // Returns a function, that, when invoked, will only be triggered at most once + // during a given window of time. + _.throttle = function(func, wait) { + var context, args, timeout, result; + var previous = 0; + var later = function() { + previous = new Date; + timeout = null; + result = func.apply(context, args); + }; + return function() { + var now = new Date; + var remaining = wait - (now - previous); + context = this; + args = arguments; + if (remaining <= 0) { + clearTimeout(timeout); + previous = now; + result = func.apply(context, args); + } else if (!timeout) { + timeout = setTimeout(later, remaining); + } + return result; + }; + }; + + // Returns a function, that, as long as it continues to be invoked, will not + // be triggered. The function will be called after it stops being called for + // N milliseconds. If `immediate` is passed, trigger the function on the + // leading edge, instead of the trailing. + _.debounce = function(func, wait, immediate) { + var timeout, result; + return function() { + var context = this, args = arguments; + var later = function() { + timeout = null; + if (!immediate) result = func.apply(context, args); + }; + var callNow = immediate && !timeout; + clearTimeout(timeout); + timeout = setTimeout(later, wait); + if (callNow) result = func.apply(context, args); + return result; + }; + }; + + // Returns a function that will be executed at most one time, no matter how + // often you call it. Useful for lazy initialization. + _.once = function(func) { + var ran = false, memo; + return function() { + if (ran) return memo; + ran = true; + memo = func.apply(this, arguments); + func = null; + return memo; + }; + }; + + // Returns the first function passed as an argument to the second, + // allowing you to adjust arguments, run code before and after, and + // conditionally execute the original function. + _.wrap = function(func, wrapper) { + return function() { + var args = [func]; + push.apply(args, arguments); + return wrapper.apply(this, args); + }; + }; + + // Returns a function that is the composition of a list of functions, each + // consuming the return value of the function that follows. + _.compose = function() { + var funcs = arguments; + return function() { + var args = arguments; + for (var i = funcs.length - 1; i >= 0; i--) { + args = [funcs[i].apply(this, args)]; + } + return args[0]; + }; + }; + + // Returns a function that will only be executed after being called N times. + _.after = function(times, func) { + if (times <= 0) return func(); + return function() { + if (--times < 1) { + return func.apply(this, arguments); + } + }; + }; + + // Object Functions + // ---------------- + + // Retrieve the names of an object's properties. + // Delegates to **ECMAScript 5**'s native `Object.keys` + _.keys = nativeKeys || function(obj) { + if (obj !== Object(obj)) throw new TypeError('Invalid object'); + var keys = []; + for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key; + return keys; + }; + + // Retrieve the values of an object's properties. + _.values = function(obj) { + var values = []; + for (var key in obj) if (_.has(obj, key)) values.push(obj[key]); + return values; + }; + + // Convert an object into a list of `[key, value]` pairs. + _.pairs = function(obj) { + var pairs = []; + for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]); + return pairs; + }; + + // Invert the keys and values of an object. The values must be serializable. + _.invert = function(obj) { + var result = {}; + for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key; + return result; + }; + + // Return a sorted list of the function names available on the object. + // Aliased as `methods` + _.functions = _.methods = function(obj) { + var names = []; + for (var key in obj) { + if (_.isFunction(obj[key])) names.push(key); + } + return names.sort(); + }; + + // Extend a given object with all the properties in passed-in object(s). + _.extend = function(obj) { + each(slice.call(arguments, 1), function(source) { + for (var prop in source) { + obj[prop] = source[prop]; + } + }); + return obj; + }; + + // Return a copy of the object only containing the whitelisted properties. + _.pick = function(obj) { + var copy = {}; + var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); + each(keys, function(key) { + if (key in obj) copy[key] = obj[key]; + }); + return copy; + }; + + // Return a copy of the object without the blacklisted properties. + _.omit = function(obj) { + var copy = {}; + var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); + for (var key in obj) { + if (!_.contains(keys, key)) copy[key] = obj[key]; + } + return copy; + }; + + // Fill in a given object with default properties. + _.defaults = function(obj) { + each(slice.call(arguments, 1), function(source) { + for (var prop in source) { + if (obj[prop] == null) obj[prop] = source[prop]; + } + }); + return obj; + }; + + // Create a (shallow-cloned) duplicate of an object. + _.clone = function(obj) { + if (!_.isObject(obj)) return obj; + return _.isArray(obj) ? obj.slice() : _.extend({}, obj); + }; + + // Invokes interceptor with the obj, and then returns obj. + // The primary purpose of this method is to "tap into" a method chain, in + // order to perform operations on intermediate results within the chain. + _.tap = function(obj, interceptor) { + interceptor(obj); + return obj; + }; + + // Internal recursive comparison function for `isEqual`. + var eq = function(a, b, aStack, bStack) { + // Identical objects are equal. `0 === -0`, but they aren't identical. + // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. + if (a === b) return a !== 0 || 1 / a == 1 / b; + // A strict comparison is necessary because `null == undefined`. + if (a == null || b == null) return a === b; + // Unwrap any wrapped objects. + if (a instanceof _) a = a._wrapped; + if (b instanceof _) b = b._wrapped; + // Compare `[[Class]]` names. + var className = toString.call(a); + if (className != toString.call(b)) return false; + switch (className) { + // Strings, numbers, dates, and booleans are compared by value. + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + return a == String(b); + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for + // other numeric values. + return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + return +a == +b; + // RegExps are compared by their source patterns and flags. + case '[object RegExp]': + return a.source == b.source && + a.global == b.global && + a.multiline == b.multiline && + a.ignoreCase == b.ignoreCase; + } + if (typeof a != 'object' || typeof b != 'object') return false; + // Assume equality for cyclic structures. The algorithm for detecting cyclic + // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + if (aStack[length] == a) return bStack[length] == b; + } + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + var size = 0, result = true; + // Recursively compare objects and arrays. + if (className == '[object Array]') { + // Compare array lengths to determine if a deep comparison is necessary. + size = a.length; + result = size == b.length; + if (result) { + // Deep compare the contents, ignoring non-numeric properties. + while (size--) { + if (!(result = eq(a[size], b[size], aStack, bStack))) break; + } + } + } else { + // Objects with different constructors are not equivalent, but `Object`s + // from different frames are. + var aCtor = a.constructor, bCtor = b.constructor; + if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && + _.isFunction(bCtor) && (bCtor instanceof bCtor))) { + return false; + } + // Deep compare objects. + for (var key in a) { + if (_.has(a, key)) { + // Count the expected number of properties. + size++; + // Deep compare each member. + if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; + } + } + // Ensure that both objects contain the same number of properties. + if (result) { + for (key in b) { + if (_.has(b, key) && !(size--)) break; + } + result = !size; + } + } + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + return result; + }; + + // Perform a deep comparison to check if two objects are equal. + _.isEqual = function(a, b) { + return eq(a, b, [], []); + }; + + // Is a given array, string, or object empty? + // An "empty" object has no enumerable own-properties. + _.isEmpty = function(obj) { + if (obj == null) return true; + if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; + for (var key in obj) if (_.has(obj, key)) return false; + return true; + }; + + // Is a given value a DOM element? + _.isElement = function(obj) { + return !!(obj && obj.nodeType === 1); + }; + + // Is a given value an array? + // Delegates to ECMA5's native Array.isArray + _.isArray = nativeIsArray || function(obj) { + return toString.call(obj) == '[object Array]'; + }; + + // Is a given variable an object? + _.isObject = function(obj) { + return obj === Object(obj); + }; + + // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. + each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { + _['is' + name] = function(obj) { + return toString.call(obj) == '[object ' + name + ']'; + }; + }); + + // Define a fallback version of the method in browsers (ahem, IE), where + // there isn't any inspectable "Arguments" type. + if (!_.isArguments(arguments)) { + _.isArguments = function(obj) { + return !!(obj && _.has(obj, 'callee')); + }; + } + + // Optimize `isFunction` if appropriate. + if (typeof (/./) !== 'function') { + _.isFunction = function(obj) { + return typeof obj === 'function'; + }; + } + + // Is a given object a finite number? + _.isFinite = function(obj) { + return isFinite( obj ) && !isNaN( parseFloat(obj) ); + }; + + // Is the given value `NaN`? (NaN is the only number which does not equal itself). + _.isNaN = function(obj) { + return _.isNumber(obj) && obj != +obj; + }; + + // Is a given value a boolean? + _.isBoolean = function(obj) { + return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; + }; + + // Is a given value equal to null? + _.isNull = function(obj) { + return obj === null; + }; + + // Is a given variable undefined? + _.isUndefined = function(obj) { + return obj === void 0; + }; + + // Shortcut function for checking if an object has a given property directly + // on itself (in other words, not on a prototype). + _.has = function(obj, key) { + return hasOwnProperty.call(obj, key); + }; + + // Utility Functions + // ----------------- + + // Run Underscore.js in *noConflict* mode, returning the `_` variable to its + // previous owner. Returns a reference to the Underscore object. + _.noConflict = function() { + root._ = previousUnderscore; + return this; + }; + + // Keep the identity function around for default iterators. + _.identity = function(value) { + return value; + }; + + // Run a function **n** times. + _.times = function(n, iterator, context) { + for (var i = 0; i < n; i++) iterator.call(context, i); + }; + + // Return a random integer between min and max (inclusive). + _.random = function(min, max) { + if (max == null) { + max = min; + min = 0; + } + return min + (0 | Math.random() * (max - min + 1)); + }; + + // List of HTML entities for escaping. + var entityMap = { + escape: { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '/': '/' + } + }; + entityMap.unescape = _.invert(entityMap.escape); + + // Regexes containing the keys and values listed immediately above. + var entityRegexes = { + escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), + unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') + }; + + // Functions for escaping and unescaping strings to/from HTML interpolation. + _.each(['escape', 'unescape'], function(method) { + _[method] = function(string) { + if (string == null) return ''; + return ('' + string).replace(entityRegexes[method], function(match) { + return entityMap[method][match]; + }); + }; + }); + + // If the value of the named property is a function then invoke it; + // otherwise, return it. + _.result = function(object, property) { + if (object == null) return null; + var value = object[property]; + return _.isFunction(value) ? value.call(object) : value; + }; + + // Add your own custom functions to the Underscore object. + _.mixin = function(obj) { + each(_.functions(obj), function(name){ + var func = _[name] = obj[name]; + _.prototype[name] = function() { + var args = [this._wrapped]; + push.apply(args, arguments); + return result.call(this, func.apply(_, args)); + }; + }); + }; + + // Generate a unique integer id (unique within the entire client session). + // Useful for temporary DOM ids. + var idCounter = 0; + _.uniqueId = function(prefix) { + var id = idCounter++; + return prefix ? prefix + id : id; + }; + + // By default, Underscore uses ERB-style template delimiters, change the + // following template settings to use alternative delimiters. + _.templateSettings = { + evaluate : /<%([\s\S]+?)%>/g, + interpolate : /<%=([\s\S]+?)%>/g, + escape : /<%-([\s\S]+?)%>/g + }; + + // When customizing `templateSettings`, if you don't want to define an + // interpolation, evaluation or escaping regex, we need one that is + // guaranteed not to match. + var noMatch = /(.)^/; + + // Certain characters need to be escaped so that they can be put into a + // string literal. + var escapes = { + "'": "'", + '\\': '\\', + '\r': 'r', + '\n': 'n', + '\t': 't', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; + + // JavaScript micro-templating, similar to John Resig's implementation. + // Underscore templating handles arbitrary delimiters, preserves whitespace, + // and correctly escapes quotes within interpolated code. + _.template = function(text, data, settings) { + settings = _.defaults({}, settings, _.templateSettings); + + // Combine delimiters into one regular expression via alternation. + var matcher = new RegExp([ + (settings.escape || noMatch).source, + (settings.interpolate || noMatch).source, + (settings.evaluate || noMatch).source + ].join('|') + '|$', 'g'); + + // Compile the template source, escaping string literals appropriately. + var index = 0; + var source = "__p+='"; + text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { + source += text.slice(index, offset) + .replace(escaper, function(match) { return '\\' + escapes[match]; }); + source += + escape ? "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'" : + interpolate ? "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'" : + evaluate ? "';\n" + evaluate + "\n__p+='" : ''; + index = offset + match.length; + }); + source += "';\n"; + + // If a variable is not specified, place data values in local scope. + if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; + + source = "var __t,__p='',__j=Array.prototype.join," + + "print=function(){__p+=__j.call(arguments,'');};\n" + + source + "return __p;\n"; + + try { + var render = new Function(settings.variable || 'obj', '_', source); + } catch (e) { + e.source = source; + throw e; + } + + if (data) return render(data, _); + var template = function(data) { + return render.call(this, data, _); + }; + + // Provide the compiled function source as a convenience for precompilation. + template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; + + return template; + }; + + // Add a "chain" function, which will delegate to the wrapper. + _.chain = function(obj) { + return _(obj).chain(); + }; + + // OOP + // --------------- + // If Underscore is called as a function, it returns a wrapped object that + // can be used OO-style. This wrapper holds altered versions of all the + // underscore functions. Wrapped objects may be chained. + + // Helper function to continue chaining intermediate results. + var result = function(obj) { + return this._chain ? _(obj).chain() : obj; + }; + + // Add all of the Underscore functions to the wrapper object. + _.mixin(_); + + // Add all mutator Array functions to the wrapper. + each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + var obj = this._wrapped; + method.apply(obj, arguments); + if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; + return result.call(this, obj); + }; + }); + + // Add all accessor Array functions to the wrapper. + each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + return result.call(this, method.apply(this._wrapped, arguments)); + }; + }); + + _.extend(_.prototype, { + + // Start chaining a wrapped Underscore object. + chain: function() { + this._chain = true; + return this; + }, + + // Extracts the result from a wrapped and chained object. + value: function() { + return this._wrapped; + } + + }); + +}).call(this); diff --git a/node/node_modules/grunt/node_modules/minimatch/LICENSE b/node/node_modules/grunt/node_modules/minimatch/LICENSE new file mode 100644 index 000000000..05a401094 --- /dev/null +++ b/node/node_modules/grunt/node_modules/minimatch/LICENSE @@ -0,0 +1,23 @@ +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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/README.md b/node/node_modules/grunt/node_modules/minimatch/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/README.md rename to node/node_modules/grunt/node_modules/minimatch/README.md diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/minimatch.js b/node/node_modules/grunt/node_modules/minimatch/minimatch.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/minimatch.js rename to node/node_modules/grunt/node_modules/minimatch/minimatch.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.npmignore b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/.npmignore similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/.npmignore rename to node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/.npmignore diff --git a/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/AUTHORS b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/AUTHORS new file mode 100644 index 000000000..016d7fbe1 --- /dev/null +++ b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/AUTHORS @@ -0,0 +1,8 @@ +# Authors, sorted by whether or not they are me +Isaac Z. Schlueter +Carlos Brito Lage +Marko Mikulicic +Trent Mick +Kevin O'Hara +Marco Rogers +Jesse Dailey diff --git a/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/LICENSE b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/LICENSE new file mode 100644 index 000000000..05a401094 --- /dev/null +++ b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/LICENSE @@ -0,0 +1,23 @@ +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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/README.md b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/README.md rename to node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/README.md diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js rename to node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/lib/lru-cache.js diff --git a/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/package.json b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/package.json new file mode 100644 index 000000000..111e5d7c2 --- /dev/null +++ b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/package.json @@ -0,0 +1,59 @@ +{ + "name": "lru-cache", + "description": "A cache object that deletes the least-recently-used items.", + "version": "2.3.0", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me" + }, + "scripts": { + "test": "tap test --gc" + }, + "main": "lib/lru-cache.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-lru-cache.git" + }, + "devDependencies": { + "tap": "", + "weak": "" + }, + "license": { + "type": "MIT", + "url": "http://github.com/isaacs/node-lru-cache/raw/master/LICENSE" + }, + "contributors": [ + { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me" + }, + { + "name": "Carlos Brito Lage", + "email": "carlos@carloslage.net" + }, + { + "name": "Marko Mikulicic", + "email": "marko.mikulicic@isti.cnr.it" + }, + { + "name": "Trent Mick", + "email": "trentm@gmail.com" + }, + { + "name": "Kevin O'Hara", + "email": "kevinohara80@gmail.com" + }, + { + "name": "Marco Rogers", + "email": "marco.rogers@gmail.com" + }, + { + "name": "Jesse Dailey", + "email": "jesse.dailey@gmail.com" + } + ], + "readme": "# lru cache\n\nA cache object that deletes the least-recently-used items.\n\n## Usage:\n\n```javascript\nvar LRU = require(\"lru-cache\")\n , options = { max: 500\n , length: function (n) { return n * 2 }\n , dispose: function (key, n) { n.close() }\n , maxAge: 1000 * 60 * 60 }\n , cache = LRU(options)\n , otherCache = LRU(50) // sets just the max size\n\ncache.set(\"key\", \"value\")\ncache.get(\"key\") // \"value\"\n\ncache.reset() // empty the cache\n```\n\nIf you put more stuff in it, then items will fall out.\n\nIf you try to put an oversized thing in it, then it'll fall out right\naway.\n\n## Options\n\n* `max` The maximum size of the cache, checked by applying the length\n function to all values in the cache. Not setting this is kind of\n silly, since that's the whole purpose of this lib, but it defaults\n to `Infinity`.\n* `maxAge` Maximum age in ms. Items are not pro-actively pruned out\n as they age, but if you try to get an item that is too old, it'll\n drop it and return undefined instead of giving it to you.\n* `length` Function that is used to calculate the length of stored\n items. If you're storing strings or buffers, then you probably want\n to do something like `function(n){return n.length}`. The default is\n `function(n){return 1}`, which is fine if you want to store `n`\n like-sized things.\n* `dispose` Function that is called on items when they are dropped\n from the cache. This can be handy if you want to close file\n descriptors or do other cleanup tasks when items are no longer\n accessible. Called with `key, value`. It's called *before*\n actually removing the item from the internal cache, so if you want\n to immediately put it back in, you'll have to do that in a\n `nextTick` or `setTimeout` callback or it won't do anything.\n* `stale` By default, if you set a `maxAge`, it'll only actually pull\n stale items out of the cache when you `get(key)`. (That is, it's\n not pre-emptively doing a `setTimeout` or anything.) If you set\n `stale:true`, it'll return the stale value before deleting it. If\n you don't set this, then it'll return `undefined` when you try to\n get a stale entry, as if it had already been deleted.\n\n## API\n\n* `set(key, value)`\n* `get(key) => value`\n\n Both of these will update the \"recently used\"-ness of the key.\n They do what you think.\n\n* `peek(key)`\n\n Returns the key value (or `undefined` if not found) without\n updating the \"recently used\"-ness of the key.\n\n (If you find yourself using this a lot, you *might* be using the\n wrong sort of data structure, but there are some use cases where\n it's handy.)\n\n* `del(key)`\n\n Deletes a key out of the cache.\n\n* `reset()`\n\n Clear the cache entirely, throwing away all values.\n\n* `has(key)`\n\n Check if a key is in the cache, without updating the recent-ness\n or deleting it for being stale.\n\n* `forEach(function(value,key,cache), [thisp])`\n\n Just like `Array.prototype.forEach`. Iterates over all the keys\n in the cache, in order of recent-ness. (Ie, more recently used\n items are iterated over first.)\n\n* `keys()`\n\n Return an array of the keys in the cache.\n\n* `values()`\n\n Return an array of the values in the cache.\n", + "readmeFilename": "README.md", + "_id": "lru-cache@2.3.0", + "_from": "lru-cache@2" +} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/s.js b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/s.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/s.js rename to node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/s.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/basic.js b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/test/basic.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/basic.js rename to node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/test/basic.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/foreach.js b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/test/foreach.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/foreach.js rename to node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/test/foreach.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js b/node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js rename to node/node_modules/grunt/node_modules/minimatch/node_modules/lru-cache/test/memory-leak.js diff --git a/node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/LICENSE b/node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/LICENSE new file mode 100644 index 000000000..0c44ae716 --- /dev/null +++ b/node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/LICENSE @@ -0,0 +1,27 @@ +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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/sigmund/README.md b/node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/README.md similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/sigmund/README.md rename to node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/README.md diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/sigmund/bench.js b/node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/bench.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/sigmund/bench.js rename to node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/bench.js diff --git a/node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/package.json b/node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/package.json new file mode 100644 index 000000000..92a63e961 --- /dev/null +++ b/node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/package.json @@ -0,0 +1,38 @@ +{ + "name": "sigmund", + "version": "1.0.0", + "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" + }, + "keywords": [ + "object", + "signature", + "key", + "data", + "psychoanalysis" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "BSD", + "readme": "# sigmund\n\nQuick and dirty signatures for Objects.\n\nThis is like a much faster `deepEquals` comparison, which returns a\nstring key suitable for caches and the like.\n\n## Usage\n\n```javascript\nfunction doSomething (someObj) {\n var key = sigmund(someObj, maxDepth) // max depth defaults to 10\n var cached = cache.get(key)\n if (cached) return cached)\n\n var result = expensiveCalculation(someObj)\n cache.set(key, result)\n return result\n}\n```\n\nThe resulting key will be as unique and reproducible as calling\n`JSON.stringify` or `util.inspect` on the object, but is much faster.\nIn order to achieve this speed, some differences are glossed over.\nFor example, the object `{0:'foo'}` will be treated identically to the\narray `['foo']`.\n\nAlso, just as there is no way to summon the soul from the scribblings\nof a cocain-addled psychoanalyst, there is no way to revive the object\nfrom the signature string that sigmund gives you. In fact, it's\nbarely even readable.\n\nAs with `sys.inspect` and `JSON.stringify`, larger objects will\nproduce larger signature strings.\n\nBecause sigmund is a bit less strict than the more thorough\nalternatives, the strings will be shorter, and also there is a\nslightly higher chance for collisions. For example, these objects\nhave the same signature:\n\n var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]}\n var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']}\n\nLike a good Freudian, sigmund is most effective when you already have\nsome understanding of what you're looking for. It can help you help\nyourself, but you must be willing to do some work as well.\n\nCycles are handled, and cyclical objects are silently omitted (though\nthe key is included in the signature output.)\n\nThe second argument is the maximum depth, which defaults to 10,\nbecause that is the maximum object traversal depth covered by most\ninsurance carriers.\n", + "readmeFilename": "README.md", + "_id": "sigmund@1.0.0", + "_from": "sigmund@~1.0.0" +} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/sigmund/sigmund.js b/node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/sigmund.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/sigmund/sigmund.js rename to node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/sigmund.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/sigmund/test/basic.js b/node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/test/basic.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/sigmund/test/basic.js rename to node/node_modules/grunt/node_modules/minimatch/node_modules/sigmund/test/basic.js diff --git a/node/node_modules/grunt/node_modules/minimatch/package.json b/node/node_modules/grunt/node_modules/minimatch/package.json new file mode 100644 index 000000000..cb515490e --- /dev/null +++ b/node/node_modules/grunt/node_modules/minimatch/package.json @@ -0,0 +1,36 @@ +{ + "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.12", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "test": "tap test" + }, + "engines": { + "node": "*" + }, + "dependencies": { + "lru-cache": "2", + "sigmund": "~1.0.0" + }, + "devDependencies": { + "tap": "" + }, + "license": { + "type": "MIT", + "url": "http://github.com/isaacs/minimatch/raw/master/LICENSE" + }, + "readme": "# minimatch\n\nA minimal matching utility.\n\n[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch)\n\n\nThis is the matching library used internally by npm.\n\nEventually, it will replace the C binding in node-glob.\n\nIt works by converting glob expressions into JavaScript `RegExp`\nobjects.\n\n## Usage\n\n```javascript\nvar minimatch = require(\"minimatch\")\n\nminimatch(\"bar.foo\", \"*.foo\") // true!\nminimatch(\"bar.foo\", \"*.bar\") // false!\n```\n\n## Features\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\n### Comparisons to other fnmatch/glob implementations\n\nWhile strict compliance with the existing standards is a worthwhile\ngoal, some discrepancies exist between minimatch 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. **Note that this is different from the way that `**` is\nhandled by ruby's `Dir` class.**\n\nIf an escaped pattern has no matches, and the `nonull` flag is set,\nthen minimatch.match returns the pattern as-provided, rather than\ninterpreting the character escapes. For example,\n`minimatch.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\n## Minimatch Class\n\nCreate a minimatch object by instanting the `minimatch.Minimatch` class.\n\n```javascript\nvar Minimatch = require(\"minimatch\").Minimatch\nvar mm = new Minimatch(pattern, options)\n```\n\n### Properties\n\n* `pattern` The original pattern the minimatch object represents.\n* `options` The options supplied to the constructor.\n* `set` A 2-dimensional array of regexp or string expressions.\n Each row in the\n array corresponds to a brace-expanded pattern. Each item in the row\n corresponds to a single path-part. For example, the pattern\n `{a,b/c}/d` would expand to a set of patterns like:\n\n [ [ a, d ]\n , [ b, c, d ] ]\n\n If a portion of the pattern doesn't have any \"magic\" in it\n (that is, it's something like `\"foo\"` rather than `fo*o?`), then it\n will be left as a string rather than converted to a regular\n expression.\n\n* `regexp` Created by the `makeRe` method. A single regular expression\n expressing the entire pattern. This is useful in cases where you wish\n to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.\n* `negate` True if the pattern is negated.\n* `comment` True if the pattern is a comment.\n* `empty` True if the pattern is `\"\"`.\n\n### Methods\n\n* `makeRe` Generate the `regexp` member if necessary, and return it.\n Will return `false` if the pattern is invalid.\n* `match(fname)` Return true if the filename matches the pattern, or\n false otherwise.\n* `matchOne(fileArray, patternArray, partial)` Take a `/`-split\n filename, and match it against a single row in the `regExpSet`. This\n method is mainly for internal use, but is exposed so that it can be\n used by a glob-walker that needs to avoid excessive filesystem calls.\n\nAll other methods are internal, and will be called as necessary.\n\n## Functions\n\nThe top-level exported function has a `cache` property, which is an LRU\ncache set to store 100 items. So, calling these methods repeatedly\nwith the same pattern and options will use the same Minimatch object,\nsaving the cost of parsing it multiple times.\n\n### minimatch(path, pattern, options)\n\nMain export. Tests a path against the pattern using the options.\n\n```javascript\nvar isJS = minimatch(file, \"*.js\", { matchBase: true })\n```\n\n### minimatch.filter(pattern, options)\n\nReturns a function that tests its\nsupplied argument, suitable for use with `Array.filter`. Example:\n\n```javascript\nvar javascripts = fileList.filter(minimatch.filter(\"*.js\", {matchBase: true}))\n```\n\n### minimatch.match(list, pattern, options)\n\nMatch against the list of\nfiles, in the style of fnmatch or glob. If nothing is matched, and\noptions.nonull is set, then return a list containing the pattern itself.\n\n```javascript\nvar javascripts = minimatch.match(fileList, \"*.js\", {matchBase: true}))\n```\n\n### minimatch.makeRe(pattern, options)\n\nMake a regular expression object from the pattern.\n\n## Options\n\nAll options are `false` by default.\n\n### debug\n\nDump a ton of stuff to stderr.\n\n### nobrace\n\nDo not expand `{a,b}` and `{1..3}` brace sets.\n\n### noglobstar\n\nDisable `**` matching against multiple folder names.\n\n### dot\n\nAllow patterns to match filenames starting with a period, even if\nthe pattern does not explicitly have a period in that spot.\n\nNote that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`\nis set.\n\n### noext\n\nDisable \"extglob\" style patterns like `+(a|b)`.\n\n### nocase\n\nPerform a case-insensitive match.\n\n### nonull\n\nWhen a match is not found by `minimatch.match`, return a list containing\nthe pattern itself. When set, an empty list is returned if there are\nno matches.\n\n### matchBase\n\nIf set, then patterns without slashes will be matched\nagainst the basename of the path if it contains slashes. For example,\n`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.\n\n### nocomment\n\nSuppress the behavior of treating `#` at the start of a pattern as a\ncomment.\n\n### nonegate\n\nSuppress the behavior of treating a leading `!` character as negation.\n\n### flipNegate\n\nReturns from negate expressions the same as if they were not negated.\n(Ie, true on a hit, false on a miss.)\n", + "readmeFilename": "README.md", + "_id": "minimatch@0.2.12", + "_from": "minimatch@~0.2.6" +} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/test/basic.js b/node/node_modules/grunt/node_modules/minimatch/test/basic.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/test/basic.js rename to node/node_modules/grunt/node_modules/minimatch/test/basic.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/test/brace-expand.js b/node/node_modules/grunt/node_modules/minimatch/test/brace-expand.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/test/brace-expand.js rename to node/node_modules/grunt/node_modules/minimatch/test/brace-expand.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/test/caching.js b/node/node_modules/grunt/node_modules/minimatch/test/caching.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/test/caching.js rename to node/node_modules/grunt/node_modules/minimatch/test/caching.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/test/defaults.js b/node/node_modules/grunt/node_modules/minimatch/test/defaults.js similarity index 100% rename from node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/test/defaults.js rename to node/node_modules/grunt/node_modules/minimatch/test/defaults.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/.npmignore b/node/node_modules/grunt/node_modules/nodeunit/.npmignore deleted file mode 100644 index 1a8250121..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -dist -stamp-build -test/fixtures/dir2 diff --git a/node/node_modules/grunt/node_modules/nodeunit/CONTRIBUTORS.md b/node/node_modules/grunt/node_modules/nodeunit/CONTRIBUTORS.md deleted file mode 100644 index fba360964..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/CONTRIBUTORS.md +++ /dev/null @@ -1,68 +0,0 @@ -Nodeunit contributors (sorted alphabeticaly) -============================================ - -* **[Alex Gorbatchev](https://github.com/alexgorbatchev)** - - * Deeper default object inspection - * Timeout to ensure flushing of console output (default reporter) - -* **[Alex Wolfe](https://github.com/alexkwolfe)** - - * HTML test reporter - -* **[Caolan McMahon](https://github.com/caolan)** - - * Author and maintainer - * Most features develpopment - -* **[Carl Fürstenberg](https://github.com/azatoth)** - - * Debian-friendly Makefile, supports both 'node' and 'nodejs' executables - * Sandbox utility - * Minimal test reporter - -* **[Gerad Suyderhoud](https://github.com/gerad)** - - * First comand-line tool - -* **[Kadir Pekel](https://github.com/kadirpekel)** - - * Improvements to default test reporter - * HTTP test utility - -* **[Λlisue](https://github.com/lambdalisue)** - - * Add machineout reporter - -* **[Matthias Lübken](https://github.com/luebken)** - - * Utility functions for tracking incomplete tests on exit - -* **[Oleg Efimov](https://github.com/Sannis)** - - * Adding 'make lint' and fixing nodelint errors - * Option parsing, --help text and config file support - * Reporters option for command-line tool - -* **[Orlando Vazquez](https://github.com/orlandov)** - - * Added jUnit XML reporter - -* **[Ryan Dahl](https://github.com/ry)** - - * Add package.json - -* **[Sam Stephenson](https://github.com/sstephenson)** - - * Coffee-script support - -* **[Thomas Mayfield](https://github.com/thegreatape)** - - * Async setUp and tearDown support for testCase - -* **[Maciej Małecki](https://github.com/mmalecki)** - - * Removal of `testCase` - -**[Full contributors list](https://github.com/caolan/nodeunit/contributors).** - diff --git a/node/node_modules/grunt/node_modules/nodeunit/Makefile b/node/node_modules/grunt/node_modules/nodeunit/Makefile deleted file mode 100644 index 8f8d8cbd7..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/Makefile +++ /dev/null @@ -1,177 +0,0 @@ -PACKAGE = nodeunit -NODEJS = $(if $(shell test -f /usr/bin/nodejs && echo "true"),nodejs,node) - -PREFIX ?= /usr/local -BINDIR ?= $(PREFIX)/bin -DATADIR ?= $(PREFIX)/share -MANDIR ?= $(PREFIX)/share/man -LIBDIR ?= $(PREFIX)/lib -NODEJSLIBDIR ?= $(LIBDIR)/$(NODEJS) - -BUILDDIR = dist - -DOCS = $(shell find doc -name '*.md' \ - |sed 's|.md|.1|g' \ - |sed 's|doc/|man1/|g' \ - ) - - -$(shell if [ ! -d $(BUILDDIR) ]; then mkdir $(BUILDDIR); fi) - -all: build doc - -browser: - # super hacky build script for browser version! - mkdir -p $(BUILDDIR)/browser - rm -rf $(BUILDDIR)/browser/* - # build browser version of nodeunit.js - cat share/license.js >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit = (function(){" >> $(BUILDDIR)/browser/nodeunit.js - cat deps/json2.js >> $(BUILDDIR)/browser/nodeunit.js - # make assert global - echo "var assert = this.assert = {};" >> $(BUILDDIR)/browser/nodeunit.js - echo "var types = {};" >> $(BUILDDIR)/browser/nodeunit.js - echo "var core = {};" >> $(BUILDDIR)/browser/nodeunit.js - echo "var nodeunit = {};" >> $(BUILDDIR)/browser/nodeunit.js - echo "var reporter = {};" >> $(BUILDDIR)/browser/nodeunit.js - cat deps/async.js >> $(BUILDDIR)/browser/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js - cat lib/assert.js >> $(BUILDDIR)/browser/nodeunit.js - echo "})(assert);" >> $(BUILDDIR)/browser/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js - cat lib/types.js >> $(BUILDDIR)/browser/nodeunit.js - echo "})(types);" >> $(BUILDDIR)/browser/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js - cat lib/core.js >> $(BUILDDIR)/browser/nodeunit.js - echo "})(core);" >> $(BUILDDIR)/browser/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js - cat lib/reporters/browser.js >> $(BUILDDIR)/browser/nodeunit.js - echo "})(reporter);" >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit = core;" >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit.assert = assert;" >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit.reporter = reporter;" >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit.run = reporter.run;" >> $(BUILDDIR)/browser/nodeunit.js - echo "return nodeunit; })();" >> $(BUILDDIR)/browser/nodeunit.js - cp $(BUILDDIR)/browser/nodeunit.js $(BUILDDIR)/browser/.nodeunit.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.nodeunit.js > $(BUILDDIR)/browser/nodeunit.js - rm $(BUILDDIR)/browser/.nodeunit.js - # copy nodeunit.css - cp share/nodeunit.css $(BUILDDIR)/browser/nodeunit.css - # create nodeunit.min.js - node_modules/uglify-js/bin/uglifyjs $(BUILDDIR)/browser/nodeunit.js > $(BUILDDIR)/browser/nodeunit.min.js - # create test scripts - mkdir -p $(BUILDDIR)/browser/test - cp test/test.html $(BUILDDIR)/browser/test/test.html - # test-base.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-base.js - cat test/test-base.js >> $(BUILDDIR)/browser/test/test-base.js - echo "})(this.test_base = {});" >> $(BUILDDIR)/browser/test/test-base.js - cp $(BUILDDIR)/browser/test/test-base.js $(BUILDDIR)/browser/.test-base.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-base.js > $(BUILDDIR)/browser/test/test-base.js - rm $(BUILDDIR)/browser/.test-base.js - # test-runmodule.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-runmodule.js - cat test/test-runmodule.js >> $(BUILDDIR)/browser/test/test-runmodule.js - echo "})(this.test_runmodule = {});" >> $(BUILDDIR)/browser/test/test-runmodule.js - cp $(BUILDDIR)/browser/test/test-runmodule.js $(BUILDDIR)/browser/.test-runmodule.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-runmodule.js > $(BUILDDIR)/browser/test/test-runmodule.js - rm $(BUILDDIR)/browser/.test-runmodule.js - # test-runtest.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-runtest.js - cat test/test-runtest.js >> $(BUILDDIR)/browser/test/test-runtest.js - echo "})(this.test_runtest = {});" >> $(BUILDDIR)/browser/test/test-runtest.js - cp $(BUILDDIR)/browser/test/test-runtest.js $(BUILDDIR)/browser/.test-runtest.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-runtest.js > $(BUILDDIR)/browser/test/test-runtest.js - rm $(BUILDDIR)/browser/.test-runtest.js - # test-testcase.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-testcase.js - cat test/test-testcase.js >> $(BUILDDIR)/browser/test/test-testcase.js - echo "})(this.test_testcase = {});" >> $(BUILDDIR)/browser/test/test-testcase.js - cp $(BUILDDIR)/browser/test/test-testcase.js $(BUILDDIR)/browser/.test-testcase.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-testcase.js > $(BUILDDIR)/browser/test/test-testcase.js - rm $(BUILDDIR)/browser/.test-testcase.js - # test-testcase-legacy.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-testcase-legacy.js - cat test/test-testcase-legacy.js >> $(BUILDDIR)/browser/test/test-testcase-legacy.js - echo "})(this.test_testcase_legacy = {});" >> $(BUILDDIR)/browser/test/test-testcase-legacy.js - cp $(BUILDDIR)/browser/test/test-testcase-legacy.js $(BUILDDIR)/browser/.test-testcase-legacy.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-testcase-legacy.js > $(BUILDDIR)/browser/test/test-testcase-legacy.js - rm $(BUILDDIR)/browser/.test-testcase-legacy.js - # copy nodeunit.js to dist/browser/test to make it easier for me to host and - # run on windows VMs with IE - cp $(BUILDDIR)/browser/nodeunit.js $(BUILDDIR)/browser/test/nodeunit.js - cp $(BUILDDIR)/browser/nodeunit.css $(BUILDDIR)/browser/test/nodeunit.css - -commonjs: - # super hacky build script for browser commonjs version! - ##### make commonjs browser module ###### - mkdir -p $(BUILDDIR)/commonjs - rm -rf $(BUILDDIR)/commonjs/* - mkdir -p $(BUILDDIR)/commonjs/deps - cp deps/json2.js $(BUILDDIR)/commonjs/deps - cp deps/async.js $(BUILDDIR)/commonjs/deps - echo "var async = require('async');" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var assert = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var types = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var core = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var nodeunit = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var reporter = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/commonjs/nodeunit.js - cat lib/assert.js >> $(BUILDDIR)/commonjs/nodeunit.js - echo "})(assert);" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/commonjs/nodeunit.js - cat lib/types.js >> $(BUILDDIR)/commonjs/nodeunit.js - echo "})(types);" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/commonjs/nodeunit.js - cat lib/core.js >> $(BUILDDIR)/commonjs/nodeunit.js - echo "})(core);" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "module.exports = core;" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "(function(exports, nodeunit){" >> $(BUILDDIR)/commonjs/nodeunit.js - cat lib/reporters/browser.js >> $(BUILDDIR)/commonjs/nodeunit.js - echo "})(reporter, module.exports);" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "module.exports.assert = assert;" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "module.exports.reporter = reporter;" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "module.exports.run = reporter.run;" >> $(BUILDDIR)/commonjs/nodeunit.js - sed -i "/\@REMOVE_LINE_FOR_BROWSER/d" $(BUILDDIR)/commonjs/nodeunit.js - sed -i "/\@REMOVE_LINE_FOR_COMMONJS/d" $(BUILDDIR)/commonjs/nodeunit.js - ##### end of commonjs browser module ##### - -build: stamp-build - -stamp-build: $(wildcard deps/* lib/*.js) - touch $@; - mkdir -p $(BUILDDIR)/nodeunit - cp -R bin node_modules deps index.js lib package.json share $(BUILDDIR)/nodeunit - printf '#!/bin/sh\n$(NODEJS) $(NODEJSLIBDIR)/$(PACKAGE)/bin/nodeunit $$@' > $(BUILDDIR)/nodeunit.sh - -test: - $(NODEJS) ./bin/nodeunit test - -install: build - install -d $(NODEJSLIBDIR) - cp -a $(BUILDDIR)/nodeunit $(NODEJSLIBDIR) - install -m 0755 $(BUILDDIR)/nodeunit.sh $(BINDIR)/nodeunit - install -d $(MANDIR)/man1/ - cp -a man1/nodeunit.1 $(MANDIR)/man1/ - -uninstall: - rm -rf $(NODEJSLIBDIR)/nodeunit $(NODEJSLIBDIR)/nodeunit.js $(BINDIR)/nodeunit - rm -rf $(MANDIR)/man1/nodeunit.1 - -clean: - rm -rf $(BUILDDIR) stamp-build - -lint: - nodelint --config nodelint.cfg ./index.js ./bin/nodeunit ./bin/nodeunit.json ./lib/*.js ./lib/reporters/*.js ./test/*.js - -doc: man1 $(DOCS) - @true - -man1: - @if ! test -d man1 ; then mkdir -p man1 ; fi - -# use `npm install ronn` for this to work. -man1/%.1: doc/%.md - ronn --roff $< > $@ - -.PHONY: browser test install uninstall build all diff --git a/node/node_modules/grunt/node_modules/nodeunit/README.md b/node/node_modules/grunt/node_modules/nodeunit/README.md deleted file mode 100644 index 359a9c7f1..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/README.md +++ /dev/null @@ -1,443 +0,0 @@ -Nodeunit -======== - -Simple syntax, powerful tools. Nodeunit provides easy async unit testing for -node.js and the browser. - -* Simple to use -* Just export the tests from a module -* Works with node.js and in the browser. -* Helps you avoid common pitfalls when testing asynchronous code -* Easy to add test cases with setUp and tearDown functions if you wish -* Flexible reporters for custom output, built-in support for HTML and jUnit XML -* Allows the use of mocks and stubs - -__Contributors__ - -* [alexgorbatchev](https://github.com/alexgorbatchev) -* [alexkwolfe](https://github.com/alexkwolfe) -* [azatoth](https://github.com/azatoth) -* [kadirpekel](https://github.com/kadirpekel) -* [lambdalisue](https://github.com/lambdalisue) -* [luebken](https://github.com/luebken) -* [orlandov](https://github.com/orlandov) -* [Sannis](https://github.com/Sannis) -* [sstephenson](https://github.com/sstephenson) -* [thegreatape](https://github.com/thegreatape) -* [mmalecki](https://github.com/mmalecki) -* and thanks to [cjohansen](https://github.com/cjohansen) for input and advice - on implementing setUp and tearDown functions. See - [cjohansen's fork](https://github.com/cjohansen/nodeunit). - -Also, check out gerad's [nodeunit-dsl](https://github.com/gerad/nodeunit-dsl) -project, which implements a 'pretty dsl on top of nodeunit'. - -More contributor information can be found in the -[CONTRIBUTORS.md](https://github.com/caolan/nodeunit/blob/master/CONTRIBUTORS.md) -file. - -Usage ------ - -Here is an example unit test module: - - exports.testSomething = function(test){ - test.expect(1); - test.ok(true, "this assertion should pass"); - test.done(); - }; - - exports.testSomethingElse = function(test){ - test.ok(false, "this assertion should fail"); - test.done(); - }; - -When run using the included test runner, this will output the following: - - - -Installation ------------- - -There are two options for installing nodeunit: - -1. Clone / download nodeunit from [github](https://github.com/caolan/nodeunit), - then: - - make && sudo make install - -2. Install via npm: - - npm install nodeunit - -API Documentation ------------------ - -Nodeunit uses the functions available in the node.js -[assert module](http://nodejs.org/docs/v0.4.2/api/assert.html): - -* __ok(value, [message])__ - Tests if value is a true value. -* __equal(actual, expected, [message])__ - Tests shallow, coercive equality - with the equal comparison operator ( == ). -* __notEqual(actual, expected, [message])__ - Tests shallow, coercive - non-equality with the not equal comparison operator ( != ). -* __deepEqual(actual, expected, [message])__ - Tests for deep equality. -* __notDeepEqual(actual, expected, [message])__ - Tests for any deep - inequality. -* __strictEqual(actual, expected, [message])__ - Tests strict equality, as - determined by the strict equality operator ( === ) -* __notStrictEqual(actual, expected, [message])__ - Tests strict non-equality, - as determined by the strict not equal operator ( !== ) -* __throws(block, [error], [message])__ - Expects block to throw an error. -* __doesNotThrow(block, [error], [message])__ - Expects block not to throw an - error. -* __ifError(value)__ - Tests if value is not a false value, throws if it is a - true value. Useful when testing the first argument, error in callbacks. - -Nodeunit also provides the following functions within tests: - -* __expect(amount)__ - Specify how many assertions are expected to run within a - test. Very useful for ensuring that all your callbacks and assertions are - run. -* __done()__ - Finish the current test function, and move on to the next. ALL - tests should call this! - -Nodeunit aims to be simple and easy to learn. This is achieved through using -existing structures (such as node.js modules) to maximum effect, and reducing -the API where possible, to make it easier to digest. - -Tests are simply exported from a module, but they are still run in the order -they are defined. - -__Note:__ Users of old nodeunit versions may remember using ok, equals and same -in the style of qunit, instead of the assert functions above. These functions -still exist for backwards compatibility, and are simply aliases to their assert -module counterparts. - - -Asynchronous Testing --------------------- - -When testing asynchronous code, there are a number of sharp edges to watch out -for. Thankfully, nodeunit is designed to help you avoid as many of these -pitfalls as possible. For the most part, testing asynchronous code in nodeunit -_just works_. - - -### Tests run in series - -While running tests in parallel seems like a good idea for speeding up your -test suite, in practice I've found it means writing much more complicated -tests. Because of node's module cache, running tests in parallel means mocking -and stubbing is pretty much impossible. One of the nicest things about testing -in javascript is the ease of doing stubs: - - var _readFile = fs.readFile; - fs.readFile = function(path, callback){ - // its a stub! - }; - // test function that uses fs.readFile - - // we're done - fs.readFile = _readFile; - -You cannot do this when running tests in parallel. In order to keep testing as -simple as possible, nodeunit avoids it. Thankfully, most unit-test suites run -fast anyway. - - -### Explicit ending of tests - -When testing async code its important that tests end at the correct point, not -just after a given number of assertions. Otherwise your tests can run short, -ending before all assertions have completed. Its important to detect too -many assertions as well as too few. Combining explicit ending of tests with -an expected number of assertions helps to avoid false test passes, so be sure -to use the test.expect() method at the start of your test functions, and -test.done() when finished. - - -Groups, setUp and tearDown --------------------------- - -Nodeunit allows the nesting of test functions: - - exports.test1 = function (test) { - ... - } - - exports.group = { - test2: function (test) { - ... - }, - test3: function (test) { - ... - } - } - -This would be run as: - - test1 - group - test2 - group - test3 - -Using these groups, Nodeunit allows you to define a `setUp` function, which is -run before each test, and a `tearDown` function, which is run after each test -calls `test.done()`: - - module.exports = { - setUp: function (callback) { - this.foo = 'bar'; - callback(); - }, - tearDown: function (callback) { - // clean up - callback(); - }, - test1: function (test) { - test.equals(this.foo, 'bar'); - test.done(); - } - }; - -In this way, its possible to have multiple groups of tests in a module, each -group with its own setUp and tearDown functions. - - -Running Tests -------------- - -Nodeunit comes with a basic command-line test runner, which can be installed -using 'sudo make install'. Example usage: - - nodeunit testmodule1.js testfolder [...] - -The default test reporter uses color output, because I think that's more fun :) I -intend to add a no-color option in future. To give you a feeling of the fun you'll -be having writing tests, lets fix the example at the start of the README: - - - -Ahhh, Doesn't that feel better? - -When using the included test runner, it will exit using the failed number of -assertions as the exit code. Exiting with 0 when all tests pass. - - -### Command-line Options - -* __--reporter FILE__ - you can set the test reporter to a custom module or -on of the modules in nodeunit/lib/reporters, when omitted, the default test runner -is used. -* __--list-reporters__ - list available build-in reporters. -* __--config FILE__ - load config options from a JSON file, allows -the customisation of color schemes for the default test reporter etc. See -bin/nodeunit.json for current available options. -* __--version__ or __-v__ - report nodeunit version -* __--help__ - show nodeunit help - - -Running tests in the browser ----------------------------- - -Nodeunit tests can also be run inside the browser. For example usage, see -the examples/browser folder. The basic syntax is as follows: - -__test.html__ - - - - Example Test Suite - - - - - - -

        - - -nodeunit with vim -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -There is [nodeunit.vim](https://github.com/lambdalisue/nodeunit.vim) so you can use nodeunit with VIM. -That compiler use __machineout__ reporter and it is useful to use with [vim-makegreen](https://github.com/reinh/vim-makegreen) - - - -Contributing ------------- - -Contributions to the project are most welcome, so feel free to fork and improve. -When submitting a pull request, please run 'make lint' first to ensure -we're following a consistent coding style. diff --git a/node/node_modules/grunt/node_modules/nodeunit/bin/nodeunit b/node/node_modules/grunt/node_modules/nodeunit/bin/nodeunit deleted file mode 100755 index 4b3f4d574..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/bin/nodeunit +++ /dev/null @@ -1,133 +0,0 @@ -#!/usr/bin/env node - -var - fs = require('fs'), - path = require('path'); - -// TODO: remove this when https://github.com/joyent/node/pull/1312 -// lands in core. -// -// Until then, use console.log from npm (https://gist.github.com/1077544) -require('../deps/console.log'); - -//require.paths.push(process.cwd()); -var args = (process.ARGV || process.argv).slice(2); - -var files = []; - -var testrunner, - config_file, - config_param_found = false, - output_param_found = false, - reporter_file = 'default', - reporter_param_found = false, - testspec_param_found = false; - testFullSpec_param_found = false; - -var usage = "Usage: nodeunit [options] testmodule1.js testfolder [...] \n" + - "Options:\n\n" + - " --config FILE the path to a JSON file with options\n" + - " --reporter FILE optional path to a reporter file to customize the output\n" + - " --list-reporters list available build-in reporters\n" + - " -t name, specify a test to run\n" + - " -f fullname, specify a specific test to run. fullname is built so: \"outerGroup - .. - innerGroup - testName\"\n" + - " -h, --help display this help and exit\n" + - " -v, --version output version information and exit"; - - - -// load default options -var content = fs.readFileSync(__dirname + '/nodeunit.json', 'utf8'); -var options = JSON.parse(content); - -// a very basic pseudo --options parser -args.forEach(function (arg) { - if (arg.slice(0, 9) === "--config=") { - config_file = arg.slice(9); - } else if (arg === '--config') { - config_param_found = true; - } else if (config_param_found) { - config_file = arg; - config_param_found = false; - } else if (arg.slice(0, 9) === "--output=") { - options.output = arg.slice(9); - } else if (arg === '--output') { - output_param_found = true; - } else if (output_param_found) { - options.output = arg; - output_param_found = false; - } else if (arg.slice(0, 11) === "--reporter=") { - reporter_file = arg.slice(11); - } else if (arg === '--reporter') { - reporter_param_found = true; - } else if (reporter_param_found) { - reporter_file = arg; - reporter_param_found = false; - } else if (arg === '-t') { - testspec_param_found = true; - } else if (testspec_param_found) { - options.testspec = arg; - testspec_param_found = false; - } else if (arg === '-f') { - testFullSpec_param_found = true; - } else if (testFullSpec_param_found) { - options.testFullSpec= arg; - testFullSpec_param_found = false; - } else if (arg === '--list-reporters') { - var reporters = fs.readdirSync(__dirname + '/../lib/reporters'); - reporters = reporters.filter(function (reporter_file) { - return (/\.js$/).test(reporter_file); - }).map(function (reporter_file) { - return reporter_file.replace(/\.js$/, ''); - }).filter(function (reporter_file) { - return reporter_file !== 'index'; - }); - console.log('Build-in reporters: '); - reporters.forEach(function (reporter_file) { - var reporter = require('../lib/reporters/' + reporter_file); - console.log(' * ' + reporter_file + (reporter.info ? ': ' + reporter.info : '')); - }); - process.exit(0); - } else if ((arg === '-v') || (arg === '--version')) { - var content = fs.readFileSync(__dirname + '/../package.json', 'utf8'); - var pkg = JSON.parse(content); - console.log(pkg.version); - process.exit(0); - } else if ((arg === '-h') || (arg === '--help')) { - console.log(usage); - process.exit(0); - } else { - files.push(arg); - } -}); - -if (files.length === 0) { - console.log('Files required.'); - console.log(usage); - process.exit(1); -} - -if (config_file) { - content = fs.readFileSync(config_file, 'utf8'); - var custom_options = JSON.parse(content); - - for (var option in custom_options) { - if (typeof option === 'string') { - options[option] = custom_options[option]; - } - } -} - -var builtin_reporters = require(__dirname + '/../lib/reporters'); -if (reporter_file in builtin_reporters) { - testrunner = builtin_reporters[reporter_file]; -} -else { - testrunner = require(reporter_file); -} - -testrunner.run(files, options, function(err) { - if (err) { - process.exit(1); - } -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/bin/nodeunit.json b/node/node_modules/grunt/node_modules/nodeunit/bin/nodeunit.json deleted file mode 100644 index 5c7778fd9..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/bin/nodeunit.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "error_prefix": "\u001B[31m", - "error_suffix": "\u001B[39m", - "ok_prefix": "\u001B[32m", - "ok_suffix": "\u001B[39m", - "bold_prefix": "\u001B[1m", - "bold_suffix": "\u001B[22m", - "assertion_prefix": "\u001B[35m", - "assertion_suffix": "\u001B[39m" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/async.js b/node/node_modules/grunt/node_modules/nodeunit/deps/async.js deleted file mode 100644 index d81255f98..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/async.js +++ /dev/null @@ -1,623 +0,0 @@ -/*global setTimeout: false, console: false */ -(function () { - - var async = {}; - - // global on the server, window in the browser - var root = this, - previous_async = root.async; - - if (typeof module !== 'undefined' && module.exports) { - module.exports = async; - } - else { - root.async = async; - } - - async.noConflict = function () { - root.async = previous_async; - return async; - }; - - //// cross-browser compatiblity functions //// - - var _forEach = 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 = []; - _forEach(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); - } - _forEach(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; - }; - - var _indexOf = function (arr, item) { - if (arr.indexOf) { - return arr.indexOf(item); - } - for (var i = 0; i < arr.length; i += 1) { - if (arr[i] === item) { - return i; - } - } - return -1; - }; - - //// exported async module functions //// - - //// nextTick implementation with browser-compatible fallback //// - if (typeof process === 'undefined' || !(process.nextTick)) { - async.nextTick = function (fn) { - setTimeout(fn, 0); - }; - } - else { - async.nextTick = process.nextTick; - } - - async.forEach = function (arr, iterator, callback) { - if (!arr.length) { - return callback(); - } - var completed = 0; - _forEach(arr, function (x) { - iterator(x, function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed === arr.length) { - callback(); - } - } - }); - }); - }; - - async.forEachSeries = function (arr, iterator, callback) { - 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(); - }; - - - var doParallel = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.forEach].concat(args)); - }; - }; - var doSeries = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.forEachSeries].concat(args)); - }; - }; - - - var _asyncMap = 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 (err, v) { - results[x.index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - }; - async.map = doParallel(_asyncMap); - async.mapSeries = doSeries(_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.forEachSeries(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); - } - else { - callback(); - } - }); - }, function (err) { - main_callback(); - }); - }; - async.detect = doParallel(_detect); - async.detectSeries = doSeries(_detect); - - async.some = function (arr, iterator, main_callback) { - async.forEach(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.forEach(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); - if (!keys.length) { - return callback(null); - } - - var completed = []; - - 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 () { - _forEach(listeners, function (fn) { - fn(); - }); - }; - - addListener(function () { - if (completed.length === keys.length) { - callback(null); - } - }); - - _forEach(keys, function (k) { - var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; - var taskCallback = function (err) { - if (err) { - callback(err); - // stop subsequent errors hitting callback multiple times - callback = function () {}; - } - else { - completed.push(k); - taskComplete(); - } - }; - var requires = task.slice(0, Math.abs(task.length - 1)) || []; - var ready = function () { - return _reduce(requires, function (a, x) { - return (a && _indexOf(completed, x) !== -1); - }, true); - }; - if (ready()) { - task[task.length - 1](taskCallback); - } - else { - var listener = function () { - if (ready()) { - removeListener(listener); - task[task.length - 1](taskCallback); - } - }; - addListener(listener); - } - }); - }; - - async.waterfall = function (tasks, callback) { - if (!tasks.length) { - return callback(); - } - callback = callback || function () {}; - var wrapIterator = function (iterator) { - return function (err) { - if (err) { - callback(err); - 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.nextTick(function () { - iterator.apply(null, args); - }); - } - }; - }; - wrapIterator(async.iterator(tasks))(); - }; - - async.parallel = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.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 || null); - }); - } - }, callback); - } - else { - var results = {}; - async.forEach(_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.series = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - 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 || null); - }); - } - }, callback); - } - else { - var results = {}; - async.forEachSeries(_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.until = function (test, iterator, callback) { - if (!test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.until(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.queue = function (worker, concurrency) { - var workers = 0; - var tasks = []; - var q = { - concurrency: concurrency, - push: function (data, callback) { - tasks.push({data: data, callback: callback}); - async.nextTick(q.process); - }, - process: function () { - if (workers < q.concurrency && tasks.length) { - var task = tasks.splice(0, 1)[0]; - workers += 1; - worker(task.data, function () { - workers -= 1; - if (task.callback) { - task.callback.apply(task, arguments); - } - q.process(); - }); - } - }, - length: function () { - return tasks.length; - } - }; - return q; - }; - - 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]) { - _forEach(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 = {}; - hasher = hasher || function (x) { - return x; - }; - return function () { - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - var key = hasher.apply(null, args); - if (key in memo) { - callback.apply(null, memo[key]); - } - else { - fn.apply(null, args.concat([function () { - memo[key] = arguments; - callback.apply(null, arguments); - }])); - } - }; - }; - -}()); diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/console.log.js b/node/node_modules/grunt/node_modules/nodeunit/deps/console.log.js deleted file mode 100644 index fe146c1ef..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/console.log.js +++ /dev/null @@ -1,55 +0,0 @@ -/* - A console.log that won't leave you hanging when node exits - 90% of this file was ripped from node.js - - License: see: https://github.com/joyent/node/blob/master/lib/console.js - */ - - // console object -var formatRegExp = /%[sdj]/g; -function format(f) { - var util = require('util'); - - if (typeof f !== 'string') { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(util.inspect(arguments[i])); - } - return objects.join(' '); - } - - - var i = 1; - var args = arguments; - var str = String(f).replace(formatRegExp, function(x) { - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': return JSON.stringify(args[i++]); - default: - return x; - } - }); - for (var len = args.length, x = args[i]; i < len; x = args[++i]) { - if (x === null || typeof x !== 'object') { - str += ' ' + x; - } else { - str += ' ' + util.inspect(x); - } - } - return str; -} - -console.log = function() { - var res = process.stdout.write(format.apply(this, arguments) + '\n'); - - // this is the first time stdout got backed up - if (!res && !process.stdout.pendingWrite) { - process.stdout.pendingWrite = true; - - // magic sauce: keep node alive until stdout has flushed - process.stdout.once('drain', function () { - process.stdout.draining = false; - }); - } -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/History.md b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/History.md deleted file mode 100644 index 00d2b5b76..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/History.md +++ /dev/null @@ -1,70 +0,0 @@ - -0.4.3 / 2011-06-20 -================== - - * Fixed stacktraces line number when used multiline js expressions [Octave] - -0.4.2 / 2011-05-11 -================== - - * Added client side support - -0.4.1 / 2011-04-21 -================== - - * Fixed error context - -0.4.0 / 2011-04-21 -================== - - * Added; ported jade's error reporting to ejs. [slaskis] - -0.3.1 / 2011-02-23 -================== - - * Fixed optional `compile()` options - -0.3.0 / 2011-02-14 -================== - - * Added 'json' filter [Yuriy Bogdanov] - * Use exported version of parse function to allow monkey-patching [Anatoliy Chakkaev] - -0.2.1 / 2010-10-07 -================== - - * Added filter support - * Fixed _cache_ option. ~4x performance increase - -0.2.0 / 2010-08-05 -================== - - * Added support for global tag config - * Added custom tag support. Closes #5 - * Fixed whitespace bug. Closes #4 - -0.1.0 / 2010-08-04 -================== - - * Faster implementation [ashleydev] - -0.0.4 / 2010-08-02 -================== - - * Fixed single quotes for content outside of template tags. [aniero] - * Changed; `exports.compile()` now expects only "locals" - -0.0.3 / 2010-07-15 -================== - - * Fixed single quotes - -0.0.2 / 2010-07-09 -================== - - * Fixed newline preservation - -0.0.1 / 2010-07-09 -================== - - * Initial release diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/Makefile b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/Makefile deleted file mode 100644 index a8b00d96a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ - -SRC = $(shell find lib -name "*.js" -type f) -UGLIFY_FLAGS = --no-mangle - -test: - @./node_modules/.bin/expresso test/*.test.js - -ejs.js: $(SRC) - @node support/compile.js $^ - -ejs.min.js: ejs.js - @uglifyjs $(UGLIFY_FLAGS) $< > $@ \ - && du ejs.min.js \ - && du ejs.js - -clean: - rm -f ejs.js - rm -f ejs.min.js - -.PHONY: test \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/Readme.md b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/Readme.md deleted file mode 100644 index 58cb10a45..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/Readme.md +++ /dev/null @@ -1,152 +0,0 @@ - -# EJS - -Embedded JavaScript templates. - -## Installation - - $ npm install ejs - -## Features - - * Complies with the [Express](http://expressjs.com) view system - * Static caching of intermediate JavaScript - * Unbuffered code for conditionals etc `<% code %>` - * Escapes html by default with `<%= code %>` - * Unescaped buffering with `<%- code %>` - * Supports tag customization - * Filter support for designer-friendly templates - * Client-side support - -## Example - - <% if (user) { %> -

        <%= user.name %>

        - <% } %> - -## Usage - - ejs.compile(str, options); - // => Function - - ejs.render(str, options); - // => str - -## Options - - - `locals` Local variables object - - `cache` Compiled functions are cached, requires `filename` - - `filename` Used by `cache` to key caches - - `scope` Function execution context - - `debug` Output generated function body - - `open` Open tag, defaulting to "<%" - - `close` Closing tag, defaulting to "%>" - -## Custom tags - -Custom tags can also be applied globally: - - var ejs = require('ejs'); - ejs.open = '{{'; - ejs.close = '}}'; - -Which would make the following a valid template: - -

        {{= title }}

        - -## Filters - -EJS conditionally supports the concept of "filters". A "filter chain" -is a designer friendly api for manipulating data, without writing JavaScript. - -Filters can be applied by supplying the _:_ modifier, so for example if we wish to take the array `[{ name: 'tj' }, { name: 'mape' }, { name: 'guillermo' }]` and output a list of names we can do this simply with filters: - -Template: - -

        <%=: users | map:'name' | join %>

        - -Output: - -

        Tj, Mape, Guillermo

        - -Render call: - - ejs.render(str, { - locals: { - users: [ - { name: 'tj' }, - { name: 'mape' }, - { name: 'guillermo' } - ] - } - }); - -Or perhaps capitalize the first user's name for display: - -

        <%=: users | first | capitalize %>

        - -## Filter list - -Currently these filters are available: - - - first - - last - - capitalize - - downcase - - upcase - - sort - - sort_by:'prop' - - size - - length - - plus:n - - minus:n - - times:n - - divided_by:n - - join:'val' - - truncate:n - - truncate_words:n - - replace:pattern,substitution - - prepend:val - - append:val - - map:'prop' - - reverse - - get:'prop' - -## Adding filters - - To add a filter simply add a method to the `.filters` object: - -```js -ejs.filters.last = function(obj) { - return obj[obj.length - 1]; -}; -``` - -## client-side support - - include `./ejs.js` or `./ejs.min.js` and `require("ejs").compile(str)`. - -## License - -(The MIT License) - -Copyright (c) 2009-2010 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/node_modules/grunt/node_modules/nodeunit/deps/ejs/benchmark.js b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/benchmark.js deleted file mode 100644 index 7b267e160..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/benchmark.js +++ /dev/null @@ -1,14 +0,0 @@ - - -var ejs = require('./lib/ejs'), - str = '<% if (foo) { %>

        <%= foo %>

        <% } %>', - times = 50000; - -console.log('rendering ' + times + ' times'); - -var start = new Date; -while (times--) { - ejs.render(str, { cache: true, filename: 'test', locals: { foo: 'bar' }}); -} - -console.log('took ' + (new Date - start) + 'ms'); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/ejs.js b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/ejs.js deleted file mode 100644 index b8c6aa1a8..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/ejs.js +++ /dev/null @@ -1,531 +0,0 @@ - -// 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[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("ejs.js", function(module, exports, require){ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./utils'); - -/** - * Library version. - */ - -exports.version = '0.4.2'; - -/** - * Filters. - * - * @type Object - */ - -var filters = exports.filters = require('./filters'); - -/** - * Intermediate js cache. - * - * @type Object - */ - -var cache = {}; - -/** - * Clear intermediate js cache. - * - * @api public - */ - -exports.clearCache = function(){ - cache = {}; -}; - -/** - * Translate filtered code into function calls. - * - * @param {String} js - * @return {String} - * @api private - */ - -function filtered(js) { - return js.substr(1).split('|').reduce(function(js, filter){ - var parts = filter.split(':') - , name = parts.shift() - , args = parts.shift() || ''; - if (args) args = ', ' + args; - return 'filters.' + name + '(' + js + args + ')'; - }); -}; - -/** - * Re-throw the given `err` in context to the - * `str` of ejs, `filename`, and `lineno`. - * - * @param {Error} err - * @param {String} str - * @param {String} filename - * @param {String} lineno - * @api private - */ - -function rethrow(err, str, filename, lineno){ - var lines = str.split('\n') - , start = Math.max(lineno - 3, 0) - , end = Math.min(lines.length, lineno + 3); - - // 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 || 'ejs') + ':' - + lineno + '\n' - + context + '\n\n' - + err.message; - - throw err; -} - -/** - * Parse the given `str` of ejs, returning the function body. - * - * @param {String} str - * @return {String} - * @api public - */ - -var parse = exports.parse = function(str, options){ - var options = options || {} - , open = options.open || exports.open || '<%' - , close = options.close || exports.close || '%>'; - - var buf = [ - "var buf = [];" - , "\nwith (locals) {" - , "\n buf.push('" - ]; - - var lineno = 1; - - for (var i = 0, len = str.length; i < len; ++i) { - if (str.slice(i, open.length + i) == open) { - i += open.length - - var prefix, postfix, line = '__stack.lineno=' + lineno; - switch (str[i]) { - case '=': - prefix = "', escape((" + line + ', '; - postfix = ")), '"; - ++i; - break; - case '-': - prefix = "', (" + line + ', '; - postfix = "), '"; - ++i; - break; - default: - prefix = "');" + line + ';'; - postfix = "; buf.push('"; - } - - var start = i; - var end = str.indexOf(close, i); - var js = str.substring(i, end); - var n = 0; - while ((n = js.indexOf("\n", n)) > -1) { - n++; - lineno++; - } - if (js[0] == ':') js = filtered(js); - buf.push(prefix, js, postfix); - i += end - start + close.length - 1; - - } else if (str[i] == "\\") { - buf.push("\\\\"); - } else if (str[i] == "'") { - buf.push("\\'"); - } else if (str[i] == "\r") { - buf.push(" "); - } else if (str[i] == "\n") { - buf.push("\\n"); - lineno++; - } else { - buf.push(str[i]); - } - } - - buf.push("');\n}\nreturn buf.join('');"); - return buf.join(''); -}; - -/** - * Compile the given `str` of ejs into a `Function`. - * - * @param {String} str - * @param {Object} options - * @return {Function} - * @api public - */ - -var compile = exports.compile = function(str, options){ - options = options || {}; - - var input = JSON.stringify(str) - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined'; - - // Adds the fancy stack trace meta info - str = [ - 'var __stack = { lineno: 1, input: ' + input + ', filename: ' + filename + ' };', - rethrow.toString(), - 'try {', - exports.parse(str, options), - '} catch (err) {', - ' rethrow(err, __stack.input, __stack.filename, __stack.lineno);', - '}' - ].join("\n"); - - if (options.debug) console.log(str); - var fn = new Function('locals, filters, escape', str); - return function(locals){ - return fn.call(this, locals, filters, utils.escape); - } -}; - -/** - * Render the given `str` of ejs. - * - * Options: - * - * - `locals` Local variables object - * - `cache` Compiled functions are cached, requires `filename` - * - `filename` Used by `cache` to key caches - * - `scope` Function execution context - * - `debug` Output generated function body - * - `open` Open tag, defaulting to "<%" - * - `close` Closing tag, defaulting to "%>" - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api public - */ - -exports.render = function(str, options){ - var fn - , options = options || {}; - if (options.cache) { - if (options.filename) { - fn = cache[options.filename] || (cache[options.filename] = compile(str, options)); - } else { - throw new Error('"cache" option requires "filename".'); - } - } else { - fn = compile(str, options); - } - return fn.call(options.scope, options.locals || {}); -}; - -/** - * Expose to require(). - */ - -if (require.extensions) { - require.extensions['.ejs'] = function(module, filename) { - source = require('fs').readFileSync(filename, 'utf-8'); - module._compile(compile(source, {}), filename); - }; -} else if (require.registerExtension) { - require.registerExtension('.ejs', function(src) { - return compile(src, {}); - }); -} - -}); // module: ejs.js - -require.register("filters.js", function(module, exports, require){ - -/*! - * EJS - Filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * First element of the target `obj`. - */ - -exports.first = function(obj) { - return obj[0]; -}; - -/** - * Last element of the target `obj`. - */ - -exports.last = function(obj) { - return obj[obj.length - 1]; -}; - -/** - * Capitalize the first letter of the target `str`. - */ - -exports.capitalize = function(str){ - str = String(str); - return str[0].toUpperCase() + str.substr(1, str.length); -}; - -/** - * Downcase the target `str`. - */ - -exports.downcase = function(str){ - return String(str).toLowerCase(); -}; - -/** - * Uppercase the target `str`. - */ - -exports.upcase = function(str){ - return String(str).toUpperCase(); -}; - -/** - * Sort the target `obj`. - */ - -exports.sort = function(obj){ - return Object.create(obj).sort(); -}; - -/** - * Sort the target `obj` by the given `prop` ascending. - */ - -exports.sort_by = function(obj, prop){ - return Object.create(obj).sort(function(a, b){ - a = a[prop], b = b[prop]; - if (a > b) return 1; - if (a < b) return -1; - return 0; - }); -}; - -/** - * Size or length of the target `obj`. - */ - -exports.size = exports.length = function(obj) { - return obj.length; -}; - -/** - * Add `a` and `b`. - */ - -exports.plus = function(a, b){ - return Number(a) + Number(b); -}; - -/** - * Subtract `b` from `a`. - */ - -exports.minus = function(a, b){ - return Number(a) - Number(b); -}; - -/** - * Multiply `a` by `b`. - */ - -exports.times = function(a, b){ - return Number(a) * Number(b); -}; - -/** - * Divide `a` by `b`. - */ - -exports.divided_by = function(a, b){ - return Number(a) / Number(b); -}; - -/** - * Join `obj` with the given `str`. - */ - -exports.join = function(obj, str){ - return obj.join(str || ', '); -}; - -/** - * Truncate `str` to `len`. - */ - -exports.truncate = function(str, len){ - str = String(str); - return str.substr(0, len); -}; - -/** - * Truncate `str` to `n` words. - */ - -exports.truncate_words = function(str, n){ - var str = String(str) - , words = str.split(/ +/); - return words.slice(0, n).join(' '); -}; - -/** - * Replace `pattern` with `substitution` in `str`. - */ - -exports.replace = function(str, pattern, substitution){ - return String(str).replace(pattern, substitution || ''); -}; - -/** - * Prepend `val` to `obj`. - */ - -exports.prepend = function(obj, val){ - return Array.isArray(obj) - ? [val].concat(obj) - : val + obj; -}; - -/** - * Append `val` to `obj`. - */ - -exports.append = function(obj, val){ - return Array.isArray(obj) - ? obj.concat(val) - : obj + val; -}; - -/** - * Map the given `prop`. - */ - -exports.map = function(arr, prop){ - return arr.map(function(obj){ - return obj[prop]; - }); -}; - -/** - * Reverse the given `obj`. - */ - -exports.reverse = function(obj){ - return Array.isArray(obj) - ? obj.reverse() - : String(obj).split('').reverse().join(''); -}; - -/** - * Get `prop` of the given `obj`. - */ - -exports.get = function(obj, prop){ - return obj[prop]; -}; - -/** - * Packs the given `obj` into json string - */ -exports.json = function(obj){ - return JSON.stringify(obj); -}; -}); // module: filters.js - -require.register("utils.js", function(module, exports, require){ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -}); // module: utils.js diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/ejs.min.js b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/ejs.min.js deleted file mode 100644 index 6b72d947c..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/ejs.min.js +++ /dev/null @@ -1,2 +0,0 @@ -// CommonJS require() -function require(p){var path=require.resolve(p),mod=require.modules[path];if(!mod)throw new Error('failed to require "'+p+'"');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]&®||require.modules[index]&&index||orig},require.register=function(path,fn){require.modules[path]=fn},require.relative=function(parent){return function(p){if("."!=p[0])return require(p);var path=parent.split("/"),segs=p.split("/");path.pop();for(var i=0;i> ":" ")+curr+"| "+line}).join("\n");err.path=filename,err.message=(filename||"ejs")+":"+lineno+"\n"+context+"\n\n"+err.message;throw err}var parse=exports.parse=function(str,options){var options=options||{},open=options.open||exports.open||"<%",close=options.close||exports.close||"%>",buf=["var buf = [];","\nwith (locals) {","\n buf.push('"],lineno=1;for(var i=0,len=str.length;ib)return 1;if(a/g,">").replace(/"/g,""")}}) \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/examples/client.html b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/examples/client.html deleted file mode 100644 index 7081a0454..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/examples/client.html +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/examples/list.ejs b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/examples/list.ejs deleted file mode 100644 index d571330ae..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/examples/list.ejs +++ /dev/null @@ -1,7 +0,0 @@ -<% if (names.length) { %> -
          - <% names.forEach(function(name){ %> -
        • <%= name %>
        • - <% }) %> -
        -<% } %> \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/examples/list.js b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/examples/list.js deleted file mode 100644 index 9cd71683b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/examples/list.js +++ /dev/null @@ -1,16 +0,0 @@ - -/** - * Module dependencies. - */ - -var ejs = require('../') - , fs = require('fs') - , str = fs.readFileSync(__dirname + '/list.ejs', 'utf8'); - -var ret = ejs.render(str, { - locals: { - names: ['foo', 'bar', 'baz'] - } -}); - -console.log(ret); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/index.js b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/index.js deleted file mode 100644 index 20bf71a3f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/ejs'); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/lib/ejs.js b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/lib/ejs.js deleted file mode 100644 index 46afa7450..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/lib/ejs.js +++ /dev/null @@ -1,251 +0,0 @@ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./utils'); - -/** - * Library version. - */ - -exports.version = '0.4.3'; - -/** - * Filters. - * - * @type Object - */ - -var filters = exports.filters = require('./filters'); - -/** - * Intermediate js cache. - * - * @type Object - */ - -var cache = {}; - -/** - * Clear intermediate js cache. - * - * @api public - */ - -exports.clearCache = function(){ - cache = {}; -}; - -/** - * Translate filtered code into function calls. - * - * @param {String} js - * @return {String} - * @api private - */ - -function filtered(js) { - return js.substr(1).split('|').reduce(function(js, filter){ - var parts = filter.split(':') - , name = parts.shift() - , args = parts.shift() || ''; - if (args) args = ', ' + args; - return 'filters.' + name + '(' + js + args + ')'; - }); -}; - -/** - * Re-throw the given `err` in context to the - * `str` of ejs, `filename`, and `lineno`. - * - * @param {Error} err - * @param {String} str - * @param {String} filename - * @param {String} lineno - * @api private - */ - -function rethrow(err, str, filename, lineno){ - var lines = str.split('\n') - , start = Math.max(lineno - 3, 0) - , end = Math.min(lines.length, lineno + 3); - - // 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 || 'ejs') + ':' - + lineno + '\n' - + context + '\n\n' - + err.message; - - throw err; -} - -/** - * Parse the given `str` of ejs, returning the function body. - * - * @param {String} str - * @return {String} - * @api public - */ - -var parse = exports.parse = function(str, options){ - var options = options || {} - , open = options.open || exports.open || '<%' - , close = options.close || exports.close || '%>'; - - var buf = [ - "var buf = [];" - , "\nwith (locals) {" - , "\n buf.push('" - ]; - - var lineno = 1; - - for (var i = 0, len = str.length; i < len; ++i) { - if (str.slice(i, open.length + i) == open) { - i += open.length - - var prefix, postfix, line = '__stack.lineno=' + lineno; - switch (str.substr(i, 1)) { - case '=': - prefix = "', escape((" + line + ', '; - postfix = ")), '"; - ++i; - break; - case '-': - prefix = "', (" + line + ', '; - postfix = "), '"; - ++i; - break; - default: - prefix = "');" + line + ';'; - postfix = "; buf.push('"; - } - - var end = str.indexOf(close, i) - , js = str.substring(i, end) - , start = i - , n = 0; - - while (~(n = js.indexOf("\n", n))) n++, lineno++; - if (js.substr(0, 1) == ':') js = filtered(js); - buf.push(prefix, js, postfix); - i += end - start + close.length - 1; - - } else if (str.substr(i, 1) == "\\") { - buf.push("\\\\"); - } else if (str.substr(i, 1) == "'") { - buf.push("\\'"); - } else if (str.substr(i, 1) == "\r") { - buf.push(" "); - } else if (str.substr(i, 1) == "\n") { - buf.push("\\n"); - lineno++; - } else { - buf.push(str.substr(i, 1)); - } - } - - buf.push("');\n}\nreturn buf.join('');"); - return buf.join(''); -}; - -/** - * Compile the given `str` of ejs into a `Function`. - * - * @param {String} str - * @param {Object} options - * @return {Function} - * @api public - */ - -var compile = exports.compile = function(str, options){ - options = options || {}; - - var input = JSON.stringify(str) - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined'; - - // Adds the fancy stack trace meta info - str = [ - 'var __stack = { lineno: 1, input: ' + input + ', filename: ' + filename + ' };', - rethrow.toString(), - 'try {', - exports.parse(str, options), - '} catch (err) {', - ' rethrow(err, __stack.input, __stack.filename, __stack.lineno);', - '}' - ].join("\n"); - - if (options.debug) console.log(str); - var fn = new Function('locals, filters, escape', str); - return function(locals){ - return fn.call(this, locals, filters, utils.escape); - } -}; - -/** - * Render the given `str` of ejs. - * - * Options: - * - * - `locals` Local variables object - * - `cache` Compiled functions are cached, requires `filename` - * - `filename` Used by `cache` to key caches - * - `scope` Function execution context - * - `debug` Output generated function body - * - `open` Open tag, defaulting to "<%" - * - `close` Closing tag, defaulting to "%>" - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api public - */ - -exports.render = function(str, options){ - var fn - , options = options || {}; - if (options.cache) { - if (options.filename) { - fn = cache[options.filename] || (cache[options.filename] = compile(str, options)); - } else { - throw new Error('"cache" option requires "filename".'); - } - } else { - fn = compile(str, options); - } - return fn.call(options.scope, options.locals || {}); -}; - -/** - * Expose to require(). - */ - -if (require.extensions) { - require.extensions['.ejs'] = function(module, filename) { - source = require('fs').readFileSync(filename, 'utf-8'); - module._compile(compile(source, {}), filename); - }; -} else if (require.registerExtension) { - require.registerExtension('.ejs', function(src) { - return compile(src, {}); - }); -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/lib/filters.js b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/lib/filters.js deleted file mode 100644 index d425c8d89..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/lib/filters.js +++ /dev/null @@ -1,198 +0,0 @@ - -/*! - * EJS - Filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * First element of the target `obj`. - */ - -exports.first = function(obj) { - return obj[0]; -}; - -/** - * Last element of the target `obj`. - */ - -exports.last = function(obj) { - return obj[obj.length - 1]; -}; - -/** - * Capitalize the first letter of the target `str`. - */ - -exports.capitalize = function(str){ - str = String(str); - return str[0].toUpperCase() + str.substr(1, str.length); -}; - -/** - * Downcase the target `str`. - */ - -exports.downcase = function(str){ - return String(str).toLowerCase(); -}; - -/** - * Uppercase the target `str`. - */ - -exports.upcase = function(str){ - return String(str).toUpperCase(); -}; - -/** - * Sort the target `obj`. - */ - -exports.sort = function(obj){ - return Object.create(obj).sort(); -}; - -/** - * Sort the target `obj` by the given `prop` ascending. - */ - -exports.sort_by = function(obj, prop){ - return Object.create(obj).sort(function(a, b){ - a = a[prop], b = b[prop]; - if (a > b) return 1; - if (a < b) return -1; - return 0; - }); -}; - -/** - * Size or length of the target `obj`. - */ - -exports.size = exports.length = function(obj) { - return obj.length; -}; - -/** - * Add `a` and `b`. - */ - -exports.plus = function(a, b){ - return Number(a) + Number(b); -}; - -/** - * Subtract `b` from `a`. - */ - -exports.minus = function(a, b){ - return Number(a) - Number(b); -}; - -/** - * Multiply `a` by `b`. - */ - -exports.times = function(a, b){ - return Number(a) * Number(b); -}; - -/** - * Divide `a` by `b`. - */ - -exports.divided_by = function(a, b){ - return Number(a) / Number(b); -}; - -/** - * Join `obj` with the given `str`. - */ - -exports.join = function(obj, str){ - return obj.join(str || ', '); -}; - -/** - * Truncate `str` to `len`. - */ - -exports.truncate = function(str, len){ - str = String(str); - return str.substr(0, len); -}; - -/** - * Truncate `str` to `n` words. - */ - -exports.truncate_words = function(str, n){ - var str = String(str) - , words = str.split(/ +/); - return words.slice(0, n).join(' '); -}; - -/** - * Replace `pattern` with `substitution` in `str`. - */ - -exports.replace = function(str, pattern, substitution){ - return String(str).replace(pattern, substitution || ''); -}; - -/** - * Prepend `val` to `obj`. - */ - -exports.prepend = function(obj, val){ - return Array.isArray(obj) - ? [val].concat(obj) - : val + obj; -}; - -/** - * Append `val` to `obj`. - */ - -exports.append = function(obj, val){ - return Array.isArray(obj) - ? obj.concat(val) - : obj + val; -}; - -/** - * Map the given `prop`. - */ - -exports.map = function(arr, prop){ - return arr.map(function(obj){ - return obj[prop]; - }); -}; - -/** - * Reverse the given `obj`. - */ - -exports.reverse = function(obj){ - return Array.isArray(obj) - ? obj.reverse() - : String(obj).split('').reverse().join(''); -}; - -/** - * Get `prop` of the given `obj`. - */ - -exports.get = function(obj, prop){ - return obj[prop]; -}; - -/** - * Packs the given `obj` into json string - */ -exports.json = function(obj){ - return JSON.stringify(obj); -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/lib/utils.js b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/lib/utils.js deleted file mode 100644 index 8d569d6f2..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/lib/utils.js +++ /dev/null @@ -1,23 +0,0 @@ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/package.json b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/package.json deleted file mode 100644 index 224b4ffa7..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "ejs", - "description": "Embedded JavaScript templates", - "version": "0.4.3", - "author": "TJ Holowaychuk ", - "keywords": ["template", "engine", "ejs"], - "devDependencies": { - "expresso": "0.9.2" - }, - "main": "./lib/ejs.js" -} \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/support/compile.js b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/support/compile.js deleted file mode 100644 index edd381584..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/support/compile.js +++ /dev/null @@ -1,173 +0,0 @@ - -/** - * Module dependencies. - */ - -var fs = require('fs'); - -/** - * Arguments. - */ - -var args = process.argv.slice(2) - , pending = args.length - , files = {}; - -console.log(''); - -// parse arguments - -args.forEach(function(file){ - var mod = file.replace('lib/', ''); - fs.readFile(file, 'utf8', function(err, js){ - if (err) throw err; - console.log(' \033[90mcompile : \033[0m\033[36m%s\033[0m', file); - files[file] = parse(js); - --pending || compile(); - }); -}); - -/** - * Parse the given `js`. - */ - -function parse(js) { - return parseInheritance(parseConditionals(js)); -} - -/** - * Parse __proto__. - */ - -function parseInheritance(js) { - return js - .replace(/^ *(\w+)\.prototype\.__proto__ * = *(\w+)\.prototype *;?/gm, function(_, child, parent){ - return child + '.prototype = new ' + parent + ';\n' - + child + '.prototype.constructor = '+ child + ';\n'; - }); -} - -/** - * Parse the given `js`, currently supporting: - * - * 'if' ['node' | 'browser'] - * 'end' - * - */ - -function parseConditionals(js) { - var lines = js.split('\n') - , len = lines.length - , buffer = true - , browser = false - , buf = [] - , line - , cond; - - for (var i = 0; i < len; ++i) { - line = lines[i]; - if (/^ *\/\/ *if *(node|browser)/gm.exec(line)) { - cond = RegExp.$1; - buffer = browser = 'browser' == cond; - } else if (/^ *\/\/ *end/.test(line)) { - buffer = true; - browser = false; - } else if (browser) { - buf.push(line.replace(/^( *)\/\//, '$1')); - } else if (buffer) { - buf.push(line); - } - } - - return buf.join('\n'); -} - -/** - * Compile the files. - */ - -function compile() { - var buf = ''; - buf += '\n// CommonJS require()\n\n'; - buf += browser.require + '\n\n'; - buf += 'require.modules = {};\n\n'; - buf += 'require.resolve = ' + browser.resolve + ';\n\n'; - buf += 'require.register = ' + browser.register + ';\n\n'; - buf += 'require.relative = ' + browser.relative + ';\n\n'; - args.forEach(function(file){ - var js = files[file]; - file = file.replace('lib/', ''); - buf += '\nrequire.register("' + file + '", function(module, exports, require){\n'; - buf += js; - buf += '\n}); // module: ' + file + '\n'; - }); - fs.writeFile('ejs.js', buf, function(err){ - if (err) throw err; - console.log(' \033[90m create : \033[0m\033[36m%s\033[0m', 'ejs.js'); - console.log(); - }); -} - -// refactored version of weepy's -// https://github.com/weepy/brequire/blob/master/browser/brequire.js - -var browser = { - - /** - * Require a module. - */ - - 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; - }, - - /** - * Resolve module path. - */ - - resolve: function(path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }, - - /** - * Return relative require(). - */ - - relative: function(parent) { - return function(p){ - if ('.' != p.substr(0, 1)) 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('/')); - }; - }, - - /** - * Register a module. - */ - - register: function(path, fn){ - require.modules[path] = fn; - } -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/test/ejs.test.js b/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/test/ejs.test.js deleted file mode 100644 index 624157d30..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/deps/ejs/test/ejs.test.js +++ /dev/null @@ -1,269 +0,0 @@ - -/** - * Module dependencies. - */ - -var ejs = require('../') - , assert = require('assert'); - -module.exports = { - 'test .version': function(){ - assert.ok(/^\d+\.\d+\.\d+$/.test(ejs.version), 'Test .version format'); - }, - - 'test html': function(){ - assert.equal('

        yay

        ', ejs.render('

        yay

        ')); - }, - - 'test buffered code': function(){ - var html = '

        tj

        ', - str = '

        <%= name %>

        ', - locals = { name: 'tj' }; - assert.equal(html, ejs.render(str, { locals: locals })); - }, - - 'test unbuffered code': function(){ - var html = '

        tj

        ', - str = '<% if (name) { %>

        <%= name %>

        <% } %>', - locals = { name: 'tj' }; - assert.equal(html, ejs.render(str, { locals: locals })); - }, - - 'test `scope` option': function(){ - var html = '

        tj

        ', - str = '

        <%= this %>

        '; - assert.equal(html, ejs.render(str, { scope: 'tj' })); - }, - - 'test escaping': function(){ - assert.equal('<script>', ejs.render('<%= " - - - - - - - - diff --git a/node/node_modules/grunt/node_modules/nodeunit/examples/nested/nested_reporter_test.unit.js b/node/node_modules/grunt/node_modules/nodeunit/examples/nested/nested_reporter_test.unit.js deleted file mode 100644 index 612adcd22..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/examples/nested/nested_reporter_test.unit.js +++ /dev/null @@ -1,94 +0,0 @@ -var testCase = require('nodeunit').testCase; -/* - This is an example test suite to demonstrate the nested test reporter. - Run with --reporter nested, e.g., - nodeunit --reporter nested nested_reporter_test.unit.js - - The test output should be something like: - - nested_reporter_test.unit.js - Test 0.1 (pass) - TC 1 - TC 1.1 - Test 1.1.1 (pass) - TC 2 - TC 2.1 - TC 2.1.1 - Test 2.1.1.1 (pass) - Test 2.1.1.2 (pass) - TC 2.2.1 - Test 2.2.1.1 (pass) - TC 2.2.1.1 - Test 2.2.1.1.1 (pass) - Test 2.2.1.2 (pass) - TC 3 - TC 3.1 - TC 3.1.1 - Test 3.1.1.1 (should fail) (fail) ✖ - AssertionError: false == true - // stack trace here. - - FAILURES: 1/8 assertions failed (6ms) -*/ - -module.exports = testCase({ - "Test 0.1": function(test) { - test.ok(true); - test.done(); - }, - - "TC 1": testCase({ - "TC 1.1": testCase({ - "Test 1.1.1": function(test) { - test.ok(true); - test.done(); - } - }) - }), - - "TC 2": testCase({ - "TC 2.1": testCase({ - "TC 2.1.1": testCase({ - "Test 2.1.1.1": function(test) { - test.ok(true); - test.done(); - }, - - "Test 2.1.1.2": function(test) { - test.ok(true); - test.done(); - } - }), - - "TC 2.2.1": testCase({ - "Test 2.2.1.1": function(test) { - test.ok(true); - test.done(); - }, - - "TC 2.2.1.1": testCase({ - "Test 2.2.1.1.1": function(test) { - test.ok(true); - test.done(); - }, - }), - - "Test 2.2.1.2": function(test) { - test.ok(true); - test.done(); - } - }) - }) - }), - - "TC 3": testCase({ - "TC 3.1": testCase({ - "TC 3.1.1": testCase({ - "Test 3.1.1.1 (should fail)": function(test) { - test.ok(false); - test.done(); - } - }) - }) - }) -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/img/example_fail.png b/node/node_modules/grunt/node_modules/nodeunit/img/example_fail.png deleted file mode 100644 index 78ff4258c..000000000 Binary files a/node/node_modules/grunt/node_modules/nodeunit/img/example_fail.png and /dev/null differ diff --git a/node/node_modules/grunt/node_modules/nodeunit/img/example_machineout.png b/node/node_modules/grunt/node_modules/nodeunit/img/example_machineout.png deleted file mode 100644 index c6bfa27b5..000000000 Binary files a/node/node_modules/grunt/node_modules/nodeunit/img/example_machineout.png and /dev/null differ diff --git a/node/node_modules/grunt/node_modules/nodeunit/img/example_pass.png b/node/node_modules/grunt/node_modules/nodeunit/img/example_pass.png deleted file mode 100644 index 069d71698..000000000 Binary files a/node/node_modules/grunt/node_modules/nodeunit/img/example_pass.png and /dev/null differ diff --git a/node/node_modules/grunt/node_modules/nodeunit/index.js b/node/node_modules/grunt/node_modules/nodeunit/index.js deleted file mode 100644 index 07867d011..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/index.js +++ /dev/null @@ -1,3 +0,0 @@ -// This file is just added for convenience so this repository can be -// directly checked out into a project's deps folder -module.exports = require('./lib/nodeunit'); diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/assert.js b/node/node_modules/grunt/node_modules/nodeunit/lib/assert.js deleted file mode 100644 index 09f588d16..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/assert.js +++ /dev/null @@ -1,354 +0,0 @@ -/** - * This file is based on the node.js assert module, but with some small - * changes for browser-compatibility - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - */ - - -/** - * Added for browser compatibility - */ - -var _keys = function(obj){ - if(Object.keys) return Object.keys(obj); - if (typeof obj != 'object' && typeof obj != 'function') { - throw new TypeError('-'); - } - var keys = []; - for(var k in obj){ - if(obj.hasOwnProperty(k)) keys.push(k); - } - return keys; -}; - - - -// 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. - - -var pSlice = Array.prototype.slice; - -// 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 = exports; - -// 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.message = options.message; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - var stackStartFunction = options.stackStartFunction || fail; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } -}; -// code from util.inherits in node -assert.AssertionError.super_ = Error; - - -// EDITED FOR BROWSER COMPATIBILITY: replaced Object.create call -// TODO: test what effect this may have -var ctor = function () { this.constructor = assert.AssertionError; }; -ctor.prototype = Error.prototype; -assert.AssertionError.prototype = new ctor(); - - -assert.AssertionError.prototype.toString = function() { - if (this.message) { - return [this.name+":", this.message].join(' '); - } else { - return [ this.name+":" - , JSON.stringify(this.expected ) - , this.operator - , JSON.stringify(this.actual) - ].join(" "); - } -}; - -// assert.AssertionError instanceof Error - -assert.AssertionError.__proto__ = Error.prototype; - -// 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);. - -assert.ok = function ok(value, message) { - if (!!!value) fail(value, true, message, "==", assert.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); - } -}; - -var Buffer = null; -if (typeof require !== 'undefined' && typeof process !== 'undefined') { - try { - Buffer = require('buffer').Buffer; - } - catch (e) { - // May be a CommonJS environment other than Node.js - Buffer = null; - } -} - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - 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 (actual instanceof Date && expected instanceof Date) { - return actual.getTime() === expected.getTime(); - - // 7.2.1 If the expcted value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object that refers to the same source and options - } else if (actual instanceof RegExp && expected instanceof RegExp) { - return actual.source === expected.source && - actual.global === expected.global && - actual.ignoreCase === expected.ignoreCase && - actual.multiline === expected.multiline; - - } else if (Buffer && actual instanceof Buffer && expected instanceof Buffer) { - return (function() { - var i, len; - - for (i = 0, len = expected.length; i < len; i++) { - if (actual[i] !== expected[i]) { - return false; - } - } - return actual.length === expected.length; - })(); - // 7.3. Other pairs that do not both pass typeof value == "object", - // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { - return actual == expected; - - // 7.4. 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 isUndefinedOrNull (value) { - return value === null || value === undefined; -} - -function isArguments (object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv (a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(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 = _keys(a), - kb = _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; -} - -// 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 (expected instanceof RegExp) { - return expected.test(actual.message || 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 (typeof expected === 'string') { - message = expected; - expected = null; - } - - try { - block(); - } catch (e) { - actual = e; - } - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail('Missing expected exception' + message); - } - - if (!shouldThrow && expectedException(actual, expected)) { - fail('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*/error, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; - -assert.ifError = function (err) { if (err) {throw err;}}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/core.js b/node/node_modules/grunt/node_modules/nodeunit/lib/core.js deleted file mode 100644 index 5281bc735..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/core.js +++ /dev/null @@ -1,318 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, it's mostly to avoid requiring code - * that is node specific - */ - -/** - * Module dependencies - */ - -var async = require('../deps/async'), //@REMOVE_LINE_FOR_BROWSER - nodeunit = require('./nodeunit'), //@REMOVE_LINE_FOR_BROWSER - types = require('./types'); //@REMOVE_LINE_FOR_BROWSER - - -/** - * Added for browser compatibility - */ - -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; -}; - - -var _copy = function (obj) { - var nobj = {}; - var keys = _keys(obj); - for (var i = 0; i < keys.length; i += 1) { - nobj[keys[i]] = obj[keys[i]]; - } - return nobj; -}; - - -/** - * Runs a test function (fn) from a loaded module. After the test function - * calls test.done(), the callback is executed with an assertionList as its - * second argument. - * - * @param {String} name - * @param {Function} fn - * @param {Object} opt - * @param {Function} callback - * @api public - */ - -exports.runTest = function (name, fn, opt, callback) { - var options = types.options(opt); - - options.testStart(name); - var start = new Date().getTime(); - var test = types.test(name, start, options, callback); - - try { - fn(test); - } - catch (e) { - test.done(e); - } -}; - -/** - * Takes an object containing test functions or other test suites as properties - * and runs each in series. After all tests have completed, the callback is - * called with a list of all assertions as the second argument. - * - * If a name is passed to this function it is prepended to all test and suite - * names that run within it. - * - * @param {String} name - * @param {Object} suite - * @param {Object} opt - * @param {Function} callback - * @api public - */ - -exports.runSuite = function (name, suite, opt, callback) { - suite = wrapGroup(suite); - var keys = _keys(suite); - - async.concatSeries(keys, function (k, cb) { - var prop = suite[k], _name; - - _name = name ? [].concat(name, k) : [k]; - _name.toString = function () { - // fallback for old one - return this.join(' - '); - }; - - if (typeof prop === 'function') { - var in_name = false, - in_specific_test = (_name.toString() === opt.testFullSpec) ? true : false; - for (var i = 0; i < _name.length; i += 1) { - if (_name[i] === opt.testspec) { - in_name = true; - } - } - - if ((!opt.testFullSpec || in_specific_test) && (!opt.testspec || in_name)) { - if (opt.moduleStart) { - opt.moduleStart(); - } - exports.runTest(_name, suite[k], opt, cb); - } - else { - return cb(); - } - } - else { - exports.runSuite(_name, suite[k], opt, cb); - } - }, callback); -}; - -/** - * Run each exported test function or test suite from a loaded module. - * - * @param {String} name - * @param {Object} mod - * @param {Object} opt - * @param {Function} callback - * @api public - */ - -exports.runModule = function (name, mod, opt, callback) { - var options = _copy(types.options(opt)); - - var _run = false; - var _moduleStart = options.moduleStart; - - mod = wrapGroup(mod); - - function run_once() { - if (!_run) { - _run = true; - _moduleStart(name); - } - } - options.moduleStart = run_once; - - var start = new Date().getTime(); - - exports.runSuite(null, mod, options, function (err, a_list) { - var end = new Date().getTime(); - var assertion_list = types.assertionList(a_list, end - start); - options.moduleDone(name, assertion_list); - if (nodeunit.complete) { - nodeunit.complete(name, assertion_list); - } - callback(null, a_list); - }); -}; - -/** - * Treats an object literal as a list of modules keyed by name. Runs each - * module and finished with calling 'done'. You can think of this as a browser - * safe alternative to runFiles in the nodeunit module. - * - * @param {Object} modules - * @param {Object} opt - * @api public - */ - -// TODO: add proper unit tests for this function -exports.runModules = function (modules, opt) { - var all_assertions = []; - var options = types.options(opt); - var start = new Date().getTime(); - - async.concatSeries(_keys(modules), function (k, cb) { - exports.runModule(k, modules[k], options, cb); - }, - function (err, all_assertions) { - var end = new Date().getTime(); - options.done(types.assertionList(all_assertions, end - start)); - }); -}; - - -/** - * Wraps a test function with setUp and tearDown functions. - * Used by testCase. - * - * @param {Function} setUp - * @param {Function} tearDown - * @param {Function} fn - * @api private - */ - -var wrapTest = function (setUp, tearDown, fn) { - return function (test) { - var context = {}; - if (tearDown) { - var done = test.done; - test.done = function (err) { - try { - tearDown.call(context, function (err2) { - if (err && err2) { - test._assertion_list.push( - types.assertion({error: err}) - ); - return done(err2); - } - done(err || err2); - }); - } - catch (e) { - done(e); - } - }; - } - if (setUp) { - setUp.call(context, function (err) { - if (err) { - return test.done(err); - } - fn.call(context, test); - }); - } - else { - fn.call(context, test); - } - }; -}; - - -/** - * Returns a serial callback from two functions. - * - * @param {Function} funcFirst - * @param {Function} funcSecond - * @api private - */ - -var getSerialCallback = function (fns) { - if (!fns.length) { - return null; - } - return function (callback) { - var that = this; - var bound_fns = []; - for (var i = 0, len = fns.length; i < len; i++) { - (function (j) { - bound_fns.push(function () { - return fns[j].apply(that, arguments); - }); - })(i); - } - return async.series(bound_fns, callback); - }; -}; - - -/** - * Wraps a group of tests with setUp and tearDown functions. - * Used by testCase. - * - * @param {Object} group - * @param {Array} setUps - parent setUp functions - * @param {Array} tearDowns - parent tearDown functions - * @api private - */ - -var wrapGroup = function (group, setUps, tearDowns) { - var tests = {}; - - var setUps = setUps ? setUps.slice(): []; - var tearDowns = tearDowns ? tearDowns.slice(): []; - - if (group.setUp) { - setUps.push(group.setUp); - delete group.setUp; - } - if (group.tearDown) { - tearDowns.unshift(group.tearDown); - delete group.tearDown; - } - - var keys = _keys(group); - - for (var i = 0; i < keys.length; i += 1) { - var k = keys[i]; - if (typeof group[k] === 'function') { - tests[k] = wrapTest( - getSerialCallback(setUps), - getSerialCallback(tearDowns), - group[k] - ); - } - else if (typeof group[k] === 'object') { - tests[k] = wrapGroup(group[k], setUps, tearDowns); - } - } - return tests; -}; - - -/** - * Backwards compatibility for test suites using old testCase API - */ - -exports.testCase = function (suite) { - return suite; -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/nodeunit.js b/node/node_modules/grunt/node_modules/nodeunit/lib/nodeunit.js deleted file mode 100644 index e20e97402..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/nodeunit.js +++ /dev/null @@ -1,104 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var async = require('../deps/async'), - types = require('./types'), - utils = require('./utils'), - core = require('./core'), - reporters = require('./reporters'), - assert = require('./assert'), - path = require('path') - events = require('events'); - - -/** - * Export sub-modules. - */ - -exports.types = types; -exports.utils = utils; -exports.reporters = reporters; -exports.assert = assert; - -// backwards compatibility -exports.testrunner = { - run: function () { - console.log( - 'WARNING: nodeunit.testrunner is going to be deprecated, please ' + - 'use nodeunit.reporters.default instead!' - ); - return reporters['default'].run.apply(this, arguments); - } -}; - - -/** - * Export all core functions - */ - -for (var k in core) { - exports[k] = core[k]; -}; - - -/** - * Load modules from paths array and run all exported tests in series. If a path - * is a directory, load all supported file types inside it as modules. This only - * reads 1 level deep in the directory and does not recurse through - * sub-directories. - * - * @param {Array} paths - * @param {Object} opt - * @api public - */ - -exports.runFiles = function (paths, opt) { - var all_assertions = []; - var options = types.options(opt); - var start = new Date().getTime(); - - if (!paths.length) { - return options.done(types.assertionList(all_assertions)); - } - - utils.modulePaths(paths, function (err, files) { - if (err) throw err; - async.concatSeries(files, function (file, cb) { - var name = path.basename(file); - exports.runModule(name, require(file), options, cb); - }, - function (err, all_assertions) { - var end = new Date().getTime(); - exports.done() - options.done(types.assertionList(all_assertions, end - start)); - }); - }); - -}; - -/* Export all prototypes from events.EventEmitter */ -var label; -for (label in events.EventEmitter.prototype) { - exports[label] = events.EventEmitter.prototype[label]; -} - -/* Emit event 'complete' on completion of a test suite. */ -exports.complete = function(name, assertions) -{ - exports.emit('complete', name, assertions); -}; - -/* Emit event 'complete' on completion of all tests. */ -exports.done = function() -{ - exports.emit('done'); -}; - -module.exports = exports; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/browser.js b/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/browser.js deleted file mode 100644 index 9836c90c9..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/browser.js +++ /dev/null @@ -1,121 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - - -/** - * NOTE: this test runner is not listed in index.js because it cannot be - * used with the command-line tool, only inside the browser. - */ - - -/** - * Reporter info string - */ - -exports.info = "Browser-based test reporter"; - - -/** - * Run all tests within each module, reporting the results - * - * @param {Array} files - * @api public - */ - -exports.run = function (modules, options) { - var start = new Date().getTime(), div; - options = options || {}; - div = options.div || document.body; - - function setText(el, txt) { - if ('innerText' in el) { - el.innerText = txt; - } - else if ('textContent' in el){ - el.textContent = txt; - } - } - - function getOrCreate(tag, id) { - var el = document.getElementById(id); - if (!el) { - el = document.createElement(tag); - el.id = id; - div.appendChild(el); - } - return el; - }; - - var header = getOrCreate('h1', 'nodeunit-header'); - var banner = getOrCreate('h2', 'nodeunit-banner'); - var userAgent = getOrCreate('h2', 'nodeunit-userAgent'); - var tests = getOrCreate('ol', 'nodeunit-tests'); - var result = getOrCreate('p', 'nodeunit-testresult'); - - setText(userAgent, navigator.userAgent); - - nodeunit.runModules(modules, { - moduleStart: function (name) { - /*var mheading = document.createElement('h2'); - mheading.innerText = name; - results.appendChild(mheading); - module = document.createElement('ol'); - results.appendChild(module);*/ - }, - testDone: function (name, assertions) { - var test = document.createElement('li'); - var strong = document.createElement('strong'); - strong.innerHTML = name + ' (' + - '' + assertions.failures() + ', ' + - '' + assertions.passes() + ', ' + - assertions.length + - ')'; - test.className = assertions.failures() ? 'fail': 'pass'; - test.appendChild(strong); - - var aList = document.createElement('ol'); - aList.style.display = 'none'; - test.onclick = function () { - var d = aList.style.display; - aList.style.display = (d == 'none') ? 'block': 'none'; - }; - for (var i=0; i' + (a.error.stack || a.error) + ''; - li.className = 'fail'; - } - else { - li.innerHTML = a.message || a.method || 'no message'; - li.className = 'pass'; - } - aList.appendChild(li); - } - test.appendChild(aList); - tests.appendChild(test); - }, - done: function (assertions) { - var end = new Date().getTime(); - var duration = end - start; - - var failures = assertions.failures(); - banner.className = failures ? 'fail': 'pass'; - - result.innerHTML = 'Tests completed in ' + duration + - ' milliseconds.
        ' + - assertions.passes() + ' assertions of ' + - '' + assertions.length + ' passed, ' + - assertions.failures() + ' failed.'; - } - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/default.js b/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/default.js deleted file mode 100644 index 9b4c66a1e..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/default.js +++ /dev/null @@ -1,131 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - track = require('../track'), - path = require('path'), - AssertionError = require('../assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Default tests reporter"; - - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options, callback) { - - if (!options) { - // load default options - var content = fs.readFileSync( - __dirname + '/../../bin/nodeunit.json', 'utf8' - ); - options = JSON.parse(content); - } - - var error = function (str) { - return options.error_prefix + str + options.error_suffix; - }; - var ok = function (str) { - return options.ok_prefix + str + options.ok_suffix; - }; - var bold = function (str) { - return options.bold_prefix + str + options.bold_suffix; - }; - var assertion_message = function (str) { - return options.assertion_prefix + str + options.assertion_suffix; - }; - - var start = new Date().getTime(); - var tracker = track.createTracker(function (tracker) { - if (tracker.unfinished()) { - console.log(''); - console.log(error(bold( - 'FAILURES: Undone tests (or their setups/teardowns): ' - ))); - var names = tracker.names(); - for (var i = 0; i < names.length; i += 1) { - console.log('- ' + names[i]); - } - console.log(''); - console.log('To fix this, make sure all tests call test.done()'); - process.reallyExit(tracker.unfinished()); - } - }); - - var opts = { - testspec: options.testspec, - testFullSpec: options.testFullSpec, - moduleStart: function (name) { - console.log('\n' + bold(name)); - }, - testDone: function (name, assertions) { - tracker.remove(name); - - if (!assertions.failures()) { - console.log('✔ ' + name); - } - else { - console.log(error('✖ ' + name) + '\n'); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log( - 'Assertion Message: ' + - assertion_message(a.message) - ); - } - console.log(a.error.stack + '\n'); - } - }); - } - }, - done: function (assertions, end) { - var end = end || new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + bold(error('FAILURES: ')) + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } - else { - console.log( - '\n' + bold(ok('OK: ')) + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - - if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined); - }, - testStart: function(name) { - tracker.put(name); - } - }; - if (files && files.length) { - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - nodeunit.runFiles(paths, opts); - } else { - nodeunit.runModules(files,opts); - } -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/eclipse.js b/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/eclipse.js deleted file mode 100644 index 6775ff126..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/eclipse.js +++ /dev/null @@ -1,104 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - track = require('../track'), - path = require('path'), - AssertionError = require('../assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Reporter for eclipse plugin"; - - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options, callback) { - - var start = new Date().getTime(); - var paths = files.map(function (p) { - if (p.indexOf('/') === 0) { - return p; - } - return path.join(process.cwd(), p); - }); - var tracker = track.createTracker(function (tracker) { - if (tracker.unfinished()) { - console.log(''); - console.log('FAILURES: Undone tests (or their setups/teardowns): '); - var names = tracker.names(); - for (var i = 0; i < names.length; i += 1) { - console.log('- ' + names[i]); - } - console.log(''); - console.log('To fix this, make sure all tests call test.done()'); - process.reallyExit(tracker.unfinished()); - } - }); - - nodeunit.runFiles(paths, { - testspec: undefined, - moduleStart: function (name) { - console.log('\n' + name); - }, - testDone: function (name, assertions) { - tracker.remove(name); - - if (!assertions.failures()) { - console.log('✔ ' + name); - } - else { - console.log('✖ ' + name + '\n'); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log( - 'Assertion Message: ' + a.message - ); - } - console.log(a.error.stack + '\n'); - } - }); - } - }, - done: function (assertions, end) { - var end = end || new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + 'FAILURES: ' + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } - else { - console.log( - '\n' + 'OK: ' + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - - if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined); - }, - testStart: function (name) { - tracker.put(name); - } - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/html.js b/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/html.js deleted file mode 100644 index 80866b6e7..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/html.js +++ /dev/null @@ -1,110 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - path = require('path'), - AssertionError = require('assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Report tests result as HTML"; - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options, callback) { - - var start = new Date().getTime(); - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - - console.log(''); - console.log(''); - console.log(''); - console.log(''); - console.log(''); - console.log(''); - nodeunit.runFiles(paths, { - testspec: options.testspec, - testFullSpec: options.testFullSpec, - moduleStart: function (name) { - console.log('

        ' + name + '

        '); - console.log('
          '); - }, - testDone: function (name, assertions) { - if (!assertions.failures()) { - console.log('
        1. ' + name + '
        2. '); - } - else { - console.log('
        3. ' + name); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log('
          ' + - 'Assertion Message: ' + a.message + - '
          '); - } - console.log('
          ');
          -                        console.log(a.error.stack);
          -                        console.log('
          '); - } - }); - console.log('
        4. '); - } - }, - moduleDone: function () { - console.log('
        '); - }, - done: function (assertions) { - var end = new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '

        FAILURES: ' + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)

        ' - ); - } - else { - console.log( - '

        OK: ' + assertions.length + - ' assertions (' + assertions.duration + 'ms)

        ' - ); - } - console.log(''); - console.log(''); - - if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined); - } - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/index.js b/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/index.js deleted file mode 100644 index b3989c011..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/index.js +++ /dev/null @@ -1,14 +0,0 @@ -module.exports = { - 'junit': require('./junit'), - 'default': require('./default'), - 'skip_passed': require('./skip_passed'), - 'minimal': require('./minimal'), - 'html': require('./html'), - 'eclipse': require('./eclipse'), - 'machineout': require('./machineout'), - 'tap': require('./tap'), - 'nested': require('./nested'), - 'verbose' : require('./verbose') - // browser test reporter is not listed because it cannot be used - // with the command line tool, only inside a browser. -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/junit.js b/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/junit.js deleted file mode 100644 index d9a1d0203..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/junit.js +++ /dev/null @@ -1,180 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - path = require('path'), - async = require('../../deps/async'), - AssertionError = require('assert').AssertionError, - child_process = require('child_process'), - ejs = require('../../deps/ejs'); - - -/** - * Reporter info string - */ - -exports.info = "jUnit XML test reports"; - - -/** - * Ensures a directory exists using mkdir -p. - * - * @param {String} path - * @param {Function} callback - * @api private - */ - -var ensureDir = function (path, callback) { - var mkdir = child_process.spawn('mkdir', ['-p', path]); - mkdir.on('error', function (err) { - callback(err); - callback = function(){}; - }); - mkdir.on('exit', function (code) { - if (code === 0) callback(); - else callback(new Error('mkdir exited with code: ' + code)); - }); -}; - - -/** - * Returns absolute version of a path. Relative paths are interpreted - * relative to process.cwd() or the cwd parameter. Paths that are already - * absolute are returned unaltered. - * - * @param {String} p - * @param {String} cwd - * @return {String} - * @api public - */ - -var abspath = function (p, /*optional*/cwd) { - if (p[0] === '/') return p; - cwd = cwd || process.cwd(); - return path.normalize(path.join(cwd, p)); -}; - - -/** - * Run all tests within each module, reporting the results to the command-line, - * then writes out junit-compatible xml documents. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, opts, callback) { - if (!opts.output) { - console.error( - 'Error: No output directory defined.\n' + - '\tEither add an "output" property to your nodeunit.json config ' + - 'file, or\n\tuse the --output command line option.' - ); - return; - } - opts.output = abspath(opts.output); - var error = function (str) { - return opts.error_prefix + str + opts.error_suffix; - }; - var ok = function (str) { - return opts.ok_prefix + str + opts.ok_suffix; - }; - var bold = function (str) { - return opts.bold_prefix + str + opts.bold_suffix; - }; - - var start = new Date().getTime(); - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - - var modules = {} - var curModule; - - nodeunit.runFiles(paths, { - testspec: opts.testspec, - testFullSpec: opts.testFullSpec, - moduleStart: function (name) { - curModule = { - errorCount: 0, - failureCount: 0, - tests: 0, - testcases: [], - name: name - }; - modules[name] = curModule; - }, - testDone: function (name, assertions) { - var testcase = {name: name}; - for (var i=0; i name_slice(['TC1', 'TC1.1', 'mytest'], 1); - * "TC1,TC1.1" - */ - var name_slice = function (name_arr, end_index) { - return name_arr.slice(0, end_index + 1).join(","); - }; - - var indent = (function () { - var txt = ''; - var i; - for (i = 0; i < spaces_per_indent; i++) { - txt += ' '; - } - return txt; - }()); - - // Indent once for each indent_level - var add_indent = function (txt, indent_level) { - var k; - for (k = 0; k < indent_level; k++) { - txt += indent; - } - return txt; - }; - - // If it's not the last element of the name_arr, it's a testCase. - var is_testCase = function (name_arr, index) { - return index === name_arr.length - 1 ? false : true; - }; - - var testCase_line = function (txt) { - return txt + "\n"; - }; - - /** - * Prints (console.log) the nested test status line(s). - * - * @param {Array} name_arr - Array of name elements. - * @param {String} status - either 'pass' or 'fail'. - * @example - * > print_status(['TC1', 'TC1.1', 'mytest'], 'pass'); - * TC1 - * TC1.1 - * mytest (pass) - */ - var print_status = function (name_arr, status) { - var txt = ''; - var _name_slice, part, i; - for (i = 0; i < name_arr.length; i++) { - _name_slice = name_slice(name_arr, i); - part = name_arr[i]; - if (!tracker.already_printed[_name_slice]) { - txt = add_indent(txt, i); - if (is_testCase(name_arr, i)) { - txt += testCase_line(part); - } else { - txt += status_text(part, status); - } - tracker.already_printed[_name_slice] = true; - } - } - console.log(txt); - }; - - nodeunit.runFiles(paths, { - testspec: options.testspec, - testFullSpec: options.testFullSpec, - moduleStart: function (name) { - console.log('\n' + bold(name)); - }, - testDone: function (name, assertions) { - tracker.remove(name); - - if (!assertions.failures()) { - print_status(name, 'pass'); - } else { - print_status(name, 'fail'); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log( - 'Assertion Message: ' + - assertion_message(a.message) - ); - } - console.log(a.error.stack + '\n'); - } - }); - } - }, - done: function (assertions, end) { - end = end || new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + bold(error('FAILURES: ')) + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } else { - console.log( - '\n' + bold(ok('OK: ')) + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - }, - testStart: function (name) { - tracker.put(name); - } - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/skip_passed.js b/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/skip_passed.js deleted file mode 100644 index 299a99a5e..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/skip_passed.js +++ /dev/null @@ -1,108 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - path = require('path'), - AssertionError = require('assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Skip passed tests output"; - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options, callback) { - - if (!options) { - // load default options - var content = fs.readFileSync( - __dirname + '/../../bin/nodeunit.json', 'utf8' - ); - options = JSON.parse(content); - } - - var error = function (str) { - return options.error_prefix + str + options.error_suffix; - }; - var ok = function (str) { - return options.ok_prefix + str + options.ok_suffix; - }; - var bold = function (str) { - return options.bold_prefix + str + options.bold_suffix; - }; - var assertion_message = function (str) { - return options.assertion_prefix + str + options.assertion_suffix; - }; - - var start = new Date().getTime(); - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - - nodeunit.runFiles(paths, { - testspec: options.testspec, - testFullSpec: options.testFullSpec, - moduleStart: function (name) { - console.log('\n' + bold(name)); - }, - testDone: function (name, assertions) { - if (assertions.failures()) { - console.log(error('✖ ' + name) + '\n'); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log( - 'Assertion Message: ' + assertion_message(a.message) - ); - } - console.log(a.error.stack + '\n'); - } - }); - } - }, - moduleDone: function (name, assertions) { - if (!assertions.failures()) { - console.log('✔ all tests passed'); - } - else { - console.log(error('✖ some tests failed')); - } - }, - done: function (assertions) { - var end = new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + bold(error('FAILURES: ')) + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } - else { - console.log( - '\n' + bold(ok('OK: ')) + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - - if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined); - } - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/tap.js b/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/tap.js deleted file mode 100644 index 9a36aafc8..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/tap.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - path = require('path'), - assert = require('tap').assert, - TapProducer = require('tap').Producer; - -/** - * Reporter info string - */ - -exports.info = "TAP output"; - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options) { - - if (!options) { - // load default options - var content = fs.readFileSync( - __dirname + '/../../bin/nodeunit.json', 'utf8' - ); - options = JSON.parse(content); - } - - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - var output = new TapProducer(); - output.pipe(process.stdout); - - nodeunit.runFiles(paths, { - testStart: function (name) { - output.write(name.toString()); - }, - testDone: function (name, assertions) { - assertions.forEach(function (e) { - var extra = {}; - if (e.error) { - extra.error = { - name: e.error.name, - message: e.error.message, - stack: e.error.stack.split(/\n/).filter(function (line) { - // exclude line of "types.js" - return ! RegExp(/types.js:83:39/).test(line); - }).join('\n') - }; - extra.wanted = e.error.expected; - extra.found = e.error.actual; - } - output.write(assert(e.passed(), e.message, extra)); - }); - }, - done: function (assertions) { - output.end(); - } - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/verbose.js b/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/verbose.js deleted file mode 100644 index 228271b54..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/reporters/verbose.js +++ /dev/null @@ -1,123 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - track = require('../track'), - path = require('path'); - AssertionError = require('../assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Verbose tests reporter" - - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options) { - - if (!options) { - // load default options - var content = fs.readFileSync( - __dirname + '/../../bin/nodeunit.json', 'utf8' - ); - options = JSON.parse(content); - } - - var error = function (str) { - return options.error_prefix + str + options.error_suffix; - }; - var ok = function (str) { - return options.ok_prefix + str + options.ok_suffix; - }; - var bold = function (str) { - return options.bold_prefix + str + options.bold_suffix; - }; - var assertion_message = function (str) { - return options.assertion_prefix + str + options.assertion_suffix; - }; - - var start = new Date().getTime(); - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - var tracker = track.createTracker(function (tracker) { - if (tracker.unfinished()) { - console.log(''); - console.log(error(bold( - 'FAILURES: Undone tests (or their setups/teardowns): ' - ))); - var names = tracker.names(); - for (var i = 0; i < names.length; i += 1) { - console.log('- ' + names[i]); - } - console.log(''); - console.log('To fix this, make sure all tests call test.done()'); - process.reallyExit(tracker.unfinished()); - } - }); - - nodeunit.runFiles(paths, { - testspec: options.testspec, - testFullSpec: options.testFullSpec, - moduleStart: function (name) { - console.log('\n' + bold(name)); - }, - testDone: function (name, assertions) { - tracker.remove(name); - - if (!assertions.failures()) { - console.log('✔ ' + name); - } - else { - console.log(error('✖ ' + name)); - } - // verbose so print everything - assertions.forEach(function (a) { - if (a.failed()) { - console.log(error(' ✖ ' + a.message)); - a = utils.betterErrors(a); - console.log(' ' + a.error.stack); - } - else { - console.log(' ✔ ' + a.message); - } - }); - }, - done: function (assertions, end) { - var end = end || new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + bold(error('FAILURES: ')) + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } - else { - console.log( - '\n' + bold(ok('OK: ')) + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - }, - testStart: function(name) { - tracker.put(name); - } - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/track.js b/node/node_modules/grunt/node_modules/nodeunit/lib/track.js deleted file mode 100644 index 5af98adfd..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/track.js +++ /dev/null @@ -1,48 +0,0 @@ -/*! - * Simple util module to track tests. Adds a process.exit hook to print - * the undone tests. - */ - - -exports.createTracker = function (on_exit) { - var names = {}; - var tracker = { - names: function () { - var arr = []; - for (var k in names) { - if (names.hasOwnProperty(k)) { - arr.push(k); - } - } - return arr; - }, - unfinished: function () { - return tracker.names().length; - }, - put: function (testname) { - names[testname] = testname; - }, - remove: function (testname) { - delete names[testname]; - } - }; - - process.on('exit', function() { - on_exit = on_exit || exports.default_on_exit; - on_exit(tracker); - }); - - return tracker; -}; - -exports.default_on_exit = function (tracker) { - if (tracker.unfinished()) { - console.log(''); - console.log('Undone tests (or their setups/teardowns): '); - var names = tracker.names(); - for (var i = 0; i < names.length; i += 1) { - console.log(names[i]); - } - process.reallyExit(tracker.unfinished()); - } -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/types.js b/node/node_modules/grunt/node_modules/nodeunit/lib/types.js deleted file mode 100644 index 2cdd1efc8..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/types.js +++ /dev/null @@ -1,189 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, it's mostly to avoid requiring code - * that is node specific - */ - -/** - * Module dependencies - */ - -var assert = require('./assert'), //@REMOVE_LINE_FOR_BROWSER - async = require('../deps/async'); //@REMOVE_LINE_FOR_BROWSER - - -/** - * Creates assertion objects representing the result of an assert call. - * Accepts an object or AssertionError as its argument. - * - * @param {object} obj - * @api public - */ - -exports.assertion = function (obj) { - return { - method: obj.method || '', - message: obj.message || (obj.error && obj.error.message) || '', - error: obj.error, - passed: function () { - return !this.error; - }, - failed: function () { - return Boolean(this.error); - } - }; -}; - -/** - * Creates an assertion list object representing a group of assertions. - * Accepts an array of assertion objects. - * - * @param {Array} arr - * @param {Number} duration - * @api public - */ - -exports.assertionList = function (arr, duration) { - var that = arr || []; - that.failures = function () { - var failures = 0; - for (var i = 0; i < this.length; i += 1) { - if (this[i].failed()) { - failures += 1; - } - } - return failures; - }; - that.passes = function () { - return that.length - that.failures(); - }; - that.duration = duration || 0; - return that; -}; - -/** - * Create a wrapper function for assert module methods. Executes a callback - * after it's complete with an assertion object representing the result. - * - * @param {Function} callback - * @api private - */ - -var assertWrapper = function (callback) { - return function (new_method, assert_method, arity) { - return function () { - var message = arguments[arity - 1]; - var a = exports.assertion({method: new_method, message: message}); - try { - assert[assert_method].apply(null, arguments); - } - catch (e) { - a.error = e; - } - callback(a); - }; - }; -}; - -/** - * Creates the 'test' object that gets passed to every test function. - * Accepts the name of the test function as its first argument, followed by - * the start time in ms, the options object and a callback function. - * - * @param {String} name - * @param {Number} start - * @param {Object} options - * @param {Function} callback - * @api public - */ - -exports.test = function (name, start, options, callback) { - var expecting; - var a_list = []; - - var wrapAssert = assertWrapper(function (a) { - a_list.push(a); - if (options.log) { - async.nextTick(function () { - options.log(a); - }); - } - }); - - var test = { - done: function (err) { - if (expecting !== undefined && expecting !== a_list.length) { - var e = new Error( - 'Expected ' + expecting + ' assertions, ' + - a_list.length + ' ran' - ); - var a1 = exports.assertion({method: 'expect', error: e}); - a_list.push(a1); - if (options.log) { - async.nextTick(function () { - options.log(a1); - }); - } - } - if (err) { - var a2 = exports.assertion({error: err}); - a_list.push(a2); - if (options.log) { - async.nextTick(function () { - options.log(a2); - }); - } - } - var end = new Date().getTime(); - async.nextTick(function () { - var assertion_list = exports.assertionList(a_list, end - start); - options.testDone(name, assertion_list); - callback(null, a_list); - }); - }, - ok: wrapAssert('ok', 'ok', 2), - same: wrapAssert('same', 'deepEqual', 3), - equals: wrapAssert('equals', 'equal', 3), - expect: function (num) { - expecting = num; - }, - _assertion_list: a_list - }; - // add all functions from the assert module - for (var k in assert) { - if (assert.hasOwnProperty(k)) { - test[k] = wrapAssert(k, k, assert[k].length); - } - } - return test; -}; - -/** - * Ensures an options object has all callbacks, adding empty callback functions - * if any are missing. - * - * @param {Object} opt - * @return {Object} - * @api public - */ - -exports.options = function (opt) { - var optionalCallback = function (name) { - opt[name] = opt[name] || function () {}; - }; - - optionalCallback('moduleStart'); - optionalCallback('moduleDone'); - optionalCallback('testStart'); - optionalCallback('testDone'); - //optionalCallback('log'); - - // 'done' callback is not optional. - - return opt; -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/lib/utils.js b/node/node_modules/grunt/node_modules/nodeunit/lib/utils.js deleted file mode 100644 index 5efd26ca5..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/lib/utils.js +++ /dev/null @@ -1,203 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var async = require('../deps/async'), - fs = require('fs'), - util = require('util'), - Script = process.binding('evals').Script || process.binding('evals').NodeScript, - http = require('http'); - - -/** - * Detect if coffee-script is available and search for .coffee as an - * extension in modulePaths if it is. - */ - -var extensionPattern; -try { - require('coffee-script'); - extensionPattern = /\.(?:js|coffee)$/; -} -catch (e) { - extensionPattern = /\.js$/; -} - - -/** - * Finds all modules at each path in an array, If a path is a directory, it - * returns all supported file types inside it. This only reads 1 level deep in - * the directory and does not recurse through sub-directories. - * - * The extension (.js, .coffee etc) is stripped from the filenames so they can - * simply be require()'ed. - * - * @param {Array} paths - * @param {Function} callback - * @api public - */ - -exports.modulePaths = function (paths, callback) { - async.concat(paths, function (p, cb) { - fs.stat(p, function (err, stats) { - if (err) { - return cb(err); - } - if (stats.isFile()) { - return cb(null, [p]); - } - if (stats.isDirectory()) { - fs.readdir(p, function (err, files) { - if (err) { - return cb(err); - } - - // filter out any filenames with unsupported extensions - var modules = files.filter(function (filename) { - return extensionPattern.exec(filename); - }); - - // remove extension from module name and prepend the - // directory path - var fullpaths = modules.map(function (filename) { - var mod_name = filename.replace(extensionPattern, ''); - return [p, mod_name].join('/'); - }); - - // sort filenames here, because Array.map changes order - fullpaths.sort(); - - cb(null, fullpaths); - }); - } - }); - }, callback); -}; - -/** - * Evaluates JavaScript files in a sandbox, returning the context. The first - * argument can either be a single filename or an array of filenames. If - * multiple filenames are given their contents are concatenated before - * evalution. The second argument is an optional context to use for the sandbox. - * - * @param files - * @param {Object} sandbox - * @return {Object} - * @api public - */ - -exports.sandbox = function (files, /*optional*/sandbox) { - var source, script, result; - if (!(files instanceof Array)) { - files = [files]; - } - source = files.map(function (file) { - return fs.readFileSync(file, 'utf8'); - }).join(''); - - if (!sandbox) { - sandbox = {}; - } - script = new Script(source); - result = script.runInNewContext(sandbox); - return sandbox; -}; - -/** - * Provides a http request, response testing environment. - * - * Example: - * - * var httputil = require('nodeunit').utils.httputil - * exports.testSomething = function(test) { - * httputil(function (req, resp) { - * resp.writeHead(200, {}); - * resp.end('test data'); - * }, - * function(server, client) { - * client.fetch('GET', '/', {}, function(resp) { - * test.equal('test data', resp.body); - * server.close(); - * test.done(); - * }) - * }); - * }; - * - * @param {Function} cgi - * @param {Function} envReady - * @api public - */ -exports.httputil = function (cgi, envReady) { - var hostname = process.env.HOSTNAME || 'localhost'; - var port = process.env.PORT || 3000; - - var server = http.createServer(cgi); - server.listen(port, hostname); - - var client = http.createClient(port, hostname); - client.fetch = function (method, path, headers, respReady) { - var request = this.request(method, path, headers); - request.end(); - request.on('response', function (response) { - response.setEncoding('utf8'); - response.on('data', function (chunk) { - if (response.body) { - response.body += chunk; - } else { - response.body = chunk; - } - }); - response.on('end', function () { - if (response.headers['content-type'] === 'application/json') { - response.bodyAsObject = JSON.parse(response.body); - } - respReady(response); - }); - }); - }; - - process.nextTick(function () { - if (envReady && typeof envReady === 'function') { - envReady(server, client); - } - }); -}; - - -/** - * Improves formatting of AssertionError messages to make deepEqual etc more - * readable. - * - * @param {Object} assertion - * @return {Object} - * @api public - */ - -exports.betterErrors = function (assertion) { - if (!assertion.error) return assertion; - - var e = assertion.error; - if (e.actual && e.expected) { - var actual = util.inspect(e.actual, false, 10).replace(/\n$/, ''); - var expected = util.inspect(e.expected, false, 10).replace(/\n$/, ''); - var multiline = ( - actual.indexOf('\n') !== -1 || - expected.indexOf('\n') !== -1 - ); - var spacing = (multiline ? '\n' : ' '); - e._message = e.message; - e.stack = ( - e.name + ':' + spacing + - actual + spacing + e.operator + spacing + - expected + '\n' + - e.stack.split('\n').slice(1).join('\n') - ); - } - return assertion; -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/man1/nodeunit.1 b/node/node_modules/grunt/node_modules/nodeunit/man1/nodeunit.1 deleted file mode 100644 index 450772da8..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/man1/nodeunit.1 +++ /dev/null @@ -1,95 +0,0 @@ -.\" Generated with Ronnjs/v0.1 -.\" http://github.com/kapouer/ronnjs/ -. -.TH "NODEUNIT" "1" "October 2010" "" "" -. -.SH "NAME" -\fBnodeunit\fR \-\- simple node\.js unit testing tool -. -.SH "SYNOPSIS" -. -.nf -nodeunit [options] [ \.\.\.] -. -.fi -. -.SH "DESCRIPTION" -Nodeunit is a simple unit testing tool based on the node\.js assert module\. -. -.IP "\(bu" 4 -Simple to use -. -.IP "\(bu" 4 -Just export the tests from a module -. -.IP "\(bu" 4 -Helps you avoid common pitfalls when testing asynchronous code -. -.IP "\(bu" 4 -Easy to add test cases with setUp and tearDown functions if you wish -. -.IP "\(bu" 4 -Allows the use of mocks and stubs -. -.IP "" 0 -. -.SH "OPTIONS" - \fB\-\-config FILE\fR: -. -.br - Load config options from a JSON file, allows the customisation - of color schemes for the default test reporter etc\. - See bin/nodeunit\.json for current available options\. -. -.P - \fB\-\-reporter FILE\fR: -. -.br - You can set the test reporter to a custom module or on of the modules - in nodeunit/lib/reporters, when omitted, the default test runner is used\. -. -.P - \fB\-\-list\-reporters\fR: -. -.br - List available build\-in reporters\. -. -.P - \fB\-h\fR, \fB\-\-help\fR: -. -.br - Display the help and exit\. -. -.P - \fB\-v\fR, \fB\-\-version\fR: -. -.br - Output version information and exit\. -. -.P - \fB\fR: - You can run nodeunit on specific files or on all \fI*\.js\fR files inside -. -.br - a directory\. -. -.SH "AUTHORS" -Written by Caolan McMahon and other nodeunit contributors\. -. -.br -Contributors list: \fIhttp://github\.com/caolan/nodeunit/contributors\fR\|\. -. -.SH "REPORTING BUGS" -Report nodeunit bugs to \fIhttp://github\.com/caolan/nodeunit/issues\fR\|\. -. -.SH "COPYRIGHT" -Copyright © 2010 Caolan McMahon\. -. -.br -Nodeunit has been released under the MIT license: -. -.br -\fIhttp://github\.com/caolan/nodeunit/raw/master/LICENSE\fR\|\. -. -.SH "SEE ALSO" -node(1) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/.bin/tap b/node/node_modules/grunt/node_modules/nodeunit/node_modules/.bin/tap deleted file mode 120000 index 999914bf5..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/.bin/tap +++ /dev/null @@ -1 +0,0 @@ -../tap/bin/tap.js \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/AUTHORS b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/AUTHORS deleted file mode 100644 index b7f6eb23f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/AUTHORS +++ /dev/null @@ -1,11 +0,0 @@ -# contributors sorted by whether or not they're me -Isaac Z. Schlueter -baudehlo -James Halliday -Jason Smith (air) -Pedro P. Candel -Stein Martin Hustad -Trent Mick -Corey Richardson -Raynos -Siddharth Mahendraker diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/README.md b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/README.md deleted file mode 100644 index db8173141..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/README.md +++ /dev/null @@ -1,84 +0,0 @@ -This is a mix-and-match set of utilities that you can use to write test -harnesses and frameworks that communicate with one another using the -Test Anything Protocol. - -If you don't yet know what TAP is, [you better ask -somebody](http://testanything.org/). - -Default Usage: - -1. Make a directory. Maybe call it 'test'. That'd be nice and obvious. -2. Put a bunch of test scripts in there. If they're node programs, then - they should be ".js". Anything else is assumed to be some kind of shell - script, which should have a shebang line. -3. `npm install tap` -4. Update package.json scripts.test to include `tap ./test` [example - gist](https://gist.github.com/4469613) -5. `npm test` - -The output will be TAP-compliant. - -For extra special bonus points, you can do something like this: - - var test = require("tap").test - test("make sure the thingie is a thing", function (t) { - t.equal(thingie, "thing", "thingie should be thing") - t.type(thingie, "string", "type of thingie is string") - t.ok(true, "this is always true") - t.notOk(false, "this is never true") - t.test("a child test", function (t) { - t.equal(this, superEasy, "right!?") - t.similar(7, 2, "ever notice 7 is kinda like 2?", {todo: true}) - t.test("so skippable", {skip: true}, function (t) { - t.plan(1) // only one test in this block - t.ok(true, "but when the flag changes, it'll pass") - // no need to end, since we had a plan. - }) - t.end() - }) - t.ok(99, "can also skip individual assertions", {skip: true}) - // end lets it know it's over. - t.end() - }) - test("another one", function (t) { - t.plan(1) - t.ok(true, "It's ok to plan, and also end. Watch.") - t.end() // but it must match the plan! - }) - -Node-tap is actually a collection of several modules, any of which may be -mixed and matched however you please. - -If you don't like this test framework, and think you can do much much -better, *I strongly encourage you to do so!* If you use this library, -however, at least to output TAP-compliant results when `process.env.TAP` -is set, then the data coming out of your framework will be much more -consumable by machines. - -You can also use this to build programs that *consume* the TAP data, so -this is very useful for CI systems and such. - -* tap-assert: A collection of assert functions that return TAP result - objects. -* tap-consumer: A stream interface for consuming TAP data. -* tap-producer: A class that produces a TAP stream by taking in result - objects. -* tap-results: A class for keeping track of TAP result objects as they - pass by, counting up skips, passes, fails, and so on. -* tap-runner: A program that runs through a directory running all the - tests in it. (Tests which may or may not be TAP-outputting tests. But - it's better if they are.) -* tap-test: A class for actually running tests. -* tap-harness: A class that runs tests. (Tests are also Harnesses, - which is how sub-tests run.) -* tap-global-harness: A default harness that provides the top-level - support for running TAP tests. - -## Experimental Code Coverage with runforcover & bunker: - -``` -TAP_COV=1 tap ./test [--cover=./lib,foo.js] [--cover-dir=./coverage] -``` - -This feature is experimental, and will most likely change somewhat -before being finalized. Feedback welcome. diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/bin/tap-http.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/bin/tap-http.js deleted file mode 100644 index 296910f9b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/bin/tap-http.js +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env node - -// just an example, really -// Run with `node tap-http.js path/to/tests/` - -var argv = process.argv.slice(2) - , path = require("path") - , Runner = require("../lib/tap-runner") - - , http = require("http") - , server = http.createServer(function (req, res) { - // it'd be nice to return a non-200 if the tests fail, but we don't - // know the status until it's done, so that would mean not being able - // to pipe the output - res.writeHead(200, {'content-type': 'text/plain'}) - new Runner(argv, null).pipe(res) - }) - -server.listen(1337) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/bin/tap-reader.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/bin/tap-reader.js deleted file mode 100755 index b196cc2a2..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/bin/tap-reader.js +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env node - -// read a tap stream from stdin. - -var TapConsumer = require("../lib/tap-consumer") - , TapProducer = require("../lib/tap-producer") - -var tc = new TapConsumer - , tp = new TapProducer - -//process.stdin.pipe(tc) -process.stdin.on("data", function (c) { - c = c + "" - // console.error(JSON.stringify(c).substr(0, 100)) - tc.write(c) -}) -process.stdin.on("end", function () { tc.end() }) -process.stdin.resume() -//tc.pipe(tp) -tc.on("data", function (c) { - tp.write(c) -}) -tc.on("end", function () { tp.end() }) - -tp.on("data", function (c) { - console.error(["output write", c]) - process.stdout.write(c) -}) - -tp.on("end", function (er, total, ok) { - if (er) throw er - process.exit(total - ok) -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/bin/tap.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/bin/tap.js deleted file mode 100755 index e7afcbcca..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/bin/tap.js +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env node - -var argv = process.argv.slice(2) - , path = require("path") - , Runner = require("../lib/tap-runner") - - , nopt = require("nopt") - - , knownOpts = - { cover: [path, false] - , "cover-dir": path - , stderr: Boolean - , stdout: Boolean - , diag: Boolean - , version: Boolean - , tap: Boolean - , timeout: Number - , gc: Boolean - } - - , shorthands = - // debugging 1: show stderr - { d: ["--stderr"] - // debugging 2: show stderr and tap - , dd: ["--stderr", "--tap"] - // debugging 3: show stderr, tap, AND always show diagnostics. - , ddd: ["--stderr", "--tap", "--diag"] - , "expose-gc": ["--gc"] - , g: ["--gc"] - , e: ["--stderr"] - , t: ["--timeout"] - , o: ["--tap"] - , c: ["--cover"] - , v: ["--version"] - , "?": ["--help"] - , h: ["--help"] - } - - , defaults = - { cover: "./lib" - , "cover-dir": "./coverage" - , stderr: process.env.TAP_STDERR - , tap: process.env.TAP - , diag: process.env.TAP_DIAG - , timeout: +process.env.TAP_TIMEOUT || 30 - , gc: false - , version: false - , help: false } - - , options = nopt(knownOpts, shorthands) - -if (options.version) { - console.log(require("../package.json").version) - process.exit(0) -} - -if (options.help) { - console.log(function(){/* - -Usage: - tap - - Run the files as tap tests, parse the output, and report the results - -Options: - - --stderr Print standard error output of tests to standard error. - --tap Print raw tap output. - --diag Print diagnostic output for passed tests, as well as failed. - (Implies --tap) - --gc Expose the garbage collector to tests. - --timeout Maximum time to wait for a subtest, in seconds. Default: 30 - --version Print the version of node tap. - --help Print this help. - -Please report bugs! https://github.com/isaacs/node-tap/issues - -*/}.toString().split(/\n/).slice(1, -1).join("\n")) - process.exit(0) -} - - -Object.keys(defaults).forEach(function (k) { - if (!options.hasOwnProperty(k)) options[k] = defaults[k] -}) - -// other tests that might rely on these -if (options.diag) process.env.TAP_DIAG = true -if (options.tap) process.env.TAP = true -if (options.timeout) process.env.TAP_TIMEOUT = options.timeout - -var r = new Runner(options) - , TapProducer = require("../lib/tap-producer") - -if (options.tap || options.diag) { - r.pipe(process.stdout) -} else { - r.on("file", function (file, results, details) { - var s = (details.ok ? "" : "not ") + "ok "+results.name - , n = details.pass + "/" + details.testsTotal - , dots = new Array(Math.max(1, 60 - s.length - n.length)).join(".") - console.log("%s %s %s", s, dots, n) - if (details.ok) { - if (details.skip) { - console.log(" skipped: %s", details.skipTotal) - } - } else { - // console.error(details) - console.log(" Command: %s", results.command) - console.log(" " + TapProducer.encode(details.list) - .split(/\n/).join("\n ")) - } - }) - r.on("end", function () { - //console.log(r) - var s = "total" - , n = r.results.pass + "/" + r.results.testsTotal - , dots = new Array(60 - s.length - n.length).join(".") - , ok = r.results.ok ? "ok" : "not ok" - console.log("%s %s %s\n\n%s", s, dots, n, ok) - if (r.doCoverage) { - console.error( "\nCoverage: %s\n" - , path.resolve(r.coverageOutDir, "index.html") ) - } - }) -} - - - -r.on("end", function () { - process.exit(r.results.tests - r.results.pass) -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/lib/bar.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/lib/bar.js deleted file mode 100644 index e7cb7addf..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/lib/bar.js +++ /dev/null @@ -1,15 +0,0 @@ -var Bar = module.exports = function(str) { - this.bar = str; - this.str = str; -}; - -Bar.prototype.foo = function() { - var self = this; - return self.bar; -}; - -Bar.prototype.baz = function() { - var self = this; - return self.str; -}; - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/lib/foo.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/lib/foo.js deleted file mode 100644 index cb9ee8f36..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/lib/foo.js +++ /dev/null @@ -1,15 +0,0 @@ -var Foo = module.exports = function(str) { - this.foo = str; - this.str = str; -}; - -Foo.prototype.bar = function() { - var self = this; - return self.foo; -}; - -Foo.prototype.baz = function() { - var self = this; - return self.str; -}; - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/test/bar.test.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/test/bar.test.js deleted file mode 100644 index 91e4bc21f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/test/bar.test.js +++ /dev/null @@ -1,20 +0,0 @@ -var test = require('tap').test, - Bar = require('../lib/bar'), - bar; - -test('setup', function(t) { - bar = new Bar('baz'); - t.ok(bar); - t.end(); -}); - -test('bar', function(t) { - t.equal('baz', bar.foo()); - t.end(); -}); - -test('teardown', function(t) { - t.ok(true); - t.end(); -}); - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/test/baz.test.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/test/baz.test.js deleted file mode 100644 index fae22d864..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/test/baz.test.js +++ /dev/null @@ -1,29 +0,0 @@ -var test = require('tap').test, - Foo = require('../lib/foo'), - Bar = require('../lib/bar'), - foo, bar; - -test('setup', function(t) { - foo = new Foo('baz'); - t.ok(foo); - bar = new Bar('baz'); - t.ok(bar); - t.end(); -}); - -test('baz from Foo', function(t) { - t.equal('baz', foo.baz()); - t.end(); -}); - -test('baz from Bar', function(t) { - t.equal('baz', bar.baz()); - t.end(); -}); - - -test('teardown', function(t) { - t.ok(true); - t.end(); -}); - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/test/foo.test.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/test/foo.test.js deleted file mode 100644 index 2aed8fda0..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/coverage-example/test/foo.test.js +++ /dev/null @@ -1,20 +0,0 @@ -var test = require('tap').test, - Foo = require('../lib/foo'), - foo; - -test('setup', function(t) { - foo = new Foo('baz'); - t.ok(foo); - t.end(); -}); - -test('bar', function(t) { - t.equal('baz', foo.bar()); - t.end(); -}); - -test('teardown', function(t) { - t.ok(true); - t.end(); -}); - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/example/lib/math.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/example/lib/math.js deleted file mode 100644 index f79862602..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/example/lib/math.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = Math diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/example/test/test-example.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/example/test/test-example.js deleted file mode 100644 index cd2549b2a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/example/test/test-example.js +++ /dev/null @@ -1,237 +0,0 @@ -var tap = require("tap") - , test = tap.test - , plan = tap.plan - , math - -test("load sut", function (t) { - math = require("../lib/math") - t.ok(math, "object loaded") - t.end() -}) - -test("validate constants", function (t) { - t.equal(math.LN10, 2.302585092994046, "ln 10") - t.equal(math.PI, 3.141592653589793, "pi") - t.equal(math.E, 2.718281828459045, "e") - t.equal(math.LOG10E, 0.4342944819032518, "log 10 e") - t.equal(math.SQRT2, 1.4142135623730951, "sqrt 2") - t.equal(math.SQRT1_2, 0.7071067811865476, "sqrt 1/2") - t.equal(math.LN2, 0.6931471805599453, "ln2") - t.end() -}) - -test("using this", function (t) { - // this also works. - this.equal(t, this, "call in scope of test obj") - this.end() -}) - -// test setTimeout, just a trivial example. -test("setTimeout", function (t) { - var start = Date.now() - setTimeout(function () { - t.ok(Date.now() >= start + 50, "timeout fired after delay") - t.end() - }, 50) -}) - -// another way to do the same, using a plan. -// this is more robust, but annoying when you have a long list -// of tests for something. For async stuff, it's generally better, -// since there's a higher risk of the control flowing off to lala land. -test("setTimeout planned", function (t) { - t.plan(1) - var start = Date.now() - setTimeout(function () { - t.ok(Date.now() >= start + 50, "timeout fired after delay") - }, 50) -}) - -// plans also are good for cases where things may fire in a non-deterministic -// order, since it won't be as obvious when everything is done. -test("setTimeout parallel", function (t) { - t.plan(2) - var start = Date.now() - setTimeout(function A () { - t.ok(Date.now() >= start + 50, "timeout A fired after delay") - }, 50) - setTimeout(function B () { - t.ok(Date.now() >= start + 50, "timeout B fired after delay") - }, 50) -}) - -// something slightly less hello worldy -test("async test", function (t) { - t.plan(4) - var fs = require("fs") - t.ok(fs, "fs library should load") - var rs = fs.createReadStream(__filename) - t.ok(rs, "read stream should start fine.") - rs.on("open", function (fd) { - t.type(fd, "number", "file descriptor should be a number") - t.equal(fd, rs.fd, "fd should match stream fd") - }) -}) - -// you can bail out of the entire everything if something is just -// Not Right (db not installed, etc.) -test("tarp", function (parent) { - if (7 === 5) { - parent.bailout("math is broken") - } - // bailout bubbles up a bit like "error" events - // if unhandled, then the parent will bail, as well. - parent.test("child bailouts", function (child) { - child.on("bailout", function (s) { - parent.fail("children shouldn't bail.") - }) - child.bailout("try to bail out, but instead just fail a test") - }) - - parent.test("child bailout 2", function (child) { - child.bailout("this one will bail out") - }) -}) - -// tests marked "todo" can fail without counting against the overall score -// never ever ever write tests to "verify" incorrect behavior! -test("unfinished test", function (t) { - t.equal(math.cos(math.PI), -1, "cos(PI)") - t.equal(math.sin(math.PI), 0, "sin(PI)") - t.equal(math.face, "your face", "math.face should be your face # TODO") - t.end() -}) - -// tests can have children. -test("http server", function (t) { - // one test plus 4 children. - t.plan(5) - - var http = require("http") - , PORT = 12346 - - t.ok(http, "http module should load") - var server - - t.test("set up server", function (t) { - t.plan(2) - server = http.createServer(function (req, res) { - t.comment("Request: "+req.url) - res.writeHead(200, {}) - res.end(req.method + " " + req.url) - }) - t.ok(server, "createServer should create a server") - server.listen(PORT, t.cb("listen should fire callback")) - }) - - // set the "parallel" flag on this one. - // That signals the harness to proceed immediately to the next test, - // and run them in parallel. - // Default behavior is to wait for each test to complete before proceeding - // to the next one. - // The first not-parallel test encountered will cause it to wait for that - // test, as well as all the parallel tests before it. - // A, B', C', D', E (where ' means "parallel") - // Runs A, and then B, C, and D in parallel, and then E. - t.test("testing POST", {parallel: true}, function (t) { - t.plan(1) - http.request("POST", { method: "POST" - , host: "localhost" - , path: "/foo" - , port: PORT }).on("response", function (res) { - t.bufferStream(res, function (s) { t.equal(s, "POST /foo") }) - }).end() - }) - - t.test("testing GET", {parallel: true}, function (t) { - t.plan(1) - http.request("POST", { method: "GET" - , host: "localhost" - , path: "/foo" - , port: PORT }).on("response", function (res) { - t.bufferStream(res, function (s) { t.equal(s, "GET /foo") }) - }).end() - }) - - // wrap in a test so that if this throws, it'll log as a failed test. - t.test("teardown", function (t) { - server.close() - t.end() - }) -}) - -// yo dawg! -test("meta-tests", function (t) { - t.plan(5) - - // t.fails() wraps a child test and succeeds if it fails. - t.fails(t.test("this should fail", function (t) { - t.ok(false, "assert false") - t.end() - })) - - // t.timesOut() wraps a child test and succeeds if it times out. - // if t.end() is called, or if a plan is completed, then it fails. - // set the timeout really low so that it will not take forever. - t.timesOut(t.test("this should timeout", { timeout: 1 }, function (t) { - t.ok(true, "assert true") - // t.end() never called. - })) - - // t.incomplete() wraps a child test and succeeds if it ends before - // the plan is finished. - t.incomplete(t.test("this should be incomplete", function (t) { - t.plan(100) - t.ok(true, "assert true") - // calling end prematurely. - t.end() - })) - - // t.bailsOut() wraps a child test and succeeds if it calls bailout() - t.bailsOut(t.test("this should bailout", function (t) { - t.bailout("oh noes, bailing out!") - })) - - // low-level analysis of subtests - t.test("verifying test success/failure expectations", function (t) { - t.once("end", function () { - var res = t.results - , is = t.equal - // hijack! - t.clear() - is(res.ok, false, "ok") - - is(res.bailedOut, false, "bailed out") - - is(res.skip, 2, "skips") - is(res.skipPass, 1, "skip that passed") - is(res.skipFail, 1, "skip that failed") - - is(res.todo, 2, "todos") - is(res.todoPass, 1, "todo that passed") - is(res.todoFail, 1, "todo that failed") - - is(res.failTotal, 3, "failures total") - is(res.fail, 1, "relevant failure") - - is(res.passTotal, 3, "passes total") - is(res.pass, 1, "relevant pass") - - is(res.testsTotal, 6, "total tests") - is(res.tests, 2, "should be 2 relevant tests") - - t.end() - }) - - // run the metatest. - // *this* is the actual SUT in this case. - t.ok(false, "failing todo #todo") - // can also set #todo or #skip explicitly - t.ok(true, "succeeding todo", {todo: true}) - t.ok(false, "failing skip #skip", {skip: true}) - t.ok(true, "suceeding skip #skip") - t.ok(false, "failing test") - t.ok(true, "succeeding test") - t.end() - }) -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/main.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/main.js deleted file mode 100644 index a9a520ab2..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/main.js +++ /dev/null @@ -1,16 +0,0 @@ - -var GlobalHarness = require("./tap-global-harness") - -// this lets you do stuff like: -// var test = require("tap").test -// test(...) -// to run stuff in the global harness. -exports = module.exports = new GlobalHarness() - -exports.createProducer = exports.Producer = require("./tap-producer") -exports.createConsumer = exports.Consumer = require("./tap-consumer") -exports.yamlish = require("yamlish") -exports.createTest = exports.Test = require("./tap-test") -exports.createHarness = exports.Harness = require("./tap-harness") -exports.createRunner = exports.Runner = require("./tap-runner") -exports.assert = require("./tap-assert") diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-assert.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-assert.js deleted file mode 100644 index 60203a03f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-assert.js +++ /dev/null @@ -1,445 +0,0 @@ -// an assert module that returns tappable data for each assertion. -var difflet = require('difflet') - , deepEqual = require('deep-equal') - , bufferEqual = require('buffer-equal') - , Buffer = require('buffer').Buffer - -module.exports = assert - -var syns = {} - , id = 1 - -function assert (ok, message, extra) { - if (extra && extra.skip) return assert.skip(message, extra) - - //console.error("assert %j", [ok, message, extra]) - //if (extra && extra.skip) return assert.skip(message, extra) - //console.error("assert", [ok, message, extra]) - ok = !!ok - var res = { id : id ++, ok: ok } - - var caller = getCaller(extra && extra.error) - if (extra && extra.error) { - res.type = extra.error.name - res.message = extra.error.message - res.code = extra.error.code - || extra.error.type - res.errno = extra.error.errno - delete extra.error - } - if (caller.file) { - res.file = caller.file - res.line = +caller.line - res.column = +caller.column - } - res.stack = caller.stack - - res.name = message || "(unnamed assert)" - - if (extra) Object.keys(extra).forEach(function (k) { - if (!res.hasOwnProperty(k)) res[k] = extra[k] - }) - - // strings and objects are hard to diff by eye - if (!ok && - res.hasOwnProperty("found") && - res.hasOwnProperty("wanted") && - res.found !== res.wanted) { - if (typeof res.wanted !== typeof res.found || - typeof res.wanted === "object" && (!res.found || !res.wanted)) { - res.type = { found: typeof found - , wanted: typeof wanted } - } else if (typeof res.wanted === "string") { - res.diff = diffString(res.found, res.wanted) - } else if (typeof res.wanted === "object") { - res.diff = diffObject(res.found, res.wanted) - } - } - - //console.error("assert return", res) - - return res -} -assert.ok = assert -syns.ok = [ "true", "assert" ] - - -function notOk (ok, message, extra) { - return assert(!ok, message, extra) -} -assert.notOk = notOk -syns.notOk = [ "false", "notok" ] - -function error (er, message, extra) { - if (!er) { - // just like notOk(er) - return assert(!er, message, extra) - } - message = message || er.message - extra = extra || {} - extra.error = er - return assert.fail(message, extra) -} -assert.error = error -syns.error = [ "ifError", "ifErr", "iferror" ] - - -function pass (message, extra) { - return assert(true, message, extra) -} -assert.pass = pass - -function fail (message, extra) { - //console.error("assert.fail", [message, extra]) - //if (extra && extra.skip) return assert.skip(message, extra) - return assert(false, message, extra) -} -assert.fail = fail - -function skip (message, extra) { - //console.error("assert.skip", message, extra) - if (!extra) extra = {} - return { id: id ++, skip: true, name: message || "" } -} -assert.skip = skip - -function throws (fn, wanted, message, extra) { - if (typeof wanted === "string") { - extra = message - message = wanted - wanted = null - } - - if (extra && extra.skip) return assert.skip(message, extra) - - var found = null - try { - fn() - } catch (e) { - found = { name: e.name, message: e.message } - } - - extra = extra || {} - - extra.found = found - if (wanted) { - wanted = { name: wanted.name, message: wanted.message } - extra.wanted = wanted - } - - if (!message) { - message = "Expected to throw" - if (wanted) message += ": "+wanted.name + " " + wanted.message - } - - return (wanted) ? assert.similar(found, wanted, message, extra) - : assert.ok(found, message, extra) -} -assert.throws = throws - - -function doesNotThrow (fn, message, extra) { - if (extra && extra.skip) return assert.skip(message, extra) - var found = null - try { - fn() - } catch (e) { - found = {name: e.name, message: e.message} - } - message = message || "Should not throw" - - return assert.equal(found, null, message, extra) -} -assert.doesNotThrow = doesNotThrow - - -function equal (a, b, message, extra) { - if (extra && extra.skip) return assert.skip(message, extra) - extra = extra || {} - message = message || "should be equal" - extra.found = a - extra.wanted = b - return assert(a === b, message, extra) -} -assert.equal = equal -syns.equal = ["equals" - ,"isEqual" - ,"is" - ,"strictEqual" - ,"strictEquals"] - - -function equivalent (a, b, message, extra) { - if (extra && extra.skip) return assert.skip(message, extra) - var extra = extra || {} - message = message || "should be equivalent" - extra.found = a - extra.wanted = b - - if (Buffer.isBuffer(a) && Buffer.isBuffer(b)) { - return assert(bufferEqual(a, b), message, extra) - } else { - return assert(deepEqual(a, b), message, extra) - } -} -assert.equivalent = equivalent -syns.equivalent = ["isEquivalent" - ,"looseEqual" - ,"looseEquals" - ,"isDeeply" - ,"same" - ,"deepEqual" - ,"deepEquals"] - - -function inequal (a, b, message, extra) { - if (extra && extra.skip) return assert.skip(message, extra) - extra = extra || {} - message = message || "should not be equal" - extra.found = a - extra.doNotWant = b - return assert(a !== b, message, extra) -} -assert.inequal = inequal -syns.inequal = ["notEqual" - ,"notEquals" - ,"notStrictEqual" - ,"notStrictEquals" - ,"isNotEqual" - ,"isNot" - ,"not" - ,"doesNotEqual" - ,"isInequal"] - - -function inequivalent (a, b, message, extra) { - if (extra && extra.skip) return assert.skip(message, extra) - extra = extra || {} - message = message || "should not be equivalent" - extra.found = a - extra.doNotWant = b - - if (Buffer.isBuffer(a) && Buffer.isBuffer(b)) { - return assert(!bufferEqual(a, b), message, extra) - } else { - return assert(!deepEqual(a, b), message, extra) - } -} -assert.inequivalent = inequivalent -syns.inequivalent = ["notEquivalent" - ,"notDeepEqual" - ,"notDeeply" - ,"notSame" - ,"isNotDeepEqual" - ,"isNotDeeply" - ,"isNotEquivalent" - ,"isInequivalent"] - -function similar (a, b, message, extra, flip) { - if (extra && extra.skip) return assert.skip(message, extra) - // test that a has all the fields in b - message = message || "should be similar" - - if (typeof a === "string" && - (Object.prototype.toString.call(b) === "[object RegExp]")) { - extra = extra || {} - extra.pattern = b - extra.string = a - var ok = a.match(b) - extra.match = ok - if (flip) ok = !ok - return assert.ok(ok, message, extra) - } - - var isObj = assert(a && typeof a === "object", message, extra) - if (!isObj.ok) { - // not an object - if (a == b) isObj.ok = true - if (flip) isObj.ok = !isObj.ok - return isObj - } - - var eq = flip ? inequivalent : equivalent - return eq(selectFields(a, b), b, message, extra) -} -assert.similar = similar -syns.similar = ["isSimilar" - ,"has" - ,"hasFields" - ,"like" - ,"isLike"] - -function dissimilar (a, b, message, extra) { - if (extra && extra.skip) return assert.skip(message, extra) - message = message || "should be dissimilar" - return similar(a, b, message, extra, true) -} -assert.dissimilar = dissimilar -syns.dissimilar = ["unsimilar" - ,"notSimilar" - ,"unlike" - ,"isUnlike" - ,"notLike" - ,"isNotLike" - ,"doesNotHave" - ,"isNotSimilar" - ,"isDissimilar"] - -function type (thing, t, message, extra) { - if (extra && extra.skip) return assert.skip(message, extra) - var name = t - if (typeof name === "function") name = name.name || "(anonymous ctor)" - //console.error("name=%s", name) - message = message || "type is "+name - var type = typeof thing - //console.error("type=%s", type) - if (!thing && type === "object") type = "null" - if (type === "object" && t !== "object") { - if (typeof t === "function") { - //console.error("it is a function!") - extra = extra || {} - extra.found = Object.getPrototypeOf(thing).constructor.name - extra.wanted = name - //console.error(thing instanceof t, name) - return assert.ok(thing instanceof t, message, extra) - } - - //console.error("check prototype chain") - // check against classnames or objects in prototype chain, as well. - // type(new Error("asdf"), "Error") - // type(Object.create(foo), foo) - var p = thing - while (p = Object.getPrototypeOf(p)) { - if (p === t || p.constructor && p.constructor.name === t) { - type = name - break - } - } - } - //console.error(type, name, type === name) - return assert.equal(type, name, message, extra) -} -assert.type = type -syns.type = ["isa"] - -// synonyms are helpful. -Object.keys(syns).forEach(function (c) { - syns[c].forEach(function (s) { - Object.defineProperty(assert, s, { value: assert[c], enumerable: false }) - }) -}) - -// helpers below - -function selectFields (a, b) { - // get the values in A of the fields in B - var ret = Array.isArray(b) ? [] : {} - Object.keys(b).forEach(function (k) { - if (!a.hasOwnProperty(k)) return - var v = b[k] - , av = a[k] - if (v && av && typeof v === "object" && typeof av === "object" - && !(v instanceof Date) - && !(v instanceof RegExp) - && !(v instanceof String) - && !(v instanceof Boolean) - && !(v instanceof Number) - && !(Array.isArray(v))) { - ret[k] = selectFields(av, v) - } else ret[k] = av - }) - return ret -} - -function sortObject (obj) { - if (typeof obj !== 'object' || Array.isArray(obj) || obj === null) { - return obj - } - - return Object.keys(obj).sort().reduce(function (acc, key) { - acc[key] = sortObject(obj[key]) - return acc - }, {}) -} - -function stringify (a) { - return JSON.stringify(sortObject(a), (function () { - var seen = [] - , keys = [] - return function (key, val) { - var s = seen.indexOf(val) - if (s !== -1) { - return "[Circular: "+keys[s]+"]" - } - if (val && typeof val === "object" || typeof val === "function") { - seen.push(val) - keys.push(val["!"] || val.name || key || "") - if (typeof val === "function") { - return val.toString().split(/\n/)[0] - } else if (typeof val.toUTCString === "function") { - return val.toUTCString() - } - } - return val - }})()) -} - -function diffString (f, w) { - if (w === f) return null - var p = 0 - , l = w.length - while (p < l && w.charAt(p) === f.charAt(p)) p ++ - w = stringify(w).substr(1).replace(/"$/, "") - f = stringify(f).substr(1).replace(/"$/, "") - return diff(f, w, p) -} - -function diffObject (f, w) { - return difflet({ indent : 2, comment : true }).compare(w, f) -} - -function diff (f, w, p) { - if (w === f) return null - var i = p || 0 // it's going to be at least p. JSON can only be bigger. - , l = w.length - while (i < l && w.charAt(i) === f.charAt(i)) i ++ - var pos = Math.max(0, i - 20) - w = w.substr(pos, 40) - f = f.substr(pos, 40) - var pointer = i - pos - return "FOUND: "+f+"\n" - + "WANTED: "+w+"\n" - + (new Array(pointer + 9).join(" ")) - + "^ (at position = "+p+")" -} - -function getCaller (er) { - // get the first file/line that isn't this file. - if (!er) er = new Error - var stack = er.stack || "" - stack = stack.split(/\n/) - for (var i = 1, l = stack.length; i < l; i ++) { - var s = stack[i].match(/\(([^):]+):([0-9]+):([0-9]+)\)$/) - if (!s) continue - var file = s[1] - , line = +s[2] - , col = +s[3] - if (file.indexOf(__dirname) === 0) continue - if (file.match(/tap-test\/test.js$/)) continue - else break - } - var res = {} - if (file && file !== __filename && !file.match(/tap-test\/test.js$/)) { - res.file = file - res.line = line - res.column = col - } - - res.stack = stack.slice(1).map(function (s) { - return s.replace(/^\s*at\s*/, "") - }) - - return res -} - - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-browser-harness.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-browser-harness.js deleted file mode 100644 index 94700f534..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-browser-harness.js +++ /dev/null @@ -1,63 +0,0 @@ -// this is just a harness that pipes to stdout. -// It's the default one. -module.exports = BrowserHarness - -var BrowserHarness = global.TAP_Browser_Harness - , inherits = require("inherits") - , Results = require("./tap-results") - , Harness = require("./tap-harness") - , Test = require("./tap-test") - -inherits(BrowserHarness, Harness) -function BrowserHarness (outPipe) { - //console.error("calling BrowserHarness") - if (browserHarness) return browserHarness - if (!(this instanceof BrowserHarness)) { - return browserHarness = new BrowserHarness - } - browserHarness = global.TAP_Browser_Harness = this - BrowserHarness.super.call(this, Test) - - if (outPipe) this.output.pipe(outPipe) - - this.test = this.test.bind(this) - - this.plan = this.plan.bind(this) - - var output = this.output - this.on("childEnd", function (child) { - //console.error("childEnd in global harness") - //console.error(child.results) - // write out the stuff for this child. - //console.error("child.conf", child.conf) - - // maybe write some other stuff about the number of tests in this - // thing, etc. I dunno. - //console.error("child results", child.results) - this.results.list.forEach(function (res) { - //delete res.error - //console.error("child resuilt", res) - output.write(res) - }) - //console.error("wrote child results") - this.results.list.length = 0 - }) - - var streamEnded = false - this.on("end", function () { - //console.error("global ending the stream") - if (!streamEnded) { - this.results.list.forEach(function (res) { - output.write(res) - }) - this.results.list.length = 0 - output.end() - streamEnded = true - } - }) - - // TODO: handle global errors - // process.on("unhandledException", function (e) { - // this.bailout("unhandled exception: " + e.message) - // }) -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-consumer.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-consumer.js deleted file mode 100644 index f1b2a6a9d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-consumer.js +++ /dev/null @@ -1,245 +0,0 @@ -module.exports = TapConsumer - -// pipe a stream into this that's emitting tap-formatted data, -// and it'll emit "data" events with test objects or comment strings -// and an "end" event with the final results. - -var yamlish = require("yamlish") - , Results = require("./tap-results") - , inherits = require("inherits") - -TapConsumer.decode = TapConsumer.parse = function (str) { - var tc = new TapConsumer - , list = [] - tc.on("data", function (res) { - list.push(res) - }) - tc.end(str) - tc.results.list = list - return tc.results -} - -inherits(TapConsumer, require("stream").Stream) -function TapConsumer () { - if (!(this instanceof TapConsumer)) { - return new TapConsumer - } - - TapConsumer.super.call(this) - this.results = new Results - this.readable = this.writable = true - - this.on("data", function (res) { - if (typeof res === "object") this.results.add(res) - }) - - this._plan = null - this._buffer = "" - this._indent = [] - this._current = null - this._actualCount = 0 - this._passed = [] - this._failed = [] - //console.error("TapConsumer ctor done") -} - -TapConsumer.prototype.bailedOut = false - -TapConsumer.prototype.write = function (chunk) { - if (!this.writable) this.emit("error", new Error("not writable")) - if (this.bailedOut) return true - - this._buffer = this._buffer + chunk - // split it up into lines. - var lines = this._buffer.split(/\r?\n/) - // ignore the last line, since it might be incomplete. - this._buffer = lines.pop() - - for (var i = 0, l = lines.length; i < l; i ++) { - //console.error([i, lines[i]]) - // see if it's indented. - var line = lines[i] - , spaces = (this._indent.length && !line.trim()) - || line.match(/^\s/) - // at this level, only interested in fully undented stuff. - if (spaces) { - var c = i - while (c < l && (!lines[c].trim() || lines[c].match(/^\s/))) { - this._indent.push(lines[c++]) - } - //console.error(c-i, "indented", this._indent, this._current) - i = c - 1 - continue - } - // some kind of line. summary, ok, notok, comment, or garbage. - // this also finishes parsing any of the indented lines from before - this._parseLine(line) - } - return true -} - -TapConsumer.prototype.end = function () { - // finish up any hanging indented sections or final buffer - if (this._buffer.match(/^\s/)) this._indent.push(this.buffer) - else this._parseLine(this._buffer) - - if (!this.bailedOut && - this._plan !== null && - this.results.testsTotal !== this._plan) { - while (this._actualCount < this._plan) { - this.emit("data", {ok: false, name:"MISSING TEST", - id:this._actualCount ++ }) - } - } - - this._parseLine("") - this._buffer = "" - this.writable = false - this.emit("end", null, this._actualCount, this._passed) -} - -TapConsumer.prototype._parseLine = function (line) { - if (this.bailedOut) return - //console.error("_parseLine", [line]) - // if there are any indented lines, and there is a - // current object already, then they belong to it. - // if there is not a current object, then they're garbage. - if (this._current && this._indent.length) { - this._parseIndented() - } - this._indent.length = 0 - if (this._current) { - if (this._current.ok) this._passed.push(this._current.id) - else this._failed.push(this._current.id) - this.emit("data", this._current) - } - this._current = null - line = line.trim() - if (!line) return - // try to see what kind of line this is. - - var bo - if (bo = line.match(/^bail out!\s*(.*)$/i)) { - this.bailedOut = true - // this.emit("error", new Error(line)) - this.emit("bailout", bo[1]) - return - } - - if (line.match(/^#/)) { // just a comment - line = line.replace(/^#+/, "").trim() - // console.error("outputting comment", [line]) - if (line) this.emit("data", line) - return - } - - var plan = line.match(/^([0-9]+)\.\.([0-9]+)(?:\s+#(.*))?$/) - if (plan) { - var start = +(plan[1]) - , end = +(plan[2]) - , comment = plan[3] - - // TODO: maybe do something else with this? - // it might be something like: "1..0 #Skip because of reasons" - this._plan = end - this.emit("plan", end, comment) - // plan must come before or after all tests. - if (this._actualCount !== 0) { - this._sawPlan = true - } - return - } - - if (line.match(/^(not )?ok(?:\s+([0-9]+))?/)) { - this._parseResultLine(line) - return - } - - // garbage. emit as a comment. - //console.error("emitting", [line.trim()]) - if (line.trim()) this.emit("data", line.trim()) -} - -TapConsumer.prototype._parseDirective = function (line) { - line = line.trim() - if (line.match(/^TODO\b/i)) { - return { todo:true, explanation: line.replace(/^TODO\s*/i, "") } - } else if (line.match(/^SKIP\b/i)) { - return { skip:true, explanation: line.replace(/^SKIP\s*/i, "") } - } -} - -TapConsumer.prototype._parseResultLine = function (line) { - this._actualCount ++ - if (this._sawPlan) { - this.emit("data", {ok: false, name:"plan in the middle of tests" - ,id:this._actualCount ++}) - } - var parsed = line.match(/^(not )?ok(?: ([0-9]+))?(?:(?: - )?(.*))?$/) - , ok = !parsed[1] - , id = +(parsed[2] || this._actualCount) - , rest = parsed[3] || "" - , name - , res = { id:id, ok:ok } - - // split on un-escaped # characters - - //console.log("# "+JSON.stringify([name, rest])) - rest = rest.replace(/([^\\])((?:\\\\)*)#/g, "$1\n$2").split("\n") - name = rest.shift() - rest = rest.filter(function (r) { return r.trim() }).join("#") - //console.log("# "+JSON.stringify([name, rest])) - - // now, let's see if there's a directive in there. - var dir = this._parseDirective(rest.trim()) - if (!dir) name += rest ? "#" + rest : "" - else { - res.ok = true - if (dir.skip) res.skip = true - else if (dir.todo) res.todo = true - if (dir.explanation) res.explanation = dir.explanation - } - res.name = name - - //console.error(line, [ok, id, name]) - this._current = res -} - -TapConsumer.prototype._parseIndented = function () { - // pull yamlish block out - var ind = this._indent - , ys - , ye - , yind - , diag - //console.error(ind, this._indent) - for (var i = 0, l = ind.length; i < l; i ++) { - var line = ind[i] - if (line === undefined) continue - var lt = line.trim() - - if (!ys) { - ys = line.match(/^(\s*)---(.*)$/) - if (ys) { - yind = ys[1] - diag = [ys[2]] - //console.error([line,ys, diag]) - continue - } else if (lt) this.emit("data", lt) - } else if (ys && !ye) { - if (line === yind + "...") ye = true - else { - diag.push(line.substr(yind.length)) - } - } else if (ys && ye && lt) this.emit("data", lt) - } - if (diag) { - //console.error('about to parse', diag) - diag = yamlish.decode(diag.join("\n")) - //console.error('parsed', diag) - Object.keys(diag).forEach(function (k) { - //console.error(this._current, k) - if (!this._current.hasOwnProperty(k)) this._current[k] = diag[k] - }, this) - } -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-cov-html.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-cov-html.js deleted file mode 100644 index 3c1c19257..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-cov-html.js +++ /dev/null @@ -1,78 +0,0 @@ -var fs = require('fs'), - path = require('path'), - asyncMap = require("slide").asyncMap, - util = require('util'); - -var CovHtml = module.exports = function(cov_stats, cov_dir, cb) { - var index = []; - - asyncMap( - Object.keys(cov_stats), - function(f, cb) { - var st = cov_stats[f], - missing_lines = st.missing.map(function(l) { - return l.number; - }), - out = '\n\n\n ' + - '\n ' + - - f + ' (' + st.loc + ')\n' + - '\n' + - '\n\n' + - '

        ' + f + ' (' + st.loc + ')' + '

        ' + - '

        Run: ' + (st.missing.length ? st.loc - st.missing.length : st.loc) + ', Missing: ' + - st.missing.length + ', Percentage: ' + st.percentage + '

        ' + - '

        Source:

        \n' + - '
          \n' + - st.lines.map(function(line) { - var number = line.number, - color = (missing_lines.indexOf(number) !== -1) ? '#fcc' : '#cfc'; - return '
        1. ' + line.source.replace(/'; - }).join('\n') + - '
        \n' + - '

        Data

        \n'+ - '
        ' + util.inspect(st, true, Infinity, false).replace(/\n';
        -
        -      fs.writeFile(
        -        cov_dir + '/' + 
        -        f.replace(process.cwd() + '/', '').replace(/\//g, '+') + '.html',
        -        out,
        -        'utf8',
        -        function(err) {
        -          if (err) {
        -            throw err;
        -          }
        -          index.push(f);
        -          cb();
        -        });
        -    },
        -    function(err) {
        -      if (err) {
        -        throw err;
        -      }
        -      var out = '\n\n\n  ' +
        -          '\n  Coverage Index\n\n' +
        -          '\n

        Code Coverage Information

        \n
          ' + - index.map(function(fname) { - return '
        • ' + fname + '
        • '; - }).join('\n') + '
        \n\n'; - - fs.writeFile(cov_dir + '/index.html', out, 'utf8', function(err) { - if (err) { - throw err; - } - cb(); - }); - } - ); -}; - - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-global-harness.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-global-harness.js deleted file mode 100644 index 10073002f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-global-harness.js +++ /dev/null @@ -1,68 +0,0 @@ -// this is just a harness that pipes to stdout. -// It's the default one. -module.exports = GlobalHarness - -var globalHarness = global.TAP_Global_Harness - , inherits = require("inherits") - , Results = require("./tap-results") - , Harness = require("./tap-harness") - , Test = require("./tap-test") - -inherits(GlobalHarness, Harness) -function GlobalHarness () { - //console.error("calling GlobalHarness") - if (globalHarness) return globalHarness - if (!(this instanceof GlobalHarness)) { - return globalHarness = new GlobalHarness - } - - globalHarness = global.TAP_Global_Harness = this - GlobalHarness.super.call(this, Test) - - this.output.pipe(process.stdout) - //this.output.on("data", function () { - // process.nextTick(process.stdout.flush.bind(process.stdout)) - //}) - - this.test = this.test.bind(this) - - this.plan = this.plan.bind(this) - - var output = this.output - this.on("childEnd", function (child) { - //console.error("childEnd in global harness") - //console.error(child.results) - // write out the stuff for this child. - //console.error("child.conf", child.conf) - - // maybe write some other stuff about the number of tests in this - // thing, etc. I dunno. - //console.error("child results", child.results) - this.results.list.forEach(function (res) { - //delete res.error - //console.error("child resuilt", res) - output.write(res) - }) - //console.error("wrote child results") - this.results.list.length = 0 - }) - - var streamEnded = false - this.on("end", function () { - //console.error("global ending the stream") - if (!streamEnded) { - this.results.list.forEach(function (res) { - output.write(res) - }) - this.results.list.length = 0 - output.end() - streamEnded = true - } - }) - - //this.on("end", this.output.end.bind(this.output)) - - process.on("unhandledException", function (e) { - this.bailout("unhandled exception: " + e.message) - }) -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-harness.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-harness.js deleted file mode 100644 index 3c0eb8051..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-harness.js +++ /dev/null @@ -1,223 +0,0 @@ -// a thing that runs tests. -// Every "test" is also a harness. If they do not have a harness, -// then they are attached to the defaut "global harness", -// which writes its results to stdout. - - -// TODO: -// - Bailout should stop running any tests. -// - "skip" in the test config obj should skip it. - -module.exports = Harness -require("inherits")(Harness, require("events").EventEmitter) - -var Results = require("./tap-results") - , TapProducer = require("./tap-producer") - , assert = require("./tap-assert") - -function Harness (Test) { - if (!(this instanceof Harness)) return new Harness(Test) - - //console.error("Test in "+this.constructor.name, Test) - - this._Test = Test - this._plan = null - this._children = [] - this._started = false - - this._testCount = 0 - this._planSum = 0 - - this.results = new Results() - // emit result events on the harness. - //this.results.on("result", function (res) { - // console.error("proxying result ev from res to harness") - // this.emit("result", res) - //}.bind(this)) - var me = this - this.results.on("result", this.emit.bind(this, "result")) - - var p = this.process.bind(this) - this.process = function () { - this._started = true - process.nextTick(p) - } - - this.output = new TapProducer() - Harness.super.call(this) -} - -// this function actually only gets called bound to -// the Harness object, and on process.nextTick. Even if -// passed as an event handler, everything *else* will -// happen before it gets called. -Harness.prototype.process = function () { - //console.error("harness process") - // "end" can emit multiple times, so only actually move on - // to the next test if the current one is actually over. - // TODO: multiple in-process tests, if all are marked "async" - if (this._current) { - if (!this._current._ended) return - // handle the current one before moving onto the next. - this.childEnd(this._current) - } - var skip = true - while (skip) { - //console.error("checking for skips") - var current = this._current = this._children.shift() - if (current) { - skip = current.conf.skip - if (skip) { - //console.error("add a failure for the skipping") - this.results.add(assert.fail(current.conf.name - ,{skip:true, diag:false})) - } - } else skip = false - } - - // keep processing through skipped tests, instead of running them. - if (current && this._bailedOut) { - return this.process() - } - - //console.error("got current?", !!current) - if (current) { - current.on("end", this.process) - current.emit("ready") - //console.error("emitted ready") - //console.error("_plan", this._plan, this.constructor.name) - } else { - //console.error("Harness process: no more left. ending") - if (this._endNice) { - this._endNice() - } else { - this.end() - } - } -} - -Harness.prototype.end = function () { - if (this._children.length) { - return this.process() - } - //console.error("harness end", this.constructor.name) - if (this._bailedOut) return - - // can't call .end() more than once. - if (this._ended) { - //console.error("adding failure for end calling") - this.results.add(assert.fail("end called more than once")) - } - - // see if the plan is completed properly, if there was one. - if (this._plan !== null) { - var total = this._testCount - if (total !== this._plan) { - this.results.add(assert.equal(total, this._plan, "test count != plan")) - } - this._plan = total - } - - //console.error("setting ended true", this.constructor.name) - this._ended = true - this.emit("end") -} - -Harness.prototype.plan = function (p) { - //console.error("setting plan", new Error().stack) - if (this._plan !== null) { - //console.error("about to add failure for calling plan") - return this.results.add(assert.fail("plan set multiple times")) - } - this._plan = p - if (p === 0 || this.results.testsTotal) { - this.end() - } -} - -Harness.prototype.childEnd = function (child) { - //console.error("childEnd") - this._testCount ++ - this._planSum += child._plan - //console.error("adding set of child.results") - - this.results.add(child.conf.name || "(unnamed test)") - this.results.addSet(child.results) - this.emit("childEnd", child) - // was this planned? - if (this._plan === this._testCount) { - //console.error("plan", [this._plan, this._testCount]) - return this.end() - } -} - -function copyObj(o) { - var copied = {} - Object.keys(o).forEach(function (k) { copied[k] = o[k] }) - return copied -} - -Harness.prototype.test = function test (name, conf, cb) { - if (this._bailedOut) return - - if (typeof conf === "function") cb = conf, conf = null - if (typeof name === "object") conf = name, name = null - if (typeof name === "function") cb = name, name = null - - conf = (conf ? copyObj(conf) : {}) - name = name || "" - - //console.error("making test", [name, conf, cb]) - - // timeout: value in milliseconds. Defaults to 30s - // Set to Infinity to have no timeout. - if (isNaN(conf.timeout)) conf.timeout = 30000 - var t = new this._Test(this, name, conf) - var self = this - if (cb) { - //console.error("attaching cb to ready event") - t.on("ready", function () { - if (!isNaN(conf.timeout) && isFinite(conf.timeout)) { - var timer = setTimeout(this.timeout.bind(this), conf.timeout) - var clear = function () { - clearTimeout(timer) - } - t.on("end", clear) - t.on("bailout", function (message) { - self.bailout(message) - clear() - }) - } - }) - t.on("ready", cb.bind(t, t)) - // proxy the child results to this object. - //t.on("result", function (res) { - // console.error("in harness, proxying result up") - // t.results.add(res) - //}) - } - return t -} - -Harness.prototype.bailout = function (message) { - // console.error("Harness bailout", this.constructor.name) - message = message || "" - //console.error("adding bailout message result") - this.results.add({bailout: message}) - // console.error(">>> results after bailout" , this.results) - this._bailedOut = true - this.emit("bailout", message) - this.output.end({bailout: message}) -} - -Harness.prototype.add = function (child) { - //console.error("adding child") - this._children.push(child) - if (!this._started) this.process() -} - -// the tearDown function is *always* guaranteed to happen. -// Even if there's a bailout. -Harness.prototype.tearDown = function (fn) { - this.on("end", fn) -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-producer.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-producer.js deleted file mode 100644 index c6593a924..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-producer.js +++ /dev/null @@ -1,130 +0,0 @@ -module.exports = TapProducer - -var Results = require("./tap-results") - , inherits = require("inherits") - , yamlish = require("yamlish") - -TapProducer.encode = function (result, diag) { - var tp = new TapProducer(diag) - , out = "" - tp.on("data", function (c) { out += c }) - if (Array.isArray(result)) { - result.forEach(tp.write, tp) - } else tp.write(result) - tp.end() - return out -} - -inherits(TapProducer, require("stream").Stream) -function TapProducer (diag) { - TapProducer.super.call(this) - this.diag = diag - this.count = 0 - this.readable = this.writable = true - this.results = new Results -} - -TapProducer.prototype.trailer = true - -TapProducer.prototype.write = function (res) { - // console.error("TapProducer.write", res) - if (typeof res === "function") throw new Error("wtf?") - if (!this.writable) this.emit("error", new Error("not writable")) - - if (!this._didHead) { - this.emit("data", "TAP version 13\n") - this._didHead = true - } - - var diag = res.diag - if (diag === undefined) diag = this.diag - - this.emit("data", encodeResult(res, this.count + 1, diag)) - - if (typeof res === "string") return true - - if (res.bailout) { - var bo = "bail out!" - if (typeof res.bailout === "string") bo += " " + res.bailout - this.emit("data", bo) - return - } - this.results.add(res, false) - - this.count ++ -} - -TapProducer.prototype.end = function (res) { - if (res) this.write(res) - // console.error("TapProducer end", res, this.results) - this.emit("data", "\n1.."+this.results.testsTotal+"\n") - if (this.trailer && typeof this.trailer !== "string") { - // summary trailer. - var trailer = "tests "+this.results.testsTotal + "\n" - if (this.results.pass) { - trailer += "pass " + this.results.pass + "\n" - } - if (this.results.fail) { - trailer += "fail " + this.results.fail + "\n" - } - if (this.results.skip) { - trailer += "skip "+this.results.skip + "\n" - } - if (this.results.todo) { - trailer += "todo "+this.results.todo + "\n" - } - if (this.results.bailedOut) { - trailer += "bailed out" + "\n" - } - - if (this.results.testsTotal === this.results.pass) { - trailer += "\nok\n" - } - this.trailer = trailer - } - if (this.trailer) this.write(this.trailer) - this.writable = false - this.emit("end", null, this.count, this.ok) -} - -function encodeResult (res, count, diag) { - // console.error(res, count, diag) - if (typeof res === "string") { - res = res.split(/\r?\n/).map(function (l) { - if (!l.trim()) return l.trim() - return "# " + l - }).join("\n") - if (res.substr(-1) !== "\n") res += "\n" - return res - } - - if (res.bailout) return "" - - - if (!!process.env.TAP_NODIAG) diag = false - else if (!!process.env.TAP_DIAG) diag = true - else if (diag === undefined) diag = !res.ok - - var output = "" - res.name = res.name && ("" + res.name).trim() - output += ( !res.ok ? "not " : "") + "ok " + count - + ( !res.name ? "" - : " " + res.name.replace(/[\r\n]/g, " ") ) - + ( res.skip ? " # SKIP" - : res.todo ? " # TODO" - : "" ) - + "\n" - - if (!diag) return output - var d = {} - , dc = 0 - Object.keys(res).filter(function (k) { - return k !== "ok" && k !== "name" && k !== "id" - }).forEach(function (k) { - dc ++ - d[k] = res[k] - }) - //console.error(d, "about to encode") - if (dc > 0) output += " ---"+yamlish.encode(d)+"\n ...\n" - return output -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-results.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-results.js deleted file mode 100644 index 6fe90e8d5..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-results.js +++ /dev/null @@ -1,71 +0,0 @@ -// A class for counting up results in a test harness. - -module.exports = Results - -var inherits = require("inherits") - , EventEmitter = require("events").EventEmitter - -inherits(Results, EventEmitter) - -function Results (r) { - //console.error("result constructor", r) - this.ok = true - this.addSet(r) -} - -Results.prototype.addSet = function (r) { - //console.error("add set of results", r) - r = r || {ok: true} - ; [ "todo" - , "todoPass" - , "todoFail" - , "skip" - , "skipPass" - , "skipFail" - , "pass" - , "passTotal" - , "fail" - , "failTotal" - , "tests" - , "testsTotal" ].forEach(function (k) { - this[k] = (this[k] || 0) + (r[k] || 0) - //console.error([k, this[k]]) - }, this) - - this.ok = this.ok && r.ok && true - this.bailedOut = this.bailedOut || r.bailedOut || false - this.list = (this.list || []).concat(r.list || []) - this.emit("set", this.list) - //console.error("after addSet", this) -} - -Results.prototype.add = function (r, addToList) { - //console.error("add result", r) - var pf = r.ok ? "pass" : "fail" - , PF = r.ok ? "Pass" : "Fail" - - this.testsTotal ++ - this[pf + "Total"] ++ - - if (r.skip) { - this["skip" + PF] ++ - this.skip ++ - } else if (r.todo) { - this["todo" + PF] ++ - this.todo ++ - } else { - this.tests ++ - this[pf] ++ - } - - if (r.bailout || typeof r.bailout === "string") { - // console.error("Bailing out in result") - this.bailedOut = true - } - this.ok = !!(this.ok && r.ok) - - if (addToList === false) return - this.list = this.list || [] - this.list.push(r) - this.emit("result", r) -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-runner.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-runner.js deleted file mode 100644 index c25c90a0a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-runner.js +++ /dev/null @@ -1,474 +0,0 @@ -var fs = require("fs") - , child_process = require("child_process") - , path = require("path") - , chain = require("slide").chain - , asyncMap = require("slide").asyncMap - , TapProducer = require("./tap-producer.js") - , TapConsumer = require("./tap-consumer.js") - , assert = require("./tap-assert.js") - , inherits = require("inherits") - , util = require("util") - , CovHtml = require("./tap-cov-html.js") - , glob = require("glob") - - // XXX Clean up the coverage options - , doCoverage = process.env.TAP_COV - || process.env.npm_package_config_coverage - || process.env.npm_config_coverage - -module.exports = Runner - -inherits(Runner, TapProducer) - -function Runner (options, cb) { - this.options = options - - var diag = this.options.diag - var dir = this.options.argv.remain - Runner.super.call(this, diag) - - this.doCoverage = doCoverage - // An array of full paths to files to obtain coverage - this.coverageFiles = [] - // The source of these files - this.coverageFilesSource = {} - // Where to write coverage information - this.coverageOutDir = this.options["coverage-dir"] - // Temporary test files bunkerified we'll remove later - this.f2delete = [] - // Raw coverage stats, as read from JSON files - this.rawCovStats = [] - // Processed coverage information, per file to cover: - this.covStats = {} - - if (dir) { - var filesToCover = this.options.cover - - if (doCoverage) { - var mkdirp = require("mkdirp") - this.coverageOutDir = path.resolve(this.coverageOutDir) - this.getFilesToCover(filesToCover) - var self = this - return mkdirp(this.coverageOutDir, 0755, function (er) { - if (er) return self.emit("error", er) - self.run(dir, cb) - }) - } - - this.run(dir, cb) - } -} - - -Runner.prototype.run = function() { - var self = this - , args = Array.prototype.slice.call(arguments) - , cb = args.pop() || finish - - function finish (er) { - if (er) { - self.emit("error", er) - } - - if (!doCoverage) return self.end() - - // Cleanup temporary test files with coverage: - self.f2delete.forEach(function(f) { - fs.unlinkSync(f) - }) - self.getFilesToCoverSource(function(err, data) { - if (err) { - self.emit("error", err) - } - self.getPerFileCovInfo(function(err, data) { - if (err) { - self.emit("error", err) - } - self.mergeCovStats(function(err, data) { - if (err) { - self.emit("error", err) - } - CovHtml(self.covStats, self.coverageOutDir, function() { - self.end() - }) - }) - }) - }) - } - - if (Array.isArray(args[0])) { - args = args[0] - } - self.runFiles(args, "", cb) -} - -Runner.prototype.runDir = function (dir, cb) { - var self = this - fs.readdir(dir, function (er, files) { - if (er) { - self.write(assert.fail("failed to readdir " + dir, { error: er })) - self.end() - return - } - files = files.sort(function(a, b) { - return a > b ? 1 : -1 - }) - files = files.filter(function(f) { - return !f.match(/^\./) - }) - files = files.map(function(file) { - return path.resolve(dir, file) - }) - - self.runFiles(files, path.resolve(dir), cb) - }) -} - - -// glob the filenames so that test/*.js works on windows -Runner.prototype.runFiles = function (files, dir, cb) { - var self = this - var globRes = [] - chain(files.map(function (f) { - return function (cb) { - glob(f, function (er, files) { - if (er) - return cb(er) - globRes.push.apply(globRes, files) - cb() - }) - } - }), function (er) { - if (er) - return cb(er) - runFiles(self, globRes, dir, cb) - }) -} - -function runFiles(self, files, dir, cb) { - chain(files.map(function(f) { - return function (cb) { - if (self._bailedOut) return - var relDir = dir || path.dirname(f) - , fileName = relDir === "." ? f : f.substr(relDir.length + 1) - - self.write(fileName) - fs.lstat(f, function(er, st) { - if (er) { - self.write(assert.fail("failed to stat " + f, {error: er})) - return cb() - } - - var cmd = f, args = [], env = {} - - if (path.extname(f) === ".js") { - cmd = "node" - if (self.options.gc) { - args.push("--expose-gc") - } - args.push(fileName) - } else if (path.extname(f) === ".coffee") { - cmd = "coffee" - args.push(fileName) - } else { - // Check if file is executable - if ((st.mode & 0100) && process.getuid) { - if (process.getuid() != st.uid) { - return cb() - } - } else if ((st.mode & 0010) && process.getgid) { - if (process.getgid() != st.gid) { - return cb() - } - } else if ((st.mode & 0001) == 0) { - return cb() - } - } - - if (st.isDirectory()) { - return self.runDir(f, cb) - } - - if (doCoverage && path.extname(f) === ".js") { - var foriginal = fs.readFileSync(f, "utf8") - , fcontents = self.coverHeader() + foriginal + self.coverFooter() - , tmpBaseName = path.basename(f, path.extname(f)) - + ".with-coverage." + process.pid + path.extname(f) - , tmpFname = path.resolve(path.dirname(f), tmpBaseName) - - fs.writeFileSync(tmpFname, fcontents, "utf8") - args.splice(-1, 1, tmpFname) - } - - for (var i in process.env) { - env[i] = process.env[i] - } - env.TAP = 1 - - var cp = child_process.spawn(cmd, args, { env: env, cwd: relDir }) - , out = "" - , err = "" - , tc = new TapConsumer() - , childTests = [f] - - var timeout = setTimeout(function () { - if (!cp._ended) { - cp._timedOut = true - cp.kill() - } - }, self.options.timeout * 1000) - - tc.on("data", function(c) { - self.emit("result", c) - self.write(c) - }) - - tc.on("bailout", function (message) { - clearTimeout(timeout) - console.log("# " + f.substr(process.cwd().length + 1)) - process.stderr.write(err) - process.stdout.write(out + "\n") - self._bailedOut = true - cp._ended = true - cp.kill() - }) - - cp.stdout.pipe(tc) - cp.stdout.on("data", function (c) { out += c }) - cp.stderr.on("data", function (c) { - if (self.options.stderr) process.stderr.write(c) - err += c - }) - - cp.on("close", function (code, signal) { - if (cp._ended) return - cp._ended = true - var ok = !cp._timedOut && code === 0 - clearTimeout(timeout) - //childTests.forEach(function (c) { self.write(c) }) - var res = { name: path.dirname(f).replace(process.cwd() + "/", "") - + "/" + fileName - , ok: ok - , exit: code } - - if (cp._timedOut) - res.timedOut = cp._timedOut - if (signal) - res.signal = signal - - if (err) { - res.stderr = err - if (tc.results.ok && - tc.results.tests === 0 && - !self.options.stderr) { - // perhaps a compilation error or something else failed. - // no need if stderr is set, since it will have been - // output already anyway. - console.error(err) - } - } - - // tc.results.ok = tc.results.ok && ok - tc.results.add(res) - res.command = [cmd].concat(args).map(JSON.stringify).join(" ") - self.emit("result", res) - self.emit("file", f, res, tc.results) - self.write(res) - self.write("\n") - if (doCoverage) { - self.f2delete.push(tmpFname) - } - cb() - }) - }) - } - }), cb) - - return self -} - - -// Get an array of full paths to files we are interested into obtain -// code coverage. -Runner.prototype.getFilesToCover = function(filesToCover) { - var self = this - filesToCover = filesToCover.split(",").map(function(f) { - return path.resolve(f) - }).filter(function(f) { - return path.existsSync(f) - }) - - function recursive(f) { - if (path.extname(f) === "") { - // Is a directory: - fs.readdirSync(f).forEach(function(p) { - recursive(f + "/" + p) - }) - } else { - self.coverageFiles.push(f) - } - } - filesToCover.forEach(function(f) { - recursive(f) - }) -} - -// Prepend to every test file to run. Note tap.test at the very top due it -// "plays" with include paths. -Runner.prototype.coverHeader = function() { - // semi here since we're injecting it before the first line, - // and don't want to mess up line numbers in the test files. - return "var ___TAP_COVERAGE = require(" - + JSON.stringify(require.resolve("runforcover")) - + ").cover(/.*/g);" -} - -// Append at the end of every test file to run. Actually, the stuff which gets -// the coverage information. -// Maybe it would be better to move into a separate file template so editing -// could be easier. -Runner.prototype.coverFooter = function() { - var self = this - // This needs to be a string with proper interpolations: - return [ "" - , "var ___TAP = require(" + JSON.stringify(require.resolve("./main.js")) + ")" - , "if (typeof ___TAP._plan === 'number') ___TAP._plan ++" - , "___TAP.test(" + JSON.stringify("___coverage") + ", function(t) {" - , " var covFiles = " + JSON.stringify(self.coverageFiles) - , " , covDir = " + JSON.stringify(self.coverageOutDir) - , " , path = require('path')" - , " , fs = require('fs')" - , " , testFnBase = path.basename(__filename, '.js') + '.json'" - , " , testFn = path.resolve(covDir, testFnBase)" - , "" - , " function asyncForEach(arr, fn, callback) {" - , " if (!arr.length) {" - , " return callback()" - , " }" - , " var completed = 0" - , " arr.forEach(function(i) {" - , " fn(i, function (err) {" - , " if (err) {" - , " callback(err)" - , " callback = function () {}" - , " } else {" - , " completed += 1" - , " if (completed === arr.length) {" - , " callback()" - , " }" - , " }" - , " })" - , " })" - , " }" - , "" - , " ___TAP_COVERAGE(function(coverageData) {" - , " var outObj = {}" - , " asyncForEach(covFiles, function(f, cb) {" - , " if (coverageData[f]) {" - , " var stats = coverageData[f].stats()" - , " , stObj = stats" - , " stObj.lines = stats.lines.map(function (l) {" - , " return { number: l.lineno, source: l.source() }" - , " })" - , " outObj[f] = stObj" - , " }" - , " cb()" - , " }, function(err) {" - , " ___TAP_COVERAGE.release()" - , " fs.writeFileSync(testFn, JSON.stringify(outObj))" - , " t.end()" - , " })" - , " })" - , "})" ].join("\n") -} - - -Runner.prototype.getFilesToCoverSource = function(cb) { - var self = this - asyncMap(self.coverageFiles, function(f, cb) { - fs.readFile(f, "utf8", function(err, data) { - var lc = 0 - if (err) { - cb(err) - } - self.coverageFilesSource[f] = data.split("\n").map(function(l) { - lc += 1 - return { number: lc, source: l } - }) - cb() - }) - }, cb) -} - -Runner.prototype.getPerFileCovInfo = function(cb) { - var self = this - , covPath = path.resolve(self.coverageOutDir) - - fs.readdir(covPath, function(err, files) { - if (err) { - self.emit("error", err) - } - var covFiles = files.filter(function(f) { - return path.extname(f) === ".json" - }) - asyncMap(covFiles, function(f, cb) { - fs.readFile(path.resolve(covPath, f), "utf8", function(err, data) { - if (err) { - cb(err) - } - self.rawCovStats.push(JSON.parse(data)) - cb() - }) - }, function(f, cb) { - fs.unlink(path.resolve(covPath, f), cb) - }, cb) - }) -} - -Runner.prototype.mergeCovStats = function(cb) { - var self = this - self.rawCovStats.forEach(function(st) { - Object.keys(st).forEach(function(i) { - // If this is the first time we reach this file, just add the info: - if (!self.covStats[i]) { - self.covStats[i] = { - missing: st[i].lines - } - } else { - // If we already added info for this file before, we need to remove - // from self.covStats any line not duplicated again (since it has - // run on such case) - self.covStats[i].missing = self.covStats[i].missing.filter( - function(l) { - return (st[i].lines.indexOf(l)) - }) - } - }) - }) - - // This is due to a bug into - // chrisdickinson/node-bunker/blob/feature/add-coverage-interface - // which is using array indexes for line numbers instead of the right number - Object.keys(self.covStats).forEach(function(f) { - self.covStats[f].missing = self.covStats[f].missing.map(function(line) { - return { number: line.number, source: line.source } - }) - }) - - Object.keys(self.coverageFilesSource).forEach(function(f) { - if (!self.covStats[f]) { - self.covStats[f] = { missing: self.coverageFilesSource[f] - , percentage: 0 - } - } - self.covStats[f].lines = self.coverageFilesSource[f] - self.covStats[f].loc = self.coverageFilesSource[f].length - - if (!self.covStats[f].percentage) { - self.covStats[f].percentage = - 1 - (self.covStats[f].missing.length / self.covStats[f].loc) - } - - }) - cb() -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-test.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-test.js deleted file mode 100644 index 15ae8fb81..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/lib/tap-test.js +++ /dev/null @@ -1,109 +0,0 @@ -// This is a very simple test framework that leverages the tap framework -// to run tests and output tap-parseable results. - -module.exports = Test - -var assert = require("./tap-assert") - , inherits = require("inherits") - , Results = require("./tap-results") - -// tests are also test harnesses -inherits(Test, require("./tap-harness")) - -function Test (harness, name, conf) { - //console.error("test ctor") - if (!(this instanceof Test)) return new Test(harness, name, conf) - - Test.super.call(this, Test) - - conf.name = name || conf.name || "(anonymous)" - this.conf = conf - - this.harness = harness - this.harness.add(this) -} - -// it's taking too long! -Test.prototype.timeout = function () { - // detect false alarms - if (this._ended) return - this.fail("Timeout!") - this.end() -} - -Test.prototype.clear = function () { - this._started = false - this._ended = false - this._plan = null - this._bailedOut = false - this._testCount = 0 - this.results = new Results() -} - -// this gets called if a test throws ever -Test.prototype.threw = function (ex) { - //console.error("threw!", ex.stack) - this.fail(ex.name + ": " + ex.message, { error: ex, thrown: true }) - // may emit further failing tests if the plan is not completed - //console.error("end, because it threw") - if (!this._ended) this.end() -} - -Test.prototype.comment = function (m) { - if (typeof m !== "string") { - return this.fail("Test.comment argument must be a string") - } - this.result("\n" + m.trim()) -} - -Test.prototype.result = function (res) { - this.results.add(res) - this._testCount ++ - this.emit("result", res) - if (this._plan === this._testCount) { - process.nextTick(this._endNice.bind(this)) - } -} - -Test.prototype._endNice = function () { - if (!this._ended) this.end() -} - -// parasitic -// Who says you can't do multiple inheritance in js? -Object.getOwnPropertyNames(assert).forEach(function (k) { - if (k === "prototype" || k === "name") return - var d = Object.getOwnPropertyDescriptor(assert, k) - , v = d.value - if (!v) return - d.value = assertParasite(v) - Object.defineProperty(Test.prototype, k, d) -}) - -function assertParasite (fn) { return function _testAssert () { - //console.error("_testAssert", fn.name, arguments) - if (this._bailedOut) return - var res = fn.apply(assert, arguments) - this.result(res) - return res -}} - -// a few tweaks on the EE emit function, because -// we want to catch all thrown errors and bubble up "bailout" -Test.prototype.emit = (function (em) { return function (t) { - // bailouts bubble until handled - if (t === "bailout" && - this.listeners(t).length === 0 && - this.harness) { - return this.harness.bailout(arguments[1]) - } - - if (t === "error") return em.apply(this, arguments) - try { - em.apply(this, arguments) - } catch (ex) { - // any exceptions in a test are a failure - //console.error("caught!", ex.stack) - this.threw(ex) - } -}})(Test.super.prototype.emit) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/.travis.yml b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/.travis.yml deleted file mode 100644 index f1d0f13c8..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/README.markdown b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/README.markdown deleted file mode 100644 index 571938a58..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/README.markdown +++ /dev/null @@ -1,62 +0,0 @@ -buffer-equal -============ - -Return whether two buffers are equal. - -[![build status](https://secure.travis-ci.org/substack/node-buffer-equal.png)](http://travis-ci.org/substack/node-buffer-equal) - -example -======= - -``` js -var bufferEqual = require('bufferEqual'); - -console.dir(bufferEqual( - new Buffer([253,254,255]), - new Buffer([253,254,255]) -)); -console.dir(bufferEqual( - new Buffer('abc'), - new Buffer('abcd') -)); -console.dir(bufferEqual( - new Buffer('abc'), - 'abc' -)); -``` - -output: - -``` -true -false -undefined -``` - -methods -======= - -``` js -var bufferEqual = require('buffer-equal') -``` - -bufferEqual(a, b) ------------------ - -Return whether the two buffers `a` and `b` are equal. - -If `a` or `b` is not a buffer, return `undefined`. - -install -======= - -With [npm](http://npmjs.org) do: - -``` -npm install buffer-equal -``` - -license -======= - -MIT diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/example/eq.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/example/eq.js deleted file mode 100644 index 1eb05095a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/example/eq.js +++ /dev/null @@ -1,14 +0,0 @@ -var bufferEqual = require('../'); - -console.dir(bufferEqual( - new Buffer([253,254,255]), - new Buffer([253,254,255]) -)); -console.dir(bufferEqual( - new Buffer('abc'), - new Buffer('abcd') -)); -console.dir(bufferEqual( - new Buffer('abc'), - 'abc' -)); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/index.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/index.js deleted file mode 100644 index 35a73c32b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/index.js +++ /dev/null @@ -1,13 +0,0 @@ -var Buffer = require('buffer').Buffer; // for use with browserify - -module.exports = function (a, b) { - if (!Buffer.isBuffer(a)) return undefined; - if (!Buffer.isBuffer(b)) return undefined; - if (a.length !== b.length) return false; - - for (var i = 0; i < a.length; i++) { - if (a[i] !== b[i]) return false; - } - - return true; -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/package.json deleted file mode 100644 index 9f7580826..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "buffer-equal", - "description": "return whether two buffers are equal", - "version": "0.0.0", - "repository": { - "type": "git", - "url": "git://github.com/substack/node-buffer-equal.git" - }, - "main": "index.js", - "keywords": [ - "buffer", - "equal" - ], - "directories": { - "example": "example", - "test": "test" - }, - "scripts": { - "test": "tap test/*.js" - }, - "devDependencies": { - "tap": "~0.2.4" - }, - "engines": { - "node": ">=0.4.0" - }, - "license": "MIT", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "readme": "buffer-equal\n============\n\nReturn whether two buffers are equal.\n\n[![build status](https://secure.travis-ci.org/substack/node-buffer-equal.png)](http://travis-ci.org/substack/node-buffer-equal)\n\nexample\n=======\n\n``` js\nvar bufferEqual = require('bufferEqual');\n\nconsole.dir(bufferEqual(\n new Buffer([253,254,255]),\n new Buffer([253,254,255])\n));\nconsole.dir(bufferEqual(\n new Buffer('abc'),\n new Buffer('abcd')\n));\nconsole.dir(bufferEqual(\n new Buffer('abc'),\n 'abc'\n));\n```\n\noutput:\n\n```\ntrue\nfalse\nundefined\n```\n\nmethods\n=======\n\n``` js\nvar bufferEqual = require('buffer-equal')\n```\n\nbufferEqual(a, b)\n-----------------\n\nReturn whether the two buffers `a` and `b` are equal.\n\nIf `a` or `b` is not a buffer, return `undefined`.\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install buffer-equal\n```\n\nlicense\n=======\n\nMIT\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/substack/node-buffer-equal/issues" - }, - "_id": "buffer-equal@0.0.0", - "_from": "buffer-equal@~0.0.0" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/test/eq.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/test/eq.js deleted file mode 100644 index 3d3400623..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/buffer-equal/test/eq.js +++ /dev/null @@ -1,35 +0,0 @@ -var bufferEqual = require('../'); -var test = require('tap').test; - -test('equal', function (t) { - var eq = bufferEqual( - new Buffer([253,254,255]), - new Buffer([253,254,255]) - ); - t.strictEqual(eq, true); - t.end(); -}); - -test('not equal', function (t) { - var eq = bufferEqual( - new Buffer('abc'), - new Buffer('abcd') - ); - t.strictEqual(eq, false); - t.end(); -}); - -test('not equal not buffer', function (t) { - var eq = bufferEqual( - new Buffer('abc'), - 'abc' - ); - t.strictEqual(eq, undefined); - t.end(); -}); - -test('equal not buffer', function (t) { - var eq = bufferEqual('abc', 'abc'); - t.strictEqual(eq, undefined); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/README.markdown b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/README.markdown deleted file mode 100644 index c3293d365..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/README.markdown +++ /dev/null @@ -1,55 +0,0 @@ -deep-equal -========== - -Node's `assert.deepEqual() algorithm` as a standalone module. - -example -======= - -``` js -var equal = require('deep-equal'); -console.dir([ - equal( - { a : [ 2, 3 ], b : [ 4 ] }, - { a : [ 2, 3 ], b : [ 4 ] } - ), - equal( - { x : 5, y : [6] }, - { x : 5, y : 6 } - ) -]); -``` - -methods -======= - -var deepEqual = require('deep-equal') - -deepEqual(a, b) ---------------- - -Compare objects `a` and `b`, returning whether they are equal according to a -recursive equality algorithm. - -install -======= - -With [npm](http://npmjs.org) do: - -``` -npm install deep-equal -``` - -test -==== - -With [npm](http://npmjs.org) do: - -``` -npm test -``` - -license -======= - -MIT. Derived largely from node's assert module. diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/example/cmp.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/example/cmp.js deleted file mode 100644 index 67014b88d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/example/cmp.js +++ /dev/null @@ -1,11 +0,0 @@ -var equal = require('../'); -console.dir([ - equal( - { a : [ 2, 3 ], b : [ 4 ] }, - { a : [ 2, 3 ], b : [ 4 ] } - ), - equal( - { x : 5, y : [6] }, - { x : 5, y : 6 } - ) -]); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/index.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/index.js deleted file mode 100644 index e4e37beb6..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/index.js +++ /dev/null @@ -1,84 +0,0 @@ -var pSlice = Array.prototype.slice; -var Object_keys = typeof Object.keys === 'function' - ? Object.keys - : function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; - } -; - -var deepEqual = module.exports = function (actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - - } else if (actual instanceof Date && expected instanceof Date) { - return actual.getTime() === expected.getTime(); - - // 7.3. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { - return actual == expected; - - // 7.4. 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 isUndefinedOrNull(value) { - return value === null || value === undefined; -} - -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(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 = 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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/package.json deleted file mode 100644 index 755b1a19a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "deep-equal", - "version": "0.0.0", - "description": "node's assert.deepEqual algorithm", - "main": "index.js", - "directories": { - "lib": ".", - "example": "example", - "test": "test" - }, - "scripts": { - "test": "tap test/*.js" - }, - "devDependencies": { - "tap": "0.0.x" - }, - "repository": { - "type": "git", - "url": "http://github.com/substack/node-deep-equal.git" - }, - "keywords": [ - "equality", - "equal", - "compare" - ], - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "license": "MIT/X11", - "engine": { - "node": ">=0.4" - }, - "readme": "deep-equal\n==========\n\nNode's `assert.deepEqual() algorithm` as a standalone module.\n\nexample\n=======\n\n``` js\nvar equal = require('deep-equal');\nconsole.dir([\n equal(\n { a : [ 2, 3 ], b : [ 4 ] },\n { a : [ 2, 3 ], b : [ 4 ] }\n ),\n equal(\n { x : 5, y : [6] },\n { x : 5, y : 6 }\n )\n]);\n```\n\nmethods\n=======\n\nvar deepEqual = require('deep-equal')\n\ndeepEqual(a, b)\n---------------\n\nCompare objects `a` and `b`, returning whether they are equal according to a\nrecursive equality algorithm.\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install deep-equal\n```\n\ntest\n====\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm test\n```\n\nlicense\n=======\n\nMIT. Derived largely from node's assert module.\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/substack/node-deep-equal/issues" - }, - "_id": "deep-equal@0.0.0", - "_from": "deep-equal@~0.0.0" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/test/cmp.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/test/cmp.js deleted file mode 100644 index 8418f0f89..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/deep-equal/test/cmp.js +++ /dev/null @@ -1,18 +0,0 @@ -var test = require('tap').test; -var equal = require('../'); - -test('equal', function (t) { - t.ok(equal( - { a : [ 2, 3 ], b : [ 4 ] }, - { a : [ 2, 3 ], b : [ 4 ] } - )); - t.end(); -}); - -test('not equal', function (t) { - t.notOk(equal( - { x : 5, y : [6] }, - { x : 5, y : 6 } - )); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/.travis.yml b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/.travis.yml deleted file mode 100644 index f1d0f13c8..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/README.markdown b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/README.markdown deleted file mode 100644 index 9ad43031d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/README.markdown +++ /dev/null @@ -1,116 +0,0 @@ -difflet -======= - -Create colorful diffs for javascript objects. - -example -======= - -string.js ---------- - -``` js -var difflet = require('difflet'); - -var s = difflet.compare({ a : 2, c : 5 }, { a : 3, b : 4 }); -process.stdout.write(s); -``` - -output: - -![colorful output](http://substack.net/images/screenshots/difflet_string.png) - -colors.js ---------- - -``` js -var diff = require('difflet')({ indent : 2 }); - -var prev = { - yy : 6, - zz : 5, - a : [1,2,3], - fn : 'beep', - c : { x : 7, z : 3 } -}; - -var next = { - a : [ 1, 2, "z", /beep/, new Buffer(3) ], - fn : function qqq () {}, - b : [5,6,7], - c : { x : 8, y : 5 } -}; - -diff(prev, next).pipe(process.stdout); -``` - -output: - -![colorful output](http://substack.net/images/screenshots/difflet_colors.png) - -green for inserts, blue for updates, red for deletes - -methods -======= - -var difflet = require('difflet') - -var diff = difflet(opts={}) ---------------------------- - -Create a difflet from optional options `opts`. - -With `opts.start(type, stream)` and `opts.stop(type, stream)`, -you can write custom handlers for all the types of differences: -`'inserted'`, `'updated'`, and `'deleted'`. -By default green is used for insertions, blue for updates, and red for -deletions. - -If `opts.indent` is set, output will span multiple lines and `opts.indent` -spaces will be used for leading whitespace. - -If `opts.comma === 'first'` then commas will be placed at the start of lines. - -Setting `opts.comment` to `true` will turn on comments with the previous -contents like this: - -![object comments](http://substack.net/images/screenshots/difflet_object_comments.png) - -diff(prev, next) ----------------- - -Return a stream with the colorful changes between objects `prev` and `next`. - -diff.compare(prev, next) ------------------------- - -Return a string with the colorful changes between `prev` and `next`. - -difflet.compare(prev, next) ---------------------------- - -Return a string with the colorful changes between `prev` and `next` with the -default options. - -install -======= - -With [npm](http://npmjs.org) do: - -``` -npm install difflet -``` - -test -==== - -With [npm](http://npmjs.org) do: - -``` -npm test -``` - -license -======= - -MIT/X11 diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/cmp_array.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/cmp_array.js deleted file mode 100644 index bc5733fa9..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/cmp_array.js +++ /dev/null @@ -1,6 +0,0 @@ -var difflet = require('../'); -var s = difflet({ indent : 2, comment : true }).compare( - [ 1, [2,3,{a:4}], 3 ], - [ 1, [[5],6,7], 4 ] -); -process.stdout.write(s); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/cmp_object.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/cmp_object.js deleted file mode 100644 index 5e00e2c03..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/cmp_object.js +++ /dev/null @@ -1,6 +0,0 @@ -var difflet = require('../'); -var s = difflet({ indent : 2, comment : true }).compare( - { z : [6,7], a : 'abcdefgh', b : [ 31, 'xxt' ] }, - { x : 5, a : 'abdcefg', b : [ 51, 'xxs' ] } -); -console.log(s); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/colors.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/colors.js deleted file mode 100644 index 332bbae3f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/colors.js +++ /dev/null @@ -1,18 +0,0 @@ -var diff = require('../')({ indent : 2 }); - -var prev = { - yy : 6, - zz : 5, - a : [1,2,3], - fn : 'beep', - c : { x : 7, z : 3 } -}; - -var next = { - a : [ 1, 2, "z", /beep/, new Buffer(3) ], - fn : function qqq () {}, - b : [5,6,7], - c : { x : 8, y : 5 } -}; - -diff(prev, next).pipe(process.stdout); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/comma_first.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/comma_first.js deleted file mode 100644 index 67ece2349..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/comma_first.js +++ /dev/null @@ -1,12 +0,0 @@ -var diff = require('../')({ - indent : 2, - comma : 'first', -}); - -var prev = { yy : 6, zz : 5, a : [1,2,3] }; -var next = { - a : [ 1, 2, 3, [4], "z", /beep/, new Buffer(3) ], - fn : 8, - b : [5,6,7] -}; -diff(prev, next).pipe(process.stdout); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/diff.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/diff.js deleted file mode 100644 index 08f6e7ae9..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/diff.js +++ /dev/null @@ -1,15 +0,0 @@ -var difflet = require('../'); -var a = { - x : 4, - z : 8, - xs : [ 5, 2, 1, { 0 : 'c' } ], -}; - -var b = { - x : 4, - y : 5, - xs : [ 5, 2, 2, { c : 5 } ], -}; - -var s = difflet({ comment : true, indent : 2 }).compare(a, b); -console.log(s); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/html.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/html.js deleted file mode 100644 index 9ff4a293c..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/html.js +++ /dev/null @@ -1,34 +0,0 @@ -var difflet = require('../'); -var ent = require('ent'); - -var tags = { - inserted : '', - updated : '', - deleted : '', -}; -var diff = difflet({ - start : function (t, s) { - s.write(tags[t]); - }, - stop : function (t, s) { - s.write(''); - }, - write : function (buf) { - stream.write(ent.encode(buf)) - }, -}); - -var prev = { - yy : 6, - zz : 5, - a : [1,2,3], - fn : function qq () {} -}; -var next = { - a : [ 1, 2, 3, [4], "z", /beep/, new Buffer([0,1,2]) ], - fn : 'I <3 robots', - b : [5,6,7] -}; - -var stream = diff(prev, next); -stream.pipe(process.stdout, { end : false }); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/string.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/string.js deleted file mode 100644 index 6cff6cb44..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/example/string.js +++ /dev/null @@ -1,4 +0,0 @@ -var difflet = require('../'); - -var s = difflet.compare({ a : 2, c : 5 }, { a : 3, b : 4 }); -process.stdout.write(s); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/index.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/index.js deleted file mode 100644 index 278e6b951..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/index.js +++ /dev/null @@ -1,377 +0,0 @@ -var traverse = require('traverse'); -var Stream = require('stream').Stream; -var charm = require('charm'); -var deepEqual = require('deep-is'); - -var exports = module.exports = function (opts_) { - var fn = difflet.bind(null, opts_); - fn.compare = function (prev, next) { - var opts = Object.keys(opts_ || {}).reduce(function (acc, key) { - acc[key] = opts_[key]; - return acc; - }, {}); - var s = opts.stream = new Stream; - var data = ''; - s.write = function (buf) { data += buf }; - s.end = function () {}; - s.readable = true; - s.writable = true; - - difflet(opts, prev, next); - return data; - }; - return fn; -}; - -exports.compare = function (prev, next) { - return exports({}).compare(prev, next); -}; - -function difflet (opts, prev, next) { - var stream = opts.stream || new Stream; - if (!opts.stream) { - stream.readable = true; - stream.writable = true; - stream.write = function (buf) { this.emit('data', buf) }; - stream.end = function () { this.emit('end') }; - } - - if (!opts) opts = {}; - if (opts.start === undefined && opts.stop === undefined) { - var c = charm(stream); - opts.start = function (type) { - c.foreground({ - inserted : 'green', - updated : 'blue', - deleted : 'red', - comment : 'cyan', - }[type]); - c.display('bright'); - }; - opts.stop = function (type) { - c.display('reset'); - }; - } - var write = function (buf) { - if (opts.write) opts.write(buf, stream) - else stream.write(buf) - }; - - var commaFirst = opts.comma === 'first'; - - var stringify = function (node, params) { - return stringifier.call(this, true, node, params || opts); - }; - var plainStringify = function (node, params) { - return stringifier.call(this, false, node, params || opts); - }; - - var levels = 0; - function set (type) { - if (levels === 0) opts.start(type, stream); - levels ++; - } - - function unset (type) { - if (--levels === 0) opts.stop(type, stream); - } - - function stringifier (insertable, node, opts) { - var indent = opts.indent; - - if (insertable) { - var prevNode = traverse.get(prev, this.path || []); - } - var inserted = insertable && prevNode === undefined; - - var indentx; - try { - indentx = indent ? Array( - ((this.path || []).length + 1) * indent + 1 - ).join(' ') : ''; - } catch (e) { - // at times we get an invalid Array size here and need to prevent crashing - indentx = ''; - } - if (commaFirst) indentx = indentx.slice(indent); - - if (Array.isArray(node)) { - var updated = (prevNode || traverse.has(prev, this.path)) - && !Array.isArray(prevNode); - if (updated) { - set('updated'); - } - - if (opts.comment && !Array.isArray(prevNode)) { - indent = 0; - } - - this.before(function () { - if (inserted) set('inserted'); - if (indent && commaFirst) { - if ((this.path || []).length === 0 - || Array.isArray(this.parent.node)) { - write('[ '); - } - else write('\n' + indentx + '[ '); - } - else if (indent) { - write('[\n' + indentx); - } - else { - write('['); - } - }); - - this.post(function (child) { - if (!child.isLast && !(indent && commaFirst)) { - write(','); - } - - var prev = prevNode && prevNode[child.key]; - if (indent && opts.comment && child.node !== prev - && (typeof child.node !== 'object' || typeof prev !== 'object') - ) { - set('comment'); - write(' // != '); - traverse(prev).forEach(function (x) { - plainStringify.call(this, x, { indent : 0 }); - }); - unset('comment'); - } - - if (!child.isLast) { - if (indent && commaFirst) { - write('\n' + indentx + ', '); - } - else if (indent) { - write('\n' + indentx); - } - } - }); - - this.after(function () { - if (indent && commaFirst) write('\n' + indentx); - else if (indent) write('\n' + indentx.slice(indent)); - - write(']'); - if (updated) unset('updated'); - if (inserted) unset('inserted'); - }); - } - else if (isRegExp(node)) { - this.block(); - - if (inserted) { - set('inserted'); - write(node.toString()); - unset('inserted'); - } - else if (insertable && prevNode !== node) { - set('updated'); - write(node.toString()); - unset('updated'); - } - else write(node.toString()); - } - else if (typeof node === 'object' - && node && typeof node.inspect === 'function') { - this.block(); - if (inserted) { - set('inserted'); - write(node.inspect()); - unset('inserted'); - } - else if (!(prevNode && typeof prevNode.inspect === 'function' - && prevNode.inspect() === node.inspect())) { - set('updated'); - write(node.inspect()); - unset('updated'); - } - else write(node.inspect()); - } - else if (typeof node == 'object' && node !== null) { - var insertedKey = false; - var deleted = insertable && typeof prevNode === 'object' && prevNode - ? Object.keys(prevNode).filter(function (key) { - return !Object.hasOwnProperty.call(node, key); - }) - : [] - ; - - this.before(function () { - if (inserted) set('inserted'); - write(indent && commaFirst && !this.isRoot - ? '\n' + indentx + '{ ' - : '{' - ); - }); - - this.pre(function (x, key) { - if (insertable) { - var obj = traverse.get(prev, this.path.concat(key)); - if (obj === undefined) { - insertedKey = true; - set('inserted'); - } - } - - if (indent && !commaFirst) write('\n' + indentx); - - plainStringify(key); - write(indent ? ' : ' : ':'); - }); - - this.post(function (child) { - if (!child.isLast && !(indent && commaFirst)) { - write(','); - } - - if (child.isLast && deleted.length) { - if (insertedKey) unset('inserted'); - insertedKey = false; - } - else if (insertedKey) { - unset('inserted'); - insertedKey = false; - } - - var prev = prevNode && prevNode[child.key]; - if (indent && opts.comment && child.node !== prev - && (typeof child.node !== 'object' || typeof prev !== 'object') - ) { - set('comment'); - write(' // != '); - traverse(prev).forEach(function (x) { - plainStringify.call(this, x, { indent : 0 }); - }); - unset('comment'); - } - - if (child.isLast && deleted.length) { - if (insertedKey) unset('inserted'); - insertedKey = false; - - if (indent && commaFirst) { - write('\n' + indentx + ', ') - } - else if (opts.comment && indent) { - write('\n' + indentx); - } - else if (indent) { - write(',\n' + indentx); - } - else write(','); - } - else { - if (!child.isLast) { - if (indent && commaFirst) { - write('\n' + indentx + ', '); - } - } - } - }); - - this.after(function () { - if (inserted) unset('inserted'); - - if (deleted.length) { - if (indent && !commaFirst - && Object.keys(node).length === 0) { - write('\n' + indentx); - } - - set('deleted'); - deleted.forEach(function (key, ix) { - if (indent && opts.comment) { - unset('deleted'); - set('comment'); - write('// '); - unset('comment'); - set('deleted'); - } - - plainStringify(key); - write(indent ? ' : ' : ':'); - traverse(prevNode[key]).forEach(function (x) { - plainStringify.call(this, x, { indent : 0 }); - }); - - var last = ix === deleted.length - 1; - if (insertable && !last) { - if (indent && commaFirst) { - write('\n' + indentx + ', '); - } - else if (indent) { - write(',\n' + indentx); - } - else write(','); - } - }); - unset('deleted'); - } - - if (commaFirst && indent) { - write(indentx.slice(indent) + ' }'); - } - else if (indent) { - write('\n' + indentx.slice(indent) + '}'); - } - else write('}'); - }); - } - else { - var changed = false; - - if (inserted) set('inserted'); - else if (insertable && !deepEqual(prevNode, node)) { - changed = true; - set('updated'); - } - - if (typeof node === 'string') { - write('"' + node.toString().replace(/"/g, '\\"') + '"'); - } - else if (isRegExp(node)) { - write(node.toString()); - } - else if (typeof node === 'function') { - write(node.name - ? '[Function: ' + node.name + ']' - : '[Function]' - ); - } - else if (node === undefined) { - write('undefined'); - } - else if (node === null) { - write('null'); - } - else { - write(node.toString()); - } - - if (inserted) unset('inserted'); - else if (changed) unset('updated'); - } - } - - if (opts.stream) { - traverse(next).forEach(stringify); - } - else process.nextTick(function () { - traverse(next).forEach(stringify); - stream.emit('end'); - }); - - return stream; -} - -function isRegExp (node) { - return node instanceof RegExp || (node - && typeof node.test === 'function' - && typeof node.exec === 'function' - && typeof node.compile === 'function' - && node.constructor && node.constructor.name === 'RegExp' - ); -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/README.markdown b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/README.markdown deleted file mode 100644 index c78d81f00..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/README.markdown +++ /dev/null @@ -1,202 +0,0 @@ -charm -===== - -Use -[ansi terminal characters](http://www.termsys.demon.co.uk/vtansi.htm) -to write colors and cursor positions. - -![me lucky charms](http://substack.net/images/charms.png) - -example -======= - -lucky ------ - -````javascript -var charm = require('charm')(process); -charm.reset(); - -var colors = [ 'red', 'cyan', 'yellow', 'green', 'blue' ]; -var text = 'Always after me lucky charms.'; - -var offset = 0; -var iv = setInterval(function () { - var y = 0, dy = 1; - for (var i = 0; i < 40; i++) { - var color = colors[(i + offset) % colors.length]; - var c = text[(i + offset) % text.length]; - charm - .move(1, dy) - .foreground(color) - .write(c) - ; - y += dy; - if (y <= 0 || y >= 5) dy *= -1; - } - charm.position(0, 1); - offset ++; -}, 150); - -charm.on('data', function (buf) { - if (buf[0] === 3) { - clearInterval(iv); - charm.destroy(); - } -}); -```` - -events -====== - -Charm objects pass along the data events from their input stream except for -events generated from querying the terminal device. - -Because charm puts stdin into raw mode, charm emits two special events: "^C" and -"^D" when the user types those combos. It's super convenient with these events -to do: - -````javascript -charm.on('^C', process.exit) -```` - -methods -======= - -var charm = require('charm')(param or stream, ...) --------------------------------------------------- - -Create a new `charm` given a `param` with `stdout` and `stdin` streams, such as -`process` or by passing the streams in themselves separately as parameters. - -Protip: you can pass in an http response object as an output stream and it will -just work™. - -charm.reset() -------------- - -Reset the entire screen, like the /usr/bin/reset command. - -charm.destroy() ---------------- - -Destroy the input stream. - -charm.write(msg) ----------------- - -Pass along `msg` to the output stream. - -charm.position(x, y) or charm.position(cb) ------------------------------------------- - -Set the cursor position to the absolute coordinates `x, y` or query the position -and get the response as `cb(x, y)`. - -charm.move(x, y) ----------------- - -Move the cursor position by the relative coordinates `x, y`. - -charm.up(y) ------------ - -Move the cursor up by `y` rows. - -charm.down(y) -------------- - -Move the cursor down by `y` rows. - -charm.left(x) -------------- - -Move the cursor left by `x` columns. - -charm.right(x) -------------- - -Move the cursor right by `x` columns. - -charm.push(withAttributes=false) --------------------------------- - -Push the cursor state and optionally the attribute state. - -charm.pop(withAttributes=false) -------------------------------- - -Pop the cursor state and optionally the attribute state. - -charm.erase(s) --------------- - -Erase a region defined by the string `s`. - -`s` can be: - -* end - erase from the cursor to the end of the line -* start - erase from the cursor to the start of the line -* line - erase the current line -* down - erase everything below the current line -* up - erase everything above the current line -* screen - erase the entire screen - -charm.display(attr) -------------------- - -Set the display mode with the string `attr`. - -`attr` can be: - -* reset -* bright -* dim -* underscore -* blink -* reverse -* hidden - -charm.foreground(color) ------------------------ - -Set the foreground color with the string `color`, which can be: - -* red -* yellow -* green -* blue -* cyan -* magenta -* black -* white - -or `color` can be an integer from 0 to 255, inclusive. - -charm.background(color) ------------------------ - -Set the background color with the string `color`, which can be: - -* red -* yellow -* green -* blue -* cyan -* magenta -* black -* white - -or `color` can be an integer from 0 to 255, inclusive. - -charm.cursor(visible) ---------------------- - -Set the cursor visibility with a boolean `visible`. - -install -======= - -With [npm](http://npmjs.org) do: - - npm install charm diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/256.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/256.js deleted file mode 100644 index 685138676..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/256.js +++ /dev/null @@ -1,17 +0,0 @@ -var charm = require('../')(process); - -function exit () { - charm.display('reset'); - process.exit(); -} -charm.on('^C', exit); - -var ix = 0; -var iv = setInterval(function () { - charm.background(ix++).write(' '); - if (ix === 256) { - clearInterval(iv); - charm.write('\n'); - exit(); - } -}, 10); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/column.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/column.js deleted file mode 100644 index 448e9c320..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/column.js +++ /dev/null @@ -1,10 +0,0 @@ -var charm = require('../')(process); - -charm - .column(16) - .write('beep') - .down() - .column(32) - .write('boop\n') - .destroy() -; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/cursor.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/cursor.js deleted file mode 100644 index 0c565b06d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/cursor.js +++ /dev/null @@ -1,22 +0,0 @@ -var charm = require('../')(process); - -charm.position(5, 10); - -charm.position(function (x, y) { - console.dir([ x, y ]); - - charm.move(7,2); - charm.push(); - process.stdout.write('lul'); - - charm.left(3).up(1).foreground('magenta'); - process.stdout.write('v'); - charm.left(1).up(1).display('reset'); - process.stdout.write('|'); - - charm.down(3); - charm.pop().background('blue'); - process.stdout.write('popped\npow'); - charm.display('reset').erase('line'); - charm.destroy(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/http_spin.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/http_spin.js deleted file mode 100644 index 53e0e4b1a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/http_spin.js +++ /dev/null @@ -1,35 +0,0 @@ -var http = require('http'); -var charmer = require('../'); - -http.createServer(function (req, res) { - res.setHeader('content-type', 'text/ansi'); - - var charm = charmer(res); - charm.reset(); - - var radius = 10; - var theta = 0; - var points = []; - - var iv = setInterval(function () { - var x = 2 + (radius + Math.cos(theta) * radius) * 2; - var y = 2 + radius + Math.sin(theta) * radius; - - points.unshift([ x, y ]); - var colors = [ 'red', 'yellow', 'green', 'cyan', 'blue', 'magenta' ]; - - points.forEach(function (p, i) { - charm.position(p[0], p[1]); - var c = colors[Math.floor(i / 12)]; - charm.background(c).write(' ') - }); - points = points.slice(0, 12 * colors.length - 1); - - theta += Math.PI / 40; - }, 50); - - req.connection.on('end', function () { - clearInterval(iv); - charm.destroy(); - }); -}).listen(8081); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/lucky.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/lucky.js deleted file mode 100644 index 08dc5b536..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/lucky.js +++ /dev/null @@ -1,30 +0,0 @@ -var charm = require('../')(process); -charm.reset(); - -var colors = [ 'red', 'cyan', 'yellow', 'green', 'blue' ]; -var text = 'Always after me lucky charms.'; - -var offset = 0; -var iv = setInterval(function () { - var y = 0, dy = 1; - for (var i = 0; i < 40; i++) { - var color = colors[(i + offset) % colors.length]; - var c = text[(i + offset) % text.length]; - charm - .move(1, dy) - .foreground(color) - .write(c) - ; - y += dy; - if (y <= 0 || y >= 5) dy *= -1; - } - charm.position(0, 1); - offset ++; -}, 150); - -charm.on('data', function (buf) { - if (buf[0] === 3) { - clearInterval(iv); - charm.destroy(); - } -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/position.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/position.js deleted file mode 100644 index 2c5ae9b7b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/position.js +++ /dev/null @@ -1,7 +0,0 @@ -var charm = require('charm')(process); - -charm.on('^C', process.exit); - -charm.position(function (x, y) { - console.log('(%d, %d)', x, y); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/progress.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/progress.js deleted file mode 100644 index f8db57b5a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/progress.js +++ /dev/null @@ -1,19 +0,0 @@ -var charm = require('../')(process); - -charm.write("Progress: 0 %"); -var i = 0; - -var increment = function () { - charm.left(i.toString().length + 2); - i = i + 1; - charm.write(i + " %"); - if (i === 100) { - charm.write("\nDone!\n"); - process.exit(); - } -}; - -var loop = setInterval(increment, 50); - -charm.on('^C',process.exit); - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/spin.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/spin.js deleted file mode 100644 index fd3e23a04..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/example/spin.js +++ /dev/null @@ -1,23 +0,0 @@ -var charm = require('../')(process); -charm.reset(); - -var radius = 10; -var theta = 0; -var points = []; - -var iv = setInterval(function () { - var x = 2 + (radius + Math.cos(theta) * radius) * 2; - var y = 2 + radius + Math.sin(theta) * radius; - - points.unshift([ x, y ]); - var colors = [ 'red', 'yellow', 'green', 'cyan', 'blue', 'magenta' ]; - - points.forEach(function (p, i) { - charm.position(p[0], p[1]); - var c = colors[Math.floor(i / 12)]; - charm.background(c).write(' ') - }); - points = points.slice(0, 12 * colors.length - 1); - - theta += Math.PI / 40; -}, 50); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/index.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/index.js deleted file mode 100644 index bcfc7a82e..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/index.js +++ /dev/null @@ -1,286 +0,0 @@ -var tty = require('tty'); -var encode = require('./lib/encode'); -var EventEmitter = require('events').EventEmitter; - -var exports = module.exports = function () { - var input = null; - function setInput (s) { - if (input) throw new Error('multiple inputs specified') - else input = s - } - - var output = null; - function setOutput (s) { - if (output) throw new Error('multiple outputs specified') - else output = s - } - - for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i]; - if (!arg) continue; - if (arg.readable) setInput(arg) - else if (arg.stdin || arg.input) setInput(arg.stdin || arg.input) - - if (arg.writable) setOutput(arg) - else if (arg.stdout || arg.output) setOutput(arg.stdout || arg.output) - - } - - return new Charm(input, output); -}; - -var Charm = exports.Charm = function (input, output) { - var self = this; - self.input = input; - self.output = output; - self.pending = []; - - if (!output) { - self.emit('error', new Error('output stream required')); - } - - if (input && typeof input.fd === 'number' && tty.isatty(input.fd)) { - if (process.stdin.setRawMode) { - process.stdin.setRawMode(true); - } - else tty.setRawMode(true); - input.resume(); - } - - if (input) { - input.on('data', function (buf) { - if (self.pending.length) { - var codes = extractCodes(buf); - var matched = false; - - for (var i = 0; i < codes.length; i++) { - for (var j = 0; j < self.pending.length; j++) { - var cb = self.pending[j]; - if (cb(codes[i])) { - matched = true; - self.pending.splice(j, 1); - break; - } - } - } - - if (matched) return; - } - - self.emit('data', buf) - - if (buf.length === 1) { - if (buf[0] === 3) self.emit('^C'); - if (buf[0] === 4) self.emit('^D'); - } - }); - } -} - -Charm.prototype = new EventEmitter; - -Charm.prototype.destroy = function () { - if (this.input) this.input.destroy() -}; - -Charm.prototype.write = function (msg) { - this.output.write(msg); - return this; -}; - -Charm.prototype.reset = function (cb) { - this.write(encode('c')); - return this; -}; - -Charm.prototype.position = function (x, y) { - // get/set absolute coordinates - if (typeof x === 'function') { - var cb = x; - this.pending.push(function (buf) { - if (buf[0] === 27 && buf[1] === encode.ord('[') - && buf[buf.length-1] === encode.ord('R')) { - var pos = buf.toString() - .slice(2,-1) - .split(';') - .map(Number) - ; - cb(pos[1], pos[0]); - return true; - } - }); - this.write(encode('[6n')); - } - else { - this.write(encode( - '[' + Math.floor(y) + ';' + Math.floor(x) + 'f' - )); - } - return this; -}; - -Charm.prototype.move = function (x, y) { - // set relative coordinates - var bufs = []; - - if (y < 0) this.up(-y) - else if (y > 0) this.down(y) - - if (x > 0) this.right(x) - else if (x < 0) this.left(-x) - - return this; -}; - -Charm.prototype.up = function (y) { - if (y === undefined) y = 1; - this.write(encode('[' + Math.floor(y) + 'A')); - return this; -}; - -Charm.prototype.down = function (y) { - if (y === undefined) y = 1; - this.write(encode('[' + Math.floor(y) + 'B')); - return this; -}; - -Charm.prototype.right = function (x) { - if (x === undefined) x = 1; - this.write(encode('[' + Math.floor(x) + 'C')); - return this; -}; - -Charm.prototype.left = function (x) { - if (x === undefined) x = 1; - this.write(encode('[' + Math.floor(x) + 'D')); - return this; -}; - -Charm.prototype.column = function (x) { - this.write(encode('[' + Math.floor(x) + 'G')); - return this; -}; - -Charm.prototype.push = function (withAttributes) { - this.write(encode(withAttributes ? '7' : '[s')); - return this; -}; - -Charm.prototype.pop = function (withAttributes) { - this.write(encode(withAttributes ? '8' : '[u')); - return this; -}; - -Charm.prototype.erase = function (s) { - if (s === 'end' || s === '$') { - this.write(encode('[K')); - } - else if (s === 'start' || s === '^') { - this.write(encode('[1K')); - } - else if (s === 'line') { - this.write(encode('[2K')); - } - else if (s === 'down') { - this.write(encode('[J')); - } - else if (s === 'up') { - this.write(encode('[1J')); - } - else if (s === 'screen') { - this.write(encode('[1J')); - } - else { - this.emit('error', new Error('Unknown erase type: ' + s)); - } - return this; -}; - -Charm.prototype.display = function (attr) { - var c = { - reset : 0, - bright : 1, - dim : 2, - underscore : 4, - blink : 5, - reverse : 7, - hidden : 8 - }[attr]; - if (c === undefined) { - this.emit('error', new Error('Unknown attribute: ' + attr)); - } - this.write(encode('[' + c + 'm')); - return this; -}; - -Charm.prototype.foreground = function (color) { - if (typeof color === 'number') { - if (color < 0 || color >= 256) { - this.emit('error', new Error('Color out of range: ' + color)); - } - this.write(encode('[38;5;' + color + 'm')); - } - else { - var c = { - black : 30, - red : 31, - green : 32, - yellow : 33, - blue : 34, - magenta : 35, - cyan : 36, - white : 37 - }[color.toLowerCase()]; - - if (!c) this.emit('error', new Error('Unknown color: ' + color)); - this.write(encode('[' + c + 'm')); - } - return this; -}; - -Charm.prototype.background = function (color) { - if (typeof color === 'number') { - if (color < 0 || color >= 256) { - this.emit('error', new Error('Color out of range: ' + color)); - } - this.write(encode('[48;5;' + color + 'm')); - } - else { - var c = { - black : 40, - red : 41, - green : 42, - yellow : 43, - blue : 44, - magenta : 45, - cyan : 46, - white : 47 - }[color.toLowerCase()]; - - if (!c) this.emit('error', new Error('Unknown color: ' + color)); - this.write(encode('[' + c + 'm')); - } - return this; -}; - -Charm.prototype.cursor = function (visible) { - this.write(encode(visible ? '[?25h' : '[?25l')); - return this; -}; - -var extractCodes = exports.extractCodes = function (buf) { - var codes = []; - var start = -1; - - for (var i = 0; i < buf.length; i++) { - if (buf[i] === 27) { - if (start >= 0) codes.push(buf.slice(start, i)); - start = i; - } - else if (start >= 0 && i === buf.length - 1) { - codes.push(buf.slice(start)); - } - } - - return codes; -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/lib/encode.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/lib/encode.js deleted file mode 100644 index 3b6417a4e..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/lib/encode.js +++ /dev/null @@ -1,18 +0,0 @@ -var encode = module.exports = function (xs) { - function bytes (s) { - if (typeof s === 'string') { - return s.split('').map(ord); - } - else if (Array.isArray(s)) { - return s.reduce(function (acc, c) { - return acc.concat(bytes(c)); - }, []); - } - } - - return new Buffer([ 0x1b ].concat(bytes(xs))); -}; - -var ord = encode.ord = function ord (c) { - return c.charCodeAt(0) -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/package.json deleted file mode 100644 index 3ff14427d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/charm/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "charm", - "version": "0.0.8", - "description": "ansi control sequences for terminal cursor hopping and colors", - "main": "index.js", - "directories": { - "lib": ".", - "example": "example", - "test": "test" - }, - "repository": { - "type": "git", - "url": "http://github.com/substack/node-charm.git" - }, - "keywords": [ - "terminal", - "ansi", - "cursor", - "color", - "console", - "control", - "escape", - "sequence" - ], - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "license": "MIT/X11", - "engine": { - "node": ">=0.4" - }, - "readme": "charm\n=====\n\nUse\n[ansi terminal characters](http://www.termsys.demon.co.uk/vtansi.htm)\nto write colors and cursor positions.\n\n![me lucky charms](http://substack.net/images/charms.png)\n\nexample\n=======\n\nlucky\n-----\n\n````javascript\nvar charm = require('charm')(process);\ncharm.reset();\n\nvar colors = [ 'red', 'cyan', 'yellow', 'green', 'blue' ];\nvar text = 'Always after me lucky charms.';\n\nvar offset = 0;\nvar iv = setInterval(function () {\n var y = 0, dy = 1;\n for (var i = 0; i < 40; i++) {\n var color = colors[(i + offset) % colors.length];\n var c = text[(i + offset) % text.length];\n charm\n .move(1, dy)\n .foreground(color)\n .write(c)\n ;\n y += dy;\n if (y <= 0 || y >= 5) dy *= -1;\n }\n charm.position(0, 1);\n offset ++;\n}, 150);\n \ncharm.on('data', function (buf) {\n if (buf[0] === 3) {\n clearInterval(iv);\n charm.destroy();\n }\n});\n````\n\nevents\n======\n\nCharm objects pass along the data events from their input stream except for\nevents generated from querying the terminal device.\n\nBecause charm puts stdin into raw mode, charm emits two special events: \"^C\" and\n\"^D\" when the user types those combos. It's super convenient with these events\nto do:\n\n````javascript\ncharm.on('^C', process.exit)\n````\n\nmethods\n=======\n\nvar charm = require('charm')(param or stream, ...)\n--------------------------------------------------\n\nCreate a new `charm` given a `param` with `stdout` and `stdin` streams, such as\n`process` or by passing the streams in themselves separately as parameters.\n\nProtip: you can pass in an http response object as an output stream and it will\njust work™.\n\ncharm.reset()\n-------------\n\nReset the entire screen, like the /usr/bin/reset command.\n\ncharm.destroy()\n---------------\n\nDestroy the input stream.\n\ncharm.write(msg)\n----------------\n\nPass along `msg` to the output stream.\n\ncharm.position(x, y) or charm.position(cb)\n------------------------------------------\n\nSet the cursor position to the absolute coordinates `x, y` or query the position\nand get the response as `cb(x, y)`.\n\ncharm.move(x, y)\n----------------\n\nMove the cursor position by the relative coordinates `x, y`.\n\ncharm.up(y)\n-----------\n\nMove the cursor up by `y` rows.\n\ncharm.down(y)\n-------------\n\nMove the cursor down by `y` rows.\n\ncharm.left(x)\n-------------\n\nMove the cursor left by `x` columns.\n\ncharm.right(x)\n-------------\n\nMove the cursor right by `x` columns.\n\ncharm.push(withAttributes=false)\n--------------------------------\n\nPush the cursor state and optionally the attribute state.\n\ncharm.pop(withAttributes=false)\n-------------------------------\n\nPop the cursor state and optionally the attribute state.\n\ncharm.erase(s)\n--------------\n\nErase a region defined by the string `s`.\n\n`s` can be:\n\n* end - erase from the cursor to the end of the line\n* start - erase from the cursor to the start of the line\n* line - erase the current line\n* down - erase everything below the current line\n* up - erase everything above the current line\n* screen - erase the entire screen\n\ncharm.display(attr)\n-------------------\n\nSet the display mode with the string `attr`.\n\n`attr` can be:\n\n* reset\n* bright\n* dim\n* underscore\n* blink\n* reverse\n* hidden\n\ncharm.foreground(color)\n-----------------------\n\nSet the foreground color with the string `color`, which can be:\n\n* red\n* yellow\n* green\n* blue\n* cyan\n* magenta\n* black\n* white\n\nor `color` can be an integer from 0 to 255, inclusive.\n\ncharm.background(color)\n-----------------------\n\nSet the background color with the string `color`, which can be:\n\n* red\n* yellow\n* green\n* blue\n* cyan\n* magenta\n* black\n* white\n\nor `color` can be an integer from 0 to 255, inclusive.\n\ncharm.cursor(visible)\n---------------------\n\nSet the cursor visibility with a boolean `visible`.\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) do:\n\n npm install charm\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/substack/node-charm/issues" - }, - "_id": "charm@0.0.8", - "_from": "charm@0.0.x" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/.travis.yml b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/.travis.yml deleted file mode 100644 index d523c5f56..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/.travis.yml +++ /dev/null @@ -1,6 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 - - 0.8 - - 0.10 diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/README.markdown b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/README.markdown deleted file mode 100644 index 876043f63..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/README.markdown +++ /dev/null @@ -1,63 +0,0 @@ -deep-is -========== - -Node's `assert.deepEqual() algorithm` as a standalone module. Exactly like -[deep-equal](https://github.com/substack/node-deep-equal) except for the fact that `deepEqual(NaN, NaN) === true`. - -This module is around [5 times faster](https://gist.github.com/2790507) -than wrapping `assert.deepEqual()` in a `try/catch`. - -[![browser support](http://ci.testling.com/thlorenz/deep-is.png)](http://ci.testling.com/thlorenz/deep-is) - -[![build status](https://secure.travis-ci.org/thlorenz/deep-is.png)](http://travis-ci.org/thlorenz/deep-is) - -example -======= - -``` js -var equal = require('deep-is'); -console.dir([ - equal( - { a : [ 2, 3 ], b : [ 4 ] }, - { a : [ 2, 3 ], b : [ 4 ] } - ), - equal( - { x : 5, y : [6] }, - { x : 5, y : 6 } - ) -]); -``` - -methods -======= - -var deepIs = require('deep-is') - -deepIs(a, b) ---------------- - -Compare objects `a` and `b`, returning whether they are equal according to a -recursive equality algorithm. - -install -======= - -With [npm](http://npmjs.org) do: - -``` -npm install deep-is -``` - -test -==== - -With [npm](http://npmjs.org) do: - -``` -npm test -``` - -license -======= - -MIT. Derived largely from node's assert module. diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/example/cmp.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/example/cmp.js deleted file mode 100644 index 67014b88d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/example/cmp.js +++ /dev/null @@ -1,11 +0,0 @@ -var equal = require('../'); -console.dir([ - equal( - { a : [ 2, 3 ], b : [ 4 ] }, - { a : [ 2, 3 ], b : [ 4 ] } - ), - equal( - { x : 5, y : [6] }, - { x : 5, y : 6 } - ) -]); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/index.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/index.js deleted file mode 100644 index 506fe2795..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/index.js +++ /dev/null @@ -1,102 +0,0 @@ -var pSlice = Array.prototype.slice; -var Object_keys = typeof Object.keys === 'function' - ? Object.keys - : function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; - } -; - -var deepEqual = module.exports = function (actual, expected) { - // enforce Object.is +0 !== -0 - if (actual === 0 && expected === 0) { - return areZerosEqual(actual, expected); - - // 7.1. All identical values are equivalent, as determined by ===. - } else if (actual === expected) { - return true; - - } else if (actual instanceof Date && expected instanceof Date) { - return actual.getTime() === expected.getTime(); - - } else if (isNumberNaN(actual)) { - return isNumberNaN(expected); - - // 7.3. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { - return actual == expected; - - // 7.4. 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 isUndefinedOrNull(value) { - return value === null || value === undefined; -} - -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function isNumberNaN(value) { - // NaN === NaN -> false - return typeof value == 'number' && value !== value; -} - -function areZerosEqual(zeroA, zeroB) { - // (1 / +0|0) -> Infinity, but (1 / -0) -> -Infinity and (Infinity !== -Infinity) - return (1 / zeroA) === (1 / zeroB); -} - -function objEquiv(a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(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 = 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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/package.json deleted file mode 100644 index a25326203..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "name": "deep-is", - "version": "0.1.1", - "description": "node's assert.deepEqual algorithm except for NaN being equal to NaN", - "main": "index.js", - "directories": { - "lib": ".", - "example": "example", - "test": "test" - }, - "scripts": { - "test": "tap test/*.js" - }, - "devDependencies": { - "tap": "~0.3.0", - "tape": "~0.0.5" - }, - "repository": { - "type": "git", - "url": "http://github.com/thlorenz/deep-is.git" - }, - "keywords": [ - "equality", - "equal", - "compare" - ], - "author": { - "name": "Thorsten Lorenz", - "email": "thlorenz@gmx.de", - "url": "http://thlorenz.com" - }, - "license": "MIT", - "testling": { - "files": "test/*.js", - "browsers": { - "ie": [ - 6, - 7, - 8, - 9 - ], - "ff": [ - 3.5, - 10, - 15 - ], - "chrome": [ - 10, - 22 - ], - "safari": [ - 5.1 - ], - "opera": [ - 12 - ] - } - }, - "readme": "deep-is\n==========\n\nNode's `assert.deepEqual() algorithm` as a standalone module. Exactly like\n[deep-equal](https://github.com/substack/node-deep-equal) except for the fact that `deepEqual(NaN, NaN) === true`.\n\nThis module is around [5 times faster](https://gist.github.com/2790507)\nthan wrapping `assert.deepEqual()` in a `try/catch`.\n\n[![browser support](http://ci.testling.com/thlorenz/deep-is.png)](http://ci.testling.com/thlorenz/deep-is)\n\n[![build status](https://secure.travis-ci.org/thlorenz/deep-is.png)](http://travis-ci.org/thlorenz/deep-is)\n\nexample\n=======\n\n``` js\nvar equal = require('deep-is');\nconsole.dir([\n equal(\n { a : [ 2, 3 ], b : [ 4 ] },\n { a : [ 2, 3 ], b : [ 4 ] }\n ),\n equal(\n { x : 5, y : [6] },\n { x : 5, y : 6 }\n )\n]);\n```\n\nmethods\n=======\n\nvar deepIs = require('deep-is')\n\ndeepIs(a, b)\n---------------\n\nCompare objects `a` and `b`, returning whether they are equal according to a\nrecursive equality algorithm.\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install deep-is\n```\n\ntest\n====\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm test\n```\n\nlicense\n=======\n\nMIT. Derived largely from node's assert module.\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/thlorenz/deep-is/issues" - }, - "_id": "deep-is@0.1.1", - "_from": "deep-is@0.1.x" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/test/NaN.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/test/NaN.js deleted file mode 100644 index ddaa5a77b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/test/NaN.js +++ /dev/null @@ -1,16 +0,0 @@ -var test = require('tape'); -var equal = require('../'); - -test('NaN and 0 values', function (t) { - t.ok(equal(NaN, NaN)); - t.notOk(equal(0, NaN)); - t.ok(equal(0, 0)); - t.notOk(equal(0, 1)); - t.end(); -}); - - -test('nested NaN values', function (t) { - t.ok(equal([ NaN, 1, NaN ], [ NaN, 1, NaN ])); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/test/cmp.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/test/cmp.js deleted file mode 100644 index 307101341..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/test/cmp.js +++ /dev/null @@ -1,23 +0,0 @@ -var test = require('tape'); -var equal = require('../'); - -test('equal', function (t) { - t.ok(equal( - { a : [ 2, 3 ], b : [ 4 ] }, - { a : [ 2, 3 ], b : [ 4 ] } - )); - t.end(); -}); - -test('not equal', function (t) { - t.notOk(equal( - { x : 5, y : [6] }, - { x : 5, y : 6 } - )); - t.end(); -}); - -test('nested nulls', function (t) { - t.ok(equal([ null, null, null ], [ null, null, null ])); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/test/neg-vs-pos-0.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/test/neg-vs-pos-0.js deleted file mode 100644 index ac26130e6..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/deep-is/test/neg-vs-pos-0.js +++ /dev/null @@ -1,15 +0,0 @@ -var test = require('tape'); -var equal = require('../'); - -test('0 values', function (t) { - t.ok(equal( 0, 0), ' 0 === 0'); - t.ok(equal( 0, +0), ' 0 === +0'); - t.ok(equal(+0, +0), '+0 === +0'); - t.ok(equal(-0, -0), '-0 === -0'); - - t.notOk(equal(-0, 0), '-0 !== 0'); - t.notOk(equal(-0, +0), '-0 !== +0'); - - t.end(); -}); - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/README.markdown b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/README.markdown deleted file mode 100644 index 275667b1a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/README.markdown +++ /dev/null @@ -1,258 +0,0 @@ -traverse -======== - -Traverse and transform objects by visiting every node on a recursive walk. - -[![build status](https://secure.travis-ci.org/substack/js-traverse.png)](http://travis-ci.org/substack/js-traverse) - -examples -======== - -transform negative numbers in-place ------------------------------------ - -negative.js - -````javascript -var traverse = require('traverse'); -var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - -traverse(obj).forEach(function (x) { - if (x < 0) this.update(x + 128); -}); - -console.dir(obj); -```` - -Output: - - [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ] - -collect leaf nodes ------------------- - -leaves.js - -````javascript -var traverse = require('traverse'); - -var obj = { - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 }, -}; - -var leaves = traverse(obj).reduce(function (acc, x) { - if (this.isLeaf) acc.push(x); - return acc; -}, []); - -console.dir(leaves); -```` - -Output: - - [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] - -scrub circular references -------------------------- - -scrub.js: - -````javascript -var traverse = require('traverse'); - -var obj = { a : 1, b : 2, c : [ 3, 4 ] }; -obj.c.push(obj); - -var scrubbed = traverse(obj).map(function (x) { - if (this.circular) this.remove() -}); -console.dir(scrubbed); -```` - -output: - - { a: 1, b: 2, c: [ 3, 4 ] } - -methods -======= - -Each method that takes an `fn` uses the context documented below in the context -section. - -.map(fn) --------- - -Execute `fn` for each node in the object and return a new object with the -results of the walk. To update nodes in the result use `this.update(value)`. - -.forEach(fn) ------------- - -Execute `fn` for each node in the object but unlike `.map()`, when -`this.update()` is called it updates the object in-place. - -.reduce(fn, acc) ----------------- - -For each node in the object, perform a -[left-fold](http://en.wikipedia.org/wiki/Fold_(higher-order_function)) -with the return value of `fn(acc, node)`. - -If `acc` isn't specified, `acc` is set to the root object for the first step -and the root element is skipped. - -.paths() --------- - -Return an `Array` of every possible non-cyclic path in the object. -Paths are `Array`s of string keys. - -.nodes() --------- - -Return an `Array` of every node in the object. - -.clone() --------- - -Create a deep clone of the object. - -.get(path) ----------- - -Get the element at the array `path`. - -.set(path, value) ------------------ - -Set the element at the array `path` to `value`. - -.has(path) ----------- - -Return whether the element at the array `path` exists. - -context -======= - -Each method that takes a callback has a context (its `this` object) with these -attributes: - -this.node ---------- - -The present node on the recursive walk - -this.path ---------- - -An array of string keys from the root to the present node - -this.parent ------------ - -The context of the node's parent. -This is `undefined` for the root node. - -this.key --------- - -The name of the key of the present node in its parent. -This is `undefined` for the root node. - -this.isRoot, this.notRoot -------------------------- - -Whether the present node is the root node - -this.isLeaf, this.notLeaf -------------------------- - -Whether or not the present node is a leaf node (has no children) - -this.level ----------- - -Depth of the node within the traversal - -this.circular -------------- - -If the node equals one of its parents, the `circular` attribute is set to the -context of that parent and the traversal progresses no deeper. - -this.update(value, stopHere=false) ----------------------------------- - -Set a new value for the present node. - -All the elements in `value` will be recursively traversed unless `stopHere` is -true. - -this.remove(stopHere=false) -------------- - -Remove the current element from the output. If the node is in an Array it will -be spliced off. Otherwise it will be deleted from its parent. - -this.delete(stopHere=false) -------------- - -Delete the current element from its parent in the output. Calls `delete` even on -Arrays. - -this.before(fn) ---------------- - -Call this function before any of the children are traversed. - -You can assign into `this.keys` here to traverse in a custom order. - -this.after(fn) --------------- - -Call this function after any of the children are traversed. - -this.pre(fn) ------------- - -Call this function before each of the children are traversed. - -this.post(fn) -------------- - -Call this function after each of the children are traversed. - - -install -======= - -Using [npm](http://npmjs.org) do: - - $ npm install traverse - -test -==== - -Using [expresso](http://github.com/visionmedia/expresso) do: - - $ expresso - - 100% wahoo, your stuff is not broken! - -in the browser -============== - -Use [browserify](https://github.com/substack/node-browserify) to run traverse in -the browser. - -traverse has been tested and works with: - -* Internet Explorer 5.5, 6.0, 7.0, 8.0, 9.0 -* Firefox 3.5 -* Chrome 6.0 -* Opera 10.6 -* Safari 5.0 diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/json.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/json.js deleted file mode 100755 index 50d612e3a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/json.js +++ /dev/null @@ -1,16 +0,0 @@ -var traverse = require('traverse'); - -var id = 54; -var callbacks = {}; -var obj = { moo : function () {}, foo : [2,3,4, function () {}] }; - -var scrubbed = traverse(obj).map(function (x) { - if (typeof x === 'function') { - callbacks[id] = { id : id, f : x, path : this.path }; - this.update('[Function]'); - id++; - } -}); - -console.dir(scrubbed); -console.dir(callbacks); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/leaves.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/leaves.js deleted file mode 100755 index c1b310b95..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/leaves.js +++ /dev/null @@ -1,15 +0,0 @@ -var traverse = require('traverse'); - -var obj = { - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 }, -}; - -var leaves = traverse(obj).reduce(function (acc, x) { - if (this.isLeaf) acc.push(x); - return acc; -}, []); - -console.dir(leaves); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/negative.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/negative.js deleted file mode 100755 index 78608a059..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/negative.js +++ /dev/null @@ -1,8 +0,0 @@ -var traverse = require('traverse'); -var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - -traverse(obj).forEach(function (x) { - if (x < 0) this.update(x + 128); -}); - -console.dir(obj); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/scrub.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/scrub.js deleted file mode 100755 index 5d15b9161..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/scrub.js +++ /dev/null @@ -1,10 +0,0 @@ -// scrub out circular references -var traverse = require('traverse'); - -var obj = { a : 1, b : 2, c : [ 3, 4 ] }; -obj.c.push(obj); - -var scrubbed = traverse(obj).map(function (x) { - if (this.circular) this.remove() -}); -console.dir(scrubbed); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/stringify.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/stringify.js deleted file mode 100755 index 167b68b23..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/examples/stringify.js +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env node -var traverse = require('traverse'); - -var obj = [ 'five', 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - -var s = ''; -traverse(obj).forEach(function to_s (node) { - if (Array.isArray(node)) { - this.before(function () { s += '[' }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += ']' }); - } - else if (typeof node == 'object') { - this.before(function () { s += '{' }); - this.pre(function (x, key) { - to_s(key); - s += ':'; - }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += '}' }); - } - else if (typeof node == 'string') { - s += '"' + node.toString().replace(/"/g, '\\"') + '"'; - } - else if (typeof node == 'function') { - s += 'null'; - } - else { - s += node.toString(); - } -}); - -console.log('JSON.stringify: ' + JSON.stringify(obj)); -console.log('this stringify: ' + s); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/fail.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/fail.js deleted file mode 100644 index 3d75f8d6f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/fail.js +++ /dev/null @@ -1,9 +0,0 @@ -tr = require("traverse") -obj = {"a": "[false]", "b": "[]", c: "[\"a string\"]"} -o = JSON.parse(JSON.stringify(obj)) -tr(o).forEach(function(e){ - if (this.isLeaf) { - //if (e === "[false]"){ this.update(false) } - if (e === "[]") { this.update([]); } - } -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/index.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/index.js deleted file mode 100644 index d5de23861..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/index.js +++ /dev/null @@ -1,310 +0,0 @@ -var traverse = module.exports = function (obj) { - return new Traverse(obj); -}; - -function Traverse (obj) { - this.value = obj; -} - -Traverse.prototype.get = function (ps) { - var node = this.value; - for (var i = 0; i < ps.length; i ++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) { - node = undefined; - break; - } - node = node[key]; - } - return node; -}; - -Traverse.prototype.has = function (ps) { - var node = this.value; - for (var i = 0; i < ps.length; i ++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) { - return false; - } - node = node[key]; - } - return true; -}; - -Traverse.prototype.set = function (ps, value) { - var node = this.value; - for (var i = 0; i < ps.length - 1; i ++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) node[key] = {}; - node = node[key]; - } - node[ps[i]] = value; - return value; -}; - -Traverse.prototype.map = function (cb) { - return walk(this.value, cb, true); -}; - -Traverse.prototype.forEach = function (cb) { - this.value = walk(this.value, cb, false); - return this.value; -}; - -Traverse.prototype.reduce = function (cb, init) { - var skip = arguments.length === 1; - var acc = skip ? this.value : init; - this.forEach(function (x) { - if (!this.isRoot || !skip) { - acc = cb.call(this, acc, x); - } - }); - return acc; -}; - -Traverse.prototype.paths = function () { - var acc = []; - this.forEach(function (x) { - acc.push(this.path); - }); - return acc; -}; - -Traverse.prototype.nodes = function () { - var acc = []; - this.forEach(function (x) { - acc.push(this.node); - }); - return acc; -}; - -Traverse.prototype.clone = function () { - var parents = [], nodes = []; - - return (function clone (src) { - for (var i = 0; i < parents.length; i++) { - if (parents[i] === src) { - return nodes[i]; - } - } - - if (typeof src === 'object' && src !== null) { - var dst = copy(src); - - parents.push(src); - nodes.push(dst); - - forEach(objectKeys(src), function (key) { - dst[key] = clone(src[key]); - }); - - parents.pop(); - nodes.pop(); - return dst; - } - else { - return src; - } - })(this.value); -}; - -function walk (root, cb, immutable) { - var path = []; - var parents = []; - var alive = true; - - return (function walker (node_) { - var node = immutable ? copy(node_) : node_; - var modifiers = {}; - - var keepGoing = true; - - var state = { - node : node, - node_ : node_, - path : [].concat(path), - parent : parents[parents.length - 1], - parents : parents, - key : path.slice(-1)[0], - isRoot : path.length === 0, - level : path.length, - circular : null, - update : function (x, stopHere) { - if (!state.isRoot) { - state.parent.node[state.key] = x; - } - state.node = x; - if (stopHere) keepGoing = false; - }, - 'delete' : function (stopHere) { - delete state.parent.node[state.key]; - if (stopHere) keepGoing = false; - }, - remove : function (stopHere) { - if (isArray(state.parent.node)) { - state.parent.node.splice(state.key, 1); - } - else { - delete state.parent.node[state.key]; - } - if (stopHere) keepGoing = false; - }, - keys : null, - before : function (f) { modifiers.before = f }, - after : function (f) { modifiers.after = f }, - pre : function (f) { modifiers.pre = f }, - post : function (f) { modifiers.post = f }, - stop : function () { alive = false }, - block : function () { keepGoing = false } - }; - - if (!alive) return state; - - function updateState() { - if (typeof state.node === 'object' && state.node !== null) { - if (!state.keys || state.node_ !== state.node) { - state.keys = objectKeys(state.node) - } - - state.isLeaf = state.keys.length == 0; - - for (var i = 0; i < parents.length; i++) { - if (parents[i].node_ === node_) { - state.circular = parents[i]; - break; - } - } - } - else { - state.isLeaf = true; - state.keys = null; - } - - state.notLeaf = !state.isLeaf; - state.notRoot = !state.isRoot; - } - - updateState(); - - // use return values to update if defined - var ret = cb.call(state, state.node); - if (ret !== undefined && state.update) state.update(ret); - - if (modifiers.before) modifiers.before.call(state, state.node); - - if (!keepGoing) return state; - - if (typeof state.node == 'object' - && state.node !== null && !state.circular) { - parents.push(state); - - updateState(); - - forEach(state.keys, function (key, i) { - path.push(key); - - if (modifiers.pre) modifiers.pre.call(state, state.node[key], key); - - var child = walker(state.node[key]); - if (immutable && Object.hasOwnProperty.call(state.node, key)) { - state.node[key] = child.node; - } - - child.isLast = i == state.keys.length - 1; - child.isFirst = i == 0; - - if (modifiers.post) modifiers.post.call(state, child); - - path.pop(); - }); - parents.pop(); - } - - if (modifiers.after) modifiers.after.call(state, state.node); - - return state; - })(root).node; -} - -function copy (src) { - if (typeof src === 'object' && src !== null) { - var dst; - - if (isArray(src)) { - dst = []; - } - else if (isDate(src)) { - dst = new Date(src); - } - else if (isRegExp(src)) { - dst = new RegExp(src); - } - else if (isError(src)) { - dst = { message: src.message }; - } - else if (isBoolean(src)) { - dst = new Boolean(src); - } - else if (isNumber(src)) { - dst = new Number(src); - } - else if (isString(src)) { - dst = new String(src); - } - else if (Object.create && Object.getPrototypeOf) { - dst = Object.create(Object.getPrototypeOf(src)); - } - else if (src.constructor === Object) { - dst = {}; - } - else { - var proto = - (src.constructor && src.constructor.prototype) - || src.__proto__ - || {} - ; - var T = function () {}; - T.prototype = proto; - dst = new T; - } - - forEach(objectKeys(src), function (key) { - dst[key] = src[key]; - }); - return dst; - } - else return src; -} - -var objectKeys = Object.keys || function keys (obj) { - var res = []; - for (var key in obj) res.push(key) - return res; -}; - -function toS (obj) { return Object.prototype.toString.call(obj) } -function isDate (obj) { return toS(obj) === '[object Date]' } -function isRegExp (obj) { return toS(obj) === '[object RegExp]' } -function isError (obj) { return toS(obj) === '[object Error]' } -function isBoolean (obj) { return toS(obj) === '[object Boolean]' } -function isNumber (obj) { return toS(obj) === '[object Number]' } -function isString (obj) { return toS(obj) === '[object String]' } - -var isArray = Array.isArray || function isArray (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -var forEach = function (xs, fn) { - if (xs.forEach) return xs.forEach(fn) - else for (var i = 0; i < xs.length; i++) { - fn(xs[i], i, xs); - } -}; - -forEach(objectKeys(Traverse.prototype), function (key) { - traverse[key] = function (obj) { - var args = [].slice.call(arguments, 1); - var t = new Traverse(obj); - return t[key].apply(t, args); - }; -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/package.json deleted file mode 100644 index f53c37959..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "traverse", - "version": "0.6.3", - "description": "traverse and transform objects by visiting every node on a recursive walk", - "main": "index.js", - "bin": {}, - "directories": { - "example": "example", - "test": "test" - }, - "dependencies": {}, - "devDependencies": { - "tap": "~0.2.5" - }, - "scripts": { - "test": "tap test/*.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/substack/js-traverse.git" - }, - "homepage": "https://github.com/substack/js-traverse", - "keywords": [ - "traverse", - "walk", - "recursive", - "map", - "forEach", - "deep", - "clone" - ], - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "license": "MIT", - "engine": { - "node": ">=0.6" - }, - "readme": "traverse\n========\n\nTraverse and transform objects by visiting every node on a recursive walk.\n\n[![build status](https://secure.travis-ci.org/substack/js-traverse.png)](http://travis-ci.org/substack/js-traverse)\n\nexamples\n========\n\ntransform negative numbers in-place\n-----------------------------------\n\nnegative.js\n\n````javascript\nvar traverse = require('traverse');\nvar obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];\n\ntraverse(obj).forEach(function (x) {\n if (x < 0) this.update(x + 128);\n});\n\nconsole.dir(obj);\n````\n\nOutput:\n\n [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ]\n\ncollect leaf nodes\n------------------\n\nleaves.js\n\n````javascript\nvar traverse = require('traverse');\n\nvar obj = {\n a : [1,2,3],\n b : 4,\n c : [5,6],\n d : { e : [7,8], f : 9 },\n};\n\nvar leaves = traverse(obj).reduce(function (acc, x) {\n if (this.isLeaf) acc.push(x);\n return acc;\n}, []);\n\nconsole.dir(leaves);\n````\n\nOutput:\n\n [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]\n\nscrub circular references\n-------------------------\n\nscrub.js:\n\n````javascript\nvar traverse = require('traverse');\n\nvar obj = { a : 1, b : 2, c : [ 3, 4 ] };\nobj.c.push(obj);\n\nvar scrubbed = traverse(obj).map(function (x) {\n if (this.circular) this.remove()\n});\nconsole.dir(scrubbed);\n````\n\noutput:\n\n { a: 1, b: 2, c: [ 3, 4 ] }\n\nmethods\n=======\n\nEach method that takes an `fn` uses the context documented below in the context\nsection.\n\n.map(fn)\n--------\n\nExecute `fn` for each node in the object and return a new object with the\nresults of the walk. To update nodes in the result use `this.update(value)`.\n\n.forEach(fn)\n------------\n\nExecute `fn` for each node in the object but unlike `.map()`, when\n`this.update()` is called it updates the object in-place.\n\n.reduce(fn, acc)\n----------------\n\nFor each node in the object, perform a\n[left-fold](http://en.wikipedia.org/wiki/Fold_(higher-order_function))\nwith the return value of `fn(acc, node)`.\n\nIf `acc` isn't specified, `acc` is set to the root object for the first step\nand the root element is skipped.\n\n.paths()\n--------\n\nReturn an `Array` of every possible non-cyclic path in the object.\nPaths are `Array`s of string keys.\n\n.nodes()\n--------\n\nReturn an `Array` of every node in the object.\n\n.clone()\n--------\n\nCreate a deep clone of the object.\n\n.get(path)\n----------\n\nGet the element at the array `path`.\n\n.set(path, value)\n-----------------\n\nSet the element at the array `path` to `value`.\n\n.has(path)\n----------\n\nReturn whether the element at the array `path` exists.\n\ncontext\n=======\n\nEach method that takes a callback has a context (its `this` object) with these\nattributes:\n\nthis.node\n---------\n\nThe present node on the recursive walk\n\nthis.path\n---------\n\nAn array of string keys from the root to the present node\n\nthis.parent\n-----------\n\nThe context of the node's parent.\nThis is `undefined` for the root node.\n\nthis.key\n--------\n\nThe name of the key of the present node in its parent.\nThis is `undefined` for the root node.\n\nthis.isRoot, this.notRoot\n-------------------------\n\nWhether the present node is the root node\n\nthis.isLeaf, this.notLeaf\n-------------------------\n\nWhether or not the present node is a leaf node (has no children)\n\nthis.level\n----------\n\nDepth of the node within the traversal\n\nthis.circular\n-------------\n\nIf the node equals one of its parents, the `circular` attribute is set to the\ncontext of that parent and the traversal progresses no deeper.\n\nthis.update(value, stopHere=false)\n----------------------------------\n\nSet a new value for the present node.\n\nAll the elements in `value` will be recursively traversed unless `stopHere` is\ntrue.\n\nthis.remove(stopHere=false)\n-------------\n\nRemove the current element from the output. If the node is in an Array it will\nbe spliced off. Otherwise it will be deleted from its parent.\n\nthis.delete(stopHere=false)\n-------------\n\nDelete the current element from its parent in the output. Calls `delete` even on\nArrays.\n\nthis.before(fn)\n---------------\n\nCall this function before any of the children are traversed.\n\nYou can assign into `this.keys` here to traverse in a custom order.\n\nthis.after(fn)\n--------------\n\nCall this function after any of the children are traversed.\n\nthis.pre(fn)\n------------\n\nCall this function before each of the children are traversed.\n\nthis.post(fn)\n-------------\n\nCall this function after each of the children are traversed.\n\n\ninstall\n=======\n\nUsing [npm](http://npmjs.org) do:\n\n $ npm install traverse\n\ntest\n====\n\nUsing [expresso](http://github.com/visionmedia/expresso) do:\n\n $ expresso\n \n 100% wahoo, your stuff is not broken!\n\nin the browser\n==============\n\nUse [browserify](https://github.com/substack/node-browserify) to run traverse in\nthe browser.\n\ntraverse has been tested and works with:\n\n* Internet Explorer 5.5, 6.0, 7.0, 8.0, 9.0\n* Firefox 3.5\n* Chrome 6.0\n* Opera 10.6\n* Safari 5.0\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/substack/js-traverse/issues" - }, - "_id": "traverse@0.6.3", - "_from": "traverse@0.6.x" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/circular.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/circular.js deleted file mode 100644 index 10e32f0be..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/circular.js +++ /dev/null @@ -1,117 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); -var deepEqual = require('./lib/deep_equal'); -var util = require('util'); - -test('circular', function (t) { - t.plan(1); - - var obj = { x : 3 }; - obj.y = obj; - traverse(obj).forEach(function (x) { - if (this.path.join('') == 'y') { - t.equal( - util.inspect(this.circular.node), - util.inspect(obj) - ); - } - }); -}); - -test('deepCirc', function (t) { - t.plan(2); - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - - var times = 0; - traverse(obj).forEach(function (x) { - if (this.circular) { - t.same(this.circular.path, []); - t.same(this.path, [ 'y', 2 ]); - } - }); -}); - -test('doubleCirc', function (t) { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - var circs = []; - traverse(obj).forEach(function (x) { - if (this.circular) { - circs.push({ circ : this.circular, self : this, node : x }); - } - }); - - t.same(circs[0].self.path, [ 'x', 3, 2 ]); - t.same(circs[0].circ.path, []); - - t.same(circs[1].self.path, [ 'y', 2 ]); - t.same(circs[1].circ.path, []); - - t.same(circs.length, 2); - t.end(); -}); - -test('circDubForEach', function (t) { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - traverse(obj).forEach(function (x) { - if (this.circular) this.update('...'); - }); - - t.same(obj, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] }); - t.end(); -}); - -test('circDubMap', function (t) { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - var c = traverse(obj).map(function (x) { - if (this.circular) { - this.update('...'); - } - }); - - t.same(c, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] }); - t.end(); -}); - -test('circClone', function (t) { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - var clone = traverse.clone(obj); - t.ok(obj !== clone); - - t.ok(clone.y[2] === clone); - t.ok(clone.y[2] !== obj); - t.ok(clone.x[3][2] === clone); - t.ok(clone.x[3][2] !== obj); - t.same(clone.x.slice(0,3), [1,2,3]); - t.same(clone.y.slice(0,2), [4,5]); - t.end(); -}); - -test('circMapScrub', function (t) { - var obj = { a : 1, b : 2 }; - obj.c = obj; - - var scrubbed = traverse(obj).map(function (node) { - if (this.circular) this.remove(); - }); - t.same( - Object.keys(scrubbed).sort(), - [ 'a', 'b' ] - ); - t.ok(deepEqual(scrubbed, { a : 1, b : 2 })); - - t.equal(obj.c, obj); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/date.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/date.js deleted file mode 100644 index 6feb13f29..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/date.js +++ /dev/null @@ -1,37 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); - -test('dateEach', function (t) { - var obj = { x : new Date, y : 10, z : 5 }; - - var counts = {}; - - traverse(obj).forEach(function (node) { - var t = (node instanceof Date && 'Date') || typeof node; - counts[t] = (counts[t] || 0) + 1; - }); - - t.same(counts, { - object : 1, - Date : 1, - number : 2, - }); - t.end(); -}); - -test('dateMap', function (t) { - var obj = { x : new Date, y : 10, z : 5 }; - - var res = traverse(obj).map(function (node) { - if (typeof node === 'number') this.update(node + 100); - }); - - t.ok(obj.x !== res.x); - t.same(res, { - x : obj.x, - y : 110, - z : 105, - }); - t.end(); -}); - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/equal.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/equal.js deleted file mode 100644 index 169b696bc..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/equal.js +++ /dev/null @@ -1,240 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); -var deepEqual = require('./lib/deep_equal'); - -test('deepDates', function (t) { - t.plan(2); - - t.ok( - deepEqual( - { d : new Date, x : [ 1, 2, 3 ] }, - { d : new Date, x : [ 1, 2, 3 ] } - ), - 'dates should be equal' - ); - - var d0 = new Date; - setTimeout(function () { - t.ok( - !deepEqual( - { d : d0, x : [ 1, 2, 3 ], }, - { d : new Date, x : [ 1, 2, 3 ] } - ), - 'microseconds should count in date equality' - ); - }, 5); -}); - -test('deepCircular', function (t) { - var a = [1]; - a.push(a); // a = [ 1, *a ] - - var b = [1]; - b.push(a); // b = [ 1, [ 1, *a ] ] - - t.ok( - !deepEqual(a, b), - 'circular ref mount points count towards equality' - ); - - var c = [1]; - c.push(c); // c = [ 1, *c ] - t.ok( - deepEqual(a, c), - 'circular refs are structurally the same here' - ); - - var d = [1]; - d.push(a); // c = [ 1, [ 1, *d ] ] - t.ok( - deepEqual(b, d), - 'non-root circular ref structural comparison' - ); - - t.end(); -}); - -test('deepInstances', function (t) { - t.ok( - !deepEqual([ new Boolean(false) ], [ false ]), - 'boolean instances are not real booleans' - ); - - t.ok( - !deepEqual([ new String('x') ], [ 'x' ]), - 'string instances are not real strings' - ); - - t.ok( - !deepEqual([ new Number(4) ], [ 4 ]), - 'number instances are not real numbers' - ); - - t.ok( - deepEqual([ new RegExp('x') ], [ /x/ ]), - 'regexp instances are real regexps' - ); - - t.ok( - !deepEqual([ new RegExp(/./) ], [ /../ ]), - 'these regexps aren\'t the same' - ); - - t.ok( - !deepEqual( - [ function (x) { return x * 2 } ], - [ function (x) { return x * 2 } ] - ), - 'functions with the same .toString() aren\'t necessarily the same' - ); - - var f = function (x) { return x * 2 }; - t.ok( - deepEqual([ f ], [ f ]), - 'these functions are actually equal' - ); - - t.end(); -}); - -test('deepEqual', function (t) { - t.ok( - !deepEqual([ 1, 2, 3 ], { 0 : 1, 1 : 2, 2 : 3 }), - 'arrays are not objects' - ); - t.end(); -}); - -test('falsy', function (t) { - t.ok( - !deepEqual([ undefined ], [ null ]), - 'null is not undefined!' - ); - - t.ok( - !deepEqual([ null ], [ undefined ]), - 'undefined is not null!' - ); - - t.ok( - !deepEqual( - { a : 1, b : 2, c : [ 3, undefined, 5 ] }, - { a : 1, b : 2, c : [ 3, null, 5 ] } - ), - 'undefined is not null, however deeply!' - ); - - t.ok( - !deepEqual( - { a : 1, b : 2, c : [ 3, undefined, 5 ] }, - { a : 1, b : 2, c : [ 3, null, 5 ] } - ), - 'null is not undefined, however deeply!' - ); - - t.ok( - !deepEqual( - { a : 1, b : 2, c : [ 3, undefined, 5 ] }, - { a : 1, b : 2, c : [ 3, null, 5 ] } - ), - 'null is not undefined, however deeply!' - ); - - t.end(); -}); - -test('deletedArrayEqual', function (t) { - var xs = [ 1, 2, 3, 4 ]; - delete xs[2]; - - var ys = Object.create(Array.prototype); - ys[0] = 1; - ys[1] = 2; - ys[3] = 4; - - t.ok( - deepEqual(xs, ys), - 'arrays with deleted elements are only equal to' - + ' arrays with similarly deleted elements' - ); - - t.ok( - !deepEqual(xs, [ 1, 2, undefined, 4 ]), - 'deleted array elements cannot be undefined' - ); - - t.ok( - !deepEqual(xs, [ 1, 2, null, 4 ]), - 'deleted array elements cannot be null' - ); - - t.end(); -}); - -test('deletedObjectEqual', function (t) { - var obj = { a : 1, b : 2, c : 3 }; - delete obj.c; - - t.ok( - deepEqual(obj, { a : 1, b : 2 }), - 'deleted object elements should not show up' - ); - - t.ok( - !deepEqual(obj, { a : 1, b : 2, c : undefined }), - 'deleted object elements are not undefined' - ); - - t.ok( - !deepEqual(obj, { a : 1, b : 2, c : null }), - 'deleted object elements are not null' - ); - - t.end(); -}); - -test('emptyKeyEqual', function (t) { - t.ok(!deepEqual( - { a : 1 }, { a : 1, '' : 55 } - )); - - t.end(); -}); - -test('deepArguments', function (t) { - t.ok( - !deepEqual( - [ 4, 5, 6 ], - (function () { return arguments })(4, 5, 6) - ), - 'arguments are not arrays' - ); - - t.ok( - deepEqual( - (function () { return arguments })(4, 5, 6), - (function () { return arguments })(4, 5, 6) - ), - 'arguments should equal' - ); - - t.end(); -}); - -test('deepUn', function (t) { - t.ok(!deepEqual({ a : 1, b : 2 }, undefined)); - t.ok(!deepEqual({ a : 1, b : 2 }, {})); - t.ok(!deepEqual(undefined, { a : 1, b : 2 })); - t.ok(!deepEqual({}, { a : 1, b : 2 })); - t.ok(deepEqual(undefined, undefined)); - t.ok(deepEqual(null, null)); - t.ok(!deepEqual(undefined, null)); - - t.end(); -}); - -test('deepLevels', function (t) { - var xs = [ 1, 2, [ 3, 4, [ 5, 6 ] ] ]; - t.ok(!deepEqual(xs, [])); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/error.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/error.js deleted file mode 100644 index 6d3b44a98..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/error.js +++ /dev/null @@ -1,11 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); - -test('traverse an Error', function (t) { - var obj = new Error("test"); - var results = traverse(obj).map(function (node) {}); - t.same(results, { message: 'test' }); - - t.end(); -}); - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/has.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/has.js deleted file mode 100644 index cc1a2e70c..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/has.js +++ /dev/null @@ -1,15 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); - -test('has', function (t) { - var obj = { a : 2, b : [ 4, 5, { c : 6 } ] }; - - t.equal(traverse(obj).has([ 'b', 2, 'c' ]), true) - t.equal(traverse(obj).has([ 'b', 2, 'c', 0 ]), false) - t.equal(traverse(obj).has([ 'b', 2, 'd' ]), false) - t.equal(traverse(obj).has([]), true) - t.equal(traverse(obj).has([ 'a' ]), true) - t.equal(traverse(obj).has([ 'a', 2 ]), false) - - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/instance.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/instance.js deleted file mode 100644 index 165bc7149..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/instance.js +++ /dev/null @@ -1,17 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); -var EventEmitter = require('events').EventEmitter; - -test('check instanceof on node elems', function (t) { - var counts = { emitter : 0 }; - - traverse([ new EventEmitter, 3, 4, { ev : new EventEmitter }]) - .forEach(function (node) { - if (node instanceof EventEmitter) counts.emitter ++; - }) - ; - - t.equal(counts.emitter, 2); - - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/interface.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/interface.js deleted file mode 100644 index 7a7fda2dd..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/interface.js +++ /dev/null @@ -1,43 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); - -test('interface map', function (t) { - var obj = { a : [ 5,6,7 ], b : { c : [8] } }; - - t.same( - traverse.paths(obj) - .sort() - .map(function (path) { return path.join('/') }) - .slice(1) - .join(' ') - , - 'a a/0 a/1 a/2 b b/c b/c/0' - ); - - t.same( - traverse.nodes(obj), - [ - { a: [ 5, 6, 7 ], b: { c: [ 8 ] } }, - [ 5, 6, 7 ], 5, 6, 7, - { c: [ 8 ] }, [ 8 ], 8 - ] - ); - - t.same( - traverse.map(obj, function (node) { - if (typeof node == 'number') { - return node + 1000; - } - else if (Array.isArray(node)) { - return node.join(' '); - } - }), - { a: '5 6 7', b: { c: '8' } } - ); - - var nodes = 0; - traverse.forEach(obj, function (node) { nodes ++ }); - t.same(nodes, 8); - - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/json.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/json.js deleted file mode 100644 index 2ab3ac456..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/json.js +++ /dev/null @@ -1,49 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); - -test('json test', function (t) { - var id = 54; - var callbacks = {}; - var obj = { moo : function () {}, foo : [2,3,4, function () {}] }; - - var scrubbed = traverse(obj).map(function (x) { - if (typeof x === 'function') { - callbacks[id] = { id : id, f : x, path : this.path }; - this.update('[Function]'); - id++; - } - }); - - t.equal( - scrubbed.moo, '[Function]', - 'obj.moo replaced with "[Function]"' - ); - - t.equal( - scrubbed.foo[3], '[Function]', - 'obj.foo[3] replaced with "[Function]"' - ); - - t.same(scrubbed, { - moo : '[Function]', - foo : [ 2, 3, 4, "[Function]" ] - }, 'Full JSON string matches'); - - t.same( - typeof obj.moo, 'function', - 'Original obj.moo still a function' - ); - - t.same( - typeof obj.foo[3], 'function', - 'Original obj.foo[3] still a function' - ); - - t.same(callbacks, { - 54: { id: 54, f : obj.moo, path: [ 'moo' ] }, - 55: { id: 55, f : obj.foo[3], path: [ 'foo', '3' ] }, - }, 'Check the generated callbacks list'); - - t.end(); -}); - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/keys.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/keys.js deleted file mode 100644 index b36bcbb0f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/keys.js +++ /dev/null @@ -1,31 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); - -test('sort test', function (t) { - var acc = []; - traverse({ - a: 30, - b: 22, - id: 9 - }).forEach(function (node) { - if ((! Array.isArray(node)) && typeof node === 'object') { - this.before(function(node) { - this.keys = Object.keys(node); - this.keys.sort(function(a, b) { - a = [a === "id" ? 0 : 1, a]; - b = [b === "id" ? 0 : 1, b]; - return a < b ? -1 : a > b ? 1 : 0; - }); - }); - } - if (this.isLeaf) acc.push(node); - }); - - t.equal( - acc.join(' '), - '9 30 22', - 'Traversal in a custom order' - ); - - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/leaves.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/leaves.js deleted file mode 100644 index 71e45298f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/leaves.js +++ /dev/null @@ -1,22 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); - -test('leaves test', function (t) { - var acc = []; - traverse({ - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 } - }).forEach(function (x) { - if (this.isLeaf) acc.push(x); - }); - - t.equal( - acc.join(' '), - '1 2 3 4 5 6 7 8 9', - 'Traversal in the right(?) order' - ); - - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/lib/deep_equal.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/lib/deep_equal.js deleted file mode 100644 index c75b04c2d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/lib/deep_equal.js +++ /dev/null @@ -1,96 +0,0 @@ -var traverse = require('../../'); - -module.exports = function (a, b) { - if (arguments.length !== 2) { - throw new Error( - 'deepEqual requires exactly two objects to compare against' - ); - } - - var equal = true; - var node = b; - - traverse(a).forEach(function (y) { - var notEqual = (function () { - equal = false; - //this.stop(); - return undefined; - }).bind(this); - - //if (node === undefined || node === null) return notEqual(); - - if (!this.isRoot) { - /* - if (!Object.hasOwnProperty.call(node, this.key)) { - return notEqual(); - } - */ - if (typeof node !== 'object') return notEqual(); - node = node[this.key]; - } - - var x = node; - - this.post(function () { - node = x; - }); - - var toS = function (o) { - return Object.prototype.toString.call(o); - }; - - if (this.circular) { - if (traverse(b).get(this.circular.path) !== x) notEqual(); - } - else if (typeof x !== typeof y) { - notEqual(); - } - else if (x === null || y === null || x === undefined || y === undefined) { - if (x !== y) notEqual(); - } - else if (x.__proto__ !== y.__proto__) { - notEqual(); - } - else if (x === y) { - // nop - } - else if (typeof x === 'function') { - if (x instanceof RegExp) { - // both regexps on account of the __proto__ check - if (x.toString() != y.toString()) notEqual(); - } - else if (x !== y) notEqual(); - } - else if (typeof x === 'object') { - if (toS(y) === '[object Arguments]' - || toS(x) === '[object Arguments]') { - if (toS(x) !== toS(y)) { - notEqual(); - } - } - else if (toS(y) === '[object RegExp]' - || toS(x) === '[object RegExp]') { - if (!x || !y || x.toString() !== y.toString()) notEqual(); - } - else if (x instanceof Date || y instanceof Date) { - if (!(x instanceof Date) || !(y instanceof Date) - || x.getTime() !== y.getTime()) { - notEqual(); - } - } - else { - var kx = Object.keys(x); - var ky = Object.keys(y); - if (kx.length !== ky.length) return notEqual(); - for (var i = 0; i < kx.length; i++) { - var k = kx[i]; - if (!Object.hasOwnProperty.call(y, k)) { - notEqual(); - } - } - } - } - }); - - return equal; -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/mutability.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/mutability.js deleted file mode 100644 index 30761a7f6..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/mutability.js +++ /dev/null @@ -1,300 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); -var deepEqual = require('./lib/deep_equal'); - -test('mutate', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = traverse(obj).forEach(function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - t.same(obj, res); - t.same(obj, { a : 1, b : 20, c : [ 3, 40 ] }); - t.end(); -}); - -test('mutateT', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = traverse.forEach(obj, function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - t.same(obj, res); - t.same(obj, { a : 1, b : 20, c : [ 3, 40 ] }); - t.end(); -}); - -test('map', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = traverse(obj).map(function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - t.same(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - t.same(res, { a : 1, b : 20, c : [ 3, 40 ] }); - t.end(); -}); - -test('mapT', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = traverse.map(obj, function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - t.same(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - t.same(res, { a : 1, b : 20, c : [ 3, 40 ] }); - t.end(); -}); - -test('clone', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = traverse(obj).clone(); - t.same(obj, res); - t.ok(obj !== res); - obj.a ++; - t.same(res.a, 1); - obj.c.push(5); - t.same(res.c, [ 3, 4 ]); - t.end(); -}); - -test('cloneT', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = traverse.clone(obj); - t.same(obj, res); - t.ok(obj !== res); - obj.a ++; - t.same(res.a, 1); - obj.c.push(5); - t.same(res.c, [ 3, 4 ]); - t.end(); -}); - -test('reduce', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = traverse(obj).reduce(function (acc, x) { - if (this.isLeaf) acc.push(x); - return acc; - }, []); - t.same(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - t.same(res, [ 1, 2, 3, 4 ]); - t.end(); -}); - -test('reduceInit', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = traverse(obj).reduce(function (acc, x) { - if (this.isRoot) assert.fail('got root'); - return acc; - }); - t.same(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - t.same(res, obj); - t.end(); -}); - -test('remove', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - traverse(obj).forEach(function (x) { - if (this.isLeaf && x % 2 == 0) this.remove(); - }); - - t.same(obj, { a : 1, c : [ 3 ] }); - t.end(); -}); - -exports.removeNoStop = function() { - var obj = { a : 1, b : 2, c : { d: 3, e: 4 }, f: 5 }; - - var keys = []; - traverse(obj).forEach(function (x) { - keys.push(this.key) - if (this.key == 'c') this.remove(); - }); - - t.same(keys, [undefined, 'a', 'b', 'c', 'd', 'e', 'f']) - t.end(); -} - -exports.removeStop = function() { - var obj = { a : 1, b : 2, c : { d: 3, e: 4 }, f: 5 }; - - var keys = []; - traverse(obj).forEach(function (x) { - keys.push(this.key) - if (this.key == 'c') this.remove(true); - }); - - t.same(keys, [undefined, 'a', 'b', 'c', 'f']) - t.end(); -} - -test('removeMap', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = traverse(obj).map(function (x) { - if (this.isLeaf && x % 2 == 0) this.remove(); - }); - - t.same(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - t.same(res, { a : 1, c : [ 3 ] }); - t.end(); -}); - -test('delete', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - traverse(obj).forEach(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - t.ok(!deepEqual( - obj, { a : 1, c : [ 3, undefined ] } - )); - - t.ok(deepEqual( - obj, { a : 1, c : [ 3 ] } - )); - - t.ok(!deepEqual( - obj, { a : 1, c : [ 3, null ] } - )); - t.end(); -}); - -test('deleteNoStop', function (t) { - var obj = { a : 1, b : 2, c : { d: 3, e: 4 } }; - - var keys = []; - traverse(obj).forEach(function (x) { - keys.push(this.key) - if (this.key == 'c') this.delete(); - }); - - t.same(keys, [undefined, 'a', 'b', 'c', 'd', 'e']) - t.end(); -}); - -test('deleteStop', function (t) { - var obj = { a : 1, b : 2, c : { d: 3, e: 4 } }; - - var keys = []; - traverse(obj).forEach(function (x) { - keys.push(this.key) - if (this.key == 'c') this.delete(true); - }); - - t.same(keys, [undefined, 'a', 'b', 'c']) - t.end(); -}); - -test('deleteRedux', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4, 5 ] }; - traverse(obj).forEach(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - t.ok(!deepEqual( - obj, { a : 1, c : [ 3, undefined, 5 ] } - )); - - t.ok(deepEqual( - obj, { a : 1, c : [ 3 ,, 5 ] } - )); - - t.ok(!deepEqual( - obj, { a : 1, c : [ 3, null, 5 ] } - )); - - t.ok(!deepEqual( - obj, { a : 1, c : [ 3, 5 ] } - )); - - t.end(); -}); - -test('deleteMap', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = traverse(obj).map(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - t.ok(deepEqual( - obj, - { a : 1, b : 2, c : [ 3, 4 ] } - )); - - var xs = [ 3, 4 ]; - delete xs[1]; - - t.ok(deepEqual( - res, { a : 1, c : xs } - )); - - t.ok(deepEqual( - res, { a : 1, c : [ 3, ] } - )); - - t.ok(deepEqual( - res, { a : 1, c : [ 3 ] } - )); - - t.end(); -}); - -test('deleteMapRedux', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4, 5 ] }; - var res = traverse(obj).map(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - t.ok(deepEqual( - obj, - { a : 1, b : 2, c : [ 3, 4, 5 ] } - )); - - var xs = [ 3, 4, 5 ]; - delete xs[1]; - - t.ok(deepEqual( - res, { a : 1, c : xs } - )); - - t.ok(!deepEqual( - res, { a : 1, c : [ 3, 5 ] } - )); - - t.ok(deepEqual( - res, { a : 1, c : [ 3 ,, 5 ] } - )); - - t.end(); -}); - -test('objectToString', function (t) { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = traverse(obj).forEach(function (x) { - if (typeof x === 'object' && !this.isRoot) { - this.update(JSON.stringify(x)); - } - }); - t.same(obj, res); - t.same(obj, { a : 1, b : 2, c : "[3,4]" }); - t.end(); -}); - -test('stringToObject', function (t) { - var obj = { a : 1, b : 2, c : "[3,4]" }; - var res = traverse(obj).forEach(function (x) { - if (typeof x === 'string') { - this.update(JSON.parse(x)); - } - else if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - t.deepEqual(obj, res); - t.deepEqual(obj, { a : 1, b : 20, c : [ 3, 40 ] }); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/negative.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/negative.js deleted file mode 100644 index fdd1cc558..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/negative.js +++ /dev/null @@ -1,21 +0,0 @@ -var traverse = require('../'); -var test = require('tap').test; - -test('negative update test', function (t) { - var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - var fixed = traverse.map(obj, function (x) { - if (x < 0) this.update(x + 128); - }); - - t.same(fixed, - [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ], - 'Negative values += 128' - ); - - t.same(obj, - [ 5, 6, -3, [ 7, 8, -2, 1 ], { f: 10, g: -13 } ], - 'Original references not modified' - ); - - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/obj.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/obj.js deleted file mode 100644 index 7f0cb709b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/obj.js +++ /dev/null @@ -1,11 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); - -test('traverse an object with nested functions', function (t) { - t.plan(1); - - function Cons (x) { - t.equal(x, 10) - }; - traverse(new Cons(10)); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/siblings.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/siblings.js deleted file mode 100644 index cdfbd7d0e..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/siblings.js +++ /dev/null @@ -1,37 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); - -test('siblings', function (t) { - var obj = { a : 1, b : 2, c : [ 4, 5, 6 ] }; - - var res = traverse(obj).reduce(function (acc, x) { - var p = '/' + this.path.join('/'); - if (this.parent) { - acc[p] = { - siblings : this.parent.keys, - key : this.key, - index : this.parent.keys.indexOf(this.key) - }; - } - else { - acc[p] = { - siblings : [], - key : this.key, - index : -1 - } - } - return acc; - }, {}); - - t.same(res, { - '/' : { siblings : [], key : undefined, index : -1 }, - '/a' : { siblings : [ 'a', 'b', 'c' ], key : 'a', index : 0 }, - '/b' : { siblings : [ 'a', 'b', 'c' ], key : 'b', index : 1 }, - '/c' : { siblings : [ 'a', 'b', 'c' ], key : 'c', index : 2 }, - '/c/0' : { siblings : [ '0', '1', '2' ], key : '0', index : 0 }, - '/c/1' : { siblings : [ '0', '1', '2' ], key : '1', index : 1 }, - '/c/2' : { siblings : [ '0', '1', '2' ], key : '2', index : 2 } - }); - - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/stop.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/stop.js deleted file mode 100644 index ecf38e48e..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/stop.js +++ /dev/null @@ -1,44 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); - -test('stop', function (t) { - var visits = 0; - traverse('abcdefghij'.split('')).forEach(function (node) { - if (typeof node === 'string') { - visits ++; - if (node === 'e') this.stop() - } - }); - - t.equal(visits, 5); - t.end(); -}); - -test('stopMap', function (t) { - var s = traverse('abcdefghij'.split('')).map(function (node) { - if (typeof node === 'string') { - if (node === 'e') this.stop() - return node.toUpperCase(); - } - }).join(''); - - t.equal(s, 'ABCDEfghij'); - t.end(); -}); - -test('stopReduce', function (t) { - var obj = { - a : [ 4, 5 ], - b : [ 6, [ 7, 8, 9 ] ] - }; - var xs = traverse(obj).reduce(function (acc, node) { - if (this.isLeaf) { - if (node === 7) this.stop(); - else acc.push(node) - } - return acc; - }, []); - - t.same(xs, [ 4, 5, 6 ]); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/stringify.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/stringify.js deleted file mode 100644 index 862598de2..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/stringify.js +++ /dev/null @@ -1,36 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); - -test('stringify', function (t) { - var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - - var s = ''; - traverse(obj).forEach(function (node) { - if (Array.isArray(node)) { - this.before(function () { s += '[' }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += ']' }); - } - else if (typeof node == 'object') { - this.before(function () { s += '{' }); - this.pre(function (x, key) { - s += '"' + key + '"' + ':'; - }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += '}' }); - } - else if (typeof node == 'function') { - s += 'null'; - } - else { - s += node.toString(); - } - }); - - t.equal(s, JSON.stringify(obj)); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/subexpr.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/subexpr.js deleted file mode 100644 index c372bf397..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/subexpr.js +++ /dev/null @@ -1,36 +0,0 @@ -var traverse = require('../'); -var test = require('tap').test; - -test('subexpr', function (t) { - var obj = [ 'a', 4, 'b', 5, 'c', 6 ]; - var r = traverse(obj).map(function (x) { - if (typeof x === 'number') { - this.update([ x - 0.1, x, x + 0.1 ], true); - } - }); - - t.same(obj, [ 'a', 4, 'b', 5, 'c', 6 ]); - t.same(r, [ - 'a', [ 3.9, 4, 4.1 ], - 'b', [ 4.9, 5, 5.1 ], - 'c', [ 5.9, 6, 6.1 ], - ]); - t.end(); -}); - -test('block', function (t) { - var obj = [ [ 1 ], [ 2 ], [ 3 ] ]; - var r = traverse(obj).map(function (x) { - if (Array.isArray(x) && !this.isRoot) { - if (x[0] === 5) this.block() - else this.update([ [ x[0] + 1 ] ]) - } - }); - - t.same(r, [ - [ [ [ [ [ 5 ] ] ] ] ], - [ [ [ [ 5 ] ] ] ], - [ [ [ 5 ] ] ], - ]); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/super_deep.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/super_deep.js deleted file mode 100644 index 088f890f1..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/test/super_deep.js +++ /dev/null @@ -1,56 +0,0 @@ -var test = require('tap').test; -var traverse = require('../'); -var deepEqual = require('./lib/deep_equal'); - -test('super_deep', function (t) { - var util = require('util'); - var a0 = make(); - var a1 = make(); - t.ok(deepEqual(a0, a1)); - - a0.c.d.moo = true; - t.ok(!deepEqual(a0, a1)); - - a1.c.d.moo = true; - t.ok(deepEqual(a0, a1)); - - // TODO: this one - //a0.c.a = a1; - //t.ok(!deepEqual(a0, a1)); - t.end(); -}); - -function make () { - var a = { self : 'a' }; - var b = { self : 'b' }; - var c = { self : 'c' }; - var d = { self : 'd' }; - var e = { self : 'e' }; - - a.a = a; - a.b = b; - a.c = c; - - b.a = a; - b.b = b; - b.c = c; - - c.a = a; - c.b = b; - c.c = c; - c.d = d; - - d.a = a; - d.b = b; - d.c = c; - d.d = d; - d.e = e; - - e.a = a; - e.b = b; - e.c = c; - e.d = d; - e.e = e; - - return a; -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/testling/leaves.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/testling/leaves.js deleted file mode 100644 index 29968dd13..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/node_modules/traverse/testling/leaves.js +++ /dev/null @@ -1,22 +0,0 @@ -var traverse = require('./'); -var test = require('testling'); - -test('leaves', function (t) { - var obj = { - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 } - }; - - var acc = []; - traverse(obj).forEach(function (x) { - if (this.isLeaf) acc.push(x); - }); - - t.deepEqual( - acc, [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ], - 'traversal in the proper order' - ); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/package.json deleted file mode 100644 index 56273c6b9..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "difflet", - "description": "colorful diffs for javascript objects", - "version": "0.2.5", - "repository": { - "type": "git", - "url": "git://github.com/substack/difflet.git" - }, - "main": "index.js", - "keywords": [ - "diff", - "object", - "compare" - ], - "directories": { - "lib": ".", - "example": "example", - "test": "test" - }, - "scripts": { - "test": "tap test/*.js" - }, - "dependencies": { - "traverse": "0.6.x", - "charm": "0.0.x", - "deep-is": "0.1.x" - }, - "devDependencies": { - "tap": "0.1.x", - "ent": "0.0.x" - }, - "engines": { - "node": ">=0.4.0" - }, - "license": "MIT", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "readme": "difflet\n=======\n\nCreate colorful diffs for javascript objects.\n\nexample\n=======\n\nstring.js\n---------\n\n``` js\nvar difflet = require('difflet');\n\nvar s = difflet.compare({ a : 2, c : 5 }, { a : 3, b : 4 });\nprocess.stdout.write(s);\n```\n\noutput:\n\n![colorful output](http://substack.net/images/screenshots/difflet_string.png)\n\ncolors.js\n---------\n\n``` js\nvar diff = require('difflet')({ indent : 2 });\n\nvar prev = {\n yy : 6,\n zz : 5,\n a : [1,2,3],\n fn : 'beep',\n c : { x : 7, z : 3 }\n};\n\nvar next = {\n a : [ 1, 2, \"z\", /beep/, new Buffer(3) ],\n fn : function qqq () {},\n b : [5,6,7],\n c : { x : 8, y : 5 }\n};\n\ndiff(prev, next).pipe(process.stdout);\n```\n\noutput:\n\n![colorful output](http://substack.net/images/screenshots/difflet_colors.png)\n\ngreen for inserts, blue for updates, red for deletes\n\nmethods\n=======\n\nvar difflet = require('difflet')\n\nvar diff = difflet(opts={})\n---------------------------\n\nCreate a difflet from optional options `opts`.\n\nWith `opts.start(type, stream)` and `opts.stop(type, stream)`,\nyou can write custom handlers for all the types of differences:\n`'inserted'`, `'updated'`, and `'deleted'`.\nBy default green is used for insertions, blue for updates, and red for\ndeletions.\n\nIf `opts.indent` is set, output will span multiple lines and `opts.indent`\nspaces will be used for leading whitespace.\n\nIf `opts.comma === 'first'` then commas will be placed at the start of lines.\n\nSetting `opts.comment` to `true` will turn on comments with the previous\ncontents like this:\n\n![object comments](http://substack.net/images/screenshots/difflet_object_comments.png)\n\ndiff(prev, next)\n----------------\n\nReturn a stream with the colorful changes between objects `prev` and `next`.\n\ndiff.compare(prev, next)\n------------------------\n\nReturn a string with the colorful changes between `prev` and `next`.\n\ndifflet.compare(prev, next)\n---------------------------\n\nReturn a string with the colorful changes between `prev` and `next` with the\ndefault options.\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install difflet\n```\n\ntest\n====\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm test\n```\n\nlicense\n=======\n\nMIT/X11\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/substack/difflet/issues" - }, - "_id": "difflet@0.2.5", - "_from": "difflet@~0.2.0" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/test/diffing-NaN.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/test/diffing-NaN.js deleted file mode 100644 index d29e6e195..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/test/diffing-NaN.js +++ /dev/null @@ -1,17 +0,0 @@ -var difflet = require('../'); -var diff = difflet(); -var test = require('tap').test; - -test('diffing NaN against NaN', function (t) { - t.plan(1); - var d = diff.compare(NaN, NaN); - - t.equal(d, 'NaN'); -}); - -test('diffing { o: NaN } against { o: NaN }', function (t) { - t.plan(1); - var d = diff.compare({ o: NaN }, { o: NaN }); - - t.equal(d, '{"o":NaN}'); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/test/html.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/test/html.js deleted file mode 100644 index 26d2ed418..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/difflet/test/html.js +++ /dev/null @@ -1,80 +0,0 @@ -var difflet = require('../'); -var test = require('tap').test; -var ent = require('ent'); - -var tags = { - inserted : 'g', - updated : 'b', - deleted : 'r', -}; - -test('html output', function (t) { - t.plan(1); - var diff = difflet({ - start : function (t, s) { - s.write('<' + tags[t] + '>'); - }, - stop : function (t, s) { - s.write(''); - }, - write : function (buf, s) { - s.write(ent.encode(buf)); - } - }); - - var stream = diff( - { yy : 6, zz : 5, a : [1,2,3], fn : function qqq () {} }, - { - a : [ 1, 2, 3, [4], "z", /beep/, new Buffer([0,1,2]) ], - fn : function rrr () {}, - b : [5,6,7] - } - ); - - var data = '' - stream.on('data', function (buf) { data += buf }); - stream.on('end', function () { - t.equal(data, - '{"a":[1,2,3,[4],"z",' - + '/beep/,<Buffer 00 01 02>],' - + '"fn":[Function: rrr],' - + '"b":[5,6,7],"yy":6,' - + '"zz":5}' - ); - t.end(); - }); -}); - -test('compare html output', function (t) { - t.plan(1); - - var diff = difflet({ - start : function (t, s) { - s.write('<' + tags[t] + '>'); - }, - stop : function (t, s) { - s.write(''); - }, - write : function (buf, s) { - s.write(ent.encode(buf)); - } - }); - - var data = diff.compare( - { yy : 6, zz : 5, a : [1,2,3], fn : function qqq () {} }, - { - a : [ 1, 2, 3, [4], "z", /beep/, new Buffer([0,1,2]) ], - fn : function rrr () {}, - b : [5,6,7] - } - ); - - t.equal(data, - '{"a":[1,2,3,[4],"z",' - + '/beep/,<Buffer 00 01 02>],' - + '"fn":[Function: rrr],' - + '"b":[5,6,7],"yy":6,' - + '"zz":5}' - ); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/README.md b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/README.md deleted file mode 100644 index cc6916451..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/glob.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/glob.js deleted file mode 100644 index f0118a4f4..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/graceful-fs/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/graceful-fs/package.json deleted file mode 100644 index 03f91c912..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/graceful-fs/package.json +++ /dev/null @@ -1,48 +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": "1.2.1", - "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", - "readme": "# graceful-fs\n\ngraceful-fs functions as a drop-in replacement for the fs module,\nmaking various improvements.\n\nThe improvements are meant to normalize behavior across different\nplatforms and environments, and to make filesystem access more\nresilient to errors.\n\n## Improvements over fs module\n\ngraceful-fs:\n\n* keeps track of how many file descriptors are open, and by default\n limits this to 1024. Any further requests to open a file are put in a\n queue until new slots become available. If 1024 turns out to be too\n much, it decreases the limit further.\n* fixes `lchmod` for Node versions prior to 0.6.2.\n* implements `fs.lutimes` if possible. Otherwise it becomes a noop.\n* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or\n `lchown` if the user isn't root.\n* makes `lchmod` and `lchown` become noops, if not available.\n* retries reading a file if `read` results in EAGAIN error.\n\nOn Windows, it retries renaming a file for up to one second if `EACCESS`\nor `EPERM` error occurs, likely because antivirus software has locked\nthe directory.\n\n## Configuration\n\nThe maximum number of open file descriptors that graceful-fs manages may\nbe adjusted by setting `fs.MAX_OPEN` to a different number. The default\nis 1024.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/node-graceful-fs/issues" - }, - "_id": "graceful-fs@1.2.1", - "_from": "graceful-fs@~1.2.0" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/inherits/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/inherits/package.json deleted file mode 100644 index aae88dbbf..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/inherits/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "inherits", - "description": "A tiny simple way to do classic inheritance in js", - "version": "1.0.0", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented" - ], - "main": "./inherits.js", - "repository": { - "type": "git", - "url": "https://github.com/isaacs/inherits" - }, - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "readme": "A dead simple way to do inheritance in JS.\n\n var inherits = require(\"inherits\")\n\n function Animal () {\n this.alive = true\n }\n Animal.prototype.say = function (what) {\n console.log(what)\n }\n\n inherits(Dog, Animal)\n function Dog () {\n Dog.super.apply(this)\n }\n Dog.prototype.sniff = function () {\n this.say(\"sniff sniff\")\n }\n Dog.prototype.bark = function () {\n this.say(\"woof woof\")\n }\n\n inherits(Chihuahua, Dog)\n function Chihuahua () {\n Chihuahua.super.apply(this)\n }\n Chihuahua.prototype.bark = function () {\n this.say(\"yip yip\")\n }\n\n // also works\n function Cat () {\n Cat.super.apply(this)\n }\n Cat.prototype.hiss = function () {\n this.say(\"CHSKKSS!!\")\n }\n inherits(Cat, Animal, {\n meow: function () { this.say(\"miao miao\") }\n })\n Cat.prototype.purr = function () {\n this.say(\"purr purr\")\n }\n\n\n var c = new Chihuahua\n assert(c instanceof Chihuahua)\n assert(c instanceof Dog)\n assert(c instanceof Animal)\n\nThe actual function is laughably small. 10-lines small.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/inherits/issues" - }, - "_id": "inherits@1.0.0", - "_from": "inherits@1", - "scripts": {} -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json deleted file mode 100644 index 73920bf2a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/lru-cache/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "lru-cache", - "description": "A cache object that deletes the least-recently-used items.", - "version": "2.3.0", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me" - }, - "scripts": { - "test": "tap test --gc" - }, - "main": "lib/lru-cache.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/node-lru-cache.git" - }, - "devDependencies": { - "tap": "", - "weak": "" - }, - "license": { - "type": "MIT", - "url": "http://github.com/isaacs/node-lru-cache/raw/master/LICENSE" - }, - "contributors": [ - { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me" - }, - { - "name": "Carlos Brito Lage", - "email": "carlos@carloslage.net" - }, - { - "name": "Marko Mikulicic", - "email": "marko.mikulicic@isti.cnr.it" - }, - { - "name": "Trent Mick", - "email": "trentm@gmail.com" - }, - { - "name": "Kevin O'Hara", - "email": "kevinohara80@gmail.com" - }, - { - "name": "Marco Rogers", - "email": "marco.rogers@gmail.com" - }, - { - "name": "Jesse Dailey", - "email": "jesse.dailey@gmail.com" - } - ], - "readme": "# lru cache\n\nA cache object that deletes the least-recently-used items.\n\n## Usage:\n\n```javascript\nvar LRU = require(\"lru-cache\")\n , options = { max: 500\n , length: function (n) { return n * 2 }\n , dispose: function (key, n) { n.close() }\n , maxAge: 1000 * 60 * 60 }\n , cache = LRU(options)\n , otherCache = LRU(50) // sets just the max size\n\ncache.set(\"key\", \"value\")\ncache.get(\"key\") // \"value\"\n\ncache.reset() // empty the cache\n```\n\nIf you put more stuff in it, then items will fall out.\n\nIf you try to put an oversized thing in it, then it'll fall out right\naway.\n\n## Options\n\n* `max` The maximum size of the cache, checked by applying the length\n function to all values in the cache. Not setting this is kind of\n silly, since that's the whole purpose of this lib, but it defaults\n to `Infinity`.\n* `maxAge` Maximum age in ms. Items are not pro-actively pruned out\n as they age, but if you try to get an item that is too old, it'll\n drop it and return undefined instead of giving it to you.\n* `length` Function that is used to calculate the length of stored\n items. If you're storing strings or buffers, then you probably want\n to do something like `function(n){return n.length}`. The default is\n `function(n){return 1}`, which is fine if you want to store `n`\n like-sized things.\n* `dispose` Function that is called on items when they are dropped\n from the cache. This can be handy if you want to close file\n descriptors or do other cleanup tasks when items are no longer\n accessible. Called with `key, value`. It's called *before*\n actually removing the item from the internal cache, so if you want\n to immediately put it back in, you'll have to do that in a\n `nextTick` or `setTimeout` callback or it won't do anything.\n* `stale` By default, if you set a `maxAge`, it'll only actually pull\n stale items out of the cache when you `get(key)`. (That is, it's\n not pre-emptively doing a `setTimeout` or anything.) If you set\n `stale:true`, it'll return the stale value before deleting it. If\n you don't set this, then it'll return `undefined` when you try to\n get a stale entry, as if it had already been deleted.\n\n## API\n\n* `set(key, value)`\n* `get(key) => value`\n\n Both of these will update the \"recently used\"-ness of the key.\n They do what you think.\n\n* `peek(key)`\n\n Returns the key value (or `undefined` if not found) without\n updating the \"recently used\"-ness of the key.\n\n (If you find yourself using this a lot, you *might* be using the\n wrong sort of data structure, but there are some use cases where\n it's handy.)\n\n* `del(key)`\n\n Deletes a key out of the cache.\n\n* `reset()`\n\n Clear the cache entirely, throwing away all values.\n\n* `has(key)`\n\n Check if a key is in the cache, without updating the recent-ness\n or deleting it for being stale.\n\n* `forEach(function(value,key,cache), [thisp])`\n\n Just like `Array.prototype.forEach`. Iterates over all the keys\n in the cache, in order of recent-ness. (Ie, more recently used\n items are iterated over first.)\n\n* `keys()`\n\n Return an array of the keys in the cache.\n\n* `values()`\n\n Return an array of the values in the cache.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/node-lru-cache/issues" - }, - "_id": "lru-cache@2.3.0", - "_from": "lru-cache@2" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json deleted file mode 100644 index ec8e2eb3e..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/node_modules/sigmund/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "sigmund", - "version": "1.0.0", - "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" - }, - "keywords": [ - "object", - "signature", - "key", - "data", - "psychoanalysis" - ], - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "BSD", - "readme": "# sigmund\n\nQuick and dirty signatures for Objects.\n\nThis is like a much faster `deepEquals` comparison, which returns a\nstring key suitable for caches and the like.\n\n## Usage\n\n```javascript\nfunction doSomething (someObj) {\n var key = sigmund(someObj, maxDepth) // max depth defaults to 10\n var cached = cache.get(key)\n if (cached) return cached)\n\n var result = expensiveCalculation(someObj)\n cache.set(key, result)\n return result\n}\n```\n\nThe resulting key will be as unique and reproducible as calling\n`JSON.stringify` or `util.inspect` on the object, but is much faster.\nIn order to achieve this speed, some differences are glossed over.\nFor example, the object `{0:'foo'}` will be treated identically to the\narray `['foo']`.\n\nAlso, just as there is no way to summon the soul from the scribblings\nof a cocain-addled psychoanalyst, there is no way to revive the object\nfrom the signature string that sigmund gives you. In fact, it's\nbarely even readable.\n\nAs with `sys.inspect` and `JSON.stringify`, larger objects will\nproduce larger signature strings.\n\nBecause sigmund is a bit less strict than the more thorough\nalternatives, the strings will be shorter, and also there is a\nslightly higher chance for collisions. For example, these objects\nhave the same signature:\n\n var obj1 = {a:'b',c:/def/,g:['h','i',{j:'',k:'l'}]}\n var obj2 = {a:'b',c:'/def/',g:['h','i','{jkl']}\n\nLike a good Freudian, sigmund is most effective when you already have\nsome understanding of what you're looking for. It can help you help\nyourself, but you must be willing to do some work as well.\n\nCycles are handled, and cyclical objects are silently omitted (though\nthe key is included in the signature output.)\n\nThe second argument is the maximum depth, which defaults to 10,\nbecause that is the maximum object traversal depth covered by most\ninsurance carriers.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/sigmund/issues" - }, - "_id": "sigmund@1.0.0", - "_from": "sigmund@~1.0.0" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/package.json deleted file mode 100644 index a34740535..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/node_modules/minimatch/package.json +++ /dev/null @@ -1,39 +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.12", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/minimatch.git" - }, - "main": "minimatch.js", - "scripts": { - "test": "tap test" - }, - "engines": { - "node": "*" - }, - "dependencies": { - "lru-cache": "2", - "sigmund": "~1.0.0" - }, - "devDependencies": { - "tap": "" - }, - "license": { - "type": "MIT", - "url": "http://github.com/isaacs/minimatch/raw/master/LICENSE" - }, - "readme": "# minimatch\n\nA minimal matching utility.\n\n[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.png)](http://travis-ci.org/isaacs/minimatch)\n\n\nThis is the matching library used internally by npm.\n\nEventually, it will replace the C binding in node-glob.\n\nIt works by converting glob expressions into JavaScript `RegExp`\nobjects.\n\n## Usage\n\n```javascript\nvar minimatch = require(\"minimatch\")\n\nminimatch(\"bar.foo\", \"*.foo\") // true!\nminimatch(\"bar.foo\", \"*.bar\") // false!\n```\n\n## Features\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\n### Comparisons to other fnmatch/glob implementations\n\nWhile strict compliance with the existing standards is a worthwhile\ngoal, some discrepancies exist between minimatch 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. **Note that this is different from the way that `**` is\nhandled by ruby's `Dir` class.**\n\nIf an escaped pattern has no matches, and the `nonull` flag is set,\nthen minimatch.match returns the pattern as-provided, rather than\ninterpreting the character escapes. For example,\n`minimatch.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\n## Minimatch Class\n\nCreate a minimatch object by instanting the `minimatch.Minimatch` class.\n\n```javascript\nvar Minimatch = require(\"minimatch\").Minimatch\nvar mm = new Minimatch(pattern, options)\n```\n\n### Properties\n\n* `pattern` The original pattern the minimatch object represents.\n* `options` The options supplied to the constructor.\n* `set` A 2-dimensional array of regexp or string expressions.\n Each row in the\n array corresponds to a brace-expanded pattern. Each item in the row\n corresponds to a single path-part. For example, the pattern\n `{a,b/c}/d` would expand to a set of patterns like:\n\n [ [ a, d ]\n , [ b, c, d ] ]\n\n If a portion of the pattern doesn't have any \"magic\" in it\n (that is, it's something like `\"foo\"` rather than `fo*o?`), then it\n will be left as a string rather than converted to a regular\n expression.\n\n* `regexp` Created by the `makeRe` method. A single regular expression\n expressing the entire pattern. This is useful in cases where you wish\n to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.\n* `negate` True if the pattern is negated.\n* `comment` True if the pattern is a comment.\n* `empty` True if the pattern is `\"\"`.\n\n### Methods\n\n* `makeRe` Generate the `regexp` member if necessary, and return it.\n Will return `false` if the pattern is invalid.\n* `match(fname)` Return true if the filename matches the pattern, or\n false otherwise.\n* `matchOne(fileArray, patternArray, partial)` Take a `/`-split\n filename, and match it against a single row in the `regExpSet`. This\n method is mainly for internal use, but is exposed so that it can be\n used by a glob-walker that needs to avoid excessive filesystem calls.\n\nAll other methods are internal, and will be called as necessary.\n\n## Functions\n\nThe top-level exported function has a `cache` property, which is an LRU\ncache set to store 100 items. So, calling these methods repeatedly\nwith the same pattern and options will use the same Minimatch object,\nsaving the cost of parsing it multiple times.\n\n### minimatch(path, pattern, options)\n\nMain export. Tests a path against the pattern using the options.\n\n```javascript\nvar isJS = minimatch(file, \"*.js\", { matchBase: true })\n```\n\n### minimatch.filter(pattern, options)\n\nReturns a function that tests its\nsupplied argument, suitable for use with `Array.filter`. Example:\n\n```javascript\nvar javascripts = fileList.filter(minimatch.filter(\"*.js\", {matchBase: true}))\n```\n\n### minimatch.match(list, pattern, options)\n\nMatch against the list of\nfiles, in the style of fnmatch or glob. If nothing is matched, and\noptions.nonull is set, then return a list containing the pattern itself.\n\n```javascript\nvar javascripts = minimatch.match(fileList, \"*.js\", {matchBase: true}))\n```\n\n### minimatch.makeRe(pattern, options)\n\nMake a regular expression object from the pattern.\n\n## Options\n\nAll options are `false` by default.\n\n### debug\n\nDump a ton of stuff to stderr.\n\n### nobrace\n\nDo not expand `{a,b}` and `{1..3}` brace sets.\n\n### noglobstar\n\nDisable `**` matching against multiple folder names.\n\n### dot\n\nAllow patterns to match filenames starting with a period, even if\nthe pattern does not explicitly have a period in that spot.\n\nNote that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`\nis set.\n\n### noext\n\nDisable \"extglob\" style patterns like `+(a|b)`.\n\n### nocase\n\nPerform a case-insensitive match.\n\n### nonull\n\nWhen a match is not found by `minimatch.match`, return a list containing\nthe pattern itself. When set, an empty list is returned if there are\nno matches.\n\n### matchBase\n\nIf set, then patterns without slashes will be matched\nagainst the basename of the path if it contains slashes. For example,\n`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.\n\n### nocomment\n\nSuppress the behavior of treating `#` at the start of a pattern as a\ncomment.\n\n### nonegate\n\nSuppress the behavior of treating a leading `!` character as negation.\n\n### flipNegate\n\nReturns from negate expressions the same as if they were not negated.\n(Ie, true on a hit, false on a miss.)\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/minimatch/issues" - }, - "_id": "minimatch@0.2.12", - "_from": "minimatch@~0.2.11" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/package.json deleted file mode 100644 index bb00ffa78..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/package.json +++ /dev/null @@ -1,39 +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.1", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/node-glob.git" - }, - "main": "glob.js", - "engines": { - "node": "*" - }, - "dependencies": { - "minimatch": "~0.2.11", - "graceful-fs": "~1.2.0", - "inherits": "1" - }, - "devDependencies": { - "tap": "~0.4.0", - "mkdirp": "0", - "rimraf": "1" - }, - "scripts": { - "test": "tap test/*.js" - }, - "license": "BSD", - "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", - "bugs": { - "url": "https://github.com/isaacs/node-glob/issues" - }, - "_id": "glob@3.2.1", - "_from": "glob@~3.2.1" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/test/bash-results.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/test/bash-results.json deleted file mode 100644 index a9bc347de..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/test/globstar-match.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/test/globstar-match.js deleted file mode 100644 index 9b234fa2a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/test/stat.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/glob/test/stat.js deleted file mode 100644 index 62917114b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/LICENSE b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/LICENSE deleted file mode 100644 index 5a8e33254..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/LICENSE +++ /dev/null @@ -1,14 +0,0 @@ - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - Version 2, December 2004 - - Copyright (C) 2004 Sam Hocevar - - Everyone is permitted to copy and distribute verbatim or modified - copies of this license document, and changing it is allowed as long - as the name is changed. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. You just DO WHAT THE FUCK YOU WANT TO. - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/inherits-old.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/inherits-old.js deleted file mode 100644 index ef39252dd..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/inherits-old.js +++ /dev/null @@ -1,40 +0,0 @@ -// This is a less perfect implementation of the inherits function, -// designed to work in cases where ES5 is not available. -// -// Note that it is a bit longer, and doesn't properly deal with -// getter/setters or property descriptor flags (enumerable, etc.) - -module.exports = inheritsOld - -function inheritsOld (c, p, proto) { - function F () { this.constructor = c } - F.prototype = p.prototype - var e = {} - for (var i in c.prototype) if (c.prototype.hasOwnProperty(i)) { - e[i] = c.prototype[i] - } - if (proto) for (var i in proto) if (proto.hasOwnProperty(i)) { - e[i] = proto[i] - } - c.prototype = new F() - for (var i in e) if (e.hasOwnProperty(i)) { - c.prototype[i] = e[i] - } - c.super = p -} - -// function Child () { -// Child.super.call(this) -// console.error([this -// ,this.constructor -// ,this.constructor === Child -// ,this.constructor.super === Parent -// ,Object.getPrototypeOf(this) === Child.prototype -// ,Object.getPrototypeOf(Object.getPrototypeOf(this)) -// === Parent.prototype -// ,this instanceof Child -// ,this instanceof Parent]) -// } -// function Parent () {} -// inheritsOld(Child, Parent) -// new Child diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/package.json deleted file mode 100644 index 487b6fa57..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/inherits/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "inherits" -, "description": "A tiny simple way to do classic inheritance in js" -, "version" : "1.0.0" -, "keywords" : ["inheritance", "class", "klass", "oop", "object-oriented"] -, "main" : "./inherits.js" -, "repository" : "https://github.com/isaacs/inherits" -, "license": { "type": "WTFPL2" } -, "author" : "Isaac Z. Schlueter (http://blog.izs.me/)" } diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/package.json deleted file mode 100644 index 5c6df9b03..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/mkdirp/package.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "name": "mkdirp", - "description": "Recursively mkdir, like `mkdir -p`", - "version": "0.3.5", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "main": "./index", - "keywords": [ - "mkdir", - "directory" - ], - "repository": { - "type": "git", - "url": "http://github.com/substack/node-mkdirp.git" - }, - "scripts": { - "test": "tap test/*.js" - }, - "devDependencies": { - "tap": "~0.4.0" - }, - "license": "MIT", - "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, mode, cb)\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\n`cb(err, made)` fires with the error or the first directory `made`\nthat had to be created, if any.\n\n## mkdirp.sync(dir, mode)\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\nReturns the first directory that had to be created, if any.\n\n# install\n\nWith [npm](http://npmjs.org) do:\n\n```\nnpm install mkdirp\n```\n\n# license\n\nMIT\n", - "readmeFilename": "readme.markdown", - "bugs": { - "url": "https://github.com/substack/node-mkdirp/issues" - }, - "_id": "mkdirp@0.3.5", - "_from": "mkdirp@~0.3" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/bin/nopt.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/bin/nopt.js deleted file mode 100755 index 30e9fdbab..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/bin/nopt.js +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env node -var nopt = require("../lib/nopt") - , types = { num: Number - , bool: Boolean - , help: Boolean - , list: Array - , "num-list": [Number, Array] - , "str-list": [String, Array] - , "bool-list": [Boolean, Array] - , str: String - , clear: Boolean - , config: Boolean - , length: Number - } - , shorthands = { s: [ "--str", "astring" ] - , b: [ "--bool" ] - , nb: [ "--no-bool" ] - , tft: [ "--bool-list", "--no-bool-list", "--bool-list", "true" ] - , "?": ["--help"] - , h: ["--help"] - , H: ["--help"] - , n: [ "--num", "125" ] - , c: ["--config"] - , l: ["--length"] - } - , parsed = nopt( types - , shorthands - , process.argv - , 2 ) - -console.log("parsed", parsed) - -if (parsed.help) { - console.log("") - console.log("nopt cli tester") - console.log("") - console.log("types") - console.log(Object.keys(types).map(function M (t) { - var type = types[t] - if (Array.isArray(type)) { - return [t, type.map(function (type) { return type.name })] - } - return [t, type && type.name] - }).reduce(function (s, i) { - s[i[0]] = i[1] - return s - }, {})) - console.log("") - console.log("shorthands") - console.log(shorthands) -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/lib/nopt.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/lib/nopt.js deleted file mode 100644 index 0e4ebc428..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/lib/nopt.js +++ /dev/null @@ -1,602 +0,0 @@ -// info about each config option. - -var debug = process.env.DEBUG_NOPT || process.env.NOPT_DEBUG - ? function () { console.error.apply(console, arguments) } - : function () {} - -var url = require("url") - , path = require("path") - , Stream = require("stream").Stream - , abbrev = require("abbrev") - -module.exports = exports = nopt -exports.clean = clean - -exports.typeDefs = - { String : { type: String, validate: validateString } - , Boolean : { type: Boolean, validate: validateBoolean } - , url : { type: url, validate: validateUrl } - , Number : { type: Number, validate: validateNumber } - , path : { type: path, validate: validatePath } - , Stream : { type: Stream, validate: validateStream } - , Date : { type: Date, validate: validateDate } - } - -function nopt (types, shorthands, args, slice) { - args = args || process.argv - types = types || {} - shorthands = shorthands || {} - if (typeof slice !== "number") slice = 2 - - debug(types, shorthands, args, slice) - - args = args.slice(slice) - var data = {} - , key - , remain = [] - , cooked = args - , original = args.slice(0) - - parse(args, data, remain, types, shorthands) - // now data is full - clean(data, types, exports.typeDefs) - data.argv = {remain:remain,cooked:cooked,original:original} - Object.defineProperty(data.argv, 'toString', { value: function () { - return this.original.map(JSON.stringify).join(" ") - }, enumerable: false }) - return data -} - -function clean (data, types, typeDefs) { - typeDefs = typeDefs || exports.typeDefs - var remove = {} - , typeDefault = [false, true, null, String, Number, Array] - - Object.keys(data).forEach(function (k) { - if (k === "argv") return - var val = data[k] - , isArray = Array.isArray(val) - , type = types[k] - if (!isArray) val = [val] - if (!type) type = typeDefault - if (type === Array) type = typeDefault.concat(Array) - if (!Array.isArray(type)) type = [type] - - debug("val=%j", val) - debug("types=", type) - val = val.map(function (val) { - // if it's an unknown value, then parse false/true/null/numbers/dates - if (typeof val === "string") { - debug("string %j", val) - val = val.trim() - if ((val === "null" && ~type.indexOf(null)) - || (val === "true" && - (~type.indexOf(true) || ~type.indexOf(Boolean))) - || (val === "false" && - (~type.indexOf(false) || ~type.indexOf(Boolean)))) { - val = JSON.parse(val) - debug("jsonable %j", val) - } else if (~type.indexOf(Number) && !isNaN(val)) { - debug("convert to number", val) - val = +val - } else if (~type.indexOf(Date) && !isNaN(Date.parse(val))) { - debug("convert to date", val) - val = new Date(val) - } - } - - if (!types.hasOwnProperty(k)) { - return val - } - - // allow `--no-blah` to set 'blah' to null if null is allowed - if (val === false && ~type.indexOf(null) && - !(~type.indexOf(false) || ~type.indexOf(Boolean))) { - val = null - } - - var d = {} - d[k] = val - debug("prevalidated val", d, val, types[k]) - if (!validate(d, k, val, types[k], typeDefs)) { - if (exports.invalidHandler) { - exports.invalidHandler(k, val, types[k], data) - } else if (exports.invalidHandler !== false) { - debug("invalid: "+k+"="+val, types[k]) - } - return remove - } - debug("validated val", d, val, types[k]) - return d[k] - }).filter(function (val) { return val !== remove }) - - if (!val.length) delete data[k] - else if (isArray) { - debug(isArray, data[k], val) - data[k] = val - } else data[k] = val[0] - - debug("k=%s val=%j", k, val, data[k]) - }) -} - -function validateString (data, k, val) { - data[k] = String(val) -} - -function validatePath (data, k, val) { - data[k] = path.resolve(String(val)) - return true -} - -function validateNumber (data, k, val) { - debug("validate Number %j %j %j", k, val, isNaN(val)) - if (isNaN(val)) return false - data[k] = +val -} - -function validateDate (data, k, val) { - debug("validate Date %j %j %j", k, val, Date.parse(val)) - var s = Date.parse(val) - if (isNaN(s)) return false - data[k] = new Date(val) -} - -function validateBoolean (data, k, val) { - if (val instanceof Boolean) val = val.valueOf() - else if (typeof val === "string") { - if (!isNaN(val)) val = !!(+val) - else if (val === "null" || val === "false") val = false - else val = true - } else val = !!val - data[k] = val -} - -function validateUrl (data, k, val) { - val = url.parse(String(val)) - if (!val.host) return false - data[k] = val.href -} - -function validateStream (data, k, val) { - if (!(val instanceof Stream)) return false - data[k] = val -} - -function validate (data, k, val, type, typeDefs) { - // arrays are lists of types. - if (Array.isArray(type)) { - for (var i = 0, l = type.length; i < l; i ++) { - if (type[i] === Array) continue - if (validate(data, k, val, type[i], typeDefs)) return true - } - delete data[k] - return false - } - - // an array of anything? - if (type === Array) return true - - // NaN is poisonous. Means that something is not allowed. - if (type !== type) { - debug("Poison NaN", k, val, type) - delete data[k] - return false - } - - // explicit list of values - if (val === type) { - debug("Explicitly allowed %j", val) - // if (isArray) (data[k] = data[k] || []).push(val) - // else data[k] = val - data[k] = val - return true - } - - // now go through the list of typeDefs, validate against each one. - var ok = false - , types = Object.keys(typeDefs) - for (var i = 0, l = types.length; i < l; i ++) { - debug("test type %j %j %j", k, val, types[i]) - var t = typeDefs[types[i]] - if (t && type === t.type) { - var d = {} - ok = false !== t.validate(d, k, val) - val = d[k] - if (ok) { - // if (isArray) (data[k] = data[k] || []).push(val) - // else data[k] = val - data[k] = val - break - } - } - } - debug("OK? %j (%j %j %j)", ok, k, val, types[i]) - - if (!ok) delete data[k] - return ok -} - -function parse (args, data, remain, types, shorthands) { - debug("parse", args, data, remain) - - var key = null - , abbrevs = abbrev(Object.keys(types)) - , shortAbbr = abbrev(Object.keys(shorthands)) - - for (var i = 0; i < args.length; i ++) { - var arg = args[i] - debug("arg", arg) - - if (arg.match(/^-{2,}$/)) { - // done with keys. - // the rest are args. - remain.push.apply(remain, args.slice(i + 1)) - args[i] = "--" - break - } - var hadEq = false - if (arg.charAt(0) === "-") { - if (arg.indexOf("=") !== -1) { - hadEq = true - var v = arg.split("=") - arg = v.shift() - v = v.join("=") - args.splice.apply(args, [i, 1].concat([arg, v])) - } - - // see if it's a shorthand - // if so, splice and back up to re-parse it. - var shRes = resolveShort(arg, shorthands, shortAbbr, abbrevs) - debug("arg=%j shRes=%j", arg, shRes) - if (shRes) { - debug(arg, shRes) - args.splice.apply(args, [i, 1].concat(shRes)) - if (arg !== shRes[0]) { - i -- - continue - } - } - arg = arg.replace(/^-+/, "") - var no = null - while (arg.toLowerCase().indexOf("no-") === 0) { - no = !no - arg = arg.substr(3) - } - - if (abbrevs[arg]) arg = abbrevs[arg] - - var isArray = types[arg] === Array || - Array.isArray(types[arg]) && types[arg].indexOf(Array) !== -1 - - // allow unknown things to be arrays if specified multiple times. - if (!types.hasOwnProperty(arg) && data.hasOwnProperty(arg)) { - if (!Array.isArray(data[arg])) - data[arg] = [data[arg]] - isArray = true - } - - var val - , la = args[i + 1] - - var isBool = typeof no === 'boolean' || - types[arg] === Boolean || - Array.isArray(types[arg]) && types[arg].indexOf(Boolean) !== -1 || - (typeof types[arg] === 'undefined' && !hadEq) || - (la === "false" && - (types[arg] === null || - Array.isArray(types[arg]) && ~types[arg].indexOf(null))) - - if (isBool) { - // just set and move along - val = !no - // however, also support --bool true or --bool false - if (la === "true" || la === "false") { - val = JSON.parse(la) - la = null - if (no) val = !val - i ++ - } - - // also support "foo":[Boolean, "bar"] and "--foo bar" - if (Array.isArray(types[arg]) && la) { - if (~types[arg].indexOf(la)) { - // an explicit type - val = la - i ++ - } else if ( la === "null" && ~types[arg].indexOf(null) ) { - // null allowed - val = null - i ++ - } else if ( !la.match(/^-{2,}[^-]/) && - !isNaN(la) && - ~types[arg].indexOf(Number) ) { - // number - val = +la - i ++ - } else if ( !la.match(/^-[^-]/) && ~types[arg].indexOf(String) ) { - // string - val = la - i ++ - } - } - - if (isArray) (data[arg] = data[arg] || []).push(val) - else data[arg] = val - - continue - } - - if (la && la.match(/^-{2,}$/)) { - la = undefined - i -- - } - - val = la === undefined ? true : la - if (isArray) (data[arg] = data[arg] || []).push(val) - else data[arg] = val - - i ++ - continue - } - remain.push(arg) - } -} - -function resolveShort (arg, shorthands, shortAbbr, abbrevs) { - // handle single-char shorthands glommed together, like - // npm ls -glp, but only if there is one dash, and only if - // all of the chars are single-char shorthands, and it's - // not a match to some other abbrev. - arg = arg.replace(/^-+/, '') - - // if it's an exact known option, then don't go any further - if (abbrevs[arg] === arg) - return null - - // if it's an exact known shortopt, same deal - if (shorthands[arg]) { - // make it an array, if it's a list of words - if (shorthands[arg] && !Array.isArray(shorthands[arg])) - shorthands[arg] = shorthands[arg].split(/\s+/) - - return shorthands[arg] - } - - // first check to see if this arg is a set of single-char shorthands - var singles = shorthands.___singles - if (!singles) { - singles = Object.keys(shorthands).filter(function (s) { - return s.length === 1 - }).reduce(function (l,r) { - l[r] = true - return l - }, {}) - shorthands.___singles = singles - debug('shorthand singles', singles) - } - - var chrs = arg.split("").filter(function (c) { - return singles[c] - }) - - if (chrs.join("") === arg) return chrs.map(function (c) { - return shorthands[c] - }).reduce(function (l, r) { - return l.concat(r) - }, []) - - - // if it's an arg abbrev, and not a literal shorthand, then prefer the arg - if (abbrevs[arg] && !shorthands[arg]) - return null - - // if it's an abbr for a shorthand, then use that - if (shortAbbr[arg]) - arg = shortAbbr[arg] - - // make it an array, if it's a list of words - if (shorthands[arg] && !Array.isArray(shorthands[arg])) - shorthands[arg] = shorthands[arg].split(/\s+/) - - return shorthands[arg] -} - -if (module === require.main) { -var assert = require("assert") - , util = require("util") - - , shorthands = - { s : ["--loglevel", "silent"] - , d : ["--loglevel", "info"] - , dd : ["--loglevel", "verbose"] - , ddd : ["--loglevel", "silly"] - , noreg : ["--no-registry"] - , reg : ["--registry"] - , "no-reg" : ["--no-registry"] - , silent : ["--loglevel", "silent"] - , verbose : ["--loglevel", "verbose"] - , h : ["--usage"] - , H : ["--usage"] - , "?" : ["--usage"] - , help : ["--usage"] - , v : ["--version"] - , f : ["--force"] - , desc : ["--description"] - , "no-desc" : ["--no-description"] - , "local" : ["--no-global"] - , l : ["--long"] - , p : ["--parseable"] - , porcelain : ["--parseable"] - , g : ["--global"] - } - - , types = - { aoa: Array - , nullstream: [null, Stream] - , date: Date - , str: String - , browser : String - , cache : path - , color : ["always", Boolean] - , depth : Number - , description : Boolean - , dev : Boolean - , editor : path - , force : Boolean - , global : Boolean - , globalconfig : path - , group : [String, Number] - , gzipbin : String - , logfd : [Number, Stream] - , loglevel : ["silent","win","error","warn","info","verbose","silly"] - , long : Boolean - , "node-version" : [false, String] - , npaturl : url - , npat : Boolean - , "onload-script" : [false, String] - , outfd : [Number, Stream] - , parseable : Boolean - , pre: Boolean - , prefix: path - , proxy : url - , "rebuild-bundle" : Boolean - , registry : url - , searchopts : String - , searchexclude: [null, String] - , shell : path - , t: [Array, String] - , tag : String - , tar : String - , tmp : path - , "unsafe-perm" : Boolean - , usage : Boolean - , user : String - , username : String - , userconfig : path - , version : Boolean - , viewer: path - , _exit : Boolean - } - -; [["-v", {version:true}, []] - ,["---v", {version:true}, []] - ,["ls -s --no-reg connect -d", - {loglevel:"info",registry:null},["ls","connect"]] - ,["ls ---s foo",{loglevel:"silent"},["ls","foo"]] - ,["ls --registry blargle", {}, ["ls"]] - ,["--no-registry", {registry:null}, []] - ,["--no-color true", {color:false}, []] - ,["--no-color false", {color:true}, []] - ,["--no-color", {color:false}, []] - ,["--color false", {color:false}, []] - ,["--color --logfd 7", {logfd:7,color:true}, []] - ,["--color=true", {color:true}, []] - ,["--logfd=10", {logfd:10}, []] - ,["--tmp=/tmp -tar=gtar",{tmp:"/tmp",tar:"gtar"},[]] - ,["--tmp=tmp -tar=gtar", - {tmp:path.resolve(process.cwd(), "tmp"),tar:"gtar"},[]] - ,["--logfd x", {}, []] - ,["a -true -- -no-false", {true:true},["a","-no-false"]] - ,["a -no-false", {false:false},["a"]] - ,["a -no-no-true", {true:true}, ["a"]] - ,["a -no-no-no-false", {false:false}, ["a"]] - ,["---NO-no-No-no-no-no-nO-no-no"+ - "-No-no-no-no-no-no-no-no-no"+ - "-no-no-no-no-NO-NO-no-no-no-no-no-no"+ - "-no-body-can-do-the-boogaloo-like-I-do" - ,{"body-can-do-the-boogaloo-like-I-do":false}, []] - ,["we are -no-strangers-to-love "+ - "--you-know=the-rules --and=so-do-i "+ - "---im-thinking-of=a-full-commitment "+ - "--no-you-would-get-this-from-any-other-guy "+ - "--no-gonna-give-you-up "+ - "-no-gonna-let-you-down=true "+ - "--no-no-gonna-run-around false "+ - "--desert-you=false "+ - "--make-you-cry false "+ - "--no-tell-a-lie "+ - "--no-no-and-hurt-you false" - ,{"strangers-to-love":false - ,"you-know":"the-rules" - ,"and":"so-do-i" - ,"you-would-get-this-from-any-other-guy":false - ,"gonna-give-you-up":false - ,"gonna-let-you-down":false - ,"gonna-run-around":false - ,"desert-you":false - ,"make-you-cry":false - ,"tell-a-lie":false - ,"and-hurt-you":false - },["we", "are"]] - ,["-t one -t two -t three" - ,{t: ["one", "two", "three"]} - ,[]] - ,["-t one -t null -t three four five null" - ,{t: ["one", "null", "three"]} - ,["four", "five", "null"]] - ,["-t foo" - ,{t:["foo"]} - ,[]] - ,["--no-t" - ,{t:["false"]} - ,[]] - ,["-no-no-t" - ,{t:["true"]} - ,[]] - ,["-aoa one -aoa null -aoa 100" - ,{aoa:["one", null, 100]} - ,[]] - ,["-str 100" - ,{str:"100"} - ,[]] - ,["--color always" - ,{color:"always"} - ,[]] - ,["--no-nullstream" - ,{nullstream:null} - ,[]] - ,["--nullstream false" - ,{nullstream:null} - ,[]] - ,["--notadate=2011-01-25" - ,{notadate: "2011-01-25"} - ,[]] - ,["--date 2011-01-25" - ,{date: new Date("2011-01-25")} - ,[]] - ,["-cl 1" - ,{config: true, length: 1} - ,[] - ,{config: Boolean, length: Number, clear: Boolean} - ,{c: "--config", l: "--length"}] - ,["--acount bla" - ,{"acount":true} - ,["bla"] - ,{account: Boolean, credentials: Boolean, options: String} - ,{a:"--account", c:"--credentials",o:"--options"}] - ,["--clear" - ,{clear:true} - ,[] - ,{clear:Boolean,con:Boolean,len:Boolean,exp:Boolean,add:Boolean,rep:Boolean} - ,{c:"--con",l:"--len",e:"--exp",a:"--add",r:"--rep"}] - ].forEach(function (test) { - var argv = test[0].split(/\s+/) - , opts = test[1] - , rem = test[2] - , actual = nopt(test[3] || types, test[4] || shorthands, argv, 0) - , parsed = actual.argv - delete actual.argv - console.log(util.inspect(actual, false, 2, true), parsed.remain) - for (var i in opts) { - var e = JSON.stringify(opts[i]) - , a = JSON.stringify(actual[i] === undefined ? null : actual[i]) - if (e && typeof e === "object") { - assert.deepEqual(e, a) - } else { - assert.equal(e, a) - } - } - assert.deepEqual(rem, parsed.remain) - }) -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/node_modules/abbrev/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/node_modules/abbrev/package.json deleted file mode 100644 index 55ed011bf..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/node_modules/abbrev/package.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "abbrev", - "version": "1.0.4", - "description": "Like ruby's abbrev module, but in js", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me" - }, - "main": "./lib/abbrev.js", - "scripts": { - "test": "node lib/abbrev.js" - }, - "repository": { - "type": "git", - "url": "http://github.com/isaacs/abbrev-js" - }, - "license": { - "type": "MIT", - "url": "https://github.com/isaacs/abbrev-js/raw/master/LICENSE" - }, - "readme": "# abbrev-js\n\nJust like [ruby's Abbrev](http://apidock.com/ruby/Abbrev).\n\nUsage:\n\n var abbrev = require(\"abbrev\");\n abbrev(\"foo\", \"fool\", \"folding\", \"flop\");\n \n // returns:\n { fl: 'flop'\n , flo: 'flop'\n , flop: 'flop'\n , fol: 'folding'\n , fold: 'folding'\n , foldi: 'folding'\n , foldin: 'folding'\n , folding: 'folding'\n , foo: 'foo'\n , fool: 'fool'\n }\n\nThis is handy for command-line scripts, or other cases where you want to be able to accept shorthands.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/abbrev-js/issues" - }, - "_id": "abbrev@1.0.4", - "_from": "abbrev@1" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/package.json deleted file mode 100644 index 36135d88a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/nopt/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "nopt", - "version": "2.1.1", - "description": "Option parsing for Node, supporting types, shorthands, etc. Used by npm.", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "main": "lib/nopt.js", - "scripts": { - "test": "node lib/nopt.js" - }, - "repository": { - "type": "git", - "url": "http://github.com/isaacs/nopt" - }, - "bin": { - "nopt": "./bin/nopt.js" - }, - "license": { - "type": "MIT", - "url": "https://github.com/isaacs/nopt/raw/master/LICENSE" - }, - "dependencies": { - "abbrev": "1" - }, - "readme": "If you want to write an option parser, and have it be good, there are\ntwo ways to do it. The Right Way, and the Wrong Way.\n\nThe Wrong Way is to sit down and write an option parser. We've all done\nthat.\n\nThe Right Way is to write some complex configurable program with so many\noptions that you go half-insane just trying to manage them all, and put\nit off with duct-tape solutions until you see exactly to the core of the\nproblem, and finally snap and write an awesome option parser.\n\nIf you want to write an option parser, don't write an option parser.\nWrite a package manager, or a source control system, or a service\nrestarter, or an operating system. You probably won't end up with a\ngood one of those, but if you don't give up, and you are relentless and\ndiligent enough in your procrastination, you may just end up with a very\nnice option parser.\n\n## USAGE\n\n // my-program.js\n var nopt = require(\"nopt\")\n , Stream = require(\"stream\").Stream\n , path = require(\"path\")\n , knownOpts = { \"foo\" : [String, null]\n , \"bar\" : [Stream, Number]\n , \"baz\" : path\n , \"bloo\" : [ \"big\", \"medium\", \"small\" ]\n , \"flag\" : Boolean\n , \"pick\" : Boolean\n , \"many\" : [String, Array]\n }\n , shortHands = { \"foofoo\" : [\"--foo\", \"Mr. Foo\"]\n , \"b7\" : [\"--bar\", \"7\"]\n , \"m\" : [\"--bloo\", \"medium\"]\n , \"p\" : [\"--pick\"]\n , \"f\" : [\"--flag\"]\n }\n // everything is optional.\n // knownOpts and shorthands default to {}\n // arg list defaults to process.argv\n // slice defaults to 2\n , parsed = nopt(knownOpts, shortHands, process.argv, 2)\n console.log(parsed)\n\nThis would give you support for any of the following:\n\n```bash\n$ node my-program.js --foo \"blerp\" --no-flag\n{ \"foo\" : \"blerp\", \"flag\" : false }\n\n$ node my-program.js ---bar 7 --foo \"Mr. Hand\" --flag\n{ bar: 7, foo: \"Mr. Hand\", flag: true }\n\n$ node my-program.js --foo \"blerp\" -f -----p\n{ foo: \"blerp\", flag: true, pick: true }\n\n$ node my-program.js -fp --foofoo\n{ foo: \"Mr. Foo\", flag: true, pick: true }\n\n$ node my-program.js --foofoo -- -fp # -- stops the flag parsing.\n{ foo: \"Mr. Foo\", argv: { remain: [\"-fp\"] } }\n\n$ node my-program.js --blatzk 1000 -fp # unknown opts are ok.\n{ blatzk: 1000, flag: true, pick: true }\n\n$ node my-program.js --blatzk true -fp # but they need a value\n{ blatzk: true, flag: true, pick: true }\n\n$ node my-program.js --no-blatzk -fp # unless they start with \"no-\"\n{ blatzk: false, flag: true, pick: true }\n\n$ node my-program.js --baz b/a/z # known paths are resolved.\n{ baz: \"/Users/isaacs/b/a/z\" }\n\n# if Array is one of the types, then it can take many\n# values, and will always be an array. The other types provided\n# specify what types are allowed in the list.\n\n$ node my-program.js --many 1 --many null --many foo\n{ many: [\"1\", \"null\", \"foo\"] }\n\n$ node my-program.js --many foo\n{ many: [\"foo\"] }\n```\n\nRead the tests at the bottom of `lib/nopt.js` for more examples of\nwhat this puppy can do.\n\n## Types\n\nThe following types are supported, and defined on `nopt.typeDefs`\n\n* String: A normal string. No parsing is done.\n* path: A file system path. Gets resolved against cwd if not absolute.\n* url: A url. If it doesn't parse, it isn't accepted.\n* Number: Must be numeric.\n* Date: Must parse as a date. If it does, and `Date` is one of the options,\n then it will return a Date object, not a string.\n* Boolean: Must be either `true` or `false`. If an option is a boolean,\n then it does not need a value, and its presence will imply `true` as\n the value. To negate boolean flags, do `--no-whatever` or `--whatever\n false`\n* NaN: Means that the option is strictly not allowed. Any value will\n fail.\n* Stream: An object matching the \"Stream\" class in node. Valuable\n for use when validating programmatically. (npm uses this to let you\n supply any WriteStream on the `outfd` and `logfd` config options.)\n* Array: If `Array` is specified as one of the types, then the value\n will be parsed as a list of options. This means that multiple values\n can be specified, and that the value will always be an array.\n\nIf a type is an array of values not on this list, then those are\nconsidered valid values. For instance, in the example above, the\n`--bloo` option can only be one of `\"big\"`, `\"medium\"`, or `\"small\"`,\nand any other value will be rejected.\n\nWhen parsing unknown fields, `\"true\"`, `\"false\"`, and `\"null\"` will be\ninterpreted as their JavaScript equivalents, and numeric values will be\ninterpreted as a number.\n\nYou can also mix types and values, or multiple types, in a list. For\ninstance `{ blah: [Number, null] }` would allow a value to be set to\neither a Number or null. When types are ordered, this implies a\npreference, and the first type that can be used to properly interpret\nthe value will be used.\n\nTo define a new type, add it to `nopt.typeDefs`. Each item in that\nhash is an object with a `type` member and a `validate` method. The\n`type` member is an object that matches what goes in the type list. The\n`validate` method is a function that gets called with `validate(data,\nkey, val)`. Validate methods should assign `data[key]` to the valid\nvalue of `val` if it can be handled properly, or return boolean\n`false` if it cannot.\n\nYou can also call `nopt.clean(data, types, typeDefs)` to clean up a\nconfig object and remove its invalid properties.\n\n## Error Handling\n\nBy default, nopt outputs a warning to standard error when invalid\noptions are found. You can change this behavior by assigning a method\nto `nopt.invalidHandler`. This method will be called with\nthe offending `nopt.invalidHandler(key, val, types)`.\n\nIf no `nopt.invalidHandler` is assigned, then it will console.error\nits whining. If it is assigned to boolean `false` then the warning is\nsuppressed.\n\n## Abbreviations\n\nYes, they are supported. If you define options like this:\n\n```javascript\n{ \"foolhardyelephants\" : Boolean\n, \"pileofmonkeys\" : Boolean }\n```\n\nThen this will work:\n\n```bash\nnode program.js --foolhar --pil\nnode program.js --no-f --pileofmon\n# etc.\n```\n\n## Shorthands\n\nShorthands are a hash of shorter option names to a snippet of args that\nthey expand to.\n\nIf multiple one-character shorthands are all combined, and the\ncombination does not unambiguously match any other option or shorthand,\nthen they will be broken up into their constituent parts. For example:\n\n```json\n{ \"s\" : [\"--loglevel\", \"silent\"]\n, \"g\" : \"--global\"\n, \"f\" : \"--force\"\n, \"p\" : \"--parseable\"\n, \"l\" : \"--long\"\n}\n```\n\n```bash\nnpm ls -sgflp\n# just like doing this:\nnpm ls --loglevel silent --global --force --long --parseable\n```\n\n## The Rest of the args\n\nThe config object returned by nopt is given a special member called\n`argv`, which is an object with the following fields:\n\n* `remain`: The remaining args after all the parsing has occurred.\n* `original`: The args as they originally appeared.\n* `cooked`: The args after flags and shorthands are expanded.\n\n## Slicing\n\nNode programs are called with more or less the exact argv as it appears\nin C land, after the v8 and node-specific options have been plucked off.\nAs such, `argv[0]` is always `node` and `argv[1]` is always the\nJavaScript program being run.\n\nThat's usually not very useful to you. So they're sliced off by\ndefault. If you want them, then you can pass in `0` as the last\nargument, or any other number that you'd like to slice off the start of\nthe list.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/nopt/issues" - }, - "_id": "nopt@2.1.1", - "_from": "nopt@~2" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/README.markdown b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/README.markdown deleted file mode 100644 index 1e56ebd68..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/README.markdown +++ /dev/null @@ -1,56 +0,0 @@ -runforcover -====== - -Runforcover is a require-hook library that uses node-bunker to provide code coverage data -for your unit test library, whatever it might be. - -methods -======= -var runforcover = require('runforcover'); - -var coverage = runforcover.cover([RegExp | path]); -------- - -Attach runforcover to the global `require` object and patch `require.extensions['.js']` to -provide coverage metadata for all files required after this point. Returns a function -object that can be called to obtain a object keying files to `CoverageData` objects, with -a method for releasing control back to vanilla `require`. Usage: - -````javascript - -var coverage = runforcover.cover(/.*/g); - -require('some/library'); - -coverage(function(coverageData) { - // coverageData is an object keyed by filename. - var stats = coverageData['/full/path/to/file.js'].stats() - - // the percentage of lines run versus total lines in file - console.log(stats.percentage); - - // the number of missing lines - console.log(stats.missing); - - // the number of lines run (seen) - console.log(stats.seen); - - // an array of line objects representing 'missed' lines - stats.lines; - - stats.lines.forEach(function(line) { - // the line number of the line: - console.log(line.number); - - // returns a string containing the source data for the line: - console.log(line.source()); - }); - - // return control back to the original require function - coverage.release(); -}); -```` - -license -======= -new BSD. diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/index.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/index.js deleted file mode 100644 index b5318ac66..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/index.js +++ /dev/null @@ -1,127 +0,0 @@ -var bunker = require('bunker'), - Module = require('module').Module, - path = require('path'), - fs = require('fs'), - vm = require('vm'); - -function CoverageData (filename, bunker) { - this.bunker = bunker; - this.filename = filename; - this.nodes = {}; -}; - -CoverageData.prototype.visit = function(node) { - ++(this.nodes[node.id] = this.nodes[node.id] || {node:node, count:0}).count; -}; - -CoverageData.prototype.missing = function() { - var nodes = this.nodes, - missing = this.bunker.nodes.filter(function(node) { - return !nodes[node.id]; - }); - - return missing; -}; - -CoverageData.prototype.stats = function() { - var missing = this.missing(), - filedata = fs.readFileSync(this.filename, 'utf8').split('\n'); - - var seenLines = [], - lines = - missing.sort(function(lhs, rhs) { - return lhs.node[0].start.line < rhs.node[0].start.line ? -1 : - lhs.node[0].start.line > rhs.node[0].start.line ? 1 : - 0; - }).filter(function(node) { - - var okay = (seenLines.indexOf(node.node[0].start.line) < 0); - if(okay) - seenLines.push(node.node[0].start.line); - return okay; - - }).map(function(node, idx, all) { - return { - lineno:node.node[0].start.line + 1, - source:function() { return filedata[node.node[0].start.line]; } - }; - }); - - return { - percentage:(filedata.length-seenLines.length)/filedata.length, - lines:lines, - missing:seenLines.length, - seen:(filedata.length-seenLines.length) - }; -}; - -module.exports.createEnvironment = function(module, filename) { - var req = function(path) { - return Module._load(path, module); - }; - req.resolve = function(request) { - return Module._resolveFilename(request, module)[1]; - } - req.paths = Module._paths; - req.main = process.mainModule; - req.extensions = Module._extensions; - req.registerExtension = function() { - throw new Error('require.registerExtension() removed. Use ' + - 'require.extensions instead.'); - } - require.cache = Module._cache; - - var ctxt = {}; - for(var k in global) - ctxt[k] = global[k]; - - ctxt.require = req; - ctxt.exports = module.exports; - ctxt.__filename = filename; - ctxt.__dirname = path.dirname(filename); - ctxt.process = process; - ctxt.console = console; - ctxt.module = module; - ctxt.global = ctxt; - - return ctxt; -}; - -module.exports.cover = function(fileRegex) { - var originalRequire = require.extensions['.js'], - coverageData = {}, - match = fileRegex instanceof RegExp ? - fileRegex : new RegExp( - fileRegex ? fileRegex.replace(/\//g, '\\/').replace(/\./g, '\\.') : '.*' - , 'g'), - target = this; - - require.extensions['.js'] = function(module, filename) { - if(!match.test(filename)) return originalRequire(module, filename); - - var context = target.createEnvironment(module, filename), - data = fs.readFileSync(filename, 'utf8'), - bunkerized = bunker(data), - coverage = coverageData[filename] = new CoverageData(filename, bunkerized); - - bunkerized.on('node', coverage.visit.bind(coverage)); - bunkerized.assign(context); - - var wrapper = '(function(ctxt) { with(ctxt) { return '+Module.wrap(bunkerized.compile())+'; } })', - compiledWrapper = vm.runInThisContext(wrapper, filename, true)(context); - - var args = [context.exports, context.require, module, filename, context.__dirname]; - return compiledWrapper.apply(module.exports, args); - }; - - var retval = function(ready) { - ready(coverageData); - }; - - retval.release = function() { - require.extensions['.js'] = originalRequire; - }; - - return retval; -}; - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/.travis.yml b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/.travis.yml deleted file mode 100644 index f1d0f13c8..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/README.markdown b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/README.markdown deleted file mode 100644 index 0d0c387bb..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/README.markdown +++ /dev/null @@ -1,82 +0,0 @@ -bunker -====== - -Bunker is a module to calculate code coverage using native javascript -[burrito](https://github.com/substack/node-burrito) AST trickery. - -[![build status](https://secure.travis-ci.org/substack/node-bunker.png)](http://travis-ci.org/substack/node-bunker) - -![code coverage](http://substack.net/images/code_coverage.png) - -examples -======== - -tiny ----- - -````javascript -var bunker = require('bunker'); -var b = bunker('var x = 0; for (var i = 0; i < 30; i++) { x++ }'); - -var counts = {}; - -b.on('node', function (node) { - if (!counts[node.id]) { - counts[node.id] = { times : 0, node : node }; - } - counts[node.id].times ++; -}); - -b.run(); - -Object.keys(counts).forEach(function (key) { - var count = counts[key]; - console.log(count.times + ' : ' + count.node.source()); -}); -```` - -output: - - $ node example/tiny.js - 1 : var x=0; - 31 : i<30 - 30 : i++ - 30 : x++; - 30 : x++ - -methods -======= - -var bunker = require('bunker'); - -var b = bunker(src) -------------------- - -Create a new bunker code coverageifier with some source `src`. - -The bunker object `b` is an `EventEmitter` that emits `'node'` events with two -parameters: - -* `node` - the [burrito](https://github.com/substack/node-burrito) node object -* `stack` - the stack, [stackedy](https://github.com/substack/node-stackedy) style - -b.include(src) --------------- - -Include some source into the bunker. - -b.compile() ------------ - -Return the source wrapped with burrito. - -b.assign(context={}) --------------------- - -Assign the statement-tracking functions into `context`. - -b.run(context={}) ------------------ - -Run the source using `vm.runInNewContext()` with some `context`. -The statement-tracking functions will be added to `context` by `assign()`. diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/example/prof.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/example/prof.js deleted file mode 100644 index 5cac4ccc2..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/example/prof.js +++ /dev/null @@ -1,51 +0,0 @@ -var bunker = require('bunker'); -var b = bunker('(' + function () { - function beep () { - var x = 0; - for (var i = 0; i < 1000; i++) { - for (var j = 0; j < 100; j++) { - x += j; - } - } - return x; - } - - beep(); - -} + ')()'); - -var counts = {}; - -b.on('node', function (node) { - if (!counts[node.id]) { - counts[node.id] = { times : 0, node : node, elapsed : 0 }; - } - counts[node.id].times ++; - - var now = Date.now(); - - if (last.id !== undefined) { - counts[last.id].elapsed += last. - } - - if (node.name === 'call') { - var start = now; - - last.id = node.id; - counts[node.id].elapsed += Date.now() - start; - } - else { - counts[node.id].elapsed += now - last; - last = now; - } -}); - -b.run(); - -Object.keys(counts).forEach(function (key) { - var count = counts[key]; - console.log( - [ count.times, count.node.source(), count.elapsed ] - .join(' : ') - ); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/example/tiny.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/example/tiny.js deleted file mode 100644 index aa5b034a4..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/example/tiny.js +++ /dev/null @@ -1,18 +0,0 @@ -var bunker = require('bunker'); -var b = bunker('var x = 0; for (var i = 0; i < 30; i++) { x++ }'); - -var counts = {}; - -b.on('node', function (node) { - if (!counts[node.id]) { - counts[node.id] = { times : 0, node : node }; - } - counts[node.id].times ++; -}); - -b.run(); - -Object.keys(counts).forEach(function (key) { - var count = counts[key]; - console.log(count.times + ' : ' + count.node.source()); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/example/top/run.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/example/top/run.js deleted file mode 100644 index d9eaa1055..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/example/top/run.js +++ /dev/null @@ -1,31 +0,0 @@ -var bunker = require('bunker'); -var fs = require('fs'); -var src = fs.readFileSync(__dirname + '/src.js', 'utf8'); - -var counts = {}; - -var b = bunker(src); -b.on('node', function (node) { - if (!counts[node.id]) { - counts[node.id] = { times : 0, node : node }; - } - counts[node.id].times ++; -}); - -b.run({ - setInterval : setInterval, - clearInterval : clearInterval, - end : function () { - Object.keys(counts) - .sort(function (a, b) { - return counts[b].times - counts[a].times - }) - .forEach(function (key) { - var count = counts[key]; - console.log( - count.times + ' : ' + count.node.source() - ); - }) - ; - } -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/example/top/src.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/example/top/src.js deleted file mode 100644 index 0c92e4811..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/example/top/src.js +++ /dev/null @@ -1,18 +0,0 @@ -function boop () { - for (var i = 0; i < 30; i++) { - nop(); - } -} - -function nop () { - return undefined; -} - -var times = 0; -var iv = setInterval(function () { - if (++times === 10) { - clearInterval(iv); - end(); - } - else boop() -}, 100); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/index.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/index.js deleted file mode 100644 index ed5d437fa..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/index.js +++ /dev/null @@ -1,116 +0,0 @@ -var burrito = require('burrito'); -var vm = require('vm'); -var EventEmitter = require('events').EventEmitter; - -module.exports = function (src) { - var b = new Bunker(); - if (src) b.include(src); - return b; -}; - -function Bunker () { - this.sources = []; - this.nodes = []; - - this.names = { - call : burrito.generateName(6), - expr : burrito.generateName(6), - stat : burrito.generateName(6), - return : burrito.generateName(6) - }; -} - -Bunker.prototype = new EventEmitter; - -Bunker.prototype.include = function (src) { - this.sources.push(src); - this.source = null; - return this; -}; - -Bunker.prototype.compile = function () { - var src = this.sources.join('\n'); - var nodes = this.nodes; - var names = this.names; - - return burrito(src, function (node) { - var i = nodes.length; - - if (node.name === 'call') { - nodes.push(node); - node.wrap(names.call + '(' + i + ')(%s)'); - } - else if (node.name === 'stat' || node.name === 'throw' - || node.name === 'var') { - nodes.push(node); - node.wrap('{' + names.stat + '(' + i + ');%s}'); - } - else if (node.name === 'return') { - nodes.push(node); - // We need to wrap the new source in a function definition - // so that UglifyJS will allow the presence of return - var stat = names.stat + '(' + i + ');'; - var wrapped = 'function ' + names.return + '() {' - + stat + node.source() - +'}' - ; - var parsed = burrito.parse(wrapped); - // Remove the function definition from the AST - parsed[1] = parsed[1][0][3]; - node.state.update(parsed, true); - } - else if (node.name === 'binary') { - nodes.push(node); - node.wrap(names.expr + '(' + i + ')(%s)'); - } - else if (node.name === 'unary-postfix' || node.name === 'unary-prefix') { - nodes.push(node); - node.wrap(names.expr + '(' + i + ')(%s)'); - } - - if (i !== nodes.length) { - node.id = i; - } - }); -}; - -Bunker.prototype.assign = function (context) { - if (!context) context = {}; - - var self = this; - var stack = []; - - context[self.names.call] = function (i) { - var node = self.nodes[i]; - stack.unshift(node); - self.emit('node', node, stack); - - return function (expr) { - stack.shift(); - return expr; - }; - }; - - context[self.names.expr] = function (i) { - var node = self.nodes[i]; - self.emit('node', node, stack); - - return function (expr) { - return expr; - }; - }; - - context[self.names.stat] = function (i) { - var node = self.nodes[i]; - self.emit('node', node, stack); - }; - - return context; -}; - -Bunker.prototype.run = function (context) { - var src = this.compile(); - vm.runInNewContext(src, this.assign(context)); - - return this; -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/.travis.yml b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/.travis.yml deleted file mode 100644 index f1d0f13c8..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/.travis.yml +++ /dev/null @@ -1,4 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/README.markdown b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/README.markdown deleted file mode 100644 index 7c9097c85..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/README.markdown +++ /dev/null @@ -1,187 +0,0 @@ -burrito -======= - -Burrito makes it easy to do crazy stuff with the javascript AST. - -This is super useful if you want to roll your own stack traces or build a code -coverage tool. - -[![build status](https://secure.travis-ci.org/substack/node-burrito.png)](http://travis-ci.org/substack/node-burrito) - -![node.wrap("burrito")](http://substack.net/images/burrito.png) - -examples -======== - -microwave ---------- - -examples/microwave.js - -````javascript -var burrito = require('burrito'); - -var res = burrito.microwave('Math.sin(2)', function (node) { - if (node.name === 'num') node.wrap('Math.PI / %s'); -}); - -console.log(res); // sin(pi / 2) == 1 -```` - -output: - - 1 - -wrap ----- - -examples/wrap.js - -````javascript -var burrito = require('burrito'); - -var src = burrito('f() && g(h())\nfoo()', function (node) { - if (node.name === 'call') node.wrap('qqq(%s)'); -}); - -console.log(src); -```` - -output: - - qqq(f()) && qqq(g(qqq(h()))); - - qqq(foo()); - -methods -======= - - var burrito = require('burrito'); - -burrito(code, cb) ------------------ - -Given some source `code` and a function `trace`, walk the ast by expression. - -The `cb` gets called with a node object described below. - -If `code` is an Array then it is assumbed to be an AST which you can generate -yourself with `burrito.parse()`. The AST must be annotated, so make sure to -`burrito.parse(src, false, true)`. - -burrito.microwave(code, context={}, cb) ---------------------------------------- - -Like `burrito()` except the result is run using -`vm.runInNewContext(res, context)`. - -node object -=========== - -node.name ---------- - -Name is a string that contains the type of the expression as named by uglify. - -node.wrap(s) ------------- - -Wrap the current expression in `s`. - -If `s` is a string, `"%s"` will be replaced with the stringified current -expression. - -If `s` is a function, it is called with the stringified current expression and -should return a new stringified expression. - -If the `node.name === "binary"`, you get the subterms "%a" and "%b" to play with -too. These subterms are applied if `s` is a function too: `s(expr, a, b)`. - -Protip: to insert multiple statements you can use javascript's lesser-known block -syntax that it gets from C: - -````javascript -if (node.name === 'stat') node.wrap('{ foo(); %s }') -```` - -node.node ---------- - -raw ast data generated by uglify - -node.value ----------- - -`node.node.slice(1)` to skip the annotations - -node.start ----------- - -The start location of the expression, like this: - -````javascript -{ type: 'name', - value: 'b', - line: 0, - col: 3, - pos: 3, - nlb: false, - comments_before: [] } -```` - -node.end --------- - -The end location of the expression, formatted the same as `node.start`. - -node.state ----------- - -The state of the traversal using traverse. - -node.source() -------------- - -Returns a stringified version of the expression. - -node.parent() -------------- - -Returns the parent `node` or `null` if the node is the root element. - -node.label() ------------- - -Return the label of the present node or `null` if there is no label. - -Labels are returned for "call", "var", "defun", and "function" nodes. - -Returns an array for "var" nodes since `var` statements can -contain multiple labels in assignment. - -install -======= - -With [npm](http://npmjs.org) you can just: - - npm install burrito - -in the browser -============== - -Burrito works in browser with -[browserify](https://github.com/substack/node-browserify). - -It has been tested against: - -* Internet Explorer 5.5, 6.0, 7.0, 8.0, 9.0 -* Firefox 3.5 -* Chrome 6.0 -* Opera 10.6 -* Safari 5.0 - -kudos -===== - -Heavily inspired by (and previously mostly lifted outright from) isaacs's nifty -tmp/instrument.js thingy from uglify-js. diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/microwave.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/microwave.js deleted file mode 100644 index c6fcf45b8..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/microwave.js +++ /dev/null @@ -1,8 +0,0 @@ -var burrito = require('burrito'); - -var res = burrito.microwave('Math.sin(2)', function (node) { - console.dir(node); - if (node.name === 'num') node.wrap('Math.PI / %s'); -}); - -console.log(res); // sin(pi / 2) == 1 diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/web/bs.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/web/bs.js deleted file mode 100644 index 3583c7f6d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/web/bs.js +++ /dev/null @@ -1,4832 +0,0 @@ -var require = function (file, cwd) { - var resolved = require.resolve(file, cwd || '/'); - var mod = require.modules[resolved]; - if (!mod) throw new Error( - 'Failed to resolve module ' + file + ', tried ' + resolved - ); - var res = mod._cached ? mod._cached : mod(); - return res; -} -var __require = require; - -require.paths = []; -require.modules = {}; -require.extensions = [".js",".coffee"]; - -require.resolve = (function () { - var core = { - 'assert': true, - 'events': true, - 'fs': true, - 'path': true, - 'vm': true - }; - - return function (x, cwd) { - if (!cwd) cwd = '/'; - - if (core[x]) return x; - var path = require.modules.path(); - var y = cwd || '.'; - - if (x.match(/^(?:\.\.?\/|\/)/)) { - var m = loadAsFileSync(path.resolve(y, x)) - || loadAsDirectorySync(path.resolve(y, x)); - if (m) return m; - } - - var n = loadNodeModulesSync(x, y); - if (n) return n; - - throw new Error("Cannot find module '" + x + "'"); - - function loadAsFileSync (x) { - if (require.modules[x]) { - return x; - } - - for (var i = 0; i < require.extensions.length; i++) { - var ext = require.extensions[i]; - if (require.modules[x + ext]) return x + ext; - } - } - - function loadAsDirectorySync (x) { - x = x.replace(/\/+$/, ''); - var pkgfile = x + '/package.json'; - if (require.modules[pkgfile]) { - var pkg = require.modules[pkgfile](); - var b = pkg.browserify; - if (typeof b === 'object' && b.main) { - var m = loadAsFileSync(path.resolve(x, b.main)); - if (m) return m; - } - else if (typeof b === 'string') { - var m = loadAsFileSync(path.resolve(x, b)); - if (m) return m; - } - else if (pkg.main) { - var m = loadAsFileSync(path.resolve(x, pkg.main)); - if (m) return m; - } - } - - return loadAsFileSync(x + '/index'); - } - - function loadNodeModulesSync (x, start) { - var dirs = nodeModulesPathsSync(start); - for (var i = 0; i < dirs.length; i++) { - var dir = dirs[i]; - var m = loadAsFileSync(dir + '/' + x); - if (m) return m; - var n = loadAsDirectorySync(dir + '/' + x); - if (n) return n; - } - - var m = loadAsFileSync(x); - if (m) return m; - } - - function nodeModulesPathsSync (start) { - var parts; - if (start === '/') parts = [ '' ]; - else parts = path.normalize(start).split('/'); - - var dirs = []; - for (var i = parts.length - 1; i >= 0; i--) { - if (parts[i] === 'node_modules') continue; - var dir = parts.slice(0, i + 1).join('/') + '/node_modules'; - dirs.push(dir); - } - - return dirs; - } - }; -})(); - -require.alias = function (from, to) { - var path = require.modules.path(); - var res = null; - try { - res = require.resolve(from + '/package.json', '/'); - } - catch (err) { - res = require.resolve(from, '/'); - } - var basedir = path.dirname(res); - - var keys = Object_keys(require.modules); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (key.slice(0, basedir.length + 1) === basedir + '/') { - var f = key.slice(basedir.length); - require.modules[to + f] = require.modules[basedir + f]; - } - else if (key === basedir) { - require.modules[to] = require.modules[basedir]; - } - } -}; - -var Object_keys = Object.keys || function (obj) { - var res = []; - for (var key in obj) res.push(key) - return res; -}; - -if (typeof process === 'undefined') process = {}; - -if (!process.nextTick) process.nextTick = function (fn) { - setTimeout(fn, 0); -}; - -if (!process.title) process.title = 'browser'; - -if (!process.binding) process.binding = function (name) { - if (name === 'evals') return require('vm') - else throw new Error('No such module') -}; - -if (!process.cwd) process.cwd = function () { return '.' }; - -require.modules["path"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "."; - var __filename = "path"; - - var require = function (file) { - return __require(file, "."); - }; - - require.resolve = function (file) { - return __require.resolve(name, "."); - }; - - require.modules = __require.modules; - __require.modules["path"]._cached = module.exports; - - (function () { - function filter (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - if (fn(xs[i], i, xs)) res.push(xs[i]); - } - return res; -} - -// resolves . and .. elements in a path array with directory names there -// must be no slashes, empty elements, or device names (c:\) in the array -// (so also no leading and trailing slashes - it does not distinguish -// relative and absolute paths) -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length; i >= 0; i--) { - var last = parts[i]; - if (last == '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } - - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; -} - -// Regex to split a filename into [*, dir, basename, ext] -// posix version -var splitPathRe = /^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/; - -// path.resolve([from ...], to) -// posix version -exports.resolve = function() { -var resolvedPath = '', - resolvedAbsolute = false; - -for (var i = arguments.length; i >= -1 && !resolvedAbsolute; i--) { - var path = (i >= 0) - ? arguments[i] - : process.cwd(); - - // Skip empty and invalid entries - if (typeof path !== 'string' || !path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; -} - -// At this point the path should be resolved to a full absolute path, but -// handle relative paths to be safe (might happen when process.cwd() fails) - -// Normalize the path -resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { - return !!p; - }), !resolvedAbsolute).join('/'); - - return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; -}; - -// path.normalize(path) -// posix version -exports.normalize = function(path) { -var isAbsolute = path.charAt(0) === '/', - trailingSlash = path.slice(-1) === '/'; - -// Normalize the path -path = normalizeArray(filter(path.split('/'), function(p) { - return !!p; - }), !isAbsolute).join('/'); - - if (!path && !isAbsolute) { - path = '.'; - } - if (path && trailingSlash) { - path += '/'; - } - - return (isAbsolute ? '/' : '') + path; -}; - - -// posix version -exports.join = function() { - var paths = Array.prototype.slice.call(arguments, 0); - return exports.normalize(filter(paths, function(p, index) { - return p && typeof p === 'string'; - }).join('/')); -}; - - -exports.dirname = function(path) { - var dir = splitPathRe.exec(path)[1] || ''; - var isWindows = false; - if (!dir) { - // No dirname - return '.'; - } else if (dir.length === 1 || - (isWindows && dir.length <= 3 && dir.charAt(1) === ':')) { - // It is just a slash or a drive letter with a slash - return dir; - } else { - // It is a full dirname, strip trailing slash - return dir.substring(0, dir.length - 1); - } -}; - - -exports.basename = function(path, ext) { - var f = splitPathRe.exec(path)[2] || ''; - // TODO: make this comparison case-insensitive on windows? - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - return f; -}; - - -exports.extname = function(path) { - return splitPathRe.exec(path)[3] || ''; -}; -; - }).call(module.exports); - - __require.modules["path"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/burrito/package.json"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/burrito"; - var __filename = "/node_modules/burrito/package.json"; - - var require = function (file) { - return __require(file, "/node_modules/burrito"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/burrito"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/burrito/package.json"]._cached = module.exports; - - (function () { - module.exports = {"name":"burrito","description":"Wrap up expressions with a trace function while walking the AST with rice and beans on the side","version":"0.2.8","repository":{"type":"git","url":"git://github.com/substack/node-burrito.git"},"main":"./index.js","keywords":["trace","ast","walk","syntax","source","tree","uglify"],"directories":{"lib":".","example":"example","test":"test"},"scripts":{"test":"expresso"},"dependencies":{"traverse":">=0.5.1 <0.6","uglify-js":"1.0.4"},"devDependencies":{"expresso":"=0.7.x"},"engines":{"node":">=0.4.0"},"license":"BSD","author":{"name":"James Halliday","email":"mail@substack.net","url":"http://substack.net"}}; - }).call(module.exports); - - __require.modules["/node_modules/burrito/package.json"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/burrito/node_modules/uglify-js/package.json"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/burrito/node_modules/uglify-js"; - var __filename = "/node_modules/burrito/node_modules/uglify-js/package.json"; - - var require = function (file) { - return __require(file, "/node_modules/burrito/node_modules/uglify-js"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/burrito/node_modules/uglify-js"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/burrito/node_modules/uglify-js/package.json"]._cached = module.exports; - - (function () { - module.exports = {"name":"uglify-js","author":{"name":"Mihai Bazon","email":"mihai.bazon@gmail.com","url":"http://mihai.bazon.net/blog"},"version":"1.0.4","main":"./uglify-js.js","bin":{"uglifyjs":"./bin/uglifyjs"},"repository":{"type":"git","url":"git@github.com:mishoo/UglifyJS.git"}}; - }).call(module.exports); - - __require.modules["/node_modules/burrito/node_modules/uglify-js/package.json"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/burrito/node_modules/uglify-js/uglify-js.js"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/burrito/node_modules/uglify-js"; - var __filename = "/node_modules/burrito/node_modules/uglify-js/uglify-js.js"; - - var require = function (file) { - return __require(file, "/node_modules/burrito/node_modules/uglify-js"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/burrito/node_modules/uglify-js"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/burrito/node_modules/uglify-js/uglify-js.js"]._cached = module.exports; - - (function () { - //convienence function(src, [options]); -function uglify(orig_code, options){ - options || (options = {}); - var jsp = uglify.parser; - var pro = uglify.uglify; - - var ast = jsp.parse(orig_code, options.strict_semicolons); // parse code and get the initial AST - ast = pro.ast_mangle(ast, options.mangle_options); // get a new AST with mangled names - ast = pro.ast_squeeze(ast, options.squeeze_options); // get an AST with compression optimizations - var final_code = pro.gen_code(ast, options.gen_options); // compressed code here - return final_code; -}; - -uglify.parser = require("./lib/parse-js"); -uglify.uglify = require("./lib/process"); - -module.exports = uglify; - }).call(module.exports); - - __require.modules["/node_modules/burrito/node_modules/uglify-js/uglify-js.js"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/burrito/node_modules/uglify-js/lib/parse-js.js"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/burrito/node_modules/uglify-js/lib"; - var __filename = "/node_modules/burrito/node_modules/uglify-js/lib/parse-js.js"; - - var require = function (file) { - return __require(file, "/node_modules/burrito/node_modules/uglify-js/lib"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/burrito/node_modules/uglify-js/lib"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/burrito/node_modules/uglify-js/lib/parse-js.js"]._cached = module.exports; - - (function () { - /*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - - This version is suitable for Node.js. With minimal changes (the - exports stuff) it should work on any JS platform. - - This file contains the tokenizer/parser. It is a port to JavaScript - of parse-js [1], a JavaScript parser library written in Common Lisp - by Marijn Haverbeke. Thank you Marijn! - - [1] http://marijn.haverbeke.nl/parse-js/ - - Exported functions: - - - tokenizer(code) -- returns a function. Call the returned - function to fetch the next token. - - - parse(code) -- returns an AST of the given JavaScript code. - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2010 (c) Mihai Bazon - Based on parse-js (http://marijn.haverbeke.nl/parse-js/). - - 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. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 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. - - ***********************************************************************/ - -/* -----[ Tokenizer (constants) ]----- */ - -var KEYWORDS = array_to_hash([ - "break", - "case", - "catch", - "const", - "continue", - "default", - "delete", - "do", - "else", - "finally", - "for", - "function", - "if", - "in", - "instanceof", - "new", - "return", - "switch", - "throw", - "try", - "typeof", - "var", - "void", - "while", - "with" -]); - -var RESERVED_WORDS = array_to_hash([ - "abstract", - "boolean", - "byte", - "char", - "class", - "debugger", - "double", - "enum", - "export", - "extends", - "final", - "float", - "goto", - "implements", - "import", - "int", - "interface", - "long", - "native", - "package", - "private", - "protected", - "public", - "short", - "static", - "super", - "synchronized", - "throws", - "transient", - "volatile" -]); - -var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([ - "return", - "new", - "delete", - "throw", - "else", - "case" -]); - -var KEYWORDS_ATOM = array_to_hash([ - "false", - "null", - "true", - "undefined" -]); - -var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^")); - -var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i; -var RE_OCT_NUMBER = /^0[0-7]+$/; -var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i; - -var OPERATORS = array_to_hash([ - "in", - "instanceof", - "typeof", - "new", - "void", - "delete", - "++", - "--", - "+", - "-", - "!", - "~", - "&", - "|", - "^", - "*", - "/", - "%", - ">>", - "<<", - ">>>", - "<", - ">", - "<=", - ">=", - "==", - "===", - "!=", - "!==", - "?", - "=", - "+=", - "-=", - "/=", - "*=", - "%=", - ">>=", - "<<=", - ">>>=", - "|=", - "^=", - "&=", - "&&", - "||" -]); - -var WHITESPACE_CHARS = array_to_hash(characters(" \u00a0\n\r\t\f\v\u200b")); - -var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{}(,.;:")); - -var PUNC_CHARS = array_to_hash(characters("[]{}(),;:")); - -var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy")); - -/* -----[ Tokenizer ]----- */ - -// regexps adapted from http://xregexp.com/plugins/#unicode -var UNICODE = { - letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0523\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971\\u0972\\u097B-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D28\\u0D2A-\\u0D39\\u0D3D\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC\\u0EDD\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8B\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10D0-\\u10FA\\u10FC\\u1100-\\u1159\\u115F-\\u11A2\\u11A8-\\u11F9\\u1200-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u1676\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19A9\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u2094\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2C6F\\u2C71-\\u2C7D\\u2C80-\\u2CE4\\u2D00-\\u2D25\\u2D30-\\u2D65\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31B7\\u31F0-\\u31FF\\u3400\\u4DB5\\u4E00\\u9FC3\\uA000-\\uA48C\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA65F\\uA662-\\uA66E\\uA67F-\\uA697\\uA717-\\uA71F\\uA722-\\uA788\\uA78B\\uA78C\\uA7FB-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA90A-\\uA925\\uA930-\\uA946\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAC00\\uD7A3\\uF900-\\uFA2D\\uFA30-\\uFA6A\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"), - non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"), - space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"), - connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]") -}; - -function is_letter(ch) { - return UNICODE.letter.test(ch); -}; - -function is_digit(ch) { - ch = ch.charCodeAt(0); - return ch >= 48 && ch <= 57; //XXX: find out if "UnicodeDigit" means something else than 0..9 -}; - -function is_alphanumeric_char(ch) { - return is_digit(ch) || is_letter(ch); -}; - -function is_unicode_combining_mark(ch) { - return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch); -}; - -function is_unicode_connector_punctuation(ch) { - return UNICODE.connector_punctuation.test(ch); -}; - -function is_identifier_start(ch) { - return ch == "$" || ch == "_" || is_letter(ch); -}; - -function is_identifier_char(ch) { - return is_identifier_start(ch) - || is_unicode_combining_mark(ch) - || is_digit(ch) - || is_unicode_connector_punctuation(ch) - || ch == "\u200c" // zero-width non-joiner - || ch == "\u200d" // zero-width joiner (in my ECMA-262 PDF, this is also 200c) - ; -}; - -function parse_js_number(num) { - if (RE_HEX_NUMBER.test(num)) { - return parseInt(num.substr(2), 16); - } else if (RE_OCT_NUMBER.test(num)) { - return parseInt(num.substr(1), 8); - } else if (RE_DEC_NUMBER.test(num)) { - return parseFloat(num); - } -}; - -function JS_Parse_Error(message, line, col, pos) { - this.message = message; - this.line = line; - this.col = col; - this.pos = pos; - try { - ({})(); - } catch(ex) { - this.stack = ex.stack; - }; -}; - -JS_Parse_Error.prototype.toString = function() { - return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack; -}; - -function js_error(message, line, col, pos) { - throw new JS_Parse_Error(message, line, col, pos); -}; - -function is_token(token, type, val) { - return token.type == type && (val == null || token.value == val); -}; - -var EX_EOF = {}; - -function tokenizer($TEXT) { - - var S = { - text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''), - pos : 0, - tokpos : 0, - line : 0, - tokline : 0, - col : 0, - tokcol : 0, - newline_before : false, - regex_allowed : false, - comments_before : [] - }; - - function peek() { return S.text.charAt(S.pos); }; - - function next(signal_eof) { - var ch = S.text.charAt(S.pos++); - if (signal_eof && !ch) - throw EX_EOF; - if (ch == "\n") { - S.newline_before = true; - ++S.line; - S.col = 0; - } else { - ++S.col; - } - return ch; - }; - - function eof() { - return !S.peek(); - }; - - function find(what, signal_eof) { - var pos = S.text.indexOf(what, S.pos); - if (signal_eof && pos == -1) throw EX_EOF; - return pos; - }; - - function start_token() { - S.tokline = S.line; - S.tokcol = S.col; - S.tokpos = S.pos; - }; - - function token(type, value, is_comment) { - S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) || - (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) || - (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value))); - var ret = { - type : type, - value : value, - line : S.tokline, - col : S.tokcol, - pos : S.tokpos, - nlb : S.newline_before - }; - if (!is_comment) { - ret.comments_before = S.comments_before; - S.comments_before = []; - } - S.newline_before = false; - return ret; - }; - - function skip_whitespace() { - while (HOP(WHITESPACE_CHARS, peek())) - next(); - }; - - function read_while(pred) { - var ret = "", ch = peek(), i = 0; - while (ch && pred(ch, i++)) { - ret += next(); - ch = peek(); - } - return ret; - }; - - function parse_error(err) { - js_error(err, S.tokline, S.tokcol, S.tokpos); - }; - - function read_num(prefix) { - var has_e = false, after_e = false, has_x = false, has_dot = prefix == "."; - var num = read_while(function(ch, i){ - if (ch == "x" || ch == "X") { - if (has_x) return false; - return has_x = true; - } - if (!has_x && (ch == "E" || ch == "e")) { - if (has_e) return false; - return has_e = after_e = true; - } - if (ch == "-") { - if (after_e || (i == 0 && !prefix)) return true; - return false; - } - if (ch == "+") return after_e; - after_e = false; - if (ch == ".") { - if (!has_dot && !has_x) - return has_dot = true; - return false; - } - return is_alphanumeric_char(ch); - }); - if (prefix) - num = prefix + num; - var valid = parse_js_number(num); - if (!isNaN(valid)) { - return token("num", valid); - } else { - parse_error("Invalid syntax: " + num); - } - }; - - function read_escaped_char() { - var ch = next(true); - switch (ch) { - case "n" : return "\n"; - case "r" : return "\r"; - case "t" : return "\t"; - case "b" : return "\b"; - case "v" : return "\v"; - case "f" : return "\f"; - case "0" : return "\0"; - case "x" : return String.fromCharCode(hex_bytes(2)); - case "u" : return String.fromCharCode(hex_bytes(4)); - default : return ch; - } - }; - - function hex_bytes(n) { - var num = 0; - for (; n > 0; --n) { - var digit = parseInt(next(true), 16); - if (isNaN(digit)) - parse_error("Invalid hex-character pattern in string"); - num = (num << 4) | digit; - } - return num; - }; - - function read_string() { - return with_eof_error("Unterminated string constant", function(){ - var quote = next(), ret = ""; - for (;;) { - var ch = next(true); - if (ch == "\\") ch = read_escaped_char(); - else if (ch == quote) break; - ret += ch; - } - return token("string", ret); - }); - }; - - function read_line_comment() { - next(); - var i = find("\n"), ret; - if (i == -1) { - ret = S.text.substr(S.pos); - S.pos = S.text.length; - } else { - ret = S.text.substring(S.pos, i); - S.pos = i; - } - return token("comment1", ret, true); - }; - - function read_multiline_comment() { - next(); - return with_eof_error("Unterminated multiline comment", function(){ - var i = find("*/", true), - text = S.text.substring(S.pos, i), - tok = token("comment2", text, true); - S.pos = i + 2; - S.line += text.split("\n").length - 1; - S.newline_before = text.indexOf("\n") >= 0; - - // https://github.com/mishoo/UglifyJS/issues/#issue/100 - if (/^@cc_on/i.test(text)) { - warn("WARNING: at line " + S.line); - warn("*** Found \"conditional comment\": " + text); - warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer."); - } - - return tok; - }); - }; - - function read_name() { - var backslash = false, name = "", ch; - while ((ch = peek()) != null) { - if (!backslash) { - if (ch == "\\") backslash = true, next(); - else if (is_identifier_char(ch)) name += next(); - else break; - } - else { - if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX"); - ch = read_escaped_char(); - if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier"); - name += ch; - backslash = false; - } - } - return name; - }; - - function read_regexp() { - return with_eof_error("Unterminated regular expression", function(){ - var prev_backslash = false, regexp = "", ch, in_class = false; - while ((ch = next(true))) if (prev_backslash) { - regexp += "\\" + ch; - prev_backslash = false; - } else if (ch == "[") { - in_class = true; - regexp += ch; - } else if (ch == "]" && in_class) { - in_class = false; - regexp += ch; - } else if (ch == "/" && !in_class) { - break; - } else if (ch == "\\") { - prev_backslash = true; - } else { - regexp += ch; - } - var mods = read_name(); - return token("regexp", [ regexp, mods ]); - }); - }; - - function read_operator(prefix) { - function grow(op) { - if (!peek()) return op; - var bigger = op + peek(); - if (HOP(OPERATORS, bigger)) { - next(); - return grow(bigger); - } else { - return op; - } - }; - return token("operator", grow(prefix || next())); - }; - - function handle_slash() { - next(); - var regex_allowed = S.regex_allowed; - switch (peek()) { - case "/": - S.comments_before.push(read_line_comment()); - S.regex_allowed = regex_allowed; - return next_token(); - case "*": - S.comments_before.push(read_multiline_comment()); - S.regex_allowed = regex_allowed; - return next_token(); - } - return S.regex_allowed ? read_regexp() : read_operator("/"); - }; - - function handle_dot() { - next(); - return is_digit(peek()) - ? read_num(".") - : token("punc", "."); - }; - - function read_word() { - var word = read_name(); - return !HOP(KEYWORDS, word) - ? token("name", word) - : HOP(OPERATORS, word) - ? token("operator", word) - : HOP(KEYWORDS_ATOM, word) - ? token("atom", word) - : token("keyword", word); - }; - - function with_eof_error(eof_error, cont) { - try { - return cont(); - } catch(ex) { - if (ex === EX_EOF) parse_error(eof_error); - else throw ex; - } - }; - - function next_token(force_regexp) { - if (force_regexp) - return read_regexp(); - skip_whitespace(); - start_token(); - var ch = peek(); - if (!ch) return token("eof"); - if (is_digit(ch)) return read_num(); - if (ch == '"' || ch == "'") return read_string(); - if (HOP(PUNC_CHARS, ch)) return token("punc", next()); - if (ch == ".") return handle_dot(); - if (ch == "/") return handle_slash(); - if (HOP(OPERATOR_CHARS, ch)) return read_operator(); - if (ch == "\\" || is_identifier_start(ch)) return read_word(); - parse_error("Unexpected character '" + ch + "'"); - }; - - next_token.context = function(nc) { - if (nc) S = nc; - return S; - }; - - return next_token; - -}; - -/* -----[ Parser (constants) ]----- */ - -var UNARY_PREFIX = array_to_hash([ - "typeof", - "void", - "delete", - "--", - "++", - "!", - "~", - "-", - "+" -]); - -var UNARY_POSTFIX = array_to_hash([ "--", "++" ]); - -var ASSIGNMENT = (function(a, ret, i){ - while (i < a.length) { - ret[a[i]] = a[i].substr(0, a[i].length - 1); - i++; - } - return ret; -})( - ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="], - { "=": true }, - 0 -); - -var PRECEDENCE = (function(a, ret){ - for (var i = 0, n = 1; i < a.length; ++i, ++n) { - var b = a[i]; - for (var j = 0; j < b.length; ++j) { - ret[b[j]] = n; - } - } - return ret; -})( - [ - ["||"], - ["&&"], - ["|"], - ["^"], - ["&"], - ["==", "===", "!=", "!=="], - ["<", ">", "<=", ">=", "in", "instanceof"], - [">>", "<<", ">>>"], - ["+", "-"], - ["*", "/", "%"] - ], - {} -); - -var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]); - -var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]); - -/* -----[ Parser ]----- */ - -function NodeWithToken(str, start, end) { - this.name = str; - this.start = start; - this.end = end; -}; - -NodeWithToken.prototype.toString = function() { return this.name; }; - -function parse($TEXT, exigent_mode, embed_tokens) { - - var S = { - input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT, - token : null, - prev : null, - peeked : null, - in_function : 0, - in_loop : 0, - labels : [] - }; - - S.token = next(); - - function is(type, value) { - return is_token(S.token, type, value); - }; - - function peek() { return S.peeked || (S.peeked = S.input()); }; - - function next() { - S.prev = S.token; - if (S.peeked) { - S.token = S.peeked; - S.peeked = null; - } else { - S.token = S.input(); - } - return S.token; - }; - - function prev() { - return S.prev; - }; - - function croak(msg, line, col, pos) { - var ctx = S.input.context(); - js_error(msg, - line != null ? line : ctx.tokline, - col != null ? col : ctx.tokcol, - pos != null ? pos : ctx.tokpos); - }; - - function token_error(token, msg) { - croak(msg, token.line, token.col); - }; - - function unexpected(token) { - if (token == null) - token = S.token; - token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); - }; - - function expect_token(type, val) { - if (is(type, val)) { - return next(); - } - token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type); - }; - - function expect(punc) { return expect_token("punc", punc); }; - - function can_insert_semicolon() { - return !exigent_mode && ( - S.token.nlb || is("eof") || is("punc", "}") - ); - }; - - function semicolon() { - if (is("punc", ";")) next(); - else if (!can_insert_semicolon()) unexpected(); - }; - - function as() { - return slice(arguments); - }; - - function parenthesised() { - expect("("); - var ex = expression(); - expect(")"); - return ex; - }; - - function add_tokens(str, start, end) { - return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end); - }; - - function maybe_embed_tokens(parser) { - if (embed_tokens) return function() { - var start = S.token; - var ast = parser.apply(this, arguments); - ast[0] = add_tokens(ast[0], start, prev()); - return ast; - }; - else return parser; - }; - - var statement = maybe_embed_tokens(function() { - if (is("operator", "/")) { - S.peeked = null; - S.token = S.input(true); // force regexp - } - switch (S.token.type) { - case "num": - case "string": - case "regexp": - case "operator": - case "atom": - return simple_statement(); - - case "name": - return is_token(peek(), "punc", ":") - ? labeled_statement(prog1(S.token.value, next, next)) - : simple_statement(); - - case "punc": - switch (S.token.value) { - case "{": - return as("block", block_()); - case "[": - case "(": - return simple_statement(); - case ";": - next(); - return as("block"); - default: - unexpected(); - } - - case "keyword": - switch (prog1(S.token.value, next)) { - case "break": - return break_cont("break"); - - case "continue": - return break_cont("continue"); - - case "debugger": - semicolon(); - return as("debugger"); - - case "do": - return (function(body){ - expect_token("keyword", "while"); - return as("do", prog1(parenthesised, semicolon), body); - })(in_loop(statement)); - - case "for": - return for_(); - - case "function": - return function_(true); - - case "if": - return if_(); - - case "return": - if (S.in_function == 0) - croak("'return' outside of function"); - return as("return", - is("punc", ";") - ? (next(), null) - : can_insert_semicolon() - ? null - : prog1(expression, semicolon)); - - case "switch": - return as("switch", parenthesised(), switch_block_()); - - case "throw": - return as("throw", prog1(expression, semicolon)); - - case "try": - return try_(); - - case "var": - return prog1(var_, semicolon); - - case "const": - return prog1(const_, semicolon); - - case "while": - return as("while", parenthesised(), in_loop(statement)); - - case "with": - return as("with", parenthesised(), statement()); - - default: - unexpected(); - } - } - }); - - function labeled_statement(label) { - S.labels.push(label); - var start = S.token, stat = statement(); - if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0])) - unexpected(start); - S.labels.pop(); - return as("label", label, stat); - }; - - function simple_statement() { - return as("stat", prog1(expression, semicolon)); - }; - - function break_cont(type) { - var name; - if (!can_insert_semicolon()) { - name = is("name") ? S.token.value : null; - } - if (name != null) { - next(); - if (!member(name, S.labels)) - croak("Label " + name + " without matching loop or statement"); - } - else if (S.in_loop == 0) - croak(type + " not inside a loop or switch"); - semicolon(); - return as(type, name); - }; - - function for_() { - expect("("); - var init = null; - if (!is("punc", ";")) { - init = is("keyword", "var") - ? (next(), var_(true)) - : expression(true, true); - if (is("operator", "in")) - return for_in(init); - } - return regular_for(init); - }; - - function regular_for(init) { - expect(";"); - var test = is("punc", ";") ? null : expression(); - expect(";"); - var step = is("punc", ")") ? null : expression(); - expect(")"); - return as("for", init, test, step, in_loop(statement)); - }; - - function for_in(init) { - var lhs = init[0] == "var" ? as("name", init[1][0]) : init; - next(); - var obj = expression(); - expect(")"); - return as("for-in", init, lhs, obj, in_loop(statement)); - }; - - var function_ = maybe_embed_tokens(function(in_statement) { - var name = is("name") ? prog1(S.token.value, next) : null; - if (in_statement && !name) - unexpected(); - expect("("); - return as(in_statement ? "defun" : "function", - name, - // arguments - (function(first, a){ - while (!is("punc", ")")) { - if (first) first = false; else expect(","); - if (!is("name")) unexpected(); - a.push(S.token.value); - next(); - } - next(); - return a; - })(true, []), - // body - (function(){ - ++S.in_function; - var loop = S.in_loop; - S.in_loop = 0; - var a = block_(); - --S.in_function; - S.in_loop = loop; - return a; - })()); - }); - - function if_() { - var cond = parenthesised(), body = statement(), belse; - if (is("keyword", "else")) { - next(); - belse = statement(); - } - return as("if", cond, body, belse); - }; - - function block_() { - expect("{"); - var a = []; - while (!is("punc", "}")) { - if (is("eof")) unexpected(); - a.push(statement()); - } - next(); - return a; - }; - - var switch_block_ = curry(in_loop, function(){ - expect("{"); - var a = [], cur = null; - while (!is("punc", "}")) { - if (is("eof")) unexpected(); - if (is("keyword", "case")) { - next(); - cur = []; - a.push([ expression(), cur ]); - expect(":"); - } - else if (is("keyword", "default")) { - next(); - expect(":"); - cur = []; - a.push([ null, cur ]); - } - else { - if (!cur) unexpected(); - cur.push(statement()); - } - } - next(); - return a; - }); - - function try_() { - var body = block_(), bcatch, bfinally; - if (is("keyword", "catch")) { - next(); - expect("("); - if (!is("name")) - croak("Name expected"); - var name = S.token.value; - next(); - expect(")"); - bcatch = [ name, block_() ]; - } - if (is("keyword", "finally")) { - next(); - bfinally = block_(); - } - if (!bcatch && !bfinally) - croak("Missing catch/finally blocks"); - return as("try", body, bcatch, bfinally); - }; - - function vardefs(no_in) { - var a = []; - for (;;) { - if (!is("name")) - unexpected(); - var name = S.token.value; - next(); - if (is("operator", "=")) { - next(); - a.push([ name, expression(false, no_in) ]); - } else { - a.push([ name ]); - } - if (!is("punc", ",")) - break; - next(); - } - return a; - }; - - function var_(no_in) { - return as("var", vardefs(no_in)); - }; - - function const_() { - return as("const", vardefs()); - }; - - function new_() { - var newexp = expr_atom(false), args; - if (is("punc", "(")) { - next(); - args = expr_list(")"); - } else { - args = []; - } - return subscripts(as("new", newexp, args), true); - }; - - var expr_atom = maybe_embed_tokens(function(allow_calls) { - if (is("operator", "new")) { - next(); - return new_(); - } - if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) { - return make_unary("unary-prefix", - prog1(S.token.value, next), - expr_atom(allow_calls)); - } - if (is("punc")) { - switch (S.token.value) { - case "(": - next(); - return subscripts(prog1(expression, curry(expect, ")")), allow_calls); - case "[": - next(); - return subscripts(array_(), allow_calls); - case "{": - next(); - return subscripts(object_(), allow_calls); - } - unexpected(); - } - if (is("keyword", "function")) { - next(); - return subscripts(function_(false), allow_calls); - } - if (HOP(ATOMIC_START_TOKEN, S.token.type)) { - var atom = S.token.type == "regexp" - ? as("regexp", S.token.value[0], S.token.value[1]) - : as(S.token.type, S.token.value); - return subscripts(prog1(atom, next), allow_calls); - } - unexpected(); - }); - - function expr_list(closing, allow_trailing_comma, allow_empty) { - var first = true, a = []; - while (!is("punc", closing)) { - if (first) first = false; else expect(","); - if (allow_trailing_comma && is("punc", closing)) break; - if (is("punc", ",") && allow_empty) { - a.push([ "atom", "undefined" ]); - } else { - a.push(expression(false)); - } - } - next(); - return a; - }; - - function array_() { - return as("array", expr_list("]", !exigent_mode, true)); - }; - - function object_() { - var first = true, a = []; - while (!is("punc", "}")) { - if (first) first = false; else expect(","); - if (!exigent_mode && is("punc", "}")) - // allow trailing comma - break; - var type = S.token.type; - var name = as_property_name(); - if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) { - a.push([ as_name(), function_(false), name ]); - } else { - expect(":"); - a.push([ name, expression(false) ]); - } - } - next(); - return as("object", a); - }; - - function as_property_name() { - switch (S.token.type) { - case "num": - case "string": - return prog1(S.token.value, next); - } - return as_name(); - }; - - function as_name() { - switch (S.token.type) { - case "name": - case "operator": - case "keyword": - case "atom": - return prog1(S.token.value, next); - default: - unexpected(); - } - }; - - function subscripts(expr, allow_calls) { - if (is("punc", ".")) { - next(); - return subscripts(as("dot", expr, as_name()), allow_calls); - } - if (is("punc", "[")) { - next(); - return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls); - } - if (allow_calls && is("punc", "(")) { - next(); - return subscripts(as("call", expr, expr_list(")")), true); - } - if (allow_calls && is("operator") && HOP(UNARY_POSTFIX, S.token.value)) { - return prog1(curry(make_unary, "unary-postfix", S.token.value, expr), - next); - } - return expr; - }; - - function make_unary(tag, op, expr) { - if ((op == "++" || op == "--") && !is_assignable(expr)) - croak("Invalid use of " + op + " operator"); - return as(tag, op, expr); - }; - - function expr_op(left, min_prec, no_in) { - var op = is("operator") ? S.token.value : null; - if (op && op == "in" && no_in) op = null; - var prec = op != null ? PRECEDENCE[op] : null; - if (prec != null && prec > min_prec) { - next(); - var right = expr_op(expr_atom(true), prec, no_in); - return expr_op(as("binary", op, left, right), min_prec, no_in); - } - return left; - }; - - function expr_ops(no_in) { - return expr_op(expr_atom(true), 0, no_in); - }; - - function maybe_conditional(no_in) { - var expr = expr_ops(no_in); - if (is("operator", "?")) { - next(); - var yes = expression(false); - expect(":"); - return as("conditional", expr, yes, expression(false, no_in)); - } - return expr; - }; - - function is_assignable(expr) { - if (!exigent_mode) return true; - switch (expr[0]) { - case "dot": - case "sub": - case "new": - case "call": - return true; - case "name": - return expr[1] != "this"; - } - }; - - function maybe_assign(no_in) { - var left = maybe_conditional(no_in), val = S.token.value; - if (is("operator") && HOP(ASSIGNMENT, val)) { - if (is_assignable(left)) { - next(); - return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in)); - } - croak("Invalid assignment"); - } - return left; - }; - - var expression = maybe_embed_tokens(function(commas, no_in) { - if (arguments.length == 0) - commas = true; - var expr = maybe_assign(no_in); - if (commas && is("punc", ",")) { - next(); - return as("seq", expr, expression(true, no_in)); - } - return expr; - }); - - function in_loop(cont) { - try { - ++S.in_loop; - return cont(); - } finally { - --S.in_loop; - } - }; - - return as("toplevel", (function(a){ - while (!is("eof")) - a.push(statement()); - return a; - })([])); - -}; - -/* -----[ Utilities ]----- */ - -function curry(f) { - var args = slice(arguments, 1); - return function() { return f.apply(this, args.concat(slice(arguments))); }; -}; - -function prog1(ret) { - if (ret instanceof Function) - ret = ret(); - for (var i = 1, n = arguments.length; --n > 0; ++i) - arguments[i](); - return ret; -}; - -function array_to_hash(a) { - var ret = {}; - for (var i = 0; i < a.length; ++i) - ret[a[i]] = true; - return ret; -}; - -function slice(a, start) { - return Array.prototype.slice.call(a, start == null ? 0 : start); -}; - -function characters(str) { - return str.split(""); -}; - -function member(name, array) { - for (var i = array.length; --i >= 0;) - if (array[i] === name) - return true; - return false; -}; - -function HOP(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -}; - -var warn = function() {}; - -/* -----[ Exports ]----- */ - -exports.tokenizer = tokenizer; -exports.parse = parse; -exports.slice = slice; -exports.curry = curry; -exports.member = member; -exports.array_to_hash = array_to_hash; -exports.PRECEDENCE = PRECEDENCE; -exports.KEYWORDS_ATOM = KEYWORDS_ATOM; -exports.RESERVED_WORDS = RESERVED_WORDS; -exports.KEYWORDS = KEYWORDS; -exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN; -exports.OPERATORS = OPERATORS; -exports.is_alphanumeric_char = is_alphanumeric_char; -exports.set_logger = function(logger) { - warn = logger; -}; -; - }).call(module.exports); - - __require.modules["/node_modules/burrito/node_modules/uglify-js/lib/parse-js.js"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/burrito/node_modules/uglify-js/lib/process.js"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/burrito/node_modules/uglify-js/lib"; - var __filename = "/node_modules/burrito/node_modules/uglify-js/lib/process.js"; - - var require = function (file) { - return __require(file, "/node_modules/burrito/node_modules/uglify-js/lib"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/burrito/node_modules/uglify-js/lib"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/burrito/node_modules/uglify-js/lib/process.js"]._cached = module.exports; - - (function () { - /*********************************************************************** - - A JavaScript tokenizer / parser / beautifier / compressor. - - This version is suitable for Node.js. With minimal changes (the - exports stuff) it should work on any JS platform. - - This file implements some AST processors. They work on data built - by parse-js. - - Exported functions: - - - ast_mangle(ast, options) -- mangles the variable/function names - in the AST. Returns an AST. - - - ast_squeeze(ast) -- employs various optimizations to make the - final generated code even smaller. Returns an AST. - - - gen_code(ast, options) -- generates JS code from the AST. Pass - true (or an object, see the code for some options) as second - argument to get "pretty" (indented) code. - - -------------------------------- (C) --------------------------------- - - Author: Mihai Bazon - - http://mihai.bazon.net/blog - - Distributed under the BSD license: - - Copyright 2010 (c) Mihai Bazon - - 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. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 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. - - ***********************************************************************/ - -var jsp = require("./parse-js"), - slice = jsp.slice, - member = jsp.member, - PRECEDENCE = jsp.PRECEDENCE, - OPERATORS = jsp.OPERATORS; - -/* -----[ helper for AST traversal ]----- */ - -function ast_walker(ast) { - function _vardefs(defs) { - return [ this[0], MAP(defs, function(def){ - var a = [ def[0] ]; - if (def.length > 1) - a[1] = walk(def[1]); - return a; - }) ]; - }; - function _block(statements) { - var out = [ this[0] ]; - if (statements != null) - out.push(MAP(statements, walk)); - return out; - }; - var walkers = { - "string": function(str) { - return [ this[0], str ]; - }, - "num": function(num) { - return [ this[0], num ]; - }, - "name": function(name) { - return [ this[0], name ]; - }, - "toplevel": function(statements) { - return [ this[0], MAP(statements, walk) ]; - }, - "block": _block, - "splice": _block, - "var": _vardefs, - "const": _vardefs, - "try": function(t, c, f) { - return [ - this[0], - MAP(t, walk), - c != null ? [ c[0], MAP(c[1], walk) ] : null, - f != null ? MAP(f, walk) : null - ]; - }, - "throw": function(expr) { - return [ this[0], walk(expr) ]; - }, - "new": function(ctor, args) { - return [ this[0], walk(ctor), MAP(args, walk) ]; - }, - "switch": function(expr, body) { - return [ this[0], walk(expr), MAP(body, function(branch){ - return [ branch[0] ? walk(branch[0]) : null, - MAP(branch[1], walk) ]; - }) ]; - }, - "break": function(label) { - return [ this[0], label ]; - }, - "continue": function(label) { - return [ this[0], label ]; - }, - "conditional": function(cond, t, e) { - return [ this[0], walk(cond), walk(t), walk(e) ]; - }, - "assign": function(op, lvalue, rvalue) { - return [ this[0], op, walk(lvalue), walk(rvalue) ]; - }, - "dot": function(expr) { - return [ this[0], walk(expr) ].concat(slice(arguments, 1)); - }, - "call": function(expr, args) { - return [ this[0], walk(expr), MAP(args, walk) ]; - }, - "function": function(name, args, body) { - return [ this[0], name, args.slice(), MAP(body, walk) ]; - }, - "defun": function(name, args, body) { - return [ this[0], name, args.slice(), MAP(body, walk) ]; - }, - "if": function(conditional, t, e) { - return [ this[0], walk(conditional), walk(t), walk(e) ]; - }, - "for": function(init, cond, step, block) { - return [ this[0], walk(init), walk(cond), walk(step), walk(block) ]; - }, - "for-in": function(vvar, key, hash, block) { - return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ]; - }, - "while": function(cond, block) { - return [ this[0], walk(cond), walk(block) ]; - }, - "do": function(cond, block) { - return [ this[0], walk(cond), walk(block) ]; - }, - "return": function(expr) { - return [ this[0], walk(expr) ]; - }, - "binary": function(op, left, right) { - return [ this[0], op, walk(left), walk(right) ]; - }, - "unary-prefix": function(op, expr) { - return [ this[0], op, walk(expr) ]; - }, - "unary-postfix": function(op, expr) { - return [ this[0], op, walk(expr) ]; - }, - "sub": function(expr, subscript) { - return [ this[0], walk(expr), walk(subscript) ]; - }, - "object": function(props) { - return [ this[0], MAP(props, function(p){ - return p.length == 2 - ? [ p[0], walk(p[1]) ] - : [ p[0], walk(p[1]), p[2] ]; // get/set-ter - }) ]; - }, - "regexp": function(rx, mods) { - return [ this[0], rx, mods ]; - }, - "array": function(elements) { - return [ this[0], MAP(elements, walk) ]; - }, - "stat": function(stat) { - return [ this[0], walk(stat) ]; - }, - "seq": function() { - return [ this[0] ].concat(MAP(slice(arguments), walk)); - }, - "label": function(name, block) { - return [ this[0], name, walk(block) ]; - }, - "with": function(expr, block) { - return [ this[0], walk(expr), walk(block) ]; - }, - "atom": function(name) { - return [ this[0], name ]; - } - }; - - var user = {}; - var stack = []; - function walk(ast) { - if (ast == null) - return null; - try { - stack.push(ast); - var type = ast[0]; - var gen = user[type]; - if (gen) { - var ret = gen.apply(ast, ast.slice(1)); - if (ret != null) - return ret; - } - gen = walkers[type]; - return gen.apply(ast, ast.slice(1)); - } finally { - stack.pop(); - } - }; - - function with_walkers(walkers, cont){ - var save = {}, i; - for (i in walkers) if (HOP(walkers, i)) { - save[i] = user[i]; - user[i] = walkers[i]; - } - var ret = cont(); - for (i in save) if (HOP(save, i)) { - if (!save[i]) delete user[i]; - else user[i] = save[i]; - } - return ret; - }; - - return { - walk: walk, - with_walkers: with_walkers, - parent: function() { - return stack[stack.length - 2]; // last one is current node - }, - stack: function() { - return stack; - } - }; -}; - -/* -----[ Scope and mangling ]----- */ - -function Scope(parent) { - this.names = {}; // names defined in this scope - this.mangled = {}; // mangled names (orig.name => mangled) - this.rev_mangled = {}; // reverse lookup (mangled => orig.name) - this.cname = -1; // current mangled name - this.refs = {}; // names referenced from this scope - this.uses_with = false; // will become TRUE if with() is detected in this or any subscopes - this.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes - this.parent = parent; // parent scope - this.children = []; // sub-scopes - if (parent) { - this.level = parent.level + 1; - parent.children.push(this); - } else { - this.level = 0; - } -}; - -var base54 = (function(){ - var DIGITS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_"; - return function(num) { - var ret = ""; - do { - ret = DIGITS.charAt(num % 54) + ret; - num = Math.floor(num / 54); - } while (num > 0); - return ret; - }; -})(); - -Scope.prototype = { - has: function(name) { - for (var s = this; s; s = s.parent) - if (HOP(s.names, name)) - return s; - }, - has_mangled: function(mname) { - for (var s = this; s; s = s.parent) - if (HOP(s.rev_mangled, mname)) - return s; - }, - toJSON: function() { - return { - names: this.names, - uses_eval: this.uses_eval, - uses_with: this.uses_with - }; - }, - - next_mangled: function() { - // we must be careful that the new mangled name: - // - // 1. doesn't shadow a mangled name from a parent - // scope, unless we don't reference the original - // name from this scope OR from any sub-scopes! - // This will get slow. - // - // 2. doesn't shadow an original name from a parent - // scope, in the event that the name is not mangled - // in the parent scope and we reference that name - // here OR IN ANY SUBSCOPES! - // - // 3. doesn't shadow a name that is referenced but not - // defined (possibly global defined elsewhere). - for (;;) { - var m = base54(++this.cname), prior; - - // case 1. - prior = this.has_mangled(m); - if (prior && this.refs[prior.rev_mangled[m]] === prior) - continue; - - // case 2. - prior = this.has(m); - if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m)) - continue; - - // case 3. - if (HOP(this.refs, m) && this.refs[m] == null) - continue; - - // I got "do" once. :-/ - if (!is_identifier(m)) - continue; - - return m; - } - }, - set_mangle: function(name, m) { - this.rev_mangled[m] = name; - return this.mangled[name] = m; - }, - get_mangled: function(name, newMangle) { - if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use - var s = this.has(name); - if (!s) return name; // not in visible scope, no mangle - if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope - if (!newMangle) return name; // not found and no mangling requested - return s.set_mangle(name, s.next_mangled()); - }, - define: function(name) { - if (name != null) - return this.names[name] = name; - } -}; - -function ast_add_scope(ast) { - - var current_scope = null; - var w = ast_walker(), walk = w.walk; - var having_eval = []; - - function with_new_scope(cont) { - current_scope = new Scope(current_scope); - var ret = current_scope.body = cont(); - ret.scope = current_scope; - current_scope = current_scope.parent; - return ret; - }; - - function define(name) { - return current_scope.define(name); - }; - - function reference(name) { - current_scope.refs[name] = true; - }; - - function _lambda(name, args, body) { - var is_defun = this[0] == "defun"; - return [ this[0], is_defun ? define(name) : name, args, with_new_scope(function(){ - if (!is_defun) define(name); - MAP(args, define); - return MAP(body, walk); - })]; - }; - - return with_new_scope(function(){ - // process AST - var ret = w.with_walkers({ - "function": _lambda, - "defun": _lambda, - "with": function(expr, block) { - for (var s = current_scope; s; s = s.parent) - s.uses_with = true; - }, - "var": function(defs) { - MAP(defs, function(d){ define(d[0]) }); - }, - "const": function(defs) { - MAP(defs, function(d){ define(d[0]) }); - }, - "try": function(t, c, f) { - if (c != null) return [ - this[0], - MAP(t, walk), - [ define(c[0]), MAP(c[1], walk) ], - f != null ? MAP(f, walk) : null - ]; - }, - "name": function(name) { - if (name == "eval") - having_eval.push(current_scope); - reference(name); - } - }, function(){ - return walk(ast); - }); - - // the reason why we need an additional pass here is - // that names can be used prior to their definition. - - // scopes where eval was detected and their parents - // are marked with uses_eval, unless they define the - // "eval" name. - MAP(having_eval, function(scope){ - if (!scope.has("eval")) while (scope) { - scope.uses_eval = true; - scope = scope.parent; - } - }); - - // for referenced names it might be useful to know - // their origin scope. current_scope here is the - // toplevel one. - function fixrefs(scope, i) { - // do children first; order shouldn't matter - for (i = scope.children.length; --i >= 0;) - fixrefs(scope.children[i]); - for (i in scope.refs) if (HOP(scope.refs, i)) { - // find origin scope and propagate the reference to origin - for (var origin = scope.has(i), s = scope; s; s = s.parent) { - s.refs[i] = origin; - if (s === origin) break; - } - } - }; - fixrefs(current_scope); - - return ret; - }); - -}; - -/* -----[ mangle names ]----- */ - -function ast_mangle(ast, options) { - var w = ast_walker(), walk = w.walk, scope; - options = options || {}; - - function get_mangled(name, newMangle) { - if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel - if (options.except && member(name, options.except)) - return name; - return scope.get_mangled(name, newMangle); - }; - - function get_define(name) { - if (options.defines) { - // we always lookup a defined symbol for the current scope FIRST, so declared - // vars trump a DEFINE symbol, but if no such var is found, then match a DEFINE value - if (!scope.has(name)) { - if (HOP(options.defines, name)) { - return options.defines[name]; - } - } - return null; - } - }; - - function _lambda(name, args, body) { - var is_defun = this[0] == "defun", extra; - if (name) { - if (is_defun) name = get_mangled(name); - else { - extra = {}; - name = extra[name] = scope.next_mangled(); - } - } - body = with_scope(body.scope, function(){ - args = MAP(args, function(name){ return get_mangled(name) }); - return MAP(body, walk); - }, extra); - return [ this[0], name, args, body ]; - }; - - function with_scope(s, cont, extra) { - var _scope = scope; - scope = s; - if (extra) for (var i in extra) if (HOP(extra, i)) { - s.set_mangle(i, extra[i]); - } - for (var i in s.names) if (HOP(s.names, i)) { - get_mangled(i, true); - } - var ret = cont(); - ret.scope = s; - scope = _scope; - return ret; - }; - - function _vardefs(defs) { - return [ this[0], MAP(defs, function(d){ - return [ get_mangled(d[0]), walk(d[1]) ]; - }) ]; - }; - - return w.with_walkers({ - "function": _lambda, - "defun": function() { - // move function declarations to the top when - // they are not in some block. - var ast = _lambda.apply(this, arguments); - switch (w.parent()[0]) { - case "toplevel": - case "function": - case "defun": - return MAP.at_top(ast); - } - return ast; - }, - "var": _vardefs, - "const": _vardefs, - "name": function(name) { - return get_define(name) || [ this[0], get_mangled(name) ]; - }, - "try": function(t, c, f) { - return [ this[0], - MAP(t, walk), - c != null ? [ get_mangled(c[0]), MAP(c[1], walk) ] : null, - f != null ? MAP(f, walk) : null ]; - }, - "toplevel": function(body) { - var self = this; - return with_scope(self.scope, function(){ - return [ self[0], MAP(body, walk) ]; - }); - } - }, function() { - return walk(ast_add_scope(ast)); - }); -}; - -/* -----[ - - compress foo["bar"] into foo.bar, - - remove block brackets {} where possible - - join consecutive var declarations - - various optimizations for IFs: - - if (cond) foo(); else bar(); ==> cond?foo():bar(); - - if (cond) foo(); ==> cond&&foo(); - - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw - - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()} - ]----- */ - -var warn = function(){}; - -function best_of(ast1, ast2) { - return gen_code(ast1).length > gen_code(ast2[0] == "stat" ? ast2[1] : ast2).length ? ast2 : ast1; -}; - -function last_stat(b) { - if (b[0] == "block" && b[1] && b[1].length > 0) - return b[1][b[1].length - 1]; - return b; -} - -function aborts(t) { - if (t) { - t = last_stat(t); - if (t[0] == "return" || t[0] == "break" || t[0] == "continue" || t[0] == "throw") - return true; - } -}; - -function boolean_expr(expr) { - return ( (expr[0] == "unary-prefix" - && member(expr[1], [ "!", "delete" ])) || - - (expr[0] == "binary" - && member(expr[1], [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ])) || - - (expr[0] == "binary" - && member(expr[1], [ "&&", "||" ]) - && boolean_expr(expr[2]) - && boolean_expr(expr[3])) || - - (expr[0] == "conditional" - && boolean_expr(expr[2]) - && boolean_expr(expr[3])) || - - (expr[0] == "assign" - && expr[1] === true - && boolean_expr(expr[3])) || - - (expr[0] == "seq" - && boolean_expr(expr[expr.length - 1])) - ); -}; - -function make_conditional(c, t, e) { - var make_real_conditional = function() { - if (c[0] == "unary-prefix" && c[1] == "!") { - return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ]; - } else { - return e ? [ "conditional", c, t, e ] : [ "binary", "&&", c, t ]; - } - }; - // shortcut the conditional if the expression has a constant value - return when_constant(c, function(ast, val){ - warn_unreachable(val ? e : t); - return (val ? t : e); - }, make_real_conditional); -}; - -function empty(b) { - return !b || (b[0] == "block" && (!b[1] || b[1].length == 0)); -}; - -function is_string(node) { - return (node[0] == "string" || - node[0] == "unary-prefix" && node[1] == "typeof" || - node[0] == "binary" && node[1] == "+" && - (is_string(node[2]) || is_string(node[3]))); -}; - -var when_constant = (function(){ - - var $NOT_CONSTANT = {}; - - // this can only evaluate constant expressions. If it finds anything - // not constant, it throws $NOT_CONSTANT. - function evaluate(expr) { - switch (expr[0]) { - case "string": - case "num": - return expr[1]; - case "name": - case "atom": - switch (expr[1]) { - case "true": return true; - case "false": return false; - } - break; - case "unary-prefix": - switch (expr[1]) { - case "!": return !evaluate(expr[2]); - case "typeof": return typeof evaluate(expr[2]); - case "~": return ~evaluate(expr[2]); - case "-": return -evaluate(expr[2]); - case "+": return +evaluate(expr[2]); - } - break; - case "binary": - var left = expr[2], right = expr[3]; - switch (expr[1]) { - case "&&" : return evaluate(left) && evaluate(right); - case "||" : return evaluate(left) || evaluate(right); - case "|" : return evaluate(left) | evaluate(right); - case "&" : return evaluate(left) & evaluate(right); - case "^" : return evaluate(left) ^ evaluate(right); - case "+" : return evaluate(left) + evaluate(right); - case "*" : return evaluate(left) * evaluate(right); - case "/" : return evaluate(left) / evaluate(right); - case "-" : return evaluate(left) - evaluate(right); - case "<<" : return evaluate(left) << evaluate(right); - case ">>" : return evaluate(left) >> evaluate(right); - case ">>>" : return evaluate(left) >>> evaluate(right); - case "==" : return evaluate(left) == evaluate(right); - case "===" : return evaluate(left) === evaluate(right); - case "!=" : return evaluate(left) != evaluate(right); - case "!==" : return evaluate(left) !== evaluate(right); - case "<" : return evaluate(left) < evaluate(right); - case "<=" : return evaluate(left) <= evaluate(right); - case ">" : return evaluate(left) > evaluate(right); - case ">=" : return evaluate(left) >= evaluate(right); - case "in" : return evaluate(left) in evaluate(right); - case "instanceof" : return evaluate(left) instanceof evaluate(right); - } - } - throw $NOT_CONSTANT; - }; - - return function(expr, yes, no) { - try { - var val = evaluate(expr), ast; - switch (typeof val) { - case "string": ast = [ "string", val ]; break; - case "number": ast = [ "num", val ]; break; - case "boolean": ast = [ "name", String(val) ]; break; - default: throw new Error("Can't handle constant of type: " + (typeof val)); - } - return yes.call(expr, ast, val); - } catch(ex) { - if (ex === $NOT_CONSTANT) { - if (expr[0] == "binary" - && (expr[1] == "===" || expr[1] == "!==") - && ((is_string(expr[2]) && is_string(expr[3])) - || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) { - expr[1] = expr[1].substr(0, 2); - } - else if (no && expr[0] == "binary" - && (expr[1] == "||" || expr[1] == "&&")) { - // the whole expression is not constant but the lval may be... - try { - var lval = evaluate(expr[2]); - expr = ((expr[1] == "&&" && (lval ? expr[3] : lval)) || - (expr[1] == "||" && (lval ? lval : expr[3])) || - expr); - } catch(ex2) { - // IGNORE... lval is not constant - } - } - return no ? no.call(expr, expr) : null; - } - else throw ex; - } - }; - -})(); - -function warn_unreachable(ast) { - if (!empty(ast)) - warn("Dropping unreachable code: " + gen_code(ast, true)); -}; - -function prepare_ifs(ast) { - var w = ast_walker(), walk = w.walk; - // In this first pass, we rewrite ifs which abort with no else with an - // if-else. For example: - // - // if (x) { - // blah(); - // return y; - // } - // foobar(); - // - // is rewritten into: - // - // if (x) { - // blah(); - // return y; - // } else { - // foobar(); - // } - function redo_if(statements) { - statements = MAP(statements, walk); - - for (var i = 0; i < statements.length; ++i) { - var fi = statements[i]; - if (fi[0] != "if") continue; - - if (fi[3] && walk(fi[3])) continue; - - var t = walk(fi[2]); - if (!aborts(t)) continue; - - var conditional = walk(fi[1]); - - var e_body = statements.slice(i + 1); - var e; - if (e_body.length == 1) e = e_body[0]; - else e = [ "block", e_body ]; - - var ret = statements.slice(0, i).concat([ [ - fi[0], // "if" - conditional, // conditional - t, // then - e // else - ] ]); - - return redo_if(ret); - } - - return statements; - }; - - function redo_if_lambda(name, args, body) { - body = redo_if(body); - return [ this[0], name, args.slice(), body ]; - }; - - function redo_if_block(statements) { - var out = [ this[0] ]; - if (statements != null) - out.push(redo_if(statements)); - return out; - }; - - return w.with_walkers({ - "defun": redo_if_lambda, - "function": redo_if_lambda, - "block": redo_if_block, - "splice": redo_if_block, - "toplevel": function(statements) { - return [ this[0], redo_if(statements) ]; - }, - "try": function(t, c, f) { - return [ - this[0], - redo_if(t), - c != null ? [ c[0], redo_if(c[1]) ] : null, - f != null ? redo_if(f) : null - ]; - }, - "with": function(expr, block) { - return [ this[0], walk(expr), redo_if(block) ]; - } - }, function() { - return walk(ast); - }); -}; - -function ast_squeeze(ast, options) { - options = defaults(options, { - make_seqs : true, - dead_code : true, - keep_comps : true, - no_warnings : false - }); - - var w = ast_walker(), walk = w.walk, scope; - - function negate(c) { - var not_c = [ "unary-prefix", "!", c ]; - switch (c[0]) { - case "unary-prefix": - return c[1] == "!" && boolean_expr(c[2]) ? c[2] : not_c; - case "seq": - c = slice(c); - c[c.length - 1] = negate(c[c.length - 1]); - return c; - case "conditional": - return best_of(not_c, [ "conditional", c[1], negate(c[2]), negate(c[3]) ]); - case "binary": - var op = c[1], left = c[2], right = c[3]; - if (!options.keep_comps) switch (op) { - case "<=" : return [ "binary", ">", left, right ]; - case "<" : return [ "binary", ">=", left, right ]; - case ">=" : return [ "binary", "<", left, right ]; - case ">" : return [ "binary", "<=", left, right ]; - } - switch (op) { - case "==" : return [ "binary", "!=", left, right ]; - case "!=" : return [ "binary", "==", left, right ]; - case "===" : return [ "binary", "!==", left, right ]; - case "!==" : return [ "binary", "===", left, right ]; - case "&&" : return best_of(not_c, [ "binary", "||", negate(left), negate(right) ]); - case "||" : return best_of(not_c, [ "binary", "&&", negate(left), negate(right) ]); - } - break; - } - return not_c; - }; - - function with_scope(s, cont) { - var _scope = scope; - scope = s; - var ret = cont(); - ret.scope = s; - scope = _scope; - return ret; - }; - - function rmblock(block) { - if (block != null && block[0] == "block" && block[1]) { - if (block[1].length == 1) - block = block[1][0]; - else if (block[1].length == 0) - block = [ "block" ]; - } - return block; - }; - - function _lambda(name, args, body) { - var is_defun = this[0] == "defun"; - body = with_scope(body.scope, function(){ - var ret = tighten(MAP(body, walk), "lambda"); - if (!is_defun && name && !HOP(scope.refs, name)) - name = null; - return ret; - }); - return [ this[0], name, args, body ]; - }; - - // we get here for blocks that have been already transformed. - // this function does a few things: - // 1. discard useless blocks - // 2. join consecutive var declarations - // 3. remove obviously dead code - // 4. transform consecutive statements using the comma operator - // 5. if block_type == "lambda" and it detects constructs like if(foo) return ... - rewrite like if (!foo) { ... } - function tighten(statements, block_type) { - statements = statements.reduce(function(a, stat){ - if (stat[0] == "block") { - if (stat[1]) { - a.push.apply(a, stat[1]); - } - } else { - a.push(stat); - } - return a; - }, []); - - statements = (function(a, prev){ - statements.forEach(function(cur){ - if (prev && ((cur[0] == "var" && prev[0] == "var") || - (cur[0] == "const" && prev[0] == "const"))) { - prev[1] = prev[1].concat(cur[1]); - } else { - a.push(cur); - prev = cur; - } - }); - return a; - })([]); - - if (options.dead_code) statements = (function(a, has_quit){ - statements.forEach(function(st){ - if (has_quit) { - if (member(st[0], [ "function", "defun" , "var", "const" ])) { - a.push(st); - } - else if (!options.no_warnings) - warn_unreachable(st); - } - else { - a.push(st); - if (member(st[0], [ "return", "throw", "break", "continue" ])) - has_quit = true; - } - }); - return a; - })([]); - - if (options.make_seqs) statements = (function(a, prev) { - statements.forEach(function(cur){ - if (prev && prev[0] == "stat" && cur[0] == "stat") { - prev[1] = [ "seq", prev[1], cur[1] ]; - } else { - a.push(cur); - prev = cur; - } - }); - return a; - })([]); - - if (block_type == "lambda") statements = (function(i, a, stat){ - while (i < statements.length) { - stat = statements[i++]; - if (stat[0] == "if" && !stat[3]) { - if (stat[2][0] == "return" && stat[2][1] == null) { - a.push(make_if(negate(stat[1]), [ "block", statements.slice(i) ])); - break; - } - var last = last_stat(stat[2]); - if (last[0] == "return" && last[1] == null) { - a.push(make_if(stat[1], [ "block", stat[2][1].slice(0, -1) ], [ "block", statements.slice(i) ])); - break; - } - } - a.push(stat); - } - return a; - })(0, []); - - return statements; - }; - - function make_if(c, t, e) { - return when_constant(c, function(ast, val){ - if (val) { - warn_unreachable(e); - return t; - } else { - warn_unreachable(t); - return e; - } - }, function() { - return make_real_if(c, t, e); - }); - }; - - function make_real_if(c, t, e) { - c = walk(c); - t = walk(t); - e = walk(e); - - if (empty(t)) { - c = negate(c); - t = e; - e = null; - } else if (empty(e)) { - e = null; - } else { - // if we have both else and then, maybe it makes sense to switch them? - (function(){ - var a = gen_code(c); - var n = negate(c); - var b = gen_code(n); - if (b.length < a.length) { - var tmp = t; - t = e; - e = tmp; - c = n; - } - })(); - } - if (empty(e) && empty(t)) - return [ "stat", c ]; - var ret = [ "if", c, t, e ]; - if (t[0] == "if" && empty(t[3]) && empty(e)) { - ret = best_of(ret, walk([ "if", [ "binary", "&&", c, t[1] ], t[2] ])); - } - else if (t[0] == "stat") { - if (e) { - if (e[0] == "stat") { - ret = best_of(ret, [ "stat", make_conditional(c, t[1], e[1]) ]); - } - } - else { - ret = best_of(ret, [ "stat", make_conditional(c, t[1]) ]); - } - } - else if (e && t[0] == e[0] && (t[0] == "return" || t[0] == "throw") && t[1] && e[1]) { - ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]); - } - else if (e && aborts(t)) { - ret = [ [ "if", c, t ] ]; - if (e[0] == "block") { - if (e[1]) ret = ret.concat(e[1]); - } - else { - ret.push(e); - } - ret = walk([ "block", ret ]); - } - else if (t && aborts(e)) { - ret = [ [ "if", negate(c), e ] ]; - if (t[0] == "block") { - if (t[1]) ret = ret.concat(t[1]); - } else { - ret.push(t); - } - ret = walk([ "block", ret ]); - } - return ret; - }; - - function _do_while(cond, body) { - return when_constant(cond, function(cond, val){ - if (!val) { - warn_unreachable(body); - return [ "block" ]; - } else { - return [ "for", null, null, null, walk(body) ]; - } - }); - }; - - ast = prepare_ifs(ast); - ast = ast_add_scope(ast); - - return w.with_walkers({ - "sub": function(expr, subscript) { - if (subscript[0] == "string") { - var name = subscript[1]; - if (is_identifier(name)) - return [ "dot", walk(expr), name ]; - else if (/^[1-9][0-9]*$/.test(name) || name === "0") - return [ "sub", walk(expr), [ "num", parseInt(name, 10) ] ]; - } - }, - "if": make_if, - "toplevel": function(body) { - return [ "toplevel", with_scope(this.scope, function(){ - return tighten(MAP(body, walk)); - }) ]; - }, - "switch": function(expr, body) { - var last = body.length - 1; - return [ "switch", walk(expr), MAP(body, function(branch, i){ - var block = tighten(MAP(branch[1], walk)); - if (i == last && block.length > 0) { - var node = block[block.length - 1]; - if (node[0] == "break" && !node[1]) - block.pop(); - } - return [ branch[0] ? walk(branch[0]) : null, block ]; - }) ]; - }, - "function": _lambda, - "defun": _lambda, - "block": function(body) { - if (body) return rmblock([ "block", tighten(MAP(body, walk)) ]); - }, - "binary": function(op, left, right) { - return when_constant([ "binary", op, walk(left), walk(right) ], function yes(c){ - return best_of(walk(c), this); - }, function no() { - return this; - }); - }, - "conditional": function(c, t, e) { - return make_conditional(walk(c), walk(t), walk(e)); - }, - "try": function(t, c, f) { - return [ - "try", - tighten(MAP(t, walk)), - c != null ? [ c[0], tighten(MAP(c[1], walk)) ] : null, - f != null ? tighten(MAP(f, walk)) : null - ]; - }, - "unary-prefix": function(op, expr) { - expr = walk(expr); - var ret = [ "unary-prefix", op, expr ]; - if (op == "!") - ret = best_of(ret, negate(expr)); - return when_constant(ret, function(ast, val){ - return walk(ast); // it's either true or false, so minifies to !0 or !1 - }, function() { return ret }); - }, - "name": function(name) { - switch (name) { - case "true": return [ "unary-prefix", "!", [ "num", 0 ]]; - case "false": return [ "unary-prefix", "!", [ "num", 1 ]]; - } - }, - "new": function(ctor, args) { - if (ctor[0] == "name" && ctor[1] == "Array" && !scope.has("Array")) { - if (args.length != 1) { - return [ "array", args ]; - } else { - return [ "call", [ "name", "Array" ], args ]; - } - } - }, - "call": function(expr, args) { - if (expr[0] == "name" && expr[1] == "Array" && args.length != 1 && !scope.has("Array")) { - return [ "array", args ]; - } - }, - "while": _do_while - }, function() { - return walk(ast); - }); -}; - -/* -----[ re-generate code from the AST ]----- */ - -var DOT_CALL_NO_PARENS = jsp.array_to_hash([ - "name", - "array", - "object", - "string", - "dot", - "sub", - "call", - "regexp" -]); - -function make_string(str, ascii_only) { - var dq = 0, sq = 0; - str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029]/g, function(s){ - switch (s) { - case "\\": return "\\\\"; - case "\b": return "\\b"; - case "\f": return "\\f"; - case "\n": return "\\n"; - case "\r": return "\\r"; - case "\t": return "\\t"; - case "\u2028": return "\\u2028"; - case "\u2029": return "\\u2029"; - case '"': ++dq; return '"'; - case "'": ++sq; return "'"; - } - return s; - }); - if (ascii_only) str = to_ascii(str); - if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'"; - else return '"' + str.replace(/\x22/g, '\\"') + '"'; -}; - -function to_ascii(str) { - return str.replace(/[\u0080-\uffff]/g, function(ch) { - var code = ch.charCodeAt(0).toString(16); - while (code.length < 4) code = "0" + code; - return "\\u" + code; - }); -}; - -var SPLICE_NEEDS_BRACKETS = jsp.array_to_hash([ "if", "while", "do", "for", "for-in", "with" ]); - -function gen_code(ast, options) { - options = defaults(options, { - indent_start : 0, - indent_level : 4, - quote_keys : false, - space_colon : false, - beautify : false, - ascii_only : false - }); - var beautify = !!options.beautify; - var indentation = 0, - newline = beautify ? "\n" : "", - space = beautify ? " " : ""; - - function encode_string(str) { - return make_string(str, options.ascii_only); - }; - - function make_name(name) { - name = name.toString(); - if (options.ascii_only) - name = to_ascii(name); - return name; - }; - - function indent(line) { - if (line == null) - line = ""; - if (beautify) - line = repeat_string(" ", options.indent_start + indentation * options.indent_level) + line; - return line; - }; - - function with_indent(cont, incr) { - if (incr == null) incr = 1; - indentation += incr; - try { return cont.apply(null, slice(arguments, 1)); } - finally { indentation -= incr; } - }; - - function add_spaces(a) { - if (beautify) - return a.join(" "); - var b = []; - for (var i = 0; i < a.length; ++i) { - var next = a[i + 1]; - b.push(a[i]); - if (next && - ((/[a-z0-9_\x24]$/i.test(a[i].toString()) && /^[a-z0-9_\x24]/i.test(next.toString())) || - (/[\+\-]$/.test(a[i].toString()) && /^[\+\-]/.test(next.toString())))) { - b.push(" "); - } - } - return b.join(""); - }; - - function add_commas(a) { - return a.join("," + space); - }; - - function parenthesize(expr) { - var gen = make(expr); - for (var i = 1; i < arguments.length; ++i) { - var el = arguments[i]; - if ((el instanceof Function && el(expr)) || expr[0] == el) - return "(" + gen + ")"; - } - return gen; - }; - - function best_of(a) { - if (a.length == 1) { - return a[0]; - } - if (a.length == 2) { - var b = a[1]; - a = a[0]; - return a.length <= b.length ? a : b; - } - return best_of([ a[0], best_of(a.slice(1)) ]); - }; - - function needs_parens(expr) { - if (expr[0] == "function" || expr[0] == "object") { - // dot/call on a literal function requires the - // function literal itself to be parenthesized - // only if it's the first "thing" in a - // statement. This means that the parent is - // "stat", but it could also be a "seq" and - // we're the first in this "seq" and the - // parent is "stat", and so on. Messy stuff, - // but it worths the trouble. - var a = slice($stack), self = a.pop(), p = a.pop(); - while (p) { - if (p[0] == "stat") return true; - if (((p[0] == "seq" || p[0] == "call" || p[0] == "dot" || p[0] == "sub" || p[0] == "conditional") && p[1] === self) || - ((p[0] == "binary" || p[0] == "assign" || p[0] == "unary-postfix") && p[2] === self)) { - self = p; - p = a.pop(); - } else { - return false; - } - } - } - return !HOP(DOT_CALL_NO_PARENS, expr[0]); - }; - - function make_num(num) { - var str = num.toString(10), a = [ str.replace(/^0\./, ".") ], m; - if (Math.floor(num) === num) { - a.push("0x" + num.toString(16).toLowerCase(), // probably pointless - "0" + num.toString(8)); // same. - if ((m = /^(.*?)(0+)$/.exec(num))) { - a.push(m[1] + "e" + m[2].length); - } - } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) { - a.push(m[2] + "e-" + (m[1].length + m[2].length), - str.substr(str.indexOf("."))); - } - return best_of(a); - }; - - var generators = { - "string": encode_string, - "num": make_num, - "name": make_name, - "toplevel": function(statements) { - return make_block_statements(statements) - .join(newline + newline); - }, - "splice": function(statements) { - var parent = $stack[$stack.length - 2][0]; - if (HOP(SPLICE_NEEDS_BRACKETS, parent)) { - // we need block brackets in this case - return make_block.apply(this, arguments); - } else { - return MAP(make_block_statements(statements, true), - function(line, i) { - // the first line is already indented - return i > 0 ? indent(line) : line; - }).join(newline); - } - }, - "block": make_block, - "var": function(defs) { - return "var " + add_commas(MAP(defs, make_1vardef)) + ";"; - }, - "const": function(defs) { - return "const " + add_commas(MAP(defs, make_1vardef)) + ";"; - }, - "try": function(tr, ca, fi) { - var out = [ "try", make_block(tr) ]; - if (ca) out.push("catch", "(" + ca[0] + ")", make_block(ca[1])); - if (fi) out.push("finally", make_block(fi)); - return add_spaces(out); - }, - "throw": function(expr) { - return add_spaces([ "throw", make(expr) ]) + ";"; - }, - "new": function(ctor, args) { - args = args.length > 0 ? "(" + add_commas(MAP(args, make)) + ")" : ""; - return add_spaces([ "new", parenthesize(ctor, "seq", "binary", "conditional", "assign", function(expr){ - var w = ast_walker(), has_call = {}; - try { - w.with_walkers({ - "call": function() { throw has_call }, - "function": function() { return this } - }, function(){ - w.walk(expr); - }); - } catch(ex) { - if (ex === has_call) - return true; - throw ex; - } - }) + args ]); - }, - "switch": function(expr, body) { - return add_spaces([ "switch", "(" + make(expr) + ")", make_switch_block(body) ]); - }, - "break": function(label) { - var out = "break"; - if (label != null) - out += " " + make_name(label); - return out + ";"; - }, - "continue": function(label) { - var out = "continue"; - if (label != null) - out += " " + make_name(label); - return out + ";"; - }, - "conditional": function(co, th, el) { - return add_spaces([ parenthesize(co, "assign", "seq", "conditional"), "?", - parenthesize(th, "seq"), ":", - parenthesize(el, "seq") ]); - }, - "assign": function(op, lvalue, rvalue) { - if (op && op !== true) op += "="; - else op = "="; - return add_spaces([ make(lvalue), op, parenthesize(rvalue, "seq") ]); - }, - "dot": function(expr) { - var out = make(expr), i = 1; - if (expr[0] == "num") { - if (!/\./.test(expr[1])) - out += "."; - } else if (needs_parens(expr)) - out = "(" + out + ")"; - while (i < arguments.length) - out += "." + make_name(arguments[i++]); - return out; - }, - "call": function(func, args) { - var f = make(func); - if (needs_parens(func)) - f = "(" + f + ")"; - return f + "(" + add_commas(MAP(args, function(expr){ - return parenthesize(expr, "seq"); - })) + ")"; - }, - "function": make_function, - "defun": make_function, - "if": function(co, th, el) { - var out = [ "if", "(" + make(co) + ")", el ? make_then(th) : make(th) ]; - if (el) { - out.push("else", make(el)); - } - return add_spaces(out); - }, - "for": function(init, cond, step, block) { - var out = [ "for" ]; - init = (init != null ? make(init) : "").replace(/;*\s*$/, ";" + space); - cond = (cond != null ? make(cond) : "").replace(/;*\s*$/, ";" + space); - step = (step != null ? make(step) : "").replace(/;*\s*$/, ""); - var args = init + cond + step; - if (args == "; ; ") args = ";;"; - out.push("(" + args + ")", make(block)); - return add_spaces(out); - }, - "for-in": function(vvar, key, hash, block) { - return add_spaces([ "for", "(" + - (vvar ? make(vvar).replace(/;+$/, "") : make(key)), - "in", - make(hash) + ")", make(block) ]); - }, - "while": function(condition, block) { - return add_spaces([ "while", "(" + make(condition) + ")", make(block) ]); - }, - "do": function(condition, block) { - return add_spaces([ "do", make(block), "while", "(" + make(condition) + ")" ]) + ";"; - }, - "return": function(expr) { - var out = [ "return" ]; - if (expr != null) out.push(make(expr)); - return add_spaces(out) + ";"; - }, - "binary": function(operator, lvalue, rvalue) { - var left = make(lvalue), right = make(rvalue); - // XXX: I'm pretty sure other cases will bite here. - // we need to be smarter. - // adding parens all the time is the safest bet. - if (member(lvalue[0], [ "assign", "conditional", "seq" ]) || - lvalue[0] == "binary" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]]) { - left = "(" + left + ")"; - } - if (member(rvalue[0], [ "assign", "conditional", "seq" ]) || - rvalue[0] == "binary" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]] && - !(rvalue[1] == operator && member(operator, [ "&&", "||", "*" ]))) { - right = "(" + right + ")"; - } - return add_spaces([ left, operator, right ]); - }, - "unary-prefix": function(operator, expr) { - var val = make(expr); - if (!(expr[0] == "num" || (expr[0] == "unary-prefix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr))) - val = "(" + val + ")"; - return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? " " : "") + val; - }, - "unary-postfix": function(operator, expr) { - var val = make(expr); - if (!(expr[0] == "num" || (expr[0] == "unary-postfix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr))) - val = "(" + val + ")"; - return val + operator; - }, - "sub": function(expr, subscript) { - var hash = make(expr); - if (needs_parens(expr)) - hash = "(" + hash + ")"; - return hash + "[" + make(subscript) + "]"; - }, - "object": function(props) { - if (props.length == 0) - return "{}"; - return "{" + newline + with_indent(function(){ - return MAP(props, function(p){ - if (p.length == 3) { - // getter/setter. The name is in p[0], the arg.list in p[1][2], the - // body in p[1][3] and type ("get" / "set") in p[2]. - return indent(make_function(p[0], p[1][2], p[1][3], p[2])); - } - var key = p[0], val = make(p[1]); - if (options.quote_keys) { - key = encode_string(key); - } else if ((typeof key == "number" || !beautify && +key + "" == key) - && parseFloat(key) >= 0) { - key = make_num(+key); - } else if (!is_identifier(key)) { - key = encode_string(key); - } - return indent(add_spaces(beautify && options.space_colon - ? [ key, ":", val ] - : [ key + ":", val ])); - }).join("," + newline); - }) + newline + indent("}"); - }, - "regexp": function(rx, mods) { - return "/" + rx + "/" + mods; - }, - "array": function(elements) { - if (elements.length == 0) return "[]"; - return add_spaces([ "[", add_commas(MAP(elements, function(el){ - if (!beautify && el[0] == "atom" && el[1] == "undefined") return ""; - return parenthesize(el, "seq"); - })), "]" ]); - }, - "stat": function(stmt) { - return make(stmt).replace(/;*\s*$/, ";"); - }, - "seq": function() { - return add_commas(MAP(slice(arguments), make)); - }, - "label": function(name, block) { - return add_spaces([ make_name(name), ":", make(block) ]); - }, - "with": function(expr, block) { - return add_spaces([ "with", "(" + make(expr) + ")", make(block) ]); - }, - "atom": function(name) { - return make_name(name); - } - }; - - // The squeezer replaces "block"-s that contain only a single - // statement with the statement itself; technically, the AST - // is correct, but this can create problems when we output an - // IF having an ELSE clause where the THEN clause ends in an - // IF *without* an ELSE block (then the outer ELSE would refer - // to the inner IF). This function checks for this case and - // adds the block brackets if needed. - function make_then(th) { - if (th[0] == "do") { - // https://github.com/mishoo/UglifyJS/issues/#issue/57 - // IE croaks with "syntax error" on code like this: - // if (foo) do ... while(cond); else ... - // we need block brackets around do/while - return make([ "block", [ th ]]); - } - var b = th; - while (true) { - var type = b[0]; - if (type == "if") { - if (!b[3]) - // no else, we must add the block - return make([ "block", [ th ]]); - b = b[3]; - } - else if (type == "while" || type == "do") b = b[2]; - else if (type == "for" || type == "for-in") b = b[4]; - else break; - } - return make(th); - }; - - function make_function(name, args, body, keyword) { - var out = keyword || "function"; - if (name) { - out += " " + make_name(name); - } - out += "(" + add_commas(MAP(args, make_name)) + ")"; - return add_spaces([ out, make_block(body) ]); - }; - - function make_block_statements(statements, noindent) { - for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) { - var stat = statements[i]; - var code = make(stat); - if (code != ";") { - if (!beautify && i == last) { - if ((stat[0] == "while" && empty(stat[2])) || - (member(stat[0], [ "for", "for-in"] ) && empty(stat[4])) || - (stat[0] == "if" && empty(stat[2]) && !stat[3]) || - (stat[0] == "if" && stat[3] && empty(stat[3]))) { - code = code.replace(/;*\s*$/, ";"); - } else { - code = code.replace(/;+\s*$/, ""); - } - } - a.push(code); - } - } - return noindent ? a : MAP(a, indent); - }; - - function make_switch_block(body) { - var n = body.length; - if (n == 0) return "{}"; - return "{" + newline + MAP(body, function(branch, i){ - var has_body = branch[1].length > 0, code = with_indent(function(){ - return indent(branch[0] - ? add_spaces([ "case", make(branch[0]) + ":" ]) - : "default:"); - }, 0.5) + (has_body ? newline + with_indent(function(){ - return make_block_statements(branch[1]).join(newline); - }) : ""); - if (!beautify && has_body && i < n - 1) - code += ";"; - return code; - }).join(newline) + newline + indent("}"); - }; - - function make_block(statements) { - if (!statements) return ";"; - if (statements.length == 0) return "{}"; - return "{" + newline + with_indent(function(){ - return make_block_statements(statements).join(newline); - }) + newline + indent("}"); - }; - - function make_1vardef(def) { - var name = def[0], val = def[1]; - if (val != null) - name = add_spaces([ make_name(name), "=", parenthesize(val, "seq") ]); - return name; - }; - - var $stack = []; - - function make(node) { - var type = node[0]; - var gen = generators[type]; - if (!gen) - throw new Error("Can't find generator for \"" + type + "\""); - $stack.push(node); - var ret = gen.apply(type, node.slice(1)); - $stack.pop(); - return ret; - }; - - return make(ast); -}; - -function split_lines(code, max_line_length) { - var splits = [ 0 ]; - jsp.parse(function(){ - var next_token = jsp.tokenizer(code); - var last_split = 0; - var prev_token; - function current_length(tok) { - return tok.pos - last_split; - }; - function split_here(tok) { - last_split = tok.pos; - splits.push(last_split); - }; - function custom(){ - var tok = next_token.apply(this, arguments); - out: { - if (prev_token) { - if (prev_token.type == "keyword") break out; - } - if (current_length(tok) > max_line_length) { - switch (tok.type) { - case "keyword": - case "atom": - case "name": - case "punc": - split_here(tok); - break out; - } - } - } - prev_token = tok; - return tok; - }; - custom.context = function() { - return next_token.context.apply(this, arguments); - }; - return custom; - }()); - return splits.map(function(pos, i){ - return code.substring(pos, splits[i + 1] || code.length); - }).join("\n"); -}; - -/* -----[ Utilities ]----- */ - -function repeat_string(str, i) { - if (i <= 0) return ""; - if (i == 1) return str; - var d = repeat_string(str, i >> 1); - d += d; - if (i & 1) d += str; - return d; -}; - -function defaults(args, defs) { - var ret = {}; - if (args === true) - args = {}; - for (var i in defs) if (HOP(defs, i)) { - ret[i] = (args && HOP(args, i)) ? args[i] : defs[i]; - } - return ret; -}; - -function is_identifier(name) { - return /^[a-z_$][a-z0-9_$]*$/i.test(name) - && name != "this" - && !HOP(jsp.KEYWORDS_ATOM, name) - && !HOP(jsp.RESERVED_WORDS, name) - && !HOP(jsp.KEYWORDS, name); -}; - -function HOP(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -}; - -// some utilities - -var MAP; - -(function(){ - MAP = function(a, f, o) { - var ret = []; - for (var i = 0; i < a.length; ++i) { - var val = f.call(o, a[i], i); - if (val instanceof AtTop) ret.unshift(val.v); - else ret.push(val); - } - return ret; - }; - MAP.at_top = function(val) { return new AtTop(val) }; - function AtTop(val) { this.v = val }; -})(); - -/* -----[ Exports ]----- */ - -exports.ast_walker = ast_walker; -exports.ast_mangle = ast_mangle; -exports.ast_squeeze = ast_squeeze; -exports.gen_code = gen_code; -exports.ast_add_scope = ast_add_scope; -exports.set_logger = function(logger) { warn = logger }; -exports.make_string = make_string; -exports.split_lines = split_lines; -exports.MAP = MAP; - -// keep this last! -exports.ast_squeeze_more = require("./squeeze-more").ast_squeeze_more; -; - }).call(module.exports); - - __require.modules["/node_modules/burrito/node_modules/uglify-js/lib/process.js"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/burrito/node_modules/uglify-js/lib/squeeze-more.js"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/burrito/node_modules/uglify-js/lib"; - var __filename = "/node_modules/burrito/node_modules/uglify-js/lib/squeeze-more.js"; - - var require = function (file) { - return __require(file, "/node_modules/burrito/node_modules/uglify-js/lib"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/burrito/node_modules/uglify-js/lib"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/burrito/node_modules/uglify-js/lib/squeeze-more.js"]._cached = module.exports; - - (function () { - var jsp = require("./parse-js"), - pro = require("./process"), - slice = jsp.slice, - member = jsp.member, - PRECEDENCE = jsp.PRECEDENCE, - OPERATORS = jsp.OPERATORS; - -function ast_squeeze_more(ast) { - var w = pro.ast_walker(), walk = w.walk; - return w.with_walkers({ - "call": function(expr, args) { - if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) { - // foo.toString() ==> foo+"" - return [ "binary", "+", expr[1], [ "string", "" ]]; - } - } - }, function() { - return walk(ast); - }); -}; - -exports.ast_squeeze_more = ast_squeeze_more; -; - }).call(module.exports); - - __require.modules["/node_modules/burrito/node_modules/uglify-js/lib/squeeze-more.js"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/burrito/node_modules/traverse/package.json"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/burrito/node_modules/traverse"; - var __filename = "/node_modules/burrito/node_modules/traverse/package.json"; - - var require = function (file) { - return __require(file, "/node_modules/burrito/node_modules/traverse"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/burrito/node_modules/traverse"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/burrito/node_modules/traverse/package.json"]._cached = module.exports; - - (function () { - module.exports = {"name":"traverse","version":"0.5.0","description":"Traverse and transform objects by visiting every node on a recursive walk","author":"James Halliday","license":"MIT/X11","main":"./index","repository":{"type":"git","url":"http://github.com/substack/js-traverse.git"},"devDependencies":{"expresso":"0.7.x"},"scripts":{"test":"expresso"}}; - }).call(module.exports); - - __require.modules["/node_modules/burrito/node_modules/traverse/package.json"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/burrito/node_modules/traverse/index.js"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/burrito/node_modules/traverse"; - var __filename = "/node_modules/burrito/node_modules/traverse/index.js"; - - var require = function (file) { - return __require(file, "/node_modules/burrito/node_modules/traverse"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/burrito/node_modules/traverse"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/burrito/node_modules/traverse/index.js"]._cached = module.exports; - - (function () { - module.exports = Traverse; -function Traverse (obj) { - if (!(this instanceof Traverse)) return new Traverse(obj); - this.value = obj; -} - -Traverse.prototype.get = function (ps) { - var node = this.value; - for (var i = 0; i < ps.length; i ++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) { - node = undefined; - break; - } - node = node[key]; - } - return node; -}; - -Traverse.prototype.set = function (ps, value) { - var node = this.value; - for (var i = 0; i < ps.length - 1; i ++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) node[key] = {}; - node = node[key]; - } - node[ps[i]] = value; - return value; -}; - -Traverse.prototype.map = function (cb) { - return walk(this.value, cb, true); -}; - -Traverse.prototype.forEach = function (cb) { - this.value = walk(this.value, cb, false); - return this.value; -}; - -Traverse.prototype.reduce = function (cb, init) { - var skip = arguments.length === 1; - var acc = skip ? this.value : init; - this.forEach(function (x) { - if (!this.isRoot || !skip) { - acc = cb.call(this, acc, x); - } - }); - return acc; -}; - -Traverse.prototype.paths = function () { - var acc = []; - this.forEach(function (x) { - acc.push(this.path); - }); - return acc; -}; - -Traverse.prototype.nodes = function () { - var acc = []; - this.forEach(function (x) { - acc.push(this.node); - }); - return acc; -}; - -Traverse.prototype.clone = function () { - var parents = [], nodes = []; - - return (function clone (src) { - for (var i = 0; i < parents.length; i++) { - if (parents[i] === src) { - return nodes[i]; - } - } - - if (typeof src === 'object' && src !== null) { - var dst = copy(src); - - parents.push(src); - nodes.push(dst); - - forEach(Object_keys(src), function (key) { - dst[key] = clone(src[key]); - }); - - parents.pop(); - nodes.pop(); - return dst; - } - else { - return src; - } - })(this.value); -}; - -function walk (root, cb, immutable) { - var path = []; - var parents = []; - var alive = true; - - return (function walker (node_) { - var node = immutable ? copy(node_) : node_; - var modifiers = {}; - - var keepGoing = true; - - var state = { - node : node, - node_ : node_, - path : [].concat(path), - parent : parents[parents.length - 1], - parents : parents, - key : path.slice(-1)[0], - isRoot : path.length === 0, - level : path.length, - circular : null, - update : function (x, stopHere) { - if (!state.isRoot) { - state.parent.node[state.key] = x; - } - state.node = x; - if (stopHere) keepGoing = false; - }, - 'delete' : function () { - delete state.parent.node[state.key]; - }, - remove : function () { - if (Array_isArray(state.parent.node)) { - state.parent.node.splice(state.key, 1); - } - else { - delete state.parent.node[state.key]; - } - }, - keys : null, - before : function (f) { modifiers.before = f }, - after : function (f) { modifiers.after = f }, - pre : function (f) { modifiers.pre = f }, - post : function (f) { modifiers.post = f }, - stop : function () { alive = false }, - block : function () { keepGoing = false } - }; - - if (!alive) return state; - - if (typeof node === 'object' && node !== null) { - state.keys = Object_keys(node); - - state.isLeaf = state.keys.length == 0; - - for (var i = 0; i < parents.length; i++) { - if (parents[i].node_ === node_) { - state.circular = parents[i]; - break; - } - } - } - else { - state.isLeaf = true; - } - - state.notLeaf = !state.isLeaf; - state.notRoot = !state.isRoot; - - // use return values to update if defined - var ret = cb.call(state, state.node); - if (ret !== undefined && state.update) state.update(ret); - - if (modifiers.before) modifiers.before.call(state, state.node); - - if (!keepGoing) return state; - - if (typeof state.node == 'object' - && state.node !== null && !state.circular) { - parents.push(state); - - forEach(state.keys, function (key, i) { - path.push(key); - - if (modifiers.pre) modifiers.pre.call(state, state.node[key], key); - - var child = walker(state.node[key]); - if (immutable && Object.hasOwnProperty.call(state.node, key)) { - state.node[key] = child.node; - } - - child.isLast = i == state.keys.length - 1; - child.isFirst = i == 0; - - if (modifiers.post) modifiers.post.call(state, child); - - path.pop(); - }); - parents.pop(); - } - - if (modifiers.after) modifiers.after.call(state, state.node); - - return state; - })(root).node; -} - -function copy (src) { - if (typeof src === 'object' && src !== null) { - var dst; - - if (Array_isArray(src)) { - dst = []; - } - else if (src instanceof Date) { - dst = new Date(src); - } - else if (src instanceof Boolean) { - dst = new Boolean(src); - } - else if (src instanceof Number) { - dst = new Number(src); - } - else if (src instanceof String) { - dst = new String(src); - } - else if (Object.create && Object.getPrototypeOf) { - dst = Object.create(Object.getPrototypeOf(src)); - } - else if (src.__proto__ || src.constructor.prototype) { - var proto = src.__proto__ || src.constructor.prototype || {}; - var T = function () {}; - T.prototype = proto; - dst = new T; - if (!dst.__proto__) dst.__proto__ = proto; - } - - forEach(Object_keys(src), function (key) { - dst[key] = src[key]; - }); - return dst; - } - else return src; -} - -var Object_keys = Object.keys || function keys (obj) { - var res = []; - for (var key in obj) res.push(key) - return res; -}; - -var Array_isArray = Array.isArray || function isArray (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -var forEach = function (xs, fn) { - if (xs.forEach) return xs.forEach(fn) - else for (var i = 0; i < xs.length; i++) { - fn(xs[i], i, xs); - } -}; - -forEach(Object_keys(Traverse.prototype), function (key) { - Traverse[key] = function (obj) { - var args = [].slice.call(arguments, 1); - var t = Traverse(obj); - return t[key].apply(t, args); - }; -}); -; - }).call(module.exports); - - __require.modules["/node_modules/burrito/node_modules/traverse/index.js"]._cached = module.exports; - return module.exports; -}; - -require.modules["vm"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "."; - var __filename = "vm"; - - var require = function (file) { - return __require(file, "."); - }; - - require.resolve = function (file) { - return __require.resolve(name, "."); - }; - - require.modules = __require.modules; - __require.modules["vm"]._cached = module.exports; - - (function () { - var Object_keys = function (obj) { - if (Object.keys) return Object.keys(obj) - else { - var res = []; - for (var key in obj) res.push(key) - return res; - } -}; - -var forEach = function (xs, fn) { - if (xs.forEach) return xs.forEach(fn) - else for (var i = 0; i < xs.length; i++) { - fn(xs[i], i, xs); - } -}; - -var Script = exports.Script = function NodeScript (code) { - if (!(this instanceof Script)) return new Script(code); - this.code = code; -}; - -var iframe = document.createElement('iframe'); -if (!iframe.style) iframe.style = {}; -iframe.style.display = 'none'; - -var iframeCapable = true; // until proven otherwise -if (navigator.appName === 'Microsoft Internet Explorer') { - var m = navigator.appVersion.match(/\bMSIE (\d+\.\d+);/); - if (m && parseFloat(m[1]) <= 9.0) { - iframeCapable = false; - } -} - -Script.prototype.runInNewContext = function (context) { - if (!context) context = {}; - - if (!iframeCapable) { - var keys = Object_keys(context); - var args = []; - for (var i = 0; i < keys.length; i++) { - args.push(context[keys[i]]); - } - - var fn = Function(keys, this.code); - return fn.apply(null, args); - } - - document.body.appendChild(iframe); - - var win = iframe.contentWindow - || (window.frames && window.frames[window.frames.length - 1]) - || window[window.length - 1] - ; - - forEach(Object_keys(context), function (key) { - win[key] = context[key]; - iframe[key] = context[key]; - }); - - if (win.eval) { - // chrome and ff can just .eval() - var res = win.eval(this.code); - } - else { - // this works in IE9 but not anything newer - iframe.setAttribute('src', - 'javascript:__browserifyVmResult=(' + this.code + ')' - ); - if ('__browserifyVmResult' in win) { - var res = win.__browserifyVmResult; - } - else { - iframeCapable = false; - res = this.runInThisContext(context); - } - } - - forEach(Object_keys(win), function (key) { - context[key] = win[key]; - }); - - document.body.removeChild(iframe); - - return res; -}; - -Script.prototype.runInThisContext = function () { - return eval(this.code); // maybe... -}; - -Script.prototype.runInContext = function (context) { - // seems to be just runInNewContext on magical context objects which are - // otherwise indistinguishable from objects except plain old objects - // for the parameter segfaults node - return this.runInNewContext(context); -}; - -forEach(Object_keys(Script.prototype), function (name) { - exports[name] = Script[name] = function (code) { - var s = Script(code); - return s[name].apply(s, [].slice.call(arguments, 1)); - }; -}); - -exports.createScript = function (code) { - return exports.Script(code); -}; - -exports.createContext = Script.createContext = function (context) { - // not really sure what this one does - // seems to just make a shallow copy - var copy = {}; - forEach(Object_keys(context), function (key) { - copy[key] = context[key]; - }); - return copy; -}; -; - }).call(module.exports); - - __require.modules["vm"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/jsonify/package.json"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/jsonify"; - var __filename = "/node_modules/jsonify/package.json"; - - var require = function (file) { - return __require(file, "/node_modules/jsonify"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/jsonify"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/jsonify/package.json"]._cached = module.exports; - - (function () { - module.exports = {"name":"jsonify","version":"0.0.0","description":"JSON without touching any globals","main":"index.js","directories":{"lib":".","test":"test"},"devDependencies":{"tap":"0.0.x","garbage":"0.0.x"},"scripts":{"test":"tap test"},"repository":{"type":"git","url":"http://github.com/substack/jsonify.git"},"keywords":["json","browser"],"author":{"name":"Douglas Crockford","url":"http://crockford.com/"},"license":"Public Domain"}; - }).call(module.exports); - - __require.modules["/node_modules/jsonify/package.json"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/jsonify/index.js"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/jsonify"; - var __filename = "/node_modules/jsonify/index.js"; - - var require = function (file) { - return __require(file, "/node_modules/jsonify"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/jsonify"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/jsonify/index.js"]._cached = module.exports; - - (function () { - exports.parse = require('./lib/parse'); -exports.stringify = require('./lib/stringify'); -; - }).call(module.exports); - - __require.modules["/node_modules/jsonify/index.js"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/jsonify/lib/parse.js"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/jsonify/lib"; - var __filename = "/node_modules/jsonify/lib/parse.js"; - - var require = function (file) { - return __require(file, "/node_modules/jsonify/lib"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/jsonify/lib"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/jsonify/lib/parse.js"]._cached = module.exports; - - (function () { - var at, // The index of the current character - ch, // The current character - escapee = { - '"': '"', - '\\': '\\', - '/': '/', - b: '\b', - f: '\f', - n: '\n', - r: '\r', - t: '\t' - }, - text, - - error = function (m) { - // Call error when something is wrong. - throw { - name: 'SyntaxError', - message: m, - at: at, - text: text - }; - }, - - next = function (c) { - // If a c parameter is provided, verify that it matches the current character. - if (c && c !== ch) { - error("Expected '" + c + "' instead of '" + ch + "'"); - } - - // Get the next character. When there are no more characters, - // return the empty string. - - ch = text.charAt(at); - at += 1; - return ch; - }, - - number = function () { - // Parse a number value. - var number, - string = ''; - - if (ch === '-') { - string = '-'; - next('-'); - } - while (ch >= '0' && ch <= '9') { - string += ch; - next(); - } - if (ch === '.') { - string += '.'; - while (next() && ch >= '0' && ch <= '9') { - string += ch; - } - } - if (ch === 'e' || ch === 'E') { - string += ch; - next(); - if (ch === '-' || ch === '+') { - string += ch; - next(); - } - while (ch >= '0' && ch <= '9') { - string += ch; - next(); - } - } - number = +string; - if (!isFinite(number)) { - error("Bad number"); - } else { - return number; - } - }, - - string = function () { - // Parse a string value. - var hex, - i, - string = '', - uffff; - - // When parsing for string values, we must look for " and \ characters. - if (ch === '"') { - while (next()) { - if (ch === '"') { - next(); - return string; - } else if (ch === '\\') { - next(); - if (ch === 'u') { - uffff = 0; - for (i = 0; i < 4; i += 1) { - hex = parseInt(next(), 16); - if (!isFinite(hex)) { - break; - } - uffff = uffff * 16 + hex; - } - string += String.fromCharCode(uffff); - } else if (typeof escapee[ch] === 'string') { - string += escapee[ch]; - } else { - break; - } - } else { - string += ch; - } - } - } - error("Bad string"); - }, - - white = function () { - -// Skip whitespace. - - while (ch && ch <= ' ') { - next(); - } - }, - - word = function () { - -// true, false, or null. - - switch (ch) { - case 't': - next('t'); - next('r'); - next('u'); - next('e'); - return true; - case 'f': - next('f'); - next('a'); - next('l'); - next('s'); - next('e'); - return false; - case 'n': - next('n'); - next('u'); - next('l'); - next('l'); - return null; - } - error("Unexpected '" + ch + "'"); - }, - - value, // Place holder for the value function. - - array = function () { - -// Parse an array value. - - var array = []; - - if (ch === '[') { - next('['); - white(); - if (ch === ']') { - next(']'); - return array; // empty array - } - while (ch) { - array.push(value()); - white(); - if (ch === ']') { - next(']'); - return array; - } - next(','); - white(); - } - } - error("Bad array"); - }, - - object = function () { - -// Parse an object value. - - var key, - object = {}; - - if (ch === '{') { - next('{'); - white(); - if (ch === '}') { - next('}'); - return object; // empty object - } - while (ch) { - key = string(); - white(); - next(':'); - if (Object.hasOwnProperty.call(object, key)) { - error('Duplicate key "' + key + '"'); - } - object[key] = value(); - white(); - if (ch === '}') { - next('}'); - return object; - } - next(','); - white(); - } - } - error("Bad object"); - }; - -value = function () { - -// Parse a JSON value. It could be an object, an array, a string, a number, -// or a word. - - white(); - switch (ch) { - case '{': - return object(); - case '[': - return array(); - case '"': - return string(); - case '-': - return number(); - default: - return ch >= '0' && ch <= '9' ? number() : word(); - } -}; - -// Return the json_parse function. It will have access to all of the above -// functions and variables. - -module.exports = function (source, reviver) { - var result; - - text = source; - at = 0; - ch = ' '; - result = value(); - white(); - if (ch) { - error("Syntax error"); - } - - // If there is a reviver function, we recursively walk the new structure, - // passing each name/value pair to the reviver function for possible - // transformation, starting with a temporary root object that holds the result - // in an empty key. If there is not a reviver function, we simply return the - // result. - - return typeof reviver === 'function' ? (function walk(holder, key) { - var k, v, value = holder[key]; - if (value && typeof value === 'object') { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } - } - return reviver.call(holder, key, value); - }({'': result}, '')) : result; -}; -; - }).call(module.exports); - - __require.modules["/node_modules/jsonify/lib/parse.js"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/jsonify/lib/stringify.js"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/jsonify/lib"; - var __filename = "/node_modules/jsonify/lib/stringify.js"; - - var require = function (file) { - return __require(file, "/node_modules/jsonify/lib"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/jsonify/lib"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/jsonify/lib/stringify.js"]._cached = module.exports; - - (function () { - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, - gap, - indent, - meta = { // table of character substitutions - '\b': '\\b', - '\t': '\\t', - '\n': '\\n', - '\f': '\\f', - '\r': '\\r', - '"' : '\\"', - '\\': '\\\\' - }, - rep; - -function quote(string) { - // If the string contains no control characters, no quote characters, and no - // backslash characters, then we can safely slap some quotes around it. - // Otherwise we must also replace the offending characters with safe escape - // sequences. - - escapable.lastIndex = 0; - return escapable.test(string) ? '"' + string.replace(escapable, function (a) { - var c = meta[a]; - return typeof c === 'string' ? c : - '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string + '"'; -} - -function str(key, holder) { - // Produce a string from holder[key]. - var i, // The loop counter. - k, // The member key. - v, // The member value. - length, - mind = gap, - partial, - value = holder[key]; - - // If the value has a toJSON method, call it to obtain a replacement value. - if (value && typeof value === 'object' && - typeof value.toJSON === 'function') { - value = value.toJSON(key); - } - - // If we were called with a replacer function, then call the replacer to - // obtain a replacement value. - if (typeof rep === 'function') { - value = rep.call(holder, key, value); - } - - // What happens next depends on the value's type. - switch (typeof value) { - case 'string': - return quote(value); - - case 'number': - // JSON numbers must be finite. Encode non-finite numbers as null. - return isFinite(value) ? String(value) : 'null'; - - case 'boolean': - case 'null': - // If the value is a boolean or null, convert it to a string. Note: - // typeof null does not produce 'null'. The case is included here in - // the remote chance that this gets fixed someday. - return String(value); - - case 'object': - if (!value) return 'null'; - gap += indent; - partial = []; - - // Array.isArray - if (Object.prototype.toString.apply(value) === '[object Array]') { - length = value.length; - for (i = 0; i < length; i += 1) { - partial[i] = str(i, value) || 'null'; - } - - // Join all of the elements together, separated with commas, and - // wrap them in brackets. - v = partial.length === 0 ? '[]' : gap ? - '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : - '[' + partial.join(',') + ']'; - gap = mind; - return v; - } - - // If the replacer is an array, use it to select the members to be - // stringified. - if (rep && typeof rep === 'object') { - length = rep.length; - for (i = 0; i < length; i += 1) { - k = rep[i]; - if (typeof k === 'string') { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - else { - // Otherwise, iterate through all of the keys in the object. - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ': ' : ':') + v); - } - } - } - } - - // Join all of the member texts together, separated with commas, - // and wrap them in braces. - - v = partial.length === 0 ? '{}' : gap ? - '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : - '{' + partial.join(',') + '}'; - gap = mind; - return v; - } -} - -module.exports = function (value, replacer, space) { - var i; - gap = ''; - indent = ''; - - // If the space parameter is a number, make an indent string containing that - // many spaces. - if (typeof space === 'number') { - for (i = 0; i < space; i += 1) { - indent += ' '; - } - } - // If the space parameter is a string, it will be used as the indent string. - else if (typeof space === 'string') { - indent = space; - } - - // If there is a replacer, it must be a function or an array. - // Otherwise, throw an error. - rep = replacer; - if (replacer && typeof replacer !== 'function' - && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { - throw new Error('JSON.stringify'); - } - - // Make a fake root object containing our value under the key of ''. - // Return the result of stringifying the value. - return str('', {'': value}); -}; -; - }).call(module.exports); - - __require.modules["/node_modules/jsonify/lib/stringify.js"]._cached = module.exports; - return module.exports; -}; - -require.modules["/node_modules/burrito/index.js"] = function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/node_modules/burrito"; - var __filename = "/node_modules/burrito/index.js"; - - var require = function (file) { - return __require(file, "/node_modules/burrito"); - }; - - require.resolve = function (file) { - return __require.resolve(name, "/node_modules/burrito"); - }; - - require.modules = __require.modules; - __require.modules["/node_modules/burrito/index.js"]._cached = module.exports; - - (function () { - var uglify = require('uglify-js'); -var parser = uglify.parser; -var parse = function (expr) { - if (typeof expr !== 'string') throw 'expression should be a string'; - - //try { - var args = [].slice.call(arguments); - var ast = parser.parse.apply(null, args); - /* } - catch (err) { - if (err.message === undefined - || err.line === undefined - || err.col === undefined - || err.pos === undefined - ) { throw err } - - var e = new SyntaxError( - err.message - + '\n at line ' + err.line + ':' + err.col + ' in expression:\n\n' - + ' ' + expr.split(/\r?\n/)[err.line] - ); - - e.original = err; - e.line = err.line; - e.col = err.col; - e.pos = err.pos; - throw e; - } - */ - return ast; -}; - -var deparse = function (ast, b) { - return uglify.uglify.gen_code(ast, { beautify : b }); -}; - -var traverse = require('traverse'); -var vm = require('vm'); - -var burrito = module.exports = function (code, cb) { - var ast = Array_isArray(code) - ? code // already an ast - : parse(code.toString(), false, true) - ; - - var ast_ = traverse(ast).map(function mapper () { - wrapNode(this, cb); - }); - - return deparse(parse(deparse(ast_)), true); -}; - -var wrapNode = burrito.wrapNode = function (state, cb) { - var node = state.node; - - var ann = Array_isArray(node) && node[0] - && typeof node[0] === 'object' && node[0].name - ? node[0] - : null - ; - - if (!ann) return undefined; - - var self = { - name : ann.name, - node : node, - start : node[0].start, - end : node[0].end, - value : node.slice(1), - state : state - }; - - self.wrap = function (s) { - var subsrc = deparse( - traverse(node).map(function (x) { - if (!this.isRoot) wrapNode(this, cb) - }) - ); - - if (self.name === 'binary') { - var a = deparse(traverse(node[2]).map(function (x) { - if (!this.isRoot) wrapNode(this, cb) - })); - var b = deparse(traverse(node[3]).map(function (x) { - if (!this.isRoot) wrapNode(this, cb) - })); - } - - var src = ''; - - if (typeof s === 'function') { - if (self.name === 'binary') { - src = s(subsrc, a, b); - } - else { - src = s(subsrc); - } - } - else { - src = s.toString() - .replace(/%s/g, function () { - return subsrc - }) - ; - - if (self.name === 'binary') { - src = src - .replace(/%a/g, function () { return a }) - .replace(/%b/g, function () { return b }) - ; - } - } - - var expr = parse(src); - state.update(expr, true); - }; - - var cache = {}; - - self.parent = state.isRoot ? null : function () { - if (!cache.parent) { - var s = state; - var x; - do { - s = s.parent; - if (s) x = wrapNode(s); - } while (s && !x); - - cache.parent = x; - } - - return cache.parent; - }; - - self.source = function () { - if (!cache.source) cache.source = deparse(node); - return cache.source; - }; - - self.label = function () { - return burrito.label(self); - }; - - if (cb) cb.call(state, self); - - if (self.node[0].name === 'conditional') { - self.wrap('[%s][0]'); - } - - return self; -} - -burrito.microwave = function (code, context, cb) { - if (!cb) { cb = context; context = {} }; - if (!context) context = {}; - - var src = burrito(code, cb); - return vm.runInNewContext(src, context); -}; - -burrito.generateName = function (len) { - var name = ''; - var lower = '$'.charCodeAt(0); - var upper = 'z'.charCodeAt(0); - - while (name.length < len) { - var c = String.fromCharCode(Math.floor( - Math.random() * (upper - lower + 1) + lower - )); - if ((name + c).match(/^[A-Za-z_$][A-Za-z0-9_$]*$/)) name += c; - } - - return name; -}; - -burrito.parse = parse; -burrito.deparse = deparse; - -burrito.label = function (node) { - if (node.name === 'call') { - if (typeof node.value[0] === 'string') { - return node.value[0]; - } - else if (node.value[0] && typeof node.value[0][1] === 'string') { - return node.value[0][1]; - } - else { - return null; - } - } - else if (node.name === 'var') { - return node.value[0].map(function (x) { return x[0] }); - } - else if (node.name === 'defun') { - return node.value[0]; - } - else if (node.name === 'function') { - return node.value[0]; - } - else { - return null; - } -}; - -var Array_isArray = Array.isArray || function isArray (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; -; - }).call(module.exports); - - __require.modules["/node_modules/burrito/index.js"]._cached = module.exports; - return module.exports; -}; - -process.nextTick(function () { - var module = { exports : {} }; - var exports = module.exports; - var __dirname = "/"; - var __filename = "//home/substack/projects/node-burrito/example/web"; - - var require = function (file) { - return __require(file, "/"); - }; - require.modules = __require.modules; - - var burrito = require('burrito'); -var json = require('jsonify'); - -var src = [ - 'function f () { g() }', - 'function g () { h() }', - 'function h () { throw "moo" + Array(x).join("!") }', - 'var x = 4', - 'f()' -].join('\r\n'); - -window.onload = function () { - burrito(src, function (node) { - document.body.innerHTML += node.name + '
        \n'; - }); -}; -if (document.readyState === 'complete') window.onload(); -; -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/web/index.html b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/web/index.html deleted file mode 100644 index 66804fba4..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/web/index.html +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - -
        
        -
        -
        diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/web/main.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/web/main.js
        deleted file mode 100644
        index cc81a8b76..000000000
        --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/web/main.js
        +++ /dev/null
        @@ -1,17 +0,0 @@
        -var burrito = require('burrito');
        -var json = require('jsonify');
        -
        -var src = [
        -    'function f () { g() }',
        -    'function g () { h() }',
        -    'function h () { throw "moo" + Array(x).join("!") }',
        -    'var x = 4',
        -    'f()'
        -].join('\r\n');
        -
        -window.onload = function () {
        -    burrito(src, function (node) {
        -        document.body.innerHTML += node.name + '
        \n'; - }); -}; -if (document.readyState === 'complete') window.onload(); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/web/server.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/web/server.js deleted file mode 100644 index 6bce0206d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/web/server.js +++ /dev/null @@ -1,12 +0,0 @@ -var express = require('express'); -var browserify = require('browserify'); - -var app = express.createServer(); -app.use(express.static(__dirname)); -app.use(browserify({ - entry : __dirname + '/main.js', - watch : true, -})); - -app.listen(8081); -console.log('Listening on :8081'); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/wrap.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/wrap.js deleted file mode 100644 index 16424012b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/example/wrap.js +++ /dev/null @@ -1,7 +0,0 @@ -var burrito = require('burrito'); - -var src = burrito('f() && g(h())\nfoo()', function (node) { - if (node.name === 'call') node.wrap('qqq(%s)'); -}); - -console.log(src); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/index.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/index.js deleted file mode 100644 index 60ef56989..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/index.js +++ /dev/null @@ -1,208 +0,0 @@ -var uglify = require('uglify-js'); -var parser = uglify.parser; -var parse = function (expr) { - if (typeof expr !== 'string') throw 'expression should be a string'; - - try { - var ast = parser.parse.apply(null, arguments); - } - catch (err) { - if (err.message === undefined - || err.line === undefined - || err.col === undefined - || err.pos === undefined - ) { throw err } - - var e = new SyntaxError( - err.message - + '\n at line ' + err.line + ':' + err.col + ' in expression:\n\n' - + ' ' + expr.split(/\r?\n/)[err.line] - ); - - e.original = err; - e.line = err.line; - e.col = err.col; - e.pos = err.pos; - throw e; - } - return ast; -}; - -var deparse = function (ast, b) { - return uglify.uglify.gen_code(ast, { beautify : b }); -}; - -var traverse = require('traverse'); -var vm = require('vm'); - -var burrito = module.exports = function (code, cb) { - var ast = Array_isArray(code) - ? code // already an ast - : parse(code.toString(), false, true) - ; - - var ast_ = traverse(ast).map(function mapper () { - wrapNode(this, cb); - }); - - return deparse(parse(deparse(ast_)), true); -}; - -var wrapNode = burrito.wrapNode = function (state, cb) { - var node = state.node; - - var ann = Array_isArray(node) && node[0] - && typeof node[0] === 'object' && node[0].name - ? node[0] - : null - ; - - if (!ann) return undefined; - - var self = { - name : ann.name, - node : node, - start : node[0].start, - end : node[0].end, - value : node.slice(1), - state : state - }; - - self.wrap = function (s) { - var subsrc = deparse( - traverse(node).map(function (x) { - if (!this.isRoot) wrapNode(this, cb) - }) - ); - - if (self.name === 'binary') { - var a = deparse(traverse(node[2]).map(function (x) { - if (!this.isRoot) wrapNode(this, cb) - })); - var b = deparse(traverse(node[3]).map(function (x) { - if (!this.isRoot) wrapNode(this, cb) - })); - } - - var src = ''; - - if (typeof s === 'function') { - if (self.name === 'binary') { - src = s(subsrc, a, b); - } - else { - src = s(subsrc); - } - } - else { - src = s.toString() - .replace(/%s/g, function () { - return subsrc - }) - ; - - if (self.name === 'binary') { - src = src - .replace(/%a/g, function () { return a }) - .replace(/%b/g, function () { return b }) - ; - } - } - - var expr = parse(src); - state.update(expr, true); - }; - - var cache = {}; - - self.parent = state.isRoot ? null : function () { - if (!cache.parent) { - var s = state; - var x; - do { - s = s.parent; - if (s) x = wrapNode(s); - } while (s && !x); - - cache.parent = x; - } - - return cache.parent; - }; - - self.source = function () { - if (!cache.source) cache.source = deparse(node); - return cache.source; - }; - - self.label = function () { - return burrito.label(self); - }; - - if (cb) cb.call(state, self); - - if (self.node[0].name === 'conditional') { - self.wrap('[%s][0]'); - } - - return self; -} - -burrito.microwave = function (code, context, cb) { - if (!cb) { cb = context; context = {} }; - if (!context) context = {}; - - var src = burrito(code, cb); - return vm.runInNewContext(src, context); -}; - -burrito.generateName = function (len) { - var name = ''; - var lower = '$'.charCodeAt(0); - var upper = 'z'.charCodeAt(0); - - while (name.length < len) { - var c = String.fromCharCode(Math.floor( - Math.random() * (upper - lower + 1) + lower - )); - if ((name + c).match(/^[A-Za-z_$][A-Za-z0-9_$]*$/)) name += c; - } - - return name; -}; - -burrito.parse = parse; -burrito.deparse = deparse; - -burrito.label = function (node) { - if (node.name === 'call') { - if (typeof node.value[0] === 'string') { - return node.value[0]; - } - else if (node.value[0] && typeof node.value[0][1] === 'string') { - return node.value[0][1]; - } - else if (node.value[0][0] === 'dot') { - return node.value[0][node.value[0].length - 1]; - } - else { - return null; - } - } - else if (node.name === 'var') { - return node.value[0].map(function (x) { return x[0] }); - } - else if (node.name === 'defun') { - return node.value[0]; - } - else if (node.name === 'function') { - return node.value[0]; - } - else { - return null; - } -}; - -var Array_isArray = Array.isArray || function isArray (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/.bin/uglifyjs b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/.bin/uglifyjs deleted file mode 120000 index fef3468b6..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/.bin/uglifyjs +++ /dev/null @@ -1 +0,0 @@ -../uglify-js/bin/uglifyjs \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/LICENSE b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/LICENSE deleted file mode 100644 index 7b75500c5..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/LICENSE +++ /dev/null @@ -1,24 +0,0 @@ -Copyright 2010 James Halliday (mail@substack.net) - -This project is free software released under the MIT/X11 license: -http://www.opensource.org/licenses/mit-license.php - -Copyright 2010 James Halliday (mail@substack.net) - -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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/README.markdown b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/README.markdown deleted file mode 100644 index f86ef7695..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/README.markdown +++ /dev/null @@ -1,237 +0,0 @@ -traverse -======== - -Traverse and transform objects by visiting every node on a recursive walk. - -examples -======== - -transform negative numbers in-place ------------------------------------ - -negative.js - -````javascript -var traverse = require('traverse'); -var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - -traverse(obj).forEach(function (x) { - if (x < 0) this.update(x + 128); -}); - -console.dir(obj); -```` - -Output: - - [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ] - -collect leaf nodes ------------------- - -leaves.js - -````javascript -var traverse = require('traverse'); - -var obj = { - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 }, -}; - -var leaves = traverse(obj).reduce(function (acc, x) { - if (this.isLeaf) acc.push(x); - return acc; -}, []); - -console.dir(leaves); -```` - -Output: - - [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ] - -scrub circular references -------------------------- - -scrub.js: - -````javascript -var traverse = require('traverse'); - -var obj = { a : 1, b : 2, c : [ 3, 4 ] }; -obj.c.push(obj); - -var scrubbed = traverse(obj).map(function (x) { - if (this.circular) this.remove() -}); -console.dir(scrubbed); -```` - -output: - - { a: 1, b: 2, c: [ 3, 4 ] } - -context -======= - -Each method that takes a callback has a context (its `this` object) with these -attributes: - -this.node ---------- - -The present node on the recursive walk - -this.path ---------- - -An array of string keys from the root to the present node - -this.parent ------------ - -The context of the node's parent. -This is `undefined` for the root node. - -this.key --------- - -The name of the key of the present node in its parent. -This is `undefined` for the root node. - -this.isRoot, this.notRoot -------------------------- - -Whether the present node is the root node - -this.isLeaf, this.notLeaf -------------------------- - -Whether or not the present node is a leaf node (has no children) - -this.level ----------- - -Depth of the node within the traversal - -this.circular -------------- - -If the node equals one of its parents, the `circular` attribute is set to the -context of that parent and the traversal progresses no deeper. - -this.update(value, stopHere=false) ----------------------------------- - -Set a new value for the present node. - -All the elements in `value` will be recursively traversed unless `stopHere` is -true. - -this.remove(stopHere=false) -------------- - -Remove the current element from the output. If the node is in an Array it will -be spliced off. Otherwise it will be deleted from its parent. - -this.delete(stopHere=false) -------------- - -Delete the current element from its parent in the output. Calls `delete` even on -Arrays. - -this.before(fn) ---------------- - -Call this function before any of the children are traversed. - -You can assign into `this.keys` here to traverse in a custom order. - -this.after(fn) --------------- - -Call this function after any of the children are traversed. - -this.pre(fn) ------------- - -Call this function before each of the children are traversed. - -this.post(fn) -------------- - -Call this function after each of the children are traversed. - -methods -======= - -.map(fn) --------- - -Execute `fn` for each node in the object and return a new object with the -results of the walk. To update nodes in the result use `this.update(value)`. - -.forEach(fn) ------------- - -Execute `fn` for each node in the object but unlike `.map()`, when -`this.update()` is called it updates the object in-place. - -.reduce(fn, acc) ----------------- - -For each node in the object, perform a -[left-fold](http://en.wikipedia.org/wiki/Fold_(higher-order_function)) -with the return value of `fn(acc, node)`. - -If `acc` isn't specified, `acc` is set to the root object for the first step -and the root element is skipped. - -.paths() --------- - -Return an `Array` of every possible non-cyclic path in the object. -Paths are `Array`s of string keys. - -.nodes() --------- - -Return an `Array` of every node in the object. - -.clone() --------- - -Create a deep clone of the object. - -install -======= - -Using [npm](http://npmjs.org) do: - - $ npm install traverse - -test -==== - -Using [expresso](http://github.com/visionmedia/expresso) do: - - $ expresso - - 100% wahoo, your stuff is not broken! - -in the browser -============== - -Use [browserify](https://github.com/substack/node-browserify) to run traverse in -the browser. - -traverse has been tested and works with: - -* Internet Explorer 5.5, 6.0, 7.0, 8.0, 9.0 -* Firefox 3.5 -* Chrome 6.0 -* Opera 10.6 -* Safari 5.0 diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/json.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/json.js deleted file mode 100755 index 50d612e3a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/json.js +++ /dev/null @@ -1,16 +0,0 @@ -var traverse = require('traverse'); - -var id = 54; -var callbacks = {}; -var obj = { moo : function () {}, foo : [2,3,4, function () {}] }; - -var scrubbed = traverse(obj).map(function (x) { - if (typeof x === 'function') { - callbacks[id] = { id : id, f : x, path : this.path }; - this.update('[Function]'); - id++; - } -}); - -console.dir(scrubbed); -console.dir(callbacks); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/leaves.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/leaves.js deleted file mode 100755 index c1b310b95..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/leaves.js +++ /dev/null @@ -1,15 +0,0 @@ -var traverse = require('traverse'); - -var obj = { - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 }, -}; - -var leaves = traverse(obj).reduce(function (acc, x) { - if (this.isLeaf) acc.push(x); - return acc; -}, []); - -console.dir(leaves); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/negative.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/negative.js deleted file mode 100755 index 78608a059..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/negative.js +++ /dev/null @@ -1,8 +0,0 @@ -var traverse = require('traverse'); -var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - -traverse(obj).forEach(function (x) { - if (x < 0) this.update(x + 128); -}); - -console.dir(obj); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/scrub.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/scrub.js deleted file mode 100755 index 5d15b9161..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/scrub.js +++ /dev/null @@ -1,10 +0,0 @@ -// scrub out circular references -var traverse = require('traverse'); - -var obj = { a : 1, b : 2, c : [ 3, 4 ] }; -obj.c.push(obj); - -var scrubbed = traverse(obj).map(function (x) { - if (this.circular) this.remove() -}); -console.dir(scrubbed); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/stringify.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/stringify.js deleted file mode 100755 index 167b68b23..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/examples/stringify.js +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env node -var traverse = require('traverse'); - -var obj = [ 'five', 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - -var s = ''; -traverse(obj).forEach(function to_s (node) { - if (Array.isArray(node)) { - this.before(function () { s += '[' }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += ']' }); - } - else if (typeof node == 'object') { - this.before(function () { s += '{' }); - this.pre(function (x, key) { - to_s(key); - s += ':'; - }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += '}' }); - } - else if (typeof node == 'string') { - s += '"' + node.toString().replace(/"/g, '\\"') + '"'; - } - else if (typeof node == 'function') { - s += 'null'; - } - else { - s += node.toString(); - } -}); - -console.log('JSON.stringify: ' + JSON.stringify(obj)); -console.log('this stringify: ' + s); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/index.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/index.js deleted file mode 100644 index 038a1ada3..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/index.js +++ /dev/null @@ -1,267 +0,0 @@ -module.exports = Traverse; -function Traverse (obj) { - if (!(this instanceof Traverse)) return new Traverse(obj); - this.value = obj; -} - -Traverse.prototype.get = function (ps) { - var node = this.value; - for (var i = 0; i < ps.length; i ++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) { - node = undefined; - break; - } - node = node[key]; - } - return node; -}; - -Traverse.prototype.set = function (ps, value) { - var node = this.value; - for (var i = 0; i < ps.length - 1; i ++) { - var key = ps[i]; - if (!Object.hasOwnProperty.call(node, key)) node[key] = {}; - node = node[key]; - } - node[ps[i]] = value; - return value; -}; - -Traverse.prototype.map = function (cb) { - return walk(this.value, cb, true); -}; - -Traverse.prototype.forEach = function (cb) { - this.value = walk(this.value, cb, false); - return this.value; -}; - -Traverse.prototype.reduce = function (cb, init) { - var skip = arguments.length === 1; - var acc = skip ? this.value : init; - this.forEach(function (x) { - if (!this.isRoot || !skip) { - acc = cb.call(this, acc, x); - } - }); - return acc; -}; - -Traverse.prototype.paths = function () { - var acc = []; - this.forEach(function (x) { - acc.push(this.path); - }); - return acc; -}; - -Traverse.prototype.nodes = function () { - var acc = []; - this.forEach(function (x) { - acc.push(this.node); - }); - return acc; -}; - -Traverse.prototype.clone = function () { - var parents = [], nodes = []; - - return (function clone (src) { - for (var i = 0; i < parents.length; i++) { - if (parents[i] === src) { - return nodes[i]; - } - } - - if (typeof src === 'object' && src !== null) { - var dst = copy(src); - - parents.push(src); - nodes.push(dst); - - forEach(Object_keys(src), function (key) { - dst[key] = clone(src[key]); - }); - - parents.pop(); - nodes.pop(); - return dst; - } - else { - return src; - } - })(this.value); -}; - -function walk (root, cb, immutable) { - var path = []; - var parents = []; - var alive = true; - - return (function walker (node_) { - var node = immutable ? copy(node_) : node_; - var modifiers = {}; - - var keepGoing = true; - - var state = { - node : node, - node_ : node_, - path : [].concat(path), - parent : parents[parents.length - 1], - parents : parents, - key : path.slice(-1)[0], - isRoot : path.length === 0, - level : path.length, - circular : null, - update : function (x, stopHere) { - if (!state.isRoot) { - state.parent.node[state.key] = x; - } - state.node = x; - if (stopHere) keepGoing = false; - }, - 'delete' : function (stopHere) { - delete state.parent.node[state.key]; - if (stopHere) keepGoing = false; - }, - remove : function (stopHere) { - if (Array_isArray(state.parent.node)) { - state.parent.node.splice(state.key, 1); - } - else { - delete state.parent.node[state.key]; - } - if (stopHere) keepGoing = false; - }, - keys : null, - before : function (f) { modifiers.before = f }, - after : function (f) { modifiers.after = f }, - pre : function (f) { modifiers.pre = f }, - post : function (f) { modifiers.post = f }, - stop : function () { alive = false }, - block : function () { keepGoing = false } - }; - - if (!alive) return state; - - if (typeof node === 'object' && node !== null) { - state.keys = Object_keys(node); - - state.isLeaf = state.keys.length == 0; - - for (var i = 0; i < parents.length; i++) { - if (parents[i].node_ === node_) { - state.circular = parents[i]; - break; - } - } - } - else { - state.isLeaf = true; - } - - state.notLeaf = !state.isLeaf; - state.notRoot = !state.isRoot; - - // use return values to update if defined - var ret = cb.call(state, state.node); - if (ret !== undefined && state.update) state.update(ret); - - if (modifiers.before) modifiers.before.call(state, state.node); - - if (!keepGoing) return state; - - if (typeof state.node == 'object' - && state.node !== null && !state.circular) { - parents.push(state); - - forEach(state.keys, function (key, i) { - path.push(key); - - if (modifiers.pre) modifiers.pre.call(state, state.node[key], key); - - var child = walker(state.node[key]); - if (immutable && Object.hasOwnProperty.call(state.node, key)) { - state.node[key] = child.node; - } - - child.isLast = i == state.keys.length - 1; - child.isFirst = i == 0; - - if (modifiers.post) modifiers.post.call(state, child); - - path.pop(); - }); - parents.pop(); - } - - if (modifiers.after) modifiers.after.call(state, state.node); - - return state; - })(root).node; -} - -function copy (src) { - if (typeof src === 'object' && src !== null) { - var dst; - - if (Array_isArray(src)) { - dst = []; - } - else if (src instanceof Date) { - dst = new Date(src); - } - else if (src instanceof Boolean) { - dst = new Boolean(src); - } - else if (src instanceof Number) { - dst = new Number(src); - } - else if (src instanceof String) { - dst = new String(src); - } - else if (Object.create && Object.getPrototypeOf) { - dst = Object.create(Object.getPrototypeOf(src)); - } - else if (src.__proto__ || src.constructor.prototype) { - var proto = src.__proto__ || src.constructor.prototype || {}; - var T = function () {}; - T.prototype = proto; - dst = new T; - if (!dst.__proto__) dst.__proto__ = proto; - } - - forEach(Object_keys(src), function (key) { - dst[key] = src[key]; - }); - return dst; - } - else return src; -} - -var Object_keys = Object.keys || function keys (obj) { - var res = []; - for (var key in obj) res.push(key) - return res; -}; - -var Array_isArray = Array.isArray || function isArray (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; - -var forEach = function (xs, fn) { - if (xs.forEach) return xs.forEach(fn) - else for (var i = 0; i < xs.length; i++) { - fn(xs[i], i, xs); - } -}; - -forEach(Object_keys(Traverse.prototype), function (key) { - Traverse[key] = function (obj) { - var args = [].slice.call(arguments, 1); - var t = Traverse(obj); - return t[key].apply(t, args); - }; -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/main.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/main.js deleted file mode 100755 index d562d379a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/main.js +++ /dev/null @@ -1,10 +0,0 @@ -// scrub out circular references -var traverse = require('./index.js'); - -var obj = { a : 1, b : 2, c : [ 3, 4 ] }; -obj.c.push(obj); - -var scrubbed = traverse(obj).map(function (x) { - if (this.circular) this.remove() -}); -console.dir(scrubbed); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/package.json deleted file mode 100644 index 1607acd4e..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/package.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "name": "traverse", - "version": "0.5.2", - "description": "Traverse and transform objects by visiting every node on a recursive walk", - "author": { - "name": "James Halliday" - }, - "license": "MIT/X11", - "main": "./index", - "repository": { - "type": "git", - "url": "http://github.com/substack/js-traverse.git" - }, - "devDependencies": { - "expresso": "0.7.x" - }, - "scripts": { - "test": "expresso" - }, - "readme": "traverse\n========\n\nTraverse and transform objects by visiting every node on a recursive walk.\n\nexamples\n========\n\ntransform negative numbers in-place\n-----------------------------------\n\nnegative.js\n\n````javascript\nvar traverse = require('traverse');\nvar obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ];\n\ntraverse(obj).forEach(function (x) {\n if (x < 0) this.update(x + 128);\n});\n\nconsole.dir(obj);\n````\n\nOutput:\n\n [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ]\n\ncollect leaf nodes\n------------------\n\nleaves.js\n\n````javascript\nvar traverse = require('traverse');\n\nvar obj = {\n a : [1,2,3],\n b : 4,\n c : [5,6],\n d : { e : [7,8], f : 9 },\n};\n\nvar leaves = traverse(obj).reduce(function (acc, x) {\n if (this.isLeaf) acc.push(x);\n return acc;\n}, []);\n\nconsole.dir(leaves);\n````\n\nOutput:\n\n [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]\n\nscrub circular references\n-------------------------\n\nscrub.js:\n\n````javascript\nvar traverse = require('traverse');\n\nvar obj = { a : 1, b : 2, c : [ 3, 4 ] };\nobj.c.push(obj);\n\nvar scrubbed = traverse(obj).map(function (x) {\n if (this.circular) this.remove()\n});\nconsole.dir(scrubbed);\n````\n\noutput:\n\n { a: 1, b: 2, c: [ 3, 4 ] }\n\ncontext\n=======\n\nEach method that takes a callback has a context (its `this` object) with these\nattributes:\n\nthis.node\n---------\n\nThe present node on the recursive walk\n\nthis.path\n---------\n\nAn array of string keys from the root to the present node\n\nthis.parent\n-----------\n\nThe context of the node's parent.\nThis is `undefined` for the root node.\n\nthis.key\n--------\n\nThe name of the key of the present node in its parent.\nThis is `undefined` for the root node.\n\nthis.isRoot, this.notRoot\n-------------------------\n\nWhether the present node is the root node\n\nthis.isLeaf, this.notLeaf\n-------------------------\n\nWhether or not the present node is a leaf node (has no children)\n\nthis.level\n----------\n\nDepth of the node within the traversal\n\nthis.circular\n-------------\n\nIf the node equals one of its parents, the `circular` attribute is set to the\ncontext of that parent and the traversal progresses no deeper.\n\nthis.update(value, stopHere=false)\n----------------------------------\n\nSet a new value for the present node.\n\nAll the elements in `value` will be recursively traversed unless `stopHere` is\ntrue.\n\nthis.remove(stopHere=false)\n-------------\n\nRemove the current element from the output. If the node is in an Array it will\nbe spliced off. Otherwise it will be deleted from its parent.\n\nthis.delete(stopHere=false)\n-------------\n\nDelete the current element from its parent in the output. Calls `delete` even on\nArrays.\n\nthis.before(fn)\n---------------\n\nCall this function before any of the children are traversed.\n\nYou can assign into `this.keys` here to traverse in a custom order.\n\nthis.after(fn)\n--------------\n\nCall this function after any of the children are traversed.\n\nthis.pre(fn)\n------------\n\nCall this function before each of the children are traversed.\n\nthis.post(fn)\n-------------\n\nCall this function after each of the children are traversed.\n\nmethods\n=======\n\n.map(fn)\n--------\n\nExecute `fn` for each node in the object and return a new object with the\nresults of the walk. To update nodes in the result use `this.update(value)`.\n\n.forEach(fn)\n------------\n\nExecute `fn` for each node in the object but unlike `.map()`, when\n`this.update()` is called it updates the object in-place.\n\n.reduce(fn, acc)\n----------------\n\nFor each node in the object, perform a\n[left-fold](http://en.wikipedia.org/wiki/Fold_(higher-order_function))\nwith the return value of `fn(acc, node)`.\n\nIf `acc` isn't specified, `acc` is set to the root object for the first step\nand the root element is skipped.\n\n.paths()\n--------\n\nReturn an `Array` of every possible non-cyclic path in the object.\nPaths are `Array`s of string keys.\n\n.nodes()\n--------\n\nReturn an `Array` of every node in the object.\n\n.clone()\n--------\n\nCreate a deep clone of the object.\n\ninstall\n=======\n\nUsing [npm](http://npmjs.org) do:\n\n $ npm install traverse\n\ntest\n====\n\nUsing [expresso](http://github.com/visionmedia/expresso) do:\n\n $ expresso\n \n 100% wahoo, your stuff is not broken!\n\nin the browser\n==============\n\nUse [browserify](https://github.com/substack/node-browserify) to run traverse in\nthe browser.\n\ntraverse has been tested and works with:\n\n* Internet Explorer 5.5, 6.0, 7.0, 8.0, 9.0\n* Firefox 3.5\n* Chrome 6.0\n* Opera 10.6\n* Safari 5.0\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/substack/js-traverse/issues" - }, - "_id": "traverse@0.5.2", - "_from": "traverse@~0.5.1" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/circular.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/circular.js deleted file mode 100644 index 916260113..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/circular.js +++ /dev/null @@ -1,115 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); -var deepEqual = require('./lib/deep_equal'); -var util = require('util'); - -exports.circular = function () { - var obj = { x : 3 }; - obj.y = obj; - var foundY = false; - Traverse(obj).forEach(function (x) { - if (this.path.join('') == 'y') { - assert.equal( - util.inspect(this.circular.node), - util.inspect(obj) - ); - foundY = true; - } - }); - assert.ok(foundY); -}; - -exports.deepCirc = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - - var times = 0; - Traverse(obj).forEach(function (x) { - if (this.circular) { - assert.deepEqual(this.circular.path, []); - assert.deepEqual(this.path, [ 'y', 2 ]); - times ++; - } - }); - - assert.deepEqual(times, 1); -}; - -exports.doubleCirc = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - var circs = []; - Traverse(obj).forEach(function (x) { - if (this.circular) { - circs.push({ circ : this.circular, self : this, node : x }); - } - }); - - assert.deepEqual(circs[0].self.path, [ 'x', 3, 2 ]); - assert.deepEqual(circs[0].circ.path, []); - - assert.deepEqual(circs[1].self.path, [ 'y', 2 ]); - assert.deepEqual(circs[1].circ.path, []); - - assert.deepEqual(circs.length, 2); -}; - -exports.circDubForEach = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - Traverse(obj).forEach(function (x) { - if (this.circular) this.update('...'); - }); - - assert.deepEqual(obj, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] }); -}; - -exports.circDubMap = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - var c = Traverse(obj).map(function (x) { - if (this.circular) { - this.update('...'); - } - }); - - assert.deepEqual(c, { x : [ 1, 2, 3, [ 4, 5, '...' ] ], y : [ 4, 5, '...' ] }); -}; - -exports.circClone = function () { - var obj = { x : [ 1, 2, 3 ], y : [ 4, 5 ] }; - obj.y[2] = obj; - obj.x.push(obj.y); - - var clone = Traverse.clone(obj); - assert.ok(obj !== clone); - - assert.ok(clone.y[2] === clone); - assert.ok(clone.y[2] !== obj); - assert.ok(clone.x[3][2] === clone); - assert.ok(clone.x[3][2] !== obj); - assert.deepEqual(clone.x.slice(0,3), [1,2,3]); - assert.deepEqual(clone.y.slice(0,2), [4,5]); -}; - -exports.circMapScrub = function () { - var obj = { a : 1, b : 2 }; - obj.c = obj; - - var scrubbed = Traverse(obj).map(function (node) { - if (this.circular) this.remove(); - }); - assert.deepEqual( - Object.keys(scrubbed).sort(), - [ 'a', 'b' ] - ); - assert.ok(deepEqual(scrubbed, { a : 1, b : 2 })); - - assert.equal(obj.c, obj); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/date.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/date.js deleted file mode 100644 index 4ca06dc38..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/date.js +++ /dev/null @@ -1,35 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports.dateEach = function () { - var obj = { x : new Date, y : 10, z : 5 }; - - var counts = {}; - - Traverse(obj).forEach(function (node) { - var t = (node instanceof Date && 'Date') || typeof node; - counts[t] = (counts[t] || 0) + 1; - }); - - assert.deepEqual(counts, { - object : 1, - Date : 1, - number : 2, - }); -}; - -exports.dateMap = function () { - var obj = { x : new Date, y : 10, z : 5 }; - - var res = Traverse(obj).map(function (node) { - if (typeof node === 'number') this.update(node + 100); - }); - - assert.ok(obj.x !== res.x); - assert.deepEqual(res, { - x : obj.x, - y : 110, - z : 105, - }); -}; - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/equal.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/equal.js deleted file mode 100644 index decc75503..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/equal.js +++ /dev/null @@ -1,220 +0,0 @@ -var assert = require('assert'); -var traverse = require('../'); -var deepEqual = require('./lib/deep_equal'); - -exports.deepDates = function () { - assert.ok( - deepEqual( - { d : new Date, x : [ 1, 2, 3 ] }, - { d : new Date, x : [ 1, 2, 3 ] } - ), - 'dates should be equal' - ); - - var d0 = new Date; - setTimeout(function () { - assert.ok( - !deepEqual( - { d : d0, x : [ 1, 2, 3 ], }, - { d : new Date, x : [ 1, 2, 3 ] } - ), - 'microseconds should count in date equality' - ); - }, 5); -}; - -exports.deepCircular = function () { - var a = [1]; - a.push(a); // a = [ 1, *a ] - - var b = [1]; - b.push(a); // b = [ 1, [ 1, *a ] ] - - assert.ok( - !deepEqual(a, b), - 'circular ref mount points count towards equality' - ); - - var c = [1]; - c.push(c); // c = [ 1, *c ] - assert.ok( - deepEqual(a, c), - 'circular refs are structurally the same here' - ); - - var d = [1]; - d.push(a); // c = [ 1, [ 1, *d ] ] - assert.ok( - deepEqual(b, d), - 'non-root circular ref structural comparison' - ); -}; - -exports.deepInstances = function () { - assert.ok( - !deepEqual([ new Boolean(false) ], [ false ]), - 'boolean instances are not real booleans' - ); - - assert.ok( - !deepEqual([ new String('x') ], [ 'x' ]), - 'string instances are not real strings' - ); - - assert.ok( - !deepEqual([ new Number(4) ], [ 4 ]), - 'number instances are not real numbers' - ); - - assert.ok( - deepEqual([ new RegExp('x') ], [ /x/ ]), - 'regexp instances are real regexps' - ); - - assert.ok( - !deepEqual([ new RegExp(/./) ], [ /../ ]), - 'these regexps aren\'t the same' - ); - - assert.ok( - !deepEqual( - [ function (x) { return x * 2 } ], - [ function (x) { return x * 2 } ] - ), - 'functions with the same .toString() aren\'t necessarily the same' - ); - - var f = function (x) { return x * 2 }; - assert.ok( - deepEqual([ f ], [ f ]), - 'these functions are actually equal' - ); -}; - -exports.deepEqual = function () { - assert.ok( - !deepEqual([ 1, 2, 3 ], { 0 : 1, 1 : 2, 2 : 3 }), - 'arrays are not objects' - ); -}; - -exports.falsy = function () { - assert.ok( - !deepEqual([ undefined ], [ null ]), - 'null is not undefined!' - ); - - assert.ok( - !deepEqual([ null ], [ undefined ]), - 'undefined is not null!' - ); - - assert.ok( - !deepEqual( - { a : 1, b : 2, c : [ 3, undefined, 5 ] }, - { a : 1, b : 2, c : [ 3, null, 5 ] } - ), - 'undefined is not null, however deeply!' - ); - - assert.ok( - !deepEqual( - { a : 1, b : 2, c : [ 3, undefined, 5 ] }, - { a : 1, b : 2, c : [ 3, null, 5 ] } - ), - 'null is not undefined, however deeply!' - ); - - assert.ok( - !deepEqual( - { a : 1, b : 2, c : [ 3, undefined, 5 ] }, - { a : 1, b : 2, c : [ 3, null, 5 ] } - ), - 'null is not undefined, however deeply!' - ); -}; - -exports.deletedArrayEqual = function () { - var xs = [ 1, 2, 3, 4 ]; - delete xs[2]; - - var ys = Object.create(Array.prototype); - ys[0] = 1; - ys[1] = 2; - ys[3] = 4; - - assert.ok( - deepEqual(xs, ys), - 'arrays with deleted elements are only equal to' - + ' arrays with similarly deleted elements' - ); - - assert.ok( - !deepEqual(xs, [ 1, 2, undefined, 4 ]), - 'deleted array elements cannot be undefined' - ); - - assert.ok( - !deepEqual(xs, [ 1, 2, null, 4 ]), - 'deleted array elements cannot be null' - ); -}; - -exports.deletedObjectEqual = function () { - var obj = { a : 1, b : 2, c : 3 }; - delete obj.c; - - assert.ok( - deepEqual(obj, { a : 1, b : 2 }), - 'deleted object elements should not show up' - ); - - assert.ok( - !deepEqual(obj, { a : 1, b : 2, c : undefined }), - 'deleted object elements are not undefined' - ); - - assert.ok( - !deepEqual(obj, { a : 1, b : 2, c : null }), - 'deleted object elements are not null' - ); -}; - -exports.emptyKeyEqual = function () { - assert.ok(!deepEqual( - { a : 1 }, { a : 1, '' : 55 } - )); -}; - -exports.deepArguments = function () { - assert.ok( - !deepEqual( - [ 4, 5, 6 ], - (function () { return arguments })(4, 5, 6) - ), - 'arguments are not arrays' - ); - - assert.ok( - deepEqual( - (function () { return arguments })(4, 5, 6), - (function () { return arguments })(4, 5, 6) - ), - 'arguments should equal' - ); -}; - -exports.deepUn = function () { - assert.ok(!deepEqual({ a : 1, b : 2 }, undefined)); - assert.ok(!deepEqual({ a : 1, b : 2 }, {})); - assert.ok(!deepEqual(undefined, { a : 1, b : 2 })); - assert.ok(!deepEqual({}, { a : 1, b : 2 })); - assert.ok(deepEqual(undefined, undefined)); - assert.ok(deepEqual(null, null)); - assert.ok(!deepEqual(undefined, null)); -}; - -exports.deepLevels = function () { - var xs = [ 1, 2, [ 3, 4, [ 5, 6 ] ] ]; - assert.ok(!deepEqual(xs, [])); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/instance.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/instance.js deleted file mode 100644 index 8d7352567..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/instance.js +++ /dev/null @@ -1,17 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); -var EventEmitter = require('events').EventEmitter; - -exports['check instanceof on node elems'] = function () { - - var counts = { emitter : 0 }; - - Traverse([ new EventEmitter, 3, 4, { ev : new EventEmitter }]) - .forEach(function (node) { - if (node instanceof EventEmitter) counts.emitter ++; - }) - ; - - assert.equal(counts.emitter, 2); -}; - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/interface.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/interface.js deleted file mode 100644 index fce5bf9a9..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/interface.js +++ /dev/null @@ -1,42 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports['interface map'] = function () { - var obj = { a : [ 5,6,7 ], b : { c : [8] } }; - - assert.deepEqual( - Traverse.paths(obj) - .sort() - .map(function (path) { return path.join('/') }) - .slice(1) - .join(' ') - , - 'a a/0 a/1 a/2 b b/c b/c/0' - ); - - assert.deepEqual( - Traverse.nodes(obj), - [ - { a: [ 5, 6, 7 ], b: { c: [ 8 ] } }, - [ 5, 6, 7 ], 5, 6, 7, - { c: [ 8 ] }, [ 8 ], 8 - ] - ); - - assert.deepEqual( - Traverse.map(obj, function (node) { - if (typeof node == 'number') { - return node + 1000; - } - else if (Array.isArray(node)) { - return node.join(' '); - } - }), - { a: '5 6 7', b: { c: '8' } } - ); - - var nodes = 0; - Traverse.forEach(obj, function (node) { nodes ++ }); - assert.deepEqual(nodes, 8); -}; - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/json.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/json.js deleted file mode 100644 index 0a045293f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/json.js +++ /dev/null @@ -1,47 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports['json test'] = function () { - var id = 54; - var callbacks = {}; - var obj = { moo : function () {}, foo : [2,3,4, function () {}] }; - - var scrubbed = Traverse(obj).map(function (x) { - if (typeof x === 'function') { - callbacks[id] = { id : id, f : x, path : this.path }; - this.update('[Function]'); - id++; - } - }); - - assert.equal( - scrubbed.moo, '[Function]', - 'obj.moo replaced with "[Function]"' - ); - - assert.equal( - scrubbed.foo[3], '[Function]', - 'obj.foo[3] replaced with "[Function]"' - ); - - assert.deepEqual(scrubbed, { - moo : '[Function]', - foo : [ 2, 3, 4, "[Function]" ] - }, 'Full JSON string matches'); - - assert.deepEqual( - typeof obj.moo, 'function', - 'Original obj.moo still a function' - ); - - assert.deepEqual( - typeof obj.foo[3], 'function', - 'Original obj.foo[3] still a function' - ); - - assert.deepEqual(callbacks, { - 54: { id: 54, f : obj.moo, path: [ 'moo' ] }, - 55: { id: 55, f : obj.foo[3], path: [ 'foo', '3' ] }, - }, 'Check the generated callbacks list'); -}; - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/keys.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/keys.js deleted file mode 100644 index 7ecd545ef..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/keys.js +++ /dev/null @@ -1,29 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports['sort test'] = function () { - var acc = []; - Traverse({ - a: 30, - b: 22, - id: 9 - }).forEach(function (node) { - if ((! Array.isArray(node)) && typeof node === 'object') { - this.before(function(node) { - this.keys = Object.keys(node); - this.keys.sort(function(a, b) { - a = [a === "id" ? 0 : 1, a]; - b = [b === "id" ? 0 : 1, b]; - return a < b ? -1 : a > b ? 1 : 0; - }); - }); - } - if (this.isLeaf) acc.push(node); - }); - - assert.equal( - acc.join(' '), - '9 30 22', - 'Traversal in a custom order' - ); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/leaves.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/leaves.js deleted file mode 100644 index e520b72e0..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/leaves.js +++ /dev/null @@ -1,21 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports['leaves test'] = function () { - var acc = []; - Traverse({ - a : [1,2,3], - b : 4, - c : [5,6], - d : { e : [7,8], f : 9 } - }).forEach(function (x) { - if (this.isLeaf) acc.push(x); - }); - - assert.equal( - acc.join(' '), - '1 2 3 4 5 6 7 8 9', - 'Traversal in the right(?) order' - ); -}; - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/lib/deep_equal.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/lib/deep_equal.js deleted file mode 100644 index 4fa07bb83..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/lib/deep_equal.js +++ /dev/null @@ -1,92 +0,0 @@ -var traverse = require('../../'); - -module.exports = function (a, b) { - if (arguments.length !== 2) { - throw new Error( - 'deepEqual requires exactly two objects to compare against' - ); - } - - var equal = true; - var node = b; - - traverse(a).forEach(function (y) { - var notEqual = (function () { - equal = false; - //this.stop(); - return undefined; - }).bind(this); - - //if (node === undefined || node === null) return notEqual(); - - if (!this.isRoot) { - /* - if (!Object.hasOwnProperty.call(node, this.key)) { - return notEqual(); - } - */ - if (typeof node !== 'object') return notEqual(); - node = node[this.key]; - } - - var x = node; - - this.post(function () { - node = x; - }); - - var toS = function (o) { - return Object.prototype.toString.call(o); - }; - - if (this.circular) { - if (traverse(b).get(this.circular.path) !== x) notEqual(); - } - else if (typeof x !== typeof y) { - notEqual(); - } - else if (x === null || y === null || x === undefined || y === undefined) { - if (x !== y) notEqual(); - } - else if (x.__proto__ !== y.__proto__) { - notEqual(); - } - else if (x === y) { - // nop - } - else if (typeof x === 'function') { - if (x instanceof RegExp) { - // both regexps on account of the __proto__ check - if (x.toString() != y.toString()) notEqual(); - } - else if (x !== y) notEqual(); - } - else if (typeof x === 'object') { - if (toS(y) === '[object Arguments]' - || toS(x) === '[object Arguments]') { - if (toS(x) !== toS(y)) { - notEqual(); - } - } - else if (x instanceof Date || y instanceof Date) { - if (!(x instanceof Date) || !(y instanceof Date) - || x.getTime() !== y.getTime()) { - notEqual(); - } - } - else { - var kx = Object.keys(x); - var ky = Object.keys(y); - if (kx.length !== ky.length) return notEqual(); - for (var i = 0; i < kx.length; i++) { - var k = kx[i]; - if (!Object.hasOwnProperty.call(y, k)) { - notEqual(); - } - } - } - } - }); - - return equal; -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/mutability.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/mutability.js deleted file mode 100644 index 2236f5631..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/mutability.js +++ /dev/null @@ -1,252 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); -var deepEqual = require('./lib/deep_equal'); - -exports.mutate = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).forEach(function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - assert.deepEqual(obj, res); - assert.deepEqual(obj, { a : 1, b : 20, c : [ 3, 40 ] }); -}; - -exports.mutateT = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse.forEach(obj, function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - assert.deepEqual(obj, res); - assert.deepEqual(obj, { a : 1, b : 20, c : [ 3, 40 ] }); -}; - -exports.map = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).map(function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, { a : 1, b : 20, c : [ 3, 40 ] }); -}; - -exports.mapT = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse.map(obj, function (x) { - if (typeof x === 'number' && x % 2 === 0) { - this.update(x * 10); - } - }); - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, { a : 1, b : 20, c : [ 3, 40 ] }); -}; - -exports.clone = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).clone(); - assert.deepEqual(obj, res); - assert.ok(obj !== res); - obj.a ++; - assert.deepEqual(res.a, 1); - obj.c.push(5); - assert.deepEqual(res.c, [ 3, 4 ]); -}; - -exports.cloneT = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse.clone(obj); - assert.deepEqual(obj, res); - assert.ok(obj !== res); - obj.a ++; - assert.deepEqual(res.a, 1); - obj.c.push(5); - assert.deepEqual(res.c, [ 3, 4 ]); -}; - -exports.reduce = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).reduce(function (acc, x) { - if (this.isLeaf) acc.push(x); - return acc; - }, []); - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, [ 1, 2, 3, 4 ]); -}; - -exports.reduceInit = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).reduce(function (acc, x) { - if (this.isRoot) assert.fail('got root'); - return acc; - }); - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, obj); -}; - -exports.remove = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - Traverse(obj).forEach(function (x) { - if (this.isLeaf && x % 2 == 0) this.remove(); - }); - - assert.deepEqual(obj, { a : 1, c : [ 3 ] }); -}; - -exports.removeNoStop = function() { - var obj = { a : 1, b : 2, c : { d: 3, e: 4 }, f: 5 }; - - var keys = []; - Traverse(obj).forEach(function (x) { - keys.push(this.key) - if (this.key == 'c') this.remove(); - }); - - assert.deepEqual(keys, [undefined, 'a', 'b', 'c', 'd', 'e', 'f']) -} - -exports.removeStop = function() { - var obj = { a : 1, b : 2, c : { d: 3, e: 4 }, f: 5 }; - - var keys = []; - Traverse(obj).forEach(function (x) { - keys.push(this.key) - if (this.key == 'c') this.remove(true); - }); - - assert.deepEqual(keys, [undefined, 'a', 'b', 'c', 'f']) -} - -exports.removeMap = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).map(function (x) { - if (this.isLeaf && x % 2 == 0) this.remove(); - }); - - assert.deepEqual(obj, { a : 1, b : 2, c : [ 3, 4 ] }); - assert.deepEqual(res, { a : 1, c : [ 3 ] }); -}; - -exports.delete = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - Traverse(obj).forEach(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - assert.ok(!deepEqual( - obj, { a : 1, c : [ 3, undefined ] } - )); - - assert.ok(deepEqual( - obj, { a : 1, c : [ 3 ] } - )); - - assert.ok(!deepEqual( - obj, { a : 1, c : [ 3, null ] } - )); -}; - -exports.deleteNoStop = function() { - var obj = { a : 1, b : 2, c : { d: 3, e: 4 } }; - - var keys = []; - Traverse(obj).forEach(function (x) { - keys.push(this.key) - if (this.key == 'c') this.delete(); - }); - - assert.deepEqual(keys, [undefined, 'a', 'b', 'c', 'd', 'e']) -} - -exports.deleteStop = function() { - var obj = { a : 1, b : 2, c : { d: 3, e: 4 } }; - - var keys = []; - Traverse(obj).forEach(function (x) { - keys.push(this.key) - if (this.key == 'c') this.delete(true); - }); - - assert.deepEqual(keys, [undefined, 'a', 'b', 'c']) -} - -exports.deleteRedux = function () { - var obj = { a : 1, b : 2, c : [ 3, 4, 5 ] }; - Traverse(obj).forEach(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - assert.ok(!deepEqual( - obj, { a : 1, c : [ 3, undefined, 5 ] } - )); - - assert.ok(deepEqual( - obj, { a : 1, c : [ 3 ,, 5 ] } - )); - - assert.ok(!deepEqual( - obj, { a : 1, c : [ 3, null, 5 ] } - )); - - assert.ok(!deepEqual( - obj, { a : 1, c : [ 3, 5 ] } - )); -}; - -exports.deleteMap = function () { - var obj = { a : 1, b : 2, c : [ 3, 4 ] }; - var res = Traverse(obj).map(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - assert.ok(deepEqual( - obj, - { a : 1, b : 2, c : [ 3, 4 ] } - )); - - var xs = [ 3, 4 ]; - delete xs[1]; - - assert.ok(deepEqual( - res, { a : 1, c : xs } - )); - - assert.ok(deepEqual( - res, { a : 1, c : [ 3, ] } - )); - - assert.ok(deepEqual( - res, { a : 1, c : [ 3 ] } - )); -}; - -exports.deleteMapRedux = function () { - var obj = { a : 1, b : 2, c : [ 3, 4, 5 ] }; - var res = Traverse(obj).map(function (x) { - if (this.isLeaf && x % 2 == 0) this.delete(); - }); - - assert.ok(deepEqual( - obj, - { a : 1, b : 2, c : [ 3, 4, 5 ] } - )); - - var xs = [ 3, 4, 5 ]; - delete xs[1]; - - assert.ok(deepEqual( - res, { a : 1, c : xs } - )); - - assert.ok(!deepEqual( - res, { a : 1, c : [ 3, 5 ] } - )); - - assert.ok(deepEqual( - res, { a : 1, c : [ 3 ,, 5 ] } - )); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/negative.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/negative.js deleted file mode 100644 index f92dfb07a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/negative.js +++ /dev/null @@ -1,20 +0,0 @@ -var Traverse = require('../'); -var assert = require('assert'); - -exports['negative update test'] = function () { - var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - var fixed = Traverse.map(obj, function (x) { - if (x < 0) this.update(x + 128); - }); - - assert.deepEqual(fixed, - [ 5, 6, 125, [ 7, 8, 126, 1 ], { f: 10, g: 115 } ], - 'Negative values += 128' - ); - - assert.deepEqual(obj, - [ 5, 6, -3, [ 7, 8, -2, 1 ], { f: 10, g: -13 } ], - 'Original references not modified' - ); -} - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/obj.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/obj.js deleted file mode 100644 index d46fd38ae..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/obj.js +++ /dev/null @@ -1,15 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports['traverse an object with nested functions'] = function () { - var to = setTimeout(function () { - assert.fail('never ran'); - }, 1000); - - function Cons (x) { - clearTimeout(to); - assert.equal(x, 10); - }; - Traverse(new Cons(10)); -}; - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/siblings.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/siblings.js deleted file mode 100644 index 99c0f1b24..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/siblings.js +++ /dev/null @@ -1,35 +0,0 @@ -var assert = require('assert'); -var traverse = require('../'); - -exports.siblings = function () { - var obj = { a : 1, b : 2, c : [ 4, 5, 6 ] }; - - var res = traverse(obj).reduce(function (acc, x) { - var p = '/' + this.path.join('/'); - if (this.parent) { - acc[p] = { - siblings : this.parent.keys, - key : this.key, - index : this.parent.keys.indexOf(this.key) - }; - } - else { - acc[p] = { - siblings : [], - key : this.key, - index : -1 - } - } - return acc; - }, {}); - - assert.deepEqual(res, { - '/' : { siblings : [], key : undefined, index : -1 }, - '/a' : { siblings : [ 'a', 'b', 'c' ], key : 'a', index : 0 }, - '/b' : { siblings : [ 'a', 'b', 'c' ], key : 'b', index : 1 }, - '/c' : { siblings : [ 'a', 'b', 'c' ], key : 'c', index : 2 }, - '/c/0' : { siblings : [ '0', '1', '2' ], key : '0', index : 0 }, - '/c/1' : { siblings : [ '0', '1', '2' ], key : '1', index : 1 }, - '/c/2' : { siblings : [ '0', '1', '2' ], key : '2', index : 2 } - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/stop.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/stop.js deleted file mode 100644 index 3529847d8..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/stop.js +++ /dev/null @@ -1,41 +0,0 @@ -var assert = require('assert'); -var traverse = require('../'); - -exports.stop = function () { - var visits = 0; - traverse('abcdefghij'.split('')).forEach(function (node) { - if (typeof node === 'string') { - visits ++; - if (node === 'e') this.stop() - } - }); - - assert.equal(visits, 5); -}; - -exports.stopMap = function () { - var s = traverse('abcdefghij'.split('')).map(function (node) { - if (typeof node === 'string') { - if (node === 'e') this.stop() - return node.toUpperCase(); - } - }).join(''); - - assert.equal(s, 'ABCDEfghij'); -}; - -exports.stopReduce = function () { - var obj = { - a : [ 4, 5 ], - b : [ 6, [ 7, 8, 9 ] ] - }; - var xs = traverse(obj).reduce(function (acc, node) { - if (this.isLeaf) { - if (node === 7) this.stop(); - else acc.push(node) - } - return acc; - }, []); - - assert.deepEqual(xs, [ 4, 5, 6 ]); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/stringify.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/stringify.js deleted file mode 100644 index 932f5d3cf..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/stringify.js +++ /dev/null @@ -1,36 +0,0 @@ -var assert = require('assert'); -var Traverse = require('../'); - -exports.stringify = function () { - var obj = [ 5, 6, -3, [ 7, 8, -2, 1 ], { f : 10, g : -13 } ]; - - var s = ''; - Traverse(obj).forEach(function (node) { - if (Array.isArray(node)) { - this.before(function () { s += '[' }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += ']' }); - } - else if (typeof node == 'object') { - this.before(function () { s += '{' }); - this.pre(function (x, key) { - s += '"' + key + '"' + ':'; - }); - this.post(function (child) { - if (!child.isLast) s += ','; - }); - this.after(function () { s += '}' }); - } - else if (typeof node == 'function') { - s += 'null'; - } - else { - s += node.toString(); - } - }); - - assert.equal(s, JSON.stringify(obj)); -} - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/subexpr.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/subexpr.js deleted file mode 100644 index a217beba9..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/subexpr.js +++ /dev/null @@ -1,34 +0,0 @@ -var traverse = require('../'); -var assert = require('assert'); - -exports.subexpr = function () { - var obj = [ 'a', 4, 'b', 5, 'c', 6 ]; - var r = traverse(obj).map(function (x) { - if (typeof x === 'number') { - this.update([ x - 0.1, x, x + 0.1 ], true); - } - }); - - assert.deepEqual(obj, [ 'a', 4, 'b', 5, 'c', 6 ]); - assert.deepEqual(r, [ - 'a', [ 3.9, 4, 4.1 ], - 'b', [ 4.9, 5, 5.1 ], - 'c', [ 5.9, 6, 6.1 ], - ]); -}; - -exports.block = function () { - var obj = [ [ 1 ], [ 2 ], [ 3 ] ]; - var r = traverse(obj).map(function (x) { - if (Array.isArray(x) && !this.isRoot) { - if (x[0] === 5) this.block() - else this.update([ [ x[0] + 1 ] ]) - } - }); - - assert.deepEqual(r, [ - [ [ [ [ [ 5 ] ] ] ] ], - [ [ [ [ 5 ] ] ] ], - [ [ [ 5 ] ] ], - ]); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/super_deep.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/super_deep.js deleted file mode 100644 index acac2fd9e..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/traverse/test/super_deep.js +++ /dev/null @@ -1,55 +0,0 @@ -var assert = require('assert'); -var traverse = require('../'); -var deepEqual = require('./lib/deep_equal'); - -exports.super_deep = function () { - var util = require('util'); - var a0 = make(); - var a1 = make(); - assert.ok(deepEqual(a0, a1)); - - a0.c.d.moo = true; - assert.ok(!deepEqual(a0, a1)); - - a1.c.d.moo = true; - assert.ok(deepEqual(a0, a1)); - - // TODO: this one - //a0.c.a = a1; - //assert.ok(!deepEqual(a0, a1)); -}; - -function make () { - var a = { self : 'a' }; - var b = { self : 'b' }; - var c = { self : 'c' }; - var d = { self : 'd' }; - var e = { self : 'e' }; - - a.a = a; - a.b = b; - a.c = c; - - b.a = a; - b.b = b; - b.c = c; - - c.a = a; - c.b = b; - c.c = c; - c.d = d; - - d.a = a; - d.b = b; - d.c = c; - d.d = d; - d.e = e; - - e.a = a; - e.b = b; - e.c = c; - e.d = d; - e.e = e; - - return a; -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/.npmignore b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/.npmignore deleted file mode 100644 index d97eaa09b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -.DS_Store -.tmp*~ -*.local.* -.pinf-* \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/README.html b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/README.html deleted file mode 100644 index 8f5223f00..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/README.html +++ /dev/null @@ -1,1026 +0,0 @@ - - - - -UglifyJS -- a JavaScript parser/compressor/beautifier - - - - - - - - - - - - -
        - -

        UglifyJS – a JavaScript parser/compressor/beautifier

        - - - - -
        -

        1 UglifyJS — a JavaScript parser/compressor/beautifier

        -
        - - -

        -This package implements a general-purpose JavaScript -parser/compressor/beautifier toolkit. It is developed on NodeJS, but it -should work on any JavaScript platform supporting the CommonJS module system -(and if your platform of choice doesn't support CommonJS, you can easily -implement it, or discard the exports.* lines from UglifyJS sources). -

        -

        -The tokenizer/parser generates an abstract syntax tree from JS code. You -can then traverse the AST to learn more about the code, or do various -manipulations on it. This part is implemented in parse-js.js and it's a -port to JavaScript of the excellent parse-js Common Lisp library from Marijn Haverbeke. -

        -

        -( See cl-uglify-js if you're looking for the Common Lisp version of -UglifyJS. ) -

        -

        -The second part of this package, implemented in process.js, inspects and -manipulates the AST generated by the parser to provide the following: -

        -
          -
        • -ability to re-generate JavaScript code from the AST. Optionally -indented—you can use this if you want to “beautify” a program that has -been compressed, so that you can inspect the source. But you can also run -our code generator to print out an AST without any whitespace, so you -achieve compression as well. - -
        • -
        • -shorten variable names (usually to single characters). Our mangler will -analyze the code and generate proper variable names, depending on scope -and usage, and is smart enough to deal with globals defined elsewhere, or -with eval() calls or with{} statements. In short, if eval() or -with{} are used in some scope, then all variables in that scope and any -variables in the parent scopes will remain unmangled, and any references -to such variables remain unmangled as well. - -
        • -
        • -various small optimizations that may lead to faster code but certainly -lead to smaller code. Where possible, we do the following: - -
            -
          • -foo["bar"] ==> foo.bar - -
          • -
          • -remove block brackets {} - -
          • -
          • -join consecutive var declarations: -var a = 10; var b = 20; ==> var a=10,b=20; - -
          • -
          • -resolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the -replacement if the result occupies less bytes; for example 1/3 would -translate to 0.333333333333, so in this case we don't replace it. - -
          • -
          • -consecutive statements in blocks are merged into a sequence; in many -cases, this leaves blocks with a single statement, so then we can remove -the block brackets. - -
          • -
          • -various optimizations for IF statements: - -
              -
            • -if (foo) bar(); else baz(); ==> foo?bar():baz(); -
            • -
            • -if (!foo) bar(); else baz(); ==> foo?baz():bar(); -
            • -
            • -if (foo) bar(); ==> foo&&bar(); -
            • -
            • -if (!foo) bar(); ==> foo||bar(); -
            • -
            • -if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); -
            • -
            • -if (foo) return bar(); else something(); ==> {if(foo)return bar();something()} - -
            • -
            -
          • -
          • -remove some unreachable code and warn about it (code that follows a -return, throw, break or continue statement, except -function/variable declarations). - -
          • -
          • -act a limited version of a pre-processor (c.f. the pre-processor of -C/C++) to allow you to safely replace selected global symbols with -specified values. When combined with the optimisations above this can -make UglifyJS operate slightly more like a compilation process, in -that when certain symbols are replaced by constant values, entire code -blocks may be optimised away as unreachable. -
          • -
          -
        • -
        - - - -
        - -
        -

        1.1 Unsafe transformations

        -
        - - -

        -The following transformations can in theory break code, although they're -probably safe in most practical cases. To enable them you need to pass the ---unsafe flag. -

        - -
        - -
        -

        1.1.1 Calls involving the global Array constructor

        -
        - - -

        -The following transformations occur: -

        - - - -
        new Array(1, 2, 3, 4)  => [1,2,3,4]
        -Array(a, b, c)         => [a,b,c]
        -new Array(5)           => Array(5)
        -new Array(a)           => Array(a)
        -
        - - - -

        -These are all safe if the Array name isn't redefined. JavaScript does allow -one to globally redefine Array (and pretty much everything, in fact) but I -personally don't see why would anyone do that. -

        -

        -UglifyJS does handle the case where Array is redefined locally, or even -globally but with a function or var declaration. Therefore, in the -following cases UglifyJS doesn't touch calls or instantiations of Array: -

        - - - -
        // case 1.  globally declared variable
        -  var Array;
        -  new Array(1, 2, 3);
        -  Array(a, b);
        -
        -  // or (can be declared later)
        -  new Array(1, 2, 3);
        -  var Array;
        -
        -  // or (can be a function)
        -  new Array(1, 2, 3);
        -  function Array() { ... }
        -
        -// case 2.  declared in a function
        -  (function(){
        -    a = new Array(1, 2, 3);
        -    b = Array(5, 6);
        -    var Array;
        -  })();
        -
        -  // or
        -  (function(Array){
        -    return Array(5, 6, 7);
        -  })();
        -
        -  // or
        -  (function(){
        -    return new Array(1, 2, 3, 4);
        -    function Array() { ... }
        -  })();
        -
        -  // etc.
        -
        - - - -
        - -
        - -
        -

        1.1.2 obj.toString() ==> obj+“”

        -
        - - -
        -
        - -
        - -
        -

        1.2 Install (NPM)

        -
        - - -

        -UglifyJS is now available through NPM — npm install uglify-js should do -the job. -

        -
        - -
        - -
        -

        1.3 Install latest code from GitHub

        -
        - - - - - -
        ## clone the repository
        -mkdir -p /where/you/wanna/put/it
        -cd /where/you/wanna/put/it
        -git clone git://github.com/mishoo/UglifyJS.git
        -
        -## make the module available to Node
        -mkdir -p ~/.node_libraries/
        -cd ~/.node_libraries/
        -ln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js
        -
        -## and if you want the CLI script too:
        -mkdir -p ~/bin
        -cd ~/bin
        -ln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs
        -  # (then add ~/bin to your $PATH if it's not there already)
        -
        - - - -
        - -
        - -
        -

        1.4 Usage

        -
        - - -

        -There is a command-line tool that exposes the functionality of this library -for your shell-scripting needs: -

        - - - -
        uglifyjs [ options... ] [ filename ]
        -
        - - - -

        -filename should be the last argument and should name the file from which -to read the JavaScript code. If you don't specify it, it will read code -from STDIN. -

        -

        -Supported options: -

        -
          -
        • --b or --beautify — output indented code; when passed, additional -options control the beautifier: - -
            -
          • --i N or --indent N — indentation level (number of spaces) - -
          • -
          • --q or --quote-keys — quote keys in literal objects (by default, -only keys that cannot be identifier names will be quotes). - -
          • -
          -
        • -
        • ---ascii — pass this argument to encode non-ASCII characters as -\uXXXX sequences. By default UglifyJS won't bother to do it and will -output Unicode characters instead. (the output is always encoded in UTF8, -but if you pass this option you'll only get ASCII). - -
        • -
        • --nm or --no-mangle — don't mangle variable names - -
        • -
        • --ns or --no-squeeze — don't call ast_squeeze() (which does various -optimizations that result in smaller, less readable code). - -
        • -
        • --mt or --mangle-toplevel — mangle names in the toplevel scope too -(by default we don't do this). - -
        • -
        • ---no-seqs — when ast_squeeze() is called (thus, unless you pass ---no-squeeze) it will reduce consecutive statements in blocks into a -sequence. For example, "a = 10; b = 20; foo();" will be written as -"a=10,b=20,foo();". In various occasions, this allows us to discard the -block brackets (since the block becomes a single statement). This is ON -by default because it seems safe and saves a few hundred bytes on some -libs that I tested it on, but pass --no-seqs to disable it. - -
        • -
        • ---no-dead-code — by default, UglifyJS will remove code that is -obviously unreachable (code that follows a return, throw, break or -continue statement and is not a function/variable declaration). Pass -this option to disable this optimization. - -
        • -
        • --nc or --no-copyright — by default, uglifyjs will keep the initial -comment tokens in the generated code (assumed to be copyright information -etc.). If you pass this it will discard it. - -
        • -
        • --o filename or --output filename — put the result in filename. If -this isn't given, the result goes to standard output (or see next one). - -
        • -
        • ---overwrite — if the code is read from a file (not from STDIN) and you -pass --overwrite then the output will be written in the same file. - -
        • -
        • ---ast — pass this if you want to get the Abstract Syntax Tree instead -of JavaScript as output. Useful for debugging or learning more about the -internals. - -
        • -
        • --v or --verbose — output some notes on STDERR (for now just how long -each operation takes). - -
        • -
        • --d SYMBOL[=VALUE] or --define SYMBOL[=VALUE] — will replace -all instances of the specified symbol where used as an identifier -(except where symbol has properly declared by a var declaration or -use as function parameter or similar) with the specified value. This -argument may be specified multiple times to define multiple -symbols - if no value is specified the symbol will be replaced with -the value true, or you can specify a numeric value (such as -1024), a quoted string value (such as ="object"= or -='https://github.com'), or the name of another symbol or keyword (such as =null or document). -This allows you, for example, to assign meaningful names to key -constant values but discard the symbolic names in the uglified -version for brevity/efficiency, or when used wth care, allows -UglifyJS to operate as a form of conditional compilation -whereby defining appropriate values may, by dint of the constant -folding and dead code removal features above, remove entire -superfluous code blocks (e.g. completely remove instrumentation or -trace code for production use). -Where string values are being defined, the handling of quotes are -likely to be subject to the specifics of your command shell -environment, so you may need to experiment with quoting styles -depending on your platform, or you may find the option ---define-from-module more suitable for use. - -
        • -
        • --define-from-module SOMEMODULE — will load the named module (as -per the NodeJS require() function) and iterate all the exported -properties of the module defining them as symbol names to be defined -(as if by the --define option) per the name of each property -(i.e. without the module name prefix) and given the value of the -property. This is a much easier way to handle and document groups of -symbols to be defined rather than a large number of --define -options. - -
        • -
        • ---unsafe — enable other additional optimizations that are known to be -unsafe in some contrived situations, but could still be generally useful. -For now only these: - -
            -
          • -foo.toString() ==> foo+"" -
          • -
          • -new Array(x,…) ==> [x,…] -
          • -
          • -new Array(x) ==> Array(x) - -
          • -
          -
        • -
        • ---max-line-len (default 32K characters) — add a newline after around -32K characters. I've seen both FF and Chrome croak when all the code was -on a single line of around 670K. Pass –max-line-len 0 to disable this -safety feature. - -
        • -
        • ---reserved-names — some libraries rely on certain names to be used, as -pointed out in issue #92 and #81, so this option allow you to exclude such -names from the mangler. For example, to keep names require and $super -intact you'd specify –reserved-names "require,$super". - -
        • -
        • ---inline-script – when you want to include the output literally in an -HTML <script> tag you can use this option to prevent </script from -showing up in the output. - -
        • -
        • ---lift-vars – when you pass this, UglifyJS will apply the following -transformations (see the notes in API, ast_lift_variables): - -
            -
          • -put all var declarations at the start of the scope -
          • -
          • -make sure a variable is declared only once -
          • -
          • -discard unused function arguments -
          • -
          • -discard unused inner (named) functions -
          • -
          • -finally, try to merge assignments into that one var declaration, if -possible. -
          • -
          -
        • -
        - - - -
        - -
        -

        1.4.1 API

        -
        - - -

        -To use the library from JavaScript, you'd do the following (example for -NodeJS): -

        - - - -
        var jsp = require("uglify-js").parser;
        -var pro = require("uglify-js").uglify;
        -
        -var orig_code = "... JS code here";
        -var ast = jsp.parse(orig_code); // parse code and get the initial AST
        -ast = pro.ast_mangle(ast); // get a new AST with mangled names
        -ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
        -var final_code = pro.gen_code(ast); // compressed code here
        -
        - - - -

        -The above performs the full compression that is possible right now. As you -can see, there are a sequence of steps which you can apply. For example if -you want compressed output but for some reason you don't want to mangle -variable names, you would simply skip the line that calls -pro.ast_mangle(ast). -

        -

        -Some of these functions take optional arguments. Here's a description: -

        -
          -
        • -jsp.parse(code, strict_semicolons) – parses JS code and returns an AST. -strict_semicolons is optional and defaults to false. If you pass -true then the parser will throw an error when it expects a semicolon and -it doesn't find it. For most JS code you don't want that, but it's useful -if you want to strictly sanitize your code. - -
        • -
        • -pro.ast_lift_variables(ast) – merge and move var declarations to the -scop of the scope; discard unused function arguments or variables; discard -unused (named) inner functions. It also tries to merge assignments -following the var declaration into it. - -

          -If your code is very hand-optimized concerning var declarations, this -lifting variable declarations might actually increase size. For me it -helps out. On jQuery it adds 865 bytes (243 after gzip). YMMV. Also -note that (since it's not enabled by default) this operation isn't yet -heavily tested (please report if you find issues!). -

          -

          -Note that although it might increase the image size (on jQuery it gains -865 bytes, 243 after gzip) it's technically more correct: in certain -situations, dead code removal might drop variable declarations, which -would not happen if the variables are lifted in advance. -

          -

          -Here's an example of what it does: -

          -
        • -
        - - - - -
        function f(a, b, c, d, e) {
        -    var q;
        -    var w;
        -    w = 10;
        -    q = 20;
        -    for (var i = 1; i < 10; ++i) {
        -        var boo = foo(a);
        -    }
        -    for (var i = 0; i < 1; ++i) {
        -        var boo = bar(c);
        -    }
        -    function foo(){ ... }
        -    function bar(){ ... }
        -    function baz(){ ... }
        -}
        -
        -// transforms into ==>
        -
        -function f(a, b, c) {
        -    var i, boo, w = 10, q = 20;
        -    for (i = 1; i < 10; ++i) {
        -        boo = foo(a);
        -    }
        -    for (i = 0; i < 1; ++i) {
        -        boo = bar(c);
        -    }
        -    function foo() { ... }
        -    function bar() { ... }
        -}
        -
        - - - -
          -
        • -pro.ast_mangle(ast, options) – generates a new AST containing mangled -(compressed) variable and function names. It supports the following -options: - -
            -
          • -toplevel – mangle toplevel names (by default we don't touch them). -
          • -
          • -except – an array of names to exclude from compression. -
          • -
          • -defines – an object with properties named after symbols to -replace (see the --define option for the script) and the values -representing the AST replacement value. - -
          • -
          -
        • -
        • -pro.ast_squeeze(ast, options) – employs further optimizations designed -to reduce the size of the code that gen_code would generate from the -AST. Returns a new AST. options can be a hash; the supported options -are: - -
            -
          • -make_seqs (default true) which will cause consecutive statements in a -block to be merged using the "sequence" (comma) operator - -
          • -
          • -dead_code (default true) which will remove unreachable code. - -
          • -
          -
        • -
        • -pro.gen_code(ast, options) – generates JS code from the AST. By -default it's minified, but using the options argument you can get nicely -formatted output. options is, well, optional :-) and if you pass it it -must be an object and supports the following properties (below you can see -the default values): - -
            -
          • -beautify: false – pass true if you want indented output -
          • -
          • -indent_start: 0 (only applies when beautify is true) – initial -indentation in spaces -
          • -
          • -indent_level: 4 (only applies when beautify is true) -- -indentation level, in spaces (pass an even number) -
          • -
          • -quote_keys: false – if you pass true it will quote all keys in -literal objects -
          • -
          • -space_colon: false (only applies when beautify is true) – wether -to put a space before the colon in object literals -
          • -
          • -ascii_only: false – pass true if you want to encode non-ASCII -characters as \uXXXX. -
          • -
          • -inline_script: false – pass true to escape occurrences of -</script in strings -
          • -
          -
        • -
        - - -
        - -
        - -
        -

        1.4.2 Beautifier shortcoming – no more comments

        -
        - - -

        -The beautifier can be used as a general purpose indentation tool. It's -useful when you want to make a minified file readable. One limitation, -though, is that it discards all comments, so you don't really want to use it -to reformat your code, unless you don't have, or don't care about, comments. -

        -

        -In fact it's not the beautifier who discards comments — they are dumped at -the parsing stage, when we build the initial AST. Comments don't really -make sense in the AST, and while we could add nodes for them, it would be -inconvenient because we'd have to add special rules to ignore them at all -the processing stages. -

        -
        - -
        - -
        -

        1.4.3 Use as a code pre-processor

        -
        - - -

        -The --define option can be used, particularly when combined with the -constant folding logic, as a form of pre-processor to enable or remove -particular constructions, such as might be used for instrumenting -development code, or to produce variations aimed at a specific -platform. -

        -

        -The code below illustrates the way this can be done, and how the -symbol replacement is performed. -

        - - - -
        CLAUSE1: if (typeof DEVMODE === 'undefined') {
        -    DEVMODE = true;
        -}
        -
        -CLAUSE2: function init() {
        -    if (DEVMODE) {
        -        console.log("init() called");
        -    }
        -    ....
        -    DEVMODE &amp;&amp; console.log("init() complete");
        -}
        -
        -CLAUSE3: function reportDeviceStatus(device) {
        -    var DEVMODE = device.mode, DEVNAME = device.name;
        -    if (DEVMODE === 'open') {
        -        ....
        -    }
        -}
        -
        - - - -

        -When the above code is normally executed, the undeclared global -variable DEVMODE will be assigned the value true (see CLAUSE1) -and so the init() function (CLAUSE2) will write messages to the -console log when executed, but in CLAUSE3 a locally declared -variable will mask access to the DEVMODE global symbol. -

        -

        -If the above code is processed by UglifyJS with an argument of ---define DEVMODE=false then UglifyJS will replace DEVMODE with the -boolean constant value false within CLAUSE1 and CLAUSE2, but it -will leave CLAUSE3 as it stands because there DEVMODE resolves to -a validly declared variable. -

        -

        -And more so, the constant-folding features of UglifyJS will recognise -that the if condition of CLAUSE1 is thus always false, and so will -remove the test and body of CLAUSE1 altogether (including the -otherwise slightly problematical statement false = true; which it -will have formed by replacing DEVMODE in the body). Similarly, -within CLAUSE2 both calls to console.log() will be removed -altogether. -

        -

        -In this way you can mimic, to a limited degree, the functionality of -the C/C++ pre-processor to enable or completely remove blocks -depending on how certain symbols are defined - perhaps using UglifyJS -to generate different versions of source aimed at different -environments -

        -

        -It is recommmended (but not made mandatory) that symbols designed for -this purpose are given names consisting of UPPER_CASE_LETTERS to -distinguish them from other (normal) symbols and avoid the sort of -clash that CLAUSE3 above illustrates. -

        -
        -
        - -
        - -
        -

        1.5 Compression – how good is it?

        -
        - - -

        -Here are updated statistics. (I also updated my Google Closure and YUI -installations). -

        -

        -We're still a lot better than YUI in terms of compression, though slightly -slower. We're still a lot faster than Closure, and compression after gzip -is comparable. -

        - - -- - - - - - - - - - -
        FileUglifyJSUglifyJS+gzipClosureClosure+gzipYUIYUI+gzip
        jquery-1.6.2.js91001 (0:01.59)3189690678 (0:07.40)31979101527 (0:01.82)34646
        paper.js142023 (0:01.65)43334134301 (0:07.42)42495173383 (0:01.58)48785
        prototype.js88544 (0:01.09)2668086955 (0:06.97)2632692130 (0:00.79)28624
        thelib-full.js (DynarchLIB)251939 (0:02.55)72535249911 (0:09.05)72696258869 (0:01.94)76584
        - - -
        - -
        - -
        -

        1.6 Bugs?

        -
        - - -

        -Unfortunately, for the time being there is no automated test suite. But I -ran the compressor manually on non-trivial code, and then I tested that the -generated code works as expected. A few hundred times. -

        -

        -DynarchLIB was started in times when there was no good JS minifier. -Therefore I was quite religious about trying to write short code manually, -and as such DL contains a lot of syntactic hacks1 such as “foo == bar ? a -= 10 : b = 20”, though the more readable version would clearly be to use -“if/else”. -

        -

        -Since the parser/compressor runs fine on DL and jQuery, I'm quite confident -that it's solid enough for production use. If you can identify any bugs, -I'd love to hear about them (use the Google Group or email me directly). -

        -
        - -
        - -
        -

        1.7 Links

        -
        - - - - - -
        - -
        - -
        -

        1.8 License

        -
        - - -

        -UglifyJS is released under the BSD license: -

        - - - -
        Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
        -Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
        -
        -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.
        -
        -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 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.
        -
        - - - - -
        -
        -
        -
        -

        Footnotes:

        -
        -

        1 I even reported a few bugs and suggested some fixes in the original -parse-js library, and Marijn pushed fixes literally in minutes. -

        -
        -
        -
        -

        Author: Mihai Bazon -

        -

        Date: 2011-08-29 19:17:55 EEST

        -

        HTML generated by org-mode 7.01trans in emacs 23

        -
        -
        - - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/README.org b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/README.org deleted file mode 100644 index 50c9c2731..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/README.org +++ /dev/null @@ -1,571 +0,0 @@ -#+TITLE: UglifyJS -- a JavaScript parser/compressor/beautifier -#+KEYWORDS: javascript, js, parser, compiler, compressor, mangle, minify, minifier -#+DESCRIPTION: a JavaScript parser/compressor/beautifier in JavaScript -#+STYLE: -#+AUTHOR: Mihai Bazon -#+EMAIL: mihai.bazon@gmail.com - -* UglifyJS --- a JavaScript parser/compressor/beautifier - -This package implements a general-purpose JavaScript -parser/compressor/beautifier toolkit. It is developed on [[http://nodejs.org/][NodeJS]], but it -should work on any JavaScript platform supporting the CommonJS module system -(and if your platform of choice doesn't support CommonJS, you can easily -implement it, or discard the =exports.*= lines from UglifyJS sources). - -The tokenizer/parser generates an abstract syntax tree from JS code. You -can then traverse the AST to learn more about the code, or do various -manipulations on it. This part is implemented in [[../lib/parse-js.js][parse-js.js]] and it's a -port to JavaScript of the excellent [[http://marijn.haverbeke.nl/parse-js/][parse-js]] Common Lisp library from [[http://marijn.haverbeke.nl/][Marijn -Haverbeke]]. - -( See [[http://github.com/mishoo/cl-uglify-js][cl-uglify-js]] if you're looking for the Common Lisp version of -UglifyJS. ) - -The second part of this package, implemented in [[../lib/process.js][process.js]], inspects and -manipulates the AST generated by the parser to provide the following: - -- ability to re-generate JavaScript code from the AST. Optionally - indented---you can use this if you want to “beautify” a program that has - been compressed, so that you can inspect the source. But you can also run - our code generator to print out an AST without any whitespace, so you - achieve compression as well. - -- shorten variable names (usually to single characters). Our mangler will - analyze the code and generate proper variable names, depending on scope - and usage, and is smart enough to deal with globals defined elsewhere, or - with =eval()= calls or =with{}= statements. In short, if =eval()= or - =with{}= are used in some scope, then all variables in that scope and any - variables in the parent scopes will remain unmangled, and any references - to such variables remain unmangled as well. - -- various small optimizations that may lead to faster code but certainly - lead to smaller code. Where possible, we do the following: - - - foo["bar"] ==> foo.bar - - - remove block brackets ={}= - - - join consecutive var declarations: - var a = 10; var b = 20; ==> var a=10,b=20; - - - resolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the - replacement if the result occupies less bytes; for example 1/3 would - translate to 0.333333333333, so in this case we don't replace it. - - - consecutive statements in blocks are merged into a sequence; in many - cases, this leaves blocks with a single statement, so then we can remove - the block brackets. - - - various optimizations for IF statements: - - - if (foo) bar(); else baz(); ==> foo?bar():baz(); - - if (!foo) bar(); else baz(); ==> foo?baz():bar(); - - if (foo) bar(); ==> foo&&bar(); - - if (!foo) bar(); ==> foo||bar(); - - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); - - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()} - - - remove some unreachable code and warn about it (code that follows a - =return=, =throw=, =break= or =continue= statement, except - function/variable declarations). - - - act a limited version of a pre-processor (c.f. the pre-processor of - C/C++) to allow you to safely replace selected global symbols with - specified values. When combined with the optimisations above this can - make UglifyJS operate slightly more like a compilation process, in - that when certain symbols are replaced by constant values, entire code - blocks may be optimised away as unreachable. - -** <> - -The following transformations can in theory break code, although they're -probably safe in most practical cases. To enable them you need to pass the -=--unsafe= flag. - -*** Calls involving the global Array constructor - -The following transformations occur: - -#+BEGIN_SRC js -new Array(1, 2, 3, 4) => [1,2,3,4] -Array(a, b, c) => [a,b,c] -new Array(5) => Array(5) -new Array(a) => Array(a) -#+END_SRC - -These are all safe if the Array name isn't redefined. JavaScript does allow -one to globally redefine Array (and pretty much everything, in fact) but I -personally don't see why would anyone do that. - -UglifyJS does handle the case where Array is redefined locally, or even -globally but with a =function= or =var= declaration. Therefore, in the -following cases UglifyJS *doesn't touch* calls or instantiations of Array: - -#+BEGIN_SRC js -// case 1. globally declared variable - var Array; - new Array(1, 2, 3); - Array(a, b); - - // or (can be declared later) - new Array(1, 2, 3); - var Array; - - // or (can be a function) - new Array(1, 2, 3); - function Array() { ... } - -// case 2. declared in a function - (function(){ - a = new Array(1, 2, 3); - b = Array(5, 6); - var Array; - })(); - - // or - (function(Array){ - return Array(5, 6, 7); - })(); - - // or - (function(){ - return new Array(1, 2, 3, 4); - function Array() { ... } - })(); - - // etc. -#+END_SRC - -*** =obj.toString()= ==> =obj+“”= - -** Install (NPM) - -UglifyJS is now available through NPM --- =npm install uglify-js= should do -the job. - -** Install latest code from GitHub - -#+BEGIN_SRC sh -## clone the repository -mkdir -p /where/you/wanna/put/it -cd /where/you/wanna/put/it -git clone git://github.com/mishoo/UglifyJS.git - -## make the module available to Node -mkdir -p ~/.node_libraries/ -cd ~/.node_libraries/ -ln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js - -## and if you want the CLI script too: -mkdir -p ~/bin -cd ~/bin -ln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs - # (then add ~/bin to your $PATH if it's not there already) -#+END_SRC - -** Usage - -There is a command-line tool that exposes the functionality of this library -for your shell-scripting needs: - -#+BEGIN_SRC sh -uglifyjs [ options... ] [ filename ] -#+END_SRC - -=filename= should be the last argument and should name the file from which -to read the JavaScript code. If you don't specify it, it will read code -from STDIN. - -Supported options: - -- =-b= or =--beautify= --- output indented code; when passed, additional - options control the beautifier: - - - =-i N= or =--indent N= --- indentation level (number of spaces) - - - =-q= or =--quote-keys= --- quote keys in literal objects (by default, - only keys that cannot be identifier names will be quotes). - -- =--ascii= --- pass this argument to encode non-ASCII characters as - =\uXXXX= sequences. By default UglifyJS won't bother to do it and will - output Unicode characters instead. (the output is always encoded in UTF8, - but if you pass this option you'll only get ASCII). - -- =-nm= or =--no-mangle= --- don't mangle variable names - -- =-ns= or =--no-squeeze= --- don't call =ast_squeeze()= (which does various - optimizations that result in smaller, less readable code). - -- =-mt= or =--mangle-toplevel= --- mangle names in the toplevel scope too - (by default we don't do this). - -- =--no-seqs= --- when =ast_squeeze()= is called (thus, unless you pass - =--no-squeeze=) it will reduce consecutive statements in blocks into a - sequence. For example, "a = 10; b = 20; foo();" will be written as - "a=10,b=20,foo();". In various occasions, this allows us to discard the - block brackets (since the block becomes a single statement). This is ON - by default because it seems safe and saves a few hundred bytes on some - libs that I tested it on, but pass =--no-seqs= to disable it. - -- =--no-dead-code= --- by default, UglifyJS will remove code that is - obviously unreachable (code that follows a =return=, =throw=, =break= or - =continue= statement and is not a function/variable declaration). Pass - this option to disable this optimization. - -- =-nc= or =--no-copyright= --- by default, =uglifyjs= will keep the initial - comment tokens in the generated code (assumed to be copyright information - etc.). If you pass this it will discard it. - -- =-o filename= or =--output filename= --- put the result in =filename=. If - this isn't given, the result goes to standard output (or see next one). - -- =--overwrite= --- if the code is read from a file (not from STDIN) and you - pass =--overwrite= then the output will be written in the same file. - -- =--ast= --- pass this if you want to get the Abstract Syntax Tree instead - of JavaScript as output. Useful for debugging or learning more about the - internals. - -- =-v= or =--verbose= --- output some notes on STDERR (for now just how long - each operation takes). - -- =-d SYMBOL[=VALUE]= or =--define SYMBOL[=VALUE]= --- will replace - all instances of the specified symbol where used as an identifier - (except where symbol has properly declared by a var declaration or - use as function parameter or similar) with the specified value. This - argument may be specified multiple times to define multiple - symbols - if no value is specified the symbol will be replaced with - the value =true=, or you can specify a numeric value (such as - =1024=), a quoted string value (such as ="object"= or - ='https://github.com'=), or the name of another symbol or keyword - (such as =null= or =document=). - This allows you, for example, to assign meaningful names to key - constant values but discard the symbolic names in the uglified - version for brevity/efficiency, or when used wth care, allows - UglifyJS to operate as a form of *conditional compilation* - whereby defining appropriate values may, by dint of the constant - folding and dead code removal features above, remove entire - superfluous code blocks (e.g. completely remove instrumentation or - trace code for production use). - Where string values are being defined, the handling of quotes are - likely to be subject to the specifics of your command shell - environment, so you may need to experiment with quoting styles - depending on your platform, or you may find the option - =--define-from-module= more suitable for use. - -- =-define-from-module SOMEMODULE= --- will load the named module (as - per the NodeJS =require()= function) and iterate all the exported - properties of the module defining them as symbol names to be defined - (as if by the =--define= option) per the name of each property - (i.e. without the module name prefix) and given the value of the - property. This is a much easier way to handle and document groups of - symbols to be defined rather than a large number of =--define= - options. - -- =--unsafe= --- enable other additional optimizations that are known to be - unsafe in some contrived situations, but could still be generally useful. - For now only these: - - - foo.toString() ==> foo+"" - - new Array(x,...) ==> [x,...] - - new Array(x) ==> Array(x) - -- =--max-line-len= (default 32K characters) --- add a newline after around - 32K characters. I've seen both FF and Chrome croak when all the code was - on a single line of around 670K. Pass --max-line-len 0 to disable this - safety feature. - -- =--reserved-names= --- some libraries rely on certain names to be used, as - pointed out in issue #92 and #81, so this option allow you to exclude such - names from the mangler. For example, to keep names =require= and =$super= - intact you'd specify --reserved-names "require,$super". - -- =--inline-script= -- when you want to include the output literally in an - HTML =\n\n\n\n
        \n\n

        UglifyJS – a JavaScript parser/compressor/beautifier

        \n\n\n\n\n
        \n

        1 UglifyJS — a JavaScript parser/compressor/beautifier

        \n
        \n\n\n

        \nThis package implements a general-purpose JavaScript\nparser/compressor/beautifier toolkit. It is developed on NodeJS, but it\nshould work on any JavaScript platform supporting the CommonJS module system\n(and if your platform of choice doesn't support CommonJS, you can easily\nimplement it, or discard the exports.* lines from UglifyJS sources).\n

        \n

        \nThe tokenizer/parser generates an abstract syntax tree from JS code. You\ncan then traverse the AST to learn more about the code, or do various\nmanipulations on it. This part is implemented in parse-js.js and it's a\nport to JavaScript of the excellent parse-js Common Lisp library from Marijn Haverbeke.\n

        \n

        \n( See cl-uglify-js if you're looking for the Common Lisp version of\nUglifyJS. )\n

        \n

        \nThe second part of this package, implemented in process.js, inspects and\nmanipulates the AST generated by the parser to provide the following:\n

        \n
          \n
        • \nability to re-generate JavaScript code from the AST. Optionally\nindented—you can use this if you want to “beautify” a program that has\nbeen compressed, so that you can inspect the source. But you can also run\nour code generator to print out an AST without any whitespace, so you\nachieve compression as well.\n\n
        • \n
        • \nshorten variable names (usually to single characters). Our mangler will\nanalyze the code and generate proper variable names, depending on scope\nand usage, and is smart enough to deal with globals defined elsewhere, or\nwith eval() calls or with{} statements. In short, if eval() or\nwith{} are used in some scope, then all variables in that scope and any\nvariables in the parent scopes will remain unmangled, and any references\nto such variables remain unmangled as well.\n\n
        • \n
        • \nvarious small optimizations that may lead to faster code but certainly\nlead to smaller code. Where possible, we do the following:\n\n
            \n
          • \nfoo[\"bar\"] ==> foo.bar\n\n
          • \n
          • \nremove block brackets {}\n\n
          • \n
          • \njoin consecutive var declarations:\nvar a = 10; var b = 20; ==> var a=10,b=20;\n\n
          • \n
          • \nresolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the\nreplacement if the result occupies less bytes; for example 1/3 would\ntranslate to 0.333333333333, so in this case we don't replace it.\n\n
          • \n
          • \nconsecutive statements in blocks are merged into a sequence; in many\ncases, this leaves blocks with a single statement, so then we can remove\nthe block brackets.\n\n
          • \n
          • \nvarious optimizations for IF statements:\n\n
              \n
            • \nif (foo) bar(); else baz(); ==> foo?bar():baz();\n
            • \n
            • \nif (!foo) bar(); else baz(); ==> foo?baz():bar();\n
            • \n
            • \nif (foo) bar(); ==> foo&&bar();\n
            • \n
            • \nif (!foo) bar(); ==> foo||bar();\n
            • \n
            • \nif (foo) return bar(); else return baz(); ==> return foo?bar():baz();\n
            • \n
            • \nif (foo) return bar(); else something(); ==> {if(foo)return bar();something()}\n\n
            • \n
            \n
          • \n
          • \nremove some unreachable code and warn about it (code that follows a\nreturn, throw, break or continue statement, except\nfunction/variable declarations).\n\n
          • \n
          • \nact a limited version of a pre-processor (c.f. the pre-processor of\nC/C++) to allow you to safely replace selected global symbols with\nspecified values. When combined with the optimisations above this can\nmake UglifyJS operate slightly more like a compilation process, in\nthat when certain symbols are replaced by constant values, entire code\nblocks may be optimised away as unreachable.\n
          • \n
          \n
        • \n
        \n\n\n\n
        \n\n
        \n

        1.1 Unsafe transformations

        \n
        \n\n\n

        \nThe following transformations can in theory break code, although they're\nprobably safe in most practical cases. To enable them you need to pass the\n--unsafe flag.\n

        \n\n
        \n\n
        \n

        1.1.1 Calls involving the global Array constructor

        \n
        \n\n\n

        \nThe following transformations occur:\n

        \n\n\n\n
        new Array(1, 2, 3, 4)  => [1,2,3,4]\nArray(a, b, c)         => [a,b,c]\nnew Array(5)           => Array(5)\nnew Array(a)           => Array(a)\n
        \n\n\n\n

        \nThese are all safe if the Array name isn't redefined. JavaScript does allow\none to globally redefine Array (and pretty much everything, in fact) but I\npersonally don't see why would anyone do that.\n

        \n

        \nUglifyJS does handle the case where Array is redefined locally, or even\nglobally but with a function or var declaration. Therefore, in the\nfollowing cases UglifyJS doesn't touch calls or instantiations of Array:\n

        \n\n\n\n
        // case 1.  globally declared variable\n  var Array;\n  new Array(1, 2, 3);\n  Array(a, b);\n\n  // or (can be declared later)\n  new Array(1, 2, 3);\n  var Array;\n\n  // or (can be a function)\n  new Array(1, 2, 3);\n  function Array() { ... }\n\n// case 2.  declared in a function\n  (function(){\n    a = new Array(1, 2, 3);\n    b = Array(5, 6);\n    var Array;\n  })();\n\n  // or\n  (function(Array){\n    return Array(5, 6, 7);\n  })();\n\n  // or\n  (function(){\n    return new Array(1, 2, 3, 4);\n    function Array() { ... }\n  })();\n\n  // etc.\n
        \n\n\n\n
        \n\n
        \n\n
        \n

        1.1.2 obj.toString() ==> obj+“”

        \n
        \n\n\n
        \n
        \n\n
        \n\n
        \n

        1.2 Install (NPM)

        \n
        \n\n\n

        \nUglifyJS is now available through NPM — npm install uglify-js should do\nthe job.\n

        \n
        \n\n
        \n\n
        \n

        1.3 Install latest code from GitHub

        \n
        \n\n\n\n\n\n
        ## clone the repository\nmkdir -p /where/you/wanna/put/it\ncd /where/you/wanna/put/it\ngit clone git://github.com/mishoo/UglifyJS.git\n\n## make the module available to Node\nmkdir -p ~/.node_libraries/\ncd ~/.node_libraries/\nln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js\n\n## and if you want the CLI script too:\nmkdir -p ~/bin\ncd ~/bin\nln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs\n  # (then add ~/bin to your $PATH if it's not there already)\n
        \n\n\n\n
        \n\n
        \n\n
        \n

        1.4 Usage

        \n
        \n\n\n

        \nThere is a command-line tool that exposes the functionality of this library\nfor your shell-scripting needs:\n

        \n\n\n\n
        uglifyjs [ options... ] [ filename ]\n
        \n\n\n\n

        \nfilename should be the last argument and should name the file from which\nto read the JavaScript code. If you don't specify it, it will read code\nfrom STDIN.\n

        \n

        \nSupported options:\n

        \n
          \n
        • \n-b or --beautify — output indented code; when passed, additional\noptions control the beautifier:\n\n
            \n
          • \n-i N or --indent N — indentation level (number of spaces)\n\n
          • \n
          • \n-q or --quote-keys — quote keys in literal objects (by default,\nonly keys that cannot be identifier names will be quotes).\n\n
          • \n
          \n
        • \n
        • \n--ascii — pass this argument to encode non-ASCII characters as\n\\uXXXX sequences. By default UglifyJS won't bother to do it and will\noutput Unicode characters instead. (the output is always encoded in UTF8,\nbut if you pass this option you'll only get ASCII).\n\n
        • \n
        • \n-nm or --no-mangle — don't mangle variable names\n\n
        • \n
        • \n-ns or --no-squeeze — don't call ast_squeeze() (which does various\noptimizations that result in smaller, less readable code).\n\n
        • \n
        • \n-mt or --mangle-toplevel — mangle names in the toplevel scope too\n(by default we don't do this).\n\n
        • \n
        • \n--no-seqs — when ast_squeeze() is called (thus, unless you pass\n--no-squeeze) it will reduce consecutive statements in blocks into a\nsequence. For example, \"a = 10; b = 20; foo();\" will be written as\n\"a=10,b=20,foo();\". In various occasions, this allows us to discard the\nblock brackets (since the block becomes a single statement). This is ON\nby default because it seems safe and saves a few hundred bytes on some\nlibs that I tested it on, but pass --no-seqs to disable it.\n\n
        • \n
        • \n--no-dead-code — by default, UglifyJS will remove code that is\nobviously unreachable (code that follows a return, throw, break or\ncontinue statement and is not a function/variable declaration). Pass\nthis option to disable this optimization.\n\n
        • \n
        • \n-nc or --no-copyright — by default, uglifyjs will keep the initial\ncomment tokens in the generated code (assumed to be copyright information\netc.). If you pass this it will discard it.\n\n
        • \n
        • \n-o filename or --output filename — put the result in filename. If\nthis isn't given, the result goes to standard output (or see next one).\n\n
        • \n
        • \n--overwrite — if the code is read from a file (not from STDIN) and you\npass --overwrite then the output will be written in the same file.\n\n
        • \n
        • \n--ast — pass this if you want to get the Abstract Syntax Tree instead\nof JavaScript as output. Useful for debugging or learning more about the\ninternals.\n\n
        • \n
        • \n-v or --verbose — output some notes on STDERR (for now just how long\neach operation takes).\n\n
        • \n
        • \n-d SYMBOL[=VALUE] or --define SYMBOL[=VALUE] — will replace\nall instances of the specified symbol where used as an identifier\n(except where symbol has properly declared by a var declaration or\nuse as function parameter or similar) with the specified value. This\nargument may be specified multiple times to define multiple\nsymbols - if no value is specified the symbol will be replaced with\nthe value true, or you can specify a numeric value (such as\n1024), a quoted string value (such as =\"object\"= or\n='https://github.com'), or the name of another symbol or keyword (such as =null or document). \nThis allows you, for example, to assign meaningful names to key\nconstant values but discard the symbolic names in the uglified\nversion for brevity/efficiency, or when used wth care, allows\nUglifyJS to operate as a form of conditional compilation\nwhereby defining appropriate values may, by dint of the constant\nfolding and dead code removal features above, remove entire\nsuperfluous code blocks (e.g. completely remove instrumentation or\ntrace code for production use).\nWhere string values are being defined, the handling of quotes are\nlikely to be subject to the specifics of your command shell\nenvironment, so you may need to experiment with quoting styles\ndepending on your platform, or you may find the option\n--define-from-module more suitable for use.\n\n
        • \n
        • \n-define-from-module SOMEMODULE — will load the named module (as\nper the NodeJS require() function) and iterate all the exported\nproperties of the module defining them as symbol names to be defined\n(as if by the --define option) per the name of each property\n(i.e. without the module name prefix) and given the value of the\nproperty. This is a much easier way to handle and document groups of\nsymbols to be defined rather than a large number of --define\noptions.\n\n
        • \n
        • \n--unsafe — enable other additional optimizations that are known to be\nunsafe in some contrived situations, but could still be generally useful.\nFor now only these:\n\n
            \n
          • \nfoo.toString() ==> foo+\"\"\n
          • \n
          • \nnew Array(x,…) ==> [x,…]\n
          • \n
          • \nnew Array(x) ==> Array(x)\n\n
          • \n
          \n
        • \n
        • \n--max-line-len (default 32K characters) — add a newline after around\n32K characters. I've seen both FF and Chrome croak when all the code was\non a single line of around 670K. Pass –max-line-len 0 to disable this\nsafety feature.\n\n
        • \n
        • \n--reserved-names — some libraries rely on certain names to be used, as\npointed out in issue #92 and #81, so this option allow you to exclude such\nnames from the mangler. For example, to keep names require and $super\nintact you'd specify –reserved-names \"require,$super\".\n\n
        • \n
        • \n--inline-script – when you want to include the output literally in an\nHTML <script> tag you can use this option to prevent </script from\nshowing up in the output.\n\n
        • \n
        • \n--lift-vars – when you pass this, UglifyJS will apply the following\ntransformations (see the notes in API, ast_lift_variables):\n\n
            \n
          • \nput all var declarations at the start of the scope\n
          • \n
          • \nmake sure a variable is declared only once\n
          • \n
          • \ndiscard unused function arguments\n
          • \n
          • \ndiscard unused inner (named) functions\n
          • \n
          • \nfinally, try to merge assignments into that one var declaration, if\npossible.\n
          • \n
          \n
        • \n
        \n\n\n\n
        \n\n
        \n

        1.4.1 API

        \n
        \n\n\n

        \nTo use the library from JavaScript, you'd do the following (example for\nNodeJS):\n

        \n\n\n\n
        var jsp = require(\"uglify-js\").parser;\nvar pro = require(\"uglify-js\").uglify;\n\nvar orig_code = \"... JS code here\";\nvar ast = jsp.parse(orig_code); // parse code and get the initial AST\nast = pro.ast_mangle(ast); // get a new AST with mangled names\nast = pro.ast_squeeze(ast); // get an AST with compression optimizations\nvar final_code = pro.gen_code(ast); // compressed code here\n
        \n\n\n\n

        \nThe above performs the full compression that is possible right now. As you\ncan see, there are a sequence of steps which you can apply. For example if\nyou want compressed output but for some reason you don't want to mangle\nvariable names, you would simply skip the line that calls\npro.ast_mangle(ast).\n

        \n

        \nSome of these functions take optional arguments. Here's a description:\n

        \n
          \n
        • \njsp.parse(code, strict_semicolons) – parses JS code and returns an AST.\nstrict_semicolons is optional and defaults to false. If you pass\ntrue then the parser will throw an error when it expects a semicolon and\nit doesn't find it. For most JS code you don't want that, but it's useful\nif you want to strictly sanitize your code.\n\n
        • \n
        • \npro.ast_lift_variables(ast) – merge and move var declarations to the\nscop of the scope; discard unused function arguments or variables; discard\nunused (named) inner functions. It also tries to merge assignments\nfollowing the var declaration into it.\n\n

          \nIf your code is very hand-optimized concerning var declarations, this\nlifting variable declarations might actually increase size. For me it\nhelps out. On jQuery it adds 865 bytes (243 after gzip). YMMV. Also\nnote that (since it's not enabled by default) this operation isn't yet\nheavily tested (please report if you find issues!).\n

          \n

          \nNote that although it might increase the image size (on jQuery it gains\n865 bytes, 243 after gzip) it's technically more correct: in certain\nsituations, dead code removal might drop variable declarations, which\nwould not happen if the variables are lifted in advance.\n

          \n

          \nHere's an example of what it does:\n

          \n
        • \n
        \n\n\n\n\n
        function f(a, b, c, d, e) {\n    var q;\n    var w;\n    w = 10;\n    q = 20;\n    for (var i = 1; i < 10; ++i) {\n        var boo = foo(a);\n    }\n    for (var i = 0; i < 1; ++i) {\n        var boo = bar(c);\n    }\n    function foo(){ ... }\n    function bar(){ ... }\n    function baz(){ ... }\n}\n\n// transforms into ==>\n\nfunction f(a, b, c) {\n    var i, boo, w = 10, q = 20;\n    for (i = 1; i < 10; ++i) {\n        boo = foo(a);\n    }\n    for (i = 0; i < 1; ++i) {\n        boo = bar(c);\n    }\n    function foo() { ... }\n    function bar() { ... }\n}\n
        \n\n\n\n
          \n
        • \npro.ast_mangle(ast, options) – generates a new AST containing mangled\n(compressed) variable and function names. It supports the following\noptions:\n\n
            \n
          • \ntoplevel – mangle toplevel names (by default we don't touch them).\n
          • \n
          • \nexcept – an array of names to exclude from compression.\n
          • \n
          • \ndefines – an object with properties named after symbols to\nreplace (see the --define option for the script) and the values\nrepresenting the AST replacement value.\n\n
          • \n
          \n
        • \n
        • \npro.ast_squeeze(ast, options) – employs further optimizations designed\nto reduce the size of the code that gen_code would generate from the\nAST. Returns a new AST. options can be a hash; the supported options\nare:\n\n
            \n
          • \nmake_seqs (default true) which will cause consecutive statements in a\nblock to be merged using the \"sequence\" (comma) operator\n\n
          • \n
          • \ndead_code (default true) which will remove unreachable code.\n\n
          • \n
          \n
        • \n
        • \npro.gen_code(ast, options) – generates JS code from the AST. By\ndefault it's minified, but using the options argument you can get nicely\nformatted output. options is, well, optional :-) and if you pass it it\nmust be an object and supports the following properties (below you can see\nthe default values):\n\n
            \n
          • \nbeautify: false – pass true if you want indented output\n
          • \n
          • \nindent_start: 0 (only applies when beautify is true) – initial\nindentation in spaces\n
          • \n
          • \nindent_level: 4 (only applies when beautify is true) --\nindentation level, in spaces (pass an even number)\n
          • \n
          • \nquote_keys: false – if you pass true it will quote all keys in\nliteral objects\n
          • \n
          • \nspace_colon: false (only applies when beautify is true) – wether\nto put a space before the colon in object literals\n
          • \n
          • \nascii_only: false – pass true if you want to encode non-ASCII\ncharacters as \\uXXXX.\n
          • \n
          • \ninline_script: false – pass true to escape occurrences of\n</script in strings\n
          • \n
          \n
        • \n
        \n\n\n
        \n\n
        \n\n
        \n

        1.4.2 Beautifier shortcoming – no more comments

        \n
        \n\n\n

        \nThe beautifier can be used as a general purpose indentation tool. It's\nuseful when you want to make a minified file readable. One limitation,\nthough, is that it discards all comments, so you don't really want to use it\nto reformat your code, unless you don't have, or don't care about, comments.\n

        \n

        \nIn fact it's not the beautifier who discards comments — they are dumped at\nthe parsing stage, when we build the initial AST. Comments don't really\nmake sense in the AST, and while we could add nodes for them, it would be\ninconvenient because we'd have to add special rules to ignore them at all\nthe processing stages.\n

        \n
        \n\n
        \n\n
        \n

        1.4.3 Use as a code pre-processor

        \n
        \n\n\n

        \nThe --define option can be used, particularly when combined with the\nconstant folding logic, as a form of pre-processor to enable or remove\nparticular constructions, such as might be used for instrumenting\ndevelopment code, or to produce variations aimed at a specific\nplatform.\n

        \n

        \nThe code below illustrates the way this can be done, and how the\nsymbol replacement is performed.\n

        \n\n\n\n
        CLAUSE1: if (typeof DEVMODE === 'undefined') {\n    DEVMODE = true;\n}\n\nCLAUSE2: function init() {\n    if (DEVMODE) {\n        console.log(\"init() called\");\n    }\n    ....\n    DEVMODE &amp;&amp; console.log(\"init() complete\");\n}\n\nCLAUSE3: function reportDeviceStatus(device) {\n    var DEVMODE = device.mode, DEVNAME = device.name;\n    if (DEVMODE === 'open') {\n        ....\n    }\n}\n
        \n\n\n\n

        \nWhen the above code is normally executed, the undeclared global\nvariable DEVMODE will be assigned the value true (see CLAUSE1)\nand so the init() function (CLAUSE2) will write messages to the\nconsole log when executed, but in CLAUSE3 a locally declared\nvariable will mask access to the DEVMODE global symbol.\n

        \n

        \nIf the above code is processed by UglifyJS with an argument of\n--define DEVMODE=false then UglifyJS will replace DEVMODE with the\nboolean constant value false within CLAUSE1 and CLAUSE2, but it\nwill leave CLAUSE3 as it stands because there DEVMODE resolves to\na validly declared variable.\n

        \n

        \nAnd more so, the constant-folding features of UglifyJS will recognise\nthat the if condition of CLAUSE1 is thus always false, and so will\nremove the test and body of CLAUSE1 altogether (including the\notherwise slightly problematical statement false = true; which it\nwill have formed by replacing DEVMODE in the body). Similarly,\nwithin CLAUSE2 both calls to console.log() will be removed\naltogether.\n

        \n

        \nIn this way you can mimic, to a limited degree, the functionality of\nthe C/C++ pre-processor to enable or completely remove blocks\ndepending on how certain symbols are defined - perhaps using UglifyJS\nto generate different versions of source aimed at different\nenvironments\n

        \n

        \nIt is recommmended (but not made mandatory) that symbols designed for\nthis purpose are given names consisting of UPPER_CASE_LETTERS to\ndistinguish them from other (normal) symbols and avoid the sort of\nclash that CLAUSE3 above illustrates.\n

        \n
        \n
        \n\n
        \n\n
        \n

        1.5 Compression – how good is it?

        \n
        \n\n\n

        \nHere are updated statistics. (I also updated my Google Closure and YUI\ninstallations).\n

        \n

        \nWe're still a lot better than YUI in terms of compression, though slightly\nslower. We're still a lot faster than Closure, and compression after gzip\nis comparable.\n

        \n\n\n\n\n\n\n\n\n\n\n\n\n\n
        FileUglifyJSUglifyJS+gzipClosureClosure+gzipYUIYUI+gzip
        jquery-1.6.2.js91001 (0:01.59)3189690678 (0:07.40)31979101527 (0:01.82)34646
        paper.js142023 (0:01.65)43334134301 (0:07.42)42495173383 (0:01.58)48785
        prototype.js88544 (0:01.09)2668086955 (0:06.97)2632692130 (0:00.79)28624
        thelib-full.js (DynarchLIB)251939 (0:02.55)72535249911 (0:09.05)72696258869 (0:01.94)76584
        \n\n\n
        \n\n
        \n\n
        \n

        1.6 Bugs?

        \n
        \n\n\n

        \nUnfortunately, for the time being there is no automated test suite. But I\nran the compressor manually on non-trivial code, and then I tested that the\ngenerated code works as expected. A few hundred times.\n

        \n

        \nDynarchLIB was started in times when there was no good JS minifier.\nTherefore I was quite religious about trying to write short code manually,\nand as such DL contains a lot of syntactic hacks1 such as “foo == bar ? a\n= 10 : b = 20”, though the more readable version would clearly be to use\n“if/else”.\n

        \n

        \nSince the parser/compressor runs fine on DL and jQuery, I'm quite confident\nthat it's solid enough for production use. If you can identify any bugs,\nI'd love to hear about them (use the Google Group or email me directly).\n

        \n
        \n\n
        \n\n
        \n

        1.7 Links

        \n
        \n\n\n\n\n\n
        \n\n
        \n\n
        \n

        1.8 License

        \n
        \n\n\n

        \nUglifyJS is released under the BSD license:\n

        \n\n\n\n
        Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>\nBased on parse-js (http://marijn.haverbeke.nl/parse-js/).\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above\n      copyright notice, this list of conditions and the following\n      disclaimer.\n\n    * Redistributions in binary form must reproduce the above\n      copyright notice, this list of conditions and the following\n      disclaimer in the documentation and/or other materials\n      provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\nEXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\nOR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\nTORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\nTHE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGE.\n
        \n\n\n\n\n
        \n
        \n
        \n
        \n

        Footnotes:

        \n
        \n

        1 I even reported a few bugs and suggested some fixes in the original\nparse-js library, and Marijn pushed fixes literally in minutes.\n

        \n
        \n
        \n
        \n

        Author: Mihai Bazon\n

        \n

        Date: 2011-08-29 19:17:55 EEST

        \n

        HTML generated by org-mode 7.01trans in emacs 23

        \n
        \n
        \n\n\n", - "readmeFilename": "README.html", - "bugs": { - "url": "https://github.com/mishoo/UglifyJS/issues" - }, - "_id": "uglify-js@1.1.1", - "_from": "uglify-js@~1.1.1" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/package.json~ b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/package.json~ deleted file mode 100644 index 8ca4d35dd..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/package.json~ +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name" : "uglify-js", - - "description" : "JavaScript parser and compressor/beautifier toolkit", - - "author" : { - "name" : "Mihai Bazon", - "email" : "mihai.bazon@gmail.com", - "url" : "http://mihai.bazon.net/blog" - }, - - "version" : "1.1.0", - - "main" : "./uglify-js.js", - - "bin" : { - "uglifyjs" : "./bin/uglifyjs" - }, - - "repository": { - "type": "git", - "url": "git@github.com:mishoo/UglifyJS.git" - } -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/beautify.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/beautify.js deleted file mode 100755 index f19369e3a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/beautify.js +++ /dev/null @@ -1,28 +0,0 @@ -#! /usr/bin/env node - -global.sys = require("sys"); -var fs = require("fs"); - -var jsp = require("../lib/parse-js"); -var pro = require("../lib/process"); - -var filename = process.argv[2]; -fs.readFile(filename, "utf8", function(err, text){ - try { - var ast = time_it("parse", function(){ return jsp.parse(text); }); - ast = time_it("mangle", function(){ return pro.ast_mangle(ast); }); - ast = time_it("squeeze", function(){ return pro.ast_squeeze(ast); }); - var gen = time_it("generate", function(){ return pro.gen_code(ast, false); }); - sys.puts(gen); - } catch(ex) { - sys.debug(ex.stack); - sys.debug(sys.inspect(ex)); - sys.debug(JSON.stringify(ex)); - } -}); - -function time_it(name, cont) { - var t1 = new Date().getTime(); - try { return cont(); } - finally { sys.debug("// " + name + ": " + ((new Date().getTime() - t1) / 1000).toFixed(3) + " sec."); } -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/testparser.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/testparser.js deleted file mode 100755 index 02c19a9c9..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/testparser.js +++ /dev/null @@ -1,403 +0,0 @@ -#! /usr/bin/env node - -var parseJS = require("../lib/parse-js"); -var sys = require("sys"); - -// write debug in a very straightforward manner -var debug = function(){ - sys.log(Array.prototype.slice.call(arguments).join(', ')); -}; - -ParserTestSuite(function(i, input, desc){ - try { - parseJS.parse(input); - debug("ok " + i + ": " + desc); - } catch(e){ - debug("FAIL " + i + " " + desc + " (" + e + ")"); - } -}); - -function ParserTestSuite(callback){ - var inps = [ - ["var abc;", "Regular variable statement w/o assignment"], - ["var abc = 5;", "Regular variable statement with assignment"], - ["/* */;", "Multiline comment"], - ['/** **/;', 'Double star multiline comment'], - ["var f = function(){;};", "Function expression in var assignment"], - ['hi; // moo\n;', 'single line comment'], - ['var varwithfunction;', 'Dont match keywords as substrings'], // difference between `var withsomevar` and `"str"` (local search and lits) - ['a + b;', 'addition'], - ["'a';", 'single string literal'], - ["'a\\n';", 'single string literal with escaped return'], - ['"a";', 'double string literal'], - ['"a\\n";', 'double string literal with escaped return'], - ['"var";', 'string is a keyword'], - ['"variable";', 'string starts with a keyword'], - ['"somevariable";', 'string contains a keyword'], - ['"somevar";', 'string ends with a keyword'], - ['500;', 'int literal'], - ['500.;', 'float literal w/o decimals'], - ['500.432;', 'float literal with decimals'], - ['.432432;', 'float literal w/o int'], - ['(a,b,c);', 'parens and comma'], - ['[1,2,abc];', 'array literal'], - ['var o = {a:1};', 'object literal unquoted key'], - ['var o = {"b":2};', 'object literal quoted key'], // opening curly may not be at the start of a statement... - ['var o = {c:c};', 'object literal keyname is identifier'], - ['var o = {a:1,"b":2,c:c};', 'object literal combinations'], - ['var x;\nvar y;', 'two lines'], - ['var x;\nfunction n(){; }', 'function def'], - ['var x;\nfunction n(abc){; }', 'function def with arg'], - ['var x;\nfunction n(abc, def){ ;}', 'function def with args'], - ['function n(){ "hello"; }', 'function def with body'], - ['/a/;', 'regex literal'], - ['/a/b;', 'regex literal with flag'], - ['/a/ / /b/;', 'regex div regex'], - ['a/b/c;', 'triple division looks like regex'], - ['+function(){/regex/;};', 'regex at start of function body'], - // http://code.google.com/p/es-lab/source/browse/trunk/tests/parser/parsertests.js?r=86 - // http://code.google.com/p/es-lab/source/browse/trunk/tests/parser/parsertests.js?r=430 - - // first tests for the lexer, should also parse as program (when you append a semi) - - // comments - ['//foo!@#^&$1234\nbar;', 'single line comment'], - ['/* abcd!@#@$* { } && null*/;', 'single line multi line comment'], - ['/*foo\nbar*/;','multi line comment'], - ['/*x*x*/;','multi line comment with *'], - ['/**/;','empty comment'], - // identifiers - ["x;",'1 identifier'], - ["_x;",'2 identifier'], - ["xyz;",'3 identifier'], - ["$x;",'4 identifier'], - ["x$;",'5 identifier'], - ["_;",'6 identifier'], - ["x5;",'7 identifier'], - ["x_y;",'8 identifier'], - ["x+5;",'9 identifier'], - ["xyz123;",'10 identifier'], - ["x1y1z1;",'11 identifier'], - ["foo\\u00D8bar;",'12 identifier unicode escape'], - //["foo�bar;",'13 identifier unicode embedded (might fail)'], - // numbers - ["5;", '1 number'], - ["5.5;", '2 number'], - ["0;", '3 number'], - ["0.0;", '4 number'], - ["0.001;", '5 number'], - ["1.e2;", '6 number'], - ["1.e-2;", '7 number'], - ["1.E2;", '8 number'], - ["1.E-2;", '9 number'], - [".5;", '10 number'], - [".5e3;", '11 number'], - [".5e-3;", '12 number'], - ["0.5e3;", '13 number'], - ["55;", '14 number'], - ["123;", '15 number'], - ["55.55;", '16 number'], - ["55.55e10;", '17 number'], - ["123.456;", '18 number'], - ["1+e;", '20 number'], - ["0x01;", '22 number'], - ["0XCAFE;", '23 number'], - ["0x12345678;", '24 number'], - ["0x1234ABCD;", '25 number'], - ["0x0001;", '26 number'], - // strings - ["\"foo\";", '1 string'], - ["\'foo\';", '2 string'], - ["\"x\";", '3 string'], - ["\'\';", '4 string'], - ["\"foo\\tbar\";", '5 string'], - ["\"!@#$%^&*()_+{}[]\";", '6 string'], - ["\"/*test*/\";", '7 string'], - ["\"//test\";", '8 string'], - ["\"\\\\\";", '9 string'], - ["\"\\u0001\";", '10 string'], - ["\"\\uFEFF\";", '11 string'], - ["\"\\u10002\";", '12 string'], - ["\"\\x55\";", '13 string'], - ["\"\\x55a\";", '14 string'], - ["\"a\\\\nb\";", '15 string'], - ['";"', '16 string: semi in a string'], - ['"a\\\nb";', '17 string: line terminator escape'], - // literals - ["null;", "null"], - ["true;", "true"], - ["false;", "false"], - // regex - ["/a/;", "1 regex"], - ["/abc/;", "2 regex"], - ["/abc[a-z]*def/g;", "3 regex"], - ["/\\b/;", "4 regex"], - ["/[a-zA-Z]/;", "5 regex"], - - // program tests (for as far as they havent been covered above) - - // regexp - ["/foo(.*)/g;", "another regexp"], - // arrays - ["[];", "1 array"], - ["[ ];", "2 array"], - ["[1];", "3 array"], - ["[1,2];", "4 array"], - ["[1,2,,];", "5 array"], - ["[1,2,3];", "6 array"], - ["[1,2,3,,,];", "7 array"], - // objects - ["{};", "1 object"], - ["({x:5});", "2 object"], - ["({x:5,y:6});", "3 object"], - ["({x:5,});", "4 object"], - ["({if:5});", "5 object"], - ["({ get x() {42;} });", "6 object"], - ["({ set y(a) {1;} });", "7 object"], - // member expression - ["o.m;", "1 member expression"], - ["o['m'];", "2 member expression"], - ["o['n']['m'];", "3 member expression"], - ["o.n.m;", "4 member expression"], - ["o.if;", "5 member expression"], - // call and invoke expressions - ["f();", "1 call/invoke expression"], - ["f(x);", "2 call/invoke expression"], - ["f(x,y);", "3 call/invoke expression"], - ["o.m();", "4 call/invoke expression"], - ["o['m'];", "5 call/invoke expression"], - ["o.m(x);", "6 call/invoke expression"], - ["o['m'](x);", "7 call/invoke expression"], - ["o.m(x,y);", "8 call/invoke expression"], - ["o['m'](x,y);", "9 call/invoke expression"], - ["f(x)(y);", "10 call/invoke expression"], - ["f().x;", "11 call/invoke expression"], - - // eval - ["eval('x');", "1 eval"], - ["(eval)('x');", "2 eval"], - ["(1,eval)('x');", "3 eval"], - ["eval(x,y);", "4 eval"], - // new expression - ["new f();", "1 new expression"], - ["new o;", "2 new expression"], - ["new o.m;", "3 new expression"], - ["new o.m(x);", "4 new expression"], - ["new o.m(x,y);", "5 new expression"], - // prefix/postfix - ["++x;", "1 pre/postfix"], - ["x++;", "2 pre/postfix"], - ["--x;", "3 pre/postfix"], - ["x--;", "4 pre/postfix"], - ["x ++;", "5 pre/postfix"], - ["x /* comment */ ++;", "6 pre/postfix"], - ["++ /* comment */ x;", "7 pre/postfix"], - // unary operators - ["delete x;", "1 unary operator"], - ["void x;", "2 unary operator"], - ["+ x;", "3 unary operator"], - ["-x;", "4 unary operator"], - ["~x;", "5 unary operator"], - ["!x;", "6 unary operator"], - // meh - ["new Date++;", "new date ++"], - ["+x++;", " + x ++"], - // expression expressions - ["1 * 2;", "1 expression expressions"], - ["1 / 2;", "2 expression expressions"], - ["1 % 2;", "3 expression expressions"], - ["1 + 2;", "4 expression expressions"], - ["1 - 2;", "5 expression expressions"], - ["1 << 2;", "6 expression expressions"], - ["1 >>> 2;", "7 expression expressions"], - ["1 >> 2;", "8 expression expressions"], - ["1 * 2 + 3;", "9 expression expressions"], - ["(1+2)*3;", "10 expression expressions"], - ["1*(2+3);", "11 expression expressions"], - ["xy;", "13 expression expressions"], - ["x<=y;", "14 expression expressions"], - ["x>=y;", "15 expression expressions"], - ["x instanceof y;", "16 expression expressions"], - ["x in y;", "17 expression expressions"], - ["x&y;", "18 expression expressions"], - ["x^y;", "19 expression expressions"], - ["x|y;", "20 expression expressions"], - ["x+y>>= y;", "1 assignment"], - ["x <<= y;", "2 assignment"], - ["x = y;", "3 assignment"], - ["x += y;", "4 assignment"], - ["x /= y;", "5 assignment"], - // comma - ["x, y;", "comma"], - // block - ["{};", "1 block"], - ["{x;};", "2 block"], - ["{x;y;};", "3 block"], - // vars - ["var x;", "1 var"], - ["var x,y;", "2 var"], - ["var x=1,y=2;", "3 var"], - ["var x,y=2;", "4 var"], - // empty - [";", "1 empty"], - ["\n;", "2 empty"], - // expression statement - ["x;", "1 expression statement"], - ["5;", "2 expression statement"], - ["1+2;", "3 expression statement"], - // if - ["if (c) x; else y;", "1 if statement"], - ["if (c) x;", "2 if statement"], - ["if (c) {} else {};", "3 if statement"], - ["if (c1) if (c2) s1; else s2;", "4 if statement"], - // while - ["do s; while (e);", "1 while statement"], - ["do { s; } while (e);", "2 while statement"], - ["while (e) s;", "3 while statement"], - ["while (e) { s; };", "4 while statement"], - // for - ["for (;;) ;", "1 for statement"], - ["for (;c;x++) x;", "2 for statement"], - ["for (i;i> 1; -var c = 8 >>> 1; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue34.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue34.js deleted file mode 100644 index 022f7a31b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue34.js +++ /dev/null @@ -1,3 +0,0 @@ -var a = {}; -a["this"] = 1; -a["that"] = 2; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue4.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue4.js deleted file mode 100644 index 0b7610379..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue4.js +++ /dev/null @@ -1,3 +0,0 @@ -var a = 2e3; -var b = 2e-3; -var c = 2e-5; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue48.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue48.js deleted file mode 100644 index 031e85b39..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue48.js +++ /dev/null @@ -1 +0,0 @@ -var s, i; s = ''; i = 0; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue50.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue50.js deleted file mode 100644 index 060f9df82..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue50.js +++ /dev/null @@ -1,9 +0,0 @@ -function bar(a) { - try { - foo(); - } catch(e) { - alert("Exception caught (foo not defined)"); - } - alert(a); // 10 in FF, "[object Error]" in IE -} -bar(10); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue53.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue53.js deleted file mode 100644 index 4f8b32f11..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue53.js +++ /dev/null @@ -1 +0,0 @@ -x = (y, z) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue54.1.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue54.1.js deleted file mode 100644 index 967052e85..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue54.1.js +++ /dev/null @@ -1,3 +0,0 @@ -foo.toString(); -a.toString(16); -b.toString.call(c); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue68.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue68.js deleted file mode 100644 index 14054d01e..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue68.js +++ /dev/null @@ -1,5 +0,0 @@ -function f() { - if (a) return; - g(); - function g(){} -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue69.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue69.js deleted file mode 100644 index d25ecd671..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue69.js +++ /dev/null @@ -1 +0,0 @@ -[(a,b)] diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue9.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue9.js deleted file mode 100644 index 61588614b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/issue9.js +++ /dev/null @@ -1,4 +0,0 @@ -var a = { - a: 1, - b: 2, // <-- trailing comma -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/mangle.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/mangle.js deleted file mode 100644 index c271a26dc..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/mangle.js +++ /dev/null @@ -1,5 +0,0 @@ -(function() { - var x = function fun(a, fun, b) { - return fun; - }; -}()); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/null_string.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/null_string.js deleted file mode 100644 index a675b1c5c..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/null_string.js +++ /dev/null @@ -1 +0,0 @@ -var nullString = "\0" \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/strict-equals.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/strict-equals.js deleted file mode 100644 index b631f4c35..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/strict-equals.js +++ /dev/null @@ -1,3 +0,0 @@ -typeof a === 'string' -b + "" !== c + "" -d < e === f < g diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/var.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/var.js deleted file mode 100644 index 609a35d2a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/var.js +++ /dev/null @@ -1,3 +0,0 @@ -// var declarations after each other should be combined -var a = 1; -var b = 2; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/whitespace.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/whitespace.js deleted file mode 100644 index 6a15c464f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/whitespace.js +++ /dev/null @@ -1,21 +0,0 @@ -function id(a) { - // Form-Feed - // Vertical Tab - // No-Break Space - ᠎// Mongolian Vowel Separator -  // En quad -  // Em quad -  // En space -  // Em space -  // Three-Per-Em Space -  // Four-Per-Em Space -  // Six-Per-Em Space -  // Figure Space -  // Punctuation Space -  // Thin Space -  // Hair Space -  // Narrow No-Break Space -  // Medium Mathematical Space -  // Ideographic Space - return a; -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/with.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/with.js deleted file mode 100644 index de266ed54..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/compress/test/with.js +++ /dev/null @@ -1,2 +0,0 @@ -with({}) { -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/scripts.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/scripts.js deleted file mode 100644 index 9fdd96c6d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/test/unit/scripts.js +++ /dev/null @@ -1,55 +0,0 @@ -var fs = require('fs'), - uglify = require('uglify-js'), - jsp = uglify.parser, - nodeunit = require('nodeunit'), - path = require('path'), - pro = uglify.uglify; - -var Script = process.binding('evals').Script; - -var scriptsPath = __dirname; - -function compress(code) { - var ast = jsp.parse(code); - ast = pro.ast_mangle(ast); - ast = pro.ast_squeeze(ast, { no_warnings: true }); - ast = pro.ast_squeeze_more(ast); - return pro.gen_code(ast); -}; - -var testDir = path.join(scriptsPath, "compress", "test"); -var expectedDir = path.join(scriptsPath, "compress", "expected"); - -function getTester(script) { - return function(test) { - var testPath = path.join(testDir, script); - var expectedPath = path.join(expectedDir, script); - var content = fs.readFileSync(testPath, 'utf-8'); - var outputCompress = compress(content); - - // Check if the noncompressdata is larger or same size as the compressed data - test.ok(content.length >= outputCompress.length); - - // Check that a recompress gives the same result - var outputReCompress = compress(content); - test.equal(outputCompress, outputReCompress); - - // Check if the compressed output is what is expected - var expected = fs.readFileSync(expectedPath, 'utf-8'); - test.equal(outputCompress, expected.replace(/(\r?\n)+$/, "")); - - test.done(); - }; -}; - -var tests = {}; - -var scripts = fs.readdirSync(testDir); -for (var i in scripts) { - var script = scripts[i]; - if (/\.js$/.test(script)) { - tests[script] = getTester(script); - } -} - -module.exports = nodeunit.testCase(tests); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/tmp/hoist.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/tmp/hoist.js deleted file mode 100644 index 4bf2b94de..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/tmp/hoist.js +++ /dev/null @@ -1,33 +0,0 @@ -function foo(arg1, arg2, arg3, arg4, arg5, arg6) { - var a = 5; - { - var d = 10, mak = 20, buz = 30; - var q = buz * 2; - } - if (moo) { - var a, b, c; - } - for (var arg1 = 0, d = 20; arg1 < 10; ++arg1) - console.log(arg3); - for (var i in mak) {} - for (j in d) {} - var d; - - function test() { - - }; - - //test(); - - (function moo(first, second){ - console.log(first); - })(1); - - (function moo(first, second){ - console.log(moo()); - })(1); -} - - -var foo; -var bar; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/tmp/instrument.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/tmp/instrument.js deleted file mode 100644 index c6a9d798a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/tmp/instrument.js +++ /dev/null @@ -1,97 +0,0 @@ -// sample on how to use the parser and walker API to instrument some code - -var jsp = require("uglify-js").parser; -var pro = require("uglify-js").uglify; - -function instrument(code) { - var ast = jsp.parse(code, false, true); // true for the third arg specifies that we want - // to have start/end tokens embedded in the - // statements - var w = pro.ast_walker(); - - // we're gonna need this to push elements that we're currently looking at, to avoid - // endless recursion. - var analyzing = []; - function do_stat() { - var ret; - if (this[0].start && analyzing.indexOf(this) < 0) { - // without the `analyzing' hack, w.walk(this) would re-enter here leading - // to infinite recursion - analyzing.push(this); - ret = [ "splice", // XXX: "block" is safer - [ [ "stat", - [ "call", [ "name", "trace" ], - [ [ "string", this[0].toString() ], - [ "num", this[0].start.line ], - [ "num", this[0].start.col ], - [ "num", this[0].end.line ], - [ "num", this[0].end.col ]]]], - w.walk(this) ]]; - analyzing.pop(this); - } - return ret; - }; - var new_ast = w.with_walkers({ - "stat" : do_stat, - "label" : do_stat, - "break" : do_stat, - "continue" : do_stat, - "debugger" : do_stat, - "var" : do_stat, - "const" : do_stat, - "return" : do_stat, - "throw" : do_stat, - "try" : do_stat, - "defun" : do_stat, - "if" : do_stat, - "while" : do_stat, - "do" : do_stat, - "for" : do_stat, - "for-in" : do_stat, - "switch" : do_stat, - "with" : do_stat - }, function(){ - return w.walk(ast); - }); - return pro.gen_code(new_ast, { beautify: true }); -} - - - - -////// test code follows. - -var code = instrument(test.toString()); -console.log(code); - -function test() { - // simple stats - a = 5; - c += a + b; - "foo"; - - // var - var foo = 5; - const bar = 6, baz = 7; - - // switch block. note we can't track case lines the same way. - switch ("foo") { - case "foo": - return 1; - case "bar": - return 2; - } - - // for/for in - for (var i = 0; i < 5; ++i) { - console.log("Hello " + i); - } - for (var i in [ 1, 2, 3]) { - console.log(i); - } - - // note however that the following is broken. I guess we - // should add the block brackets in this case... - for (var i = 0; i < 5; ++i) - console.log("foo"); -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/tmp/instrument2.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/tmp/instrument2.js deleted file mode 100644 index 6aee5f3fe..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/tmp/instrument2.js +++ /dev/null @@ -1,138 +0,0 @@ -// sample on how to use the parser and walker API to instrument some code - -var jsp = require("uglify-js").parser; -var pro = require("uglify-js").uglify; - -function instrument(code) { - var ast = jsp.parse(code, false, true); // true for the third arg specifies that we want - // to have start/end tokens embedded in the - // statements - var w = pro.ast_walker(); - - function trace (line, comment) { - var code = pro.gen_code(line, { beautify: true }); - var data = line[0] - - var args = [] - if (!comment) comment = "" - if (typeof data === "object") { - code = code.split(/\n/).shift() - args = [ [ "string", data.toString() ], - [ "string", code ], - [ "num", data.start.line ], - [ "num", data.start.col ], - [ "num", data.end.line ], - [ "num", data.end.col ]] - } else { - args = [ [ "string", data ], - [ "string", code ]] - - } - return [ "call", [ "name", "trace" ], args ]; - } - - // we're gonna need this to push elements that we're currently looking at, to avoid - // endless recursion. - var analyzing = []; - function do_stat() { - var ret; - if (this[0].start && analyzing.indexOf(this) < 0) { - // without the `analyzing' hack, w.walk(this) would re-enter here leading - // to infinite recursion - analyzing.push(this); - ret = [ "splice", - [ [ "stat", trace(this) ], - w.walk(this) ]]; - analyzing.pop(this); - } - return ret; - } - - function do_cond(c, t, f) { - return [ this[0], w.walk(c), - ["seq", trace(t), w.walk(t) ], - ["seq", trace(f), w.walk(f) ]]; - } - - function do_binary(c, l, r) { - if (c !== "&&" && c !== "||") { - return [this[0], c, w.walk(l), w.walk(r)]; - } - return [ this[0], c, - ["seq", trace(l), w.walk(l) ], - ["seq", trace(r), w.walk(r) ]]; - } - - var new_ast = w.with_walkers({ - "stat" : do_stat, - "label" : do_stat, - "break" : do_stat, - "continue" : do_stat, - "debugger" : do_stat, - "var" : do_stat, - "const" : do_stat, - "return" : do_stat, - "throw" : do_stat, - "try" : do_stat, - "defun" : do_stat, - "if" : do_stat, - "while" : do_stat, - "do" : do_stat, - "for" : do_stat, - "for-in" : do_stat, - "switch" : do_stat, - "with" : do_stat, - "conditional" : do_cond, - "binary" : do_binary - }, function(){ - return w.walk(ast); - }); - return pro.gen_code(new_ast, { beautify: true }); -} - - -////// test code follows. - -var code = instrument(test.toString()); -console.log(code); - -function test() { - // simple stats - a = 5; - c += a + b; - "foo"; - - // var - var foo = 5; - const bar = 6, baz = 7; - - // switch block. note we can't track case lines the same way. - switch ("foo") { - case "foo": - return 1; - case "bar": - return 2; - } - - // for/for in - for (var i = 0; i < 5; ++i) { - console.log("Hello " + i); - } - for (var i in [ 1, 2, 3]) { - console.log(i); - } - - for (var i = 0; i < 5; ++i) - console.log("foo"); - - for (var i = 0; i < 5; ++i) { - console.log("foo"); - } - - var k = plurp() ? 1 : 0; - var x = a ? doX(y) && goZoo("zoo") - : b ? blerg({ x: y }) - : null; - - var x = X || Y; -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/tmp/test.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/tmp/test.js deleted file mode 100755 index f295fba84..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/tmp/test.js +++ /dev/null @@ -1,30 +0,0 @@ -#! /usr/bin/env node - -global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util"); -var fs = require("fs"); -var uglify = require("uglify-js"), // symlink ~/.node_libraries/uglify-js.js to ../uglify-js.js - jsp = uglify.parser, - pro = uglify.uglify; - -var code = fs.readFileSync("hoist.js", "utf8"); -var ast = jsp.parse(code); - -ast = pro.ast_lift_variables(ast); - -var w = pro.ast_walker(); -ast = w.with_walkers({ - "function": function() { - var node = w.dive(this); // walk depth first - console.log(pro.gen_code(node, { beautify: true })); - return node; - }, - "name": function(name) { - return [ this[0], "X" ]; - } -}, function(){ - return w.walk(ast); -}); - -console.log(pro.gen_code(ast, { - beautify: true -})); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/uglify-js.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/uglify-js.js deleted file mode 100644 index 4305e232e..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/node_modules/uglify-js/uglify-js.js +++ /dev/null @@ -1,17 +0,0 @@ -//convienence function(src, [options]); -function uglify(orig_code, options){ - options || (options = {}); - var jsp = uglify.parser; - var pro = uglify.uglify; - - var ast = jsp.parse(orig_code, options.strict_semicolons); // parse code and get the initial AST - ast = pro.ast_mangle(ast, options.mangle_options); // get a new AST with mangled names - ast = pro.ast_squeeze(ast, options.squeeze_options); // get an AST with compression optimizations - var final_code = pro.gen_code(ast, options.gen_options); // compressed code here - return final_code; -}; - -uglify.parser = require("./lib/parse-js"); -uglify.uglify = require("./lib/process"); - -module.exports = uglify \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/package.json deleted file mode 100644 index 29a8d1d46..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "burrito", - "description": "Wrap up expressions with a trace function while walking the AST with rice and beans on the side", - "version": "0.2.12", - "repository": { - "type": "git", - "url": "git://github.com/substack/node-burrito.git" - }, - "main": "./index.js", - "keywords": [ - "trace", - "ast", - "walk", - "syntax", - "source", - "tree", - "uglify" - ], - "directories": { - "lib": ".", - "example": "example", - "test": "test" - }, - "scripts": { - "test": "tap test/*.js" - }, - "dependencies": { - "traverse": "~0.5.1", - "uglify-js": "~1.1.1" - }, - "devDependencies": { - "tap": "~0.2.5" - }, - "engines": { - "node": ">=0.4.0" - }, - "license": "BSD", - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "readme": "burrito\n=======\n\nBurrito makes it easy to do crazy stuff with the javascript AST.\n\nThis is super useful if you want to roll your own stack traces or build a code\ncoverage tool.\n\n[![build status](https://secure.travis-ci.org/substack/node-burrito.png)](http://travis-ci.org/substack/node-burrito)\n\n![node.wrap(\"burrito\")](http://substack.net/images/burrito.png)\n\nexamples\n========\n\nmicrowave\n---------\n\nexamples/microwave.js\n\n````javascript\nvar burrito = require('burrito');\n\nvar res = burrito.microwave('Math.sin(2)', function (node) {\n if (node.name === 'num') node.wrap('Math.PI / %s');\n});\n\nconsole.log(res); // sin(pi / 2) == 1\n````\n\noutput:\n\n 1\n\nwrap\n----\n\nexamples/wrap.js\n\n````javascript\nvar burrito = require('burrito');\n\nvar src = burrito('f() && g(h())\\nfoo()', function (node) {\n if (node.name === 'call') node.wrap('qqq(%s)');\n});\n\nconsole.log(src);\n````\n\noutput:\n\n qqq(f()) && qqq(g(qqq(h())));\n\n qqq(foo());\n\nmethods\n=======\n\n var burrito = require('burrito');\n\nburrito(code, cb)\n-----------------\n\nGiven some source `code` and a function `trace`, walk the ast by expression.\n\nThe `cb` gets called with a node object described below.\n\nIf `code` is an Array then it is assumbed to be an AST which you can generate\nyourself with `burrito.parse()`. The AST must be annotated, so make sure to\n`burrito.parse(src, false, true)`.\n\nburrito.microwave(code, context={}, cb)\n---------------------------------------\n\nLike `burrito()` except the result is run using\n`vm.runInNewContext(res, context)`.\n\nnode object\n===========\n\nnode.name\n---------\n\nName is a string that contains the type of the expression as named by uglify.\n\nnode.wrap(s)\n------------\n\nWrap the current expression in `s`.\n\nIf `s` is a string, `\"%s\"` will be replaced with the stringified current\nexpression.\n\nIf `s` is a function, it is called with the stringified current expression and\nshould return a new stringified expression.\n\nIf the `node.name === \"binary\"`, you get the subterms \"%a\" and \"%b\" to play with\ntoo. These subterms are applied if `s` is a function too: `s(expr, a, b)`.\n\nProtip: to insert multiple statements you can use javascript's lesser-known block\nsyntax that it gets from C:\n\n````javascript\nif (node.name === 'stat') node.wrap('{ foo(); %s }')\n````\n\nnode.node\n---------\n\nraw ast data generated by uglify\n\nnode.value\n----------\n\n`node.node.slice(1)` to skip the annotations\n\nnode.start\n----------\n\nThe start location of the expression, like this:\n\n````javascript\n{ type: 'name',\n value: 'b',\n line: 0,\n col: 3,\n pos: 3,\n nlb: false,\n comments_before: [] }\n````\n\nnode.end\n--------\n\nThe end location of the expression, formatted the same as `node.start`.\n\nnode.state\n----------\n\nThe state of the traversal using traverse.\n\nnode.source()\n-------------\n\nReturns a stringified version of the expression.\n\nnode.parent()\n-------------\n\nReturns the parent `node` or `null` if the node is the root element.\n\nnode.label()\n------------\n\nReturn the label of the present node or `null` if there is no label.\n\nLabels are returned for \"call\", \"var\", \"defun\", and \"function\" nodes.\n\nReturns an array for \"var\" nodes since `var` statements can\ncontain multiple labels in assignment.\n\ninstall\n=======\n\nWith [npm](http://npmjs.org) you can just:\n\n npm install burrito\n\nin the browser\n==============\n\nBurrito works in browser with\n[browserify](https://github.com/substack/node-browserify).\n\nIt has been tested against:\n\n* Internet Explorer 5.5, 6.0, 7.0, 8.0, 9.0\n* Firefox 3.5\n* Chrome 6.0\n* Opera 10.6\n* Safari 5.0\n\nkudos\n=====\n\nHeavily inspired by (and previously mostly lifted outright from) isaacs's nifty\ntmp/instrument.js thingy from uglify-js.\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/substack/node-burrito/issues" - }, - "_id": "burrito@0.2.12", - "_from": "burrito@>=0.2.5 <0.3" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/ast.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/ast.js deleted file mode 100644 index 503b5abf1..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/ast.js +++ /dev/null @@ -1,31 +0,0 @@ -var test = require('tap').test; -var burrito = require('../'); -var vm = require('vm'); - -test('ast', function (t) { - t.plan(2); - - var ast = burrito.parse('f(g(h(5)))', false, true); - var src = burrito(ast, function (node) { - if (node.name === 'call') { - node.wrap(function (s) { - return 'z(' + s + ')'; - }); - } - }); - - var times = 0; - t.equal( - vm.runInNewContext(src, { - f : function (x) { return x + 1 }, - g : function (x) { return x + 2 }, - h : function (x) { return x + 3 }, - z : function (x) { - times ++; - return x * 10; - }, - }), - (((((5 + 3) * 10) + 2) * 10) + 1) * 10 - ); - t.equal(times, 3); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/err.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/err.js deleted file mode 100644 index af1611d9d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/err.js +++ /dev/null @@ -1,52 +0,0 @@ -var test = require('tap').test; -var burrito = require('../'); - -test('wrap error', function (t) { - t.plan(6); - - try { - var src = burrito('f() && g()', function (node) { - if (node.name === 'binary') node.wrap('h(%a, %b') - }); - t.fail('should have blown up'); - } - catch (err) { - t.ok(err.message.match(/unexpected/i)); - t.ok(err instanceof SyntaxError); - t.ok(!err.stack.match(/uglify-js/)); - t.equal(err.line, 0); - t.equal(err.col, 10); - t.equal(err.pos, 10); - } -}); - -test('non string', function (t) { - t.plan(3); - - t.throws(function () { - burrito.parse(new Buffer('[]')); - }); - - t.throws(function () { - burrito.parse(new String('[]')); - }); - - t.throws(function () { - burrito.parse(); - }); -}); - -test('syntax error', function (t) { - t.plan(3); - try { - var src = burrito('f() && g())', function (node) { - if (node.name === 'binary') node.wrap('h(%a, %b)') - }); - assert.fail('should have blown up'); - } - catch (err) { - t.ok(err.message.match(/unexpected/i)); - t.ok(err instanceof SyntaxError); - t.ok(!err.stack.match(/uglify-js/)); - } -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/fail.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/fail.js deleted file mode 100644 index 70d453f87..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/fail.js +++ /dev/null @@ -1,9 +0,0 @@ -var burrito = require('../'); -var test = require('tap').test; -var fs = require('fs'); -var src = fs.readFileSync(__dirname + '/fail/src.js', 'utf8'); - -test('fail', function (t) { - burrito(src, function (node) {}); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/fail/src.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/fail/src.js deleted file mode 100644 index eb027363a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/fail/src.js +++ /dev/null @@ -1,60 +0,0 @@ -var path = require('path') - -module.exports = function(fs, ready) { - var global_files = {} - - var recurse = function(dir, okay) { - fs.readdir(dir, function(err, dir_files) { - var countdown = 0 - , files = [] - , dirs = [] - , checked = 0 - dir_files.forEach(function(file, idx, all) { - fs.stat(path.join(dir, file), function(err, stat) { - if(stat.isDirectory() && !/node_modules/g.test(dir)) { - dirs.push(file) - } else if(/\.js$/g.test(file)) { - files.push(file) - } - - if(++checked >= dir_files.length) - recurse_dirs() - }) - }) - - function recurse_dirs() { - var total = 0 - dirs.forEach(function(this_dir) { - recurse(path.join(dir, this_dir), function(err, data) { - if(++total >= dirs.length) - recurse_files() - }) - }) - - if(!dirs.length) - recurse_files() - } - - function recurse_files() { - var total = 0 - files.forEach(function(file) { - fs.readFile(path.join(dir, file), 'utf8', function(err, src) { - global_files[path.join(dir, file)] = src - ++total >= files.length && - okay(null, global_files) - }) - }) - - if(!files.length) - okay(null, global_files) - } - - if(!dir_files.length) - okay(null, global_files) - }) - } - - recurse('.', ready) -} - - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/label.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/label.js deleted file mode 100644 index 368d7c42a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/label.js +++ /dev/null @@ -1,92 +0,0 @@ -var test = require('tap').test; -var burrito = require('../'); - -test('call label', function (t) { - t.plan(1); - - burrito('foo(10)', function (node) { - if (node.name === 'call') { - t.equal(node.label(), 'foo'); - } - }); -}); - -test('var label', function (t) { - t.plan(1); - - burrito('var x = 2', function (node) { - if (node.name === 'var') { - t.same(node.label(), [ 'x' ]); - } - }); -}); - -test('vars label', function (t) { - t.plan(1); - - burrito('var x = 2, y = 3', function (node) { - if (node.name === 'var') { - t.same(node.label(), [ 'x', 'y' ]); - } - }); -}); - -test('defun label', function (t) { - t.plan(1); - - burrito('function moo () {}', function (node) { - if (node.name === 'defun') { - t.same(node.label(), 'moo'); - } - }); -}); - -test('function label', function (t) { - t.plan(1); - - burrito('(function zzz () {})()', function (node) { - if (node.name === 'function') { - t.same(node.label(), 'zzz'); - } - }); -}); - -test('anon function label', function (t) { - t.plan(1); - - burrito('(function () {})()', function (node) { - if (node.name === 'function') { - t.equal(node.label(), null); - } - }); -}); - -test('dot call label', function (t) { - t.plan(1); - - burrito('process.nextTick(fn)', function (node) { - if (node.name === 'call') { - t.equal(node.label(), 'nextTick'); - } - }); -}); - -test('triple dot label', function (t) { - t.plan(1); - - burrito('a.b.c(fn)', function (node) { - if (node.name === 'call') { - t.equal(node.label(), 'c'); - } - }); -}); - -test('expr label', function (t) { - t.plan(1); - - burrito('a.b[x+1](fn)', function (node) { - if (node.name === 'call') { - t.ok(node.label() === null); - } - }); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/microwave.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/microwave.js deleted file mode 100644 index 43f80a782..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/microwave.js +++ /dev/null @@ -1,34 +0,0 @@ -var test = require('tap').test; -var burrito = require('../'); - -test('microwave', function (t) { - t.plan(4); - - var context = { - f : function (x) { return x + 1 }, - g : function (x) { return x + 2 }, - h : function (x) { return x + 3 }, - z : function (x) { - t.ok(true); // 3 times - return x * 10; - }, - }; - - var res = burrito.microwave('f(g(h(5)))', context, function (node) { - if (node.name === 'call') { - node.wrap(function (s) { - return 'z(' + s + ')'; - }); - } - }); - - t.equal(res, (((((5 + 3) * 10) + 2) * 10) + 1) * 10); -}); - -test('empty context', function (t) { - var res = burrito.microwave('Math.sin(2)', function (node) { - if (node.name === 'num') node.wrap('Math.PI / %s'); - }); - t.equal(res, 1); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/parent.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/parent.js deleted file mode 100644 index 2d613afb3..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/parent.js +++ /dev/null @@ -1,27 +0,0 @@ -var test = require('tap').test; -var burrito = require('../'); - -test('check parent', function (t) { - t.plan(5); - var src = 'Math.tan(0) + Math.sin(0)'; - - var res = burrito.microwave(src, function (node) { - if (node.name === 'binary') { - node.wrap('%a - %b'); - } - else if (node.name === 'num') { - t.equal(node.parent().value[0][0], 'dot'); - - var fn = node.parent().value[0][2]; - if (fn === 'sin') { - node.wrap('Math.PI / 2'); - } - else if (fn === 'tan') { - node.wrap('Math.PI / 4'); - } - else t.fail('Unknown fn'); - } - }); - - t.equal(res, Math.tan(Math.PI / 4) - Math.sin(Math.PI / 2)); // ~ 0 -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/wrap.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/wrap.js deleted file mode 100644 index b9eda494c..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/node_modules/burrito/test/wrap.js +++ /dev/null @@ -1,159 +0,0 @@ -var test = require('tap').test; -var burrito = require('../'); -var vm = require('vm'); - -test('preserve ternary parentheses', function (t) { - var originalSource = '"anything" + (x ? y : z) + "anything"'; - var burritoSource = burrito(originalSource, function (node) { - // do nothing. we just want to check that ternary parens are persisted - }); - - var ctxt = { - x : false, - y : 'y_'+~~(Math.random()*10), - z : 'z_'+~~(Math.random()*10) - }; - - var expectedOutput = vm.runInNewContext(originalSource, ctxt); - var burritoOutput = vm.runInNewContext(burritoSource, ctxt); - - t.equal(burritoOutput, expectedOutput); - - ctxt.x = true; - - expectedOutput = vm.runInNewContext(originalSource, ctxt); - burritoOutput = vm.runInNewContext(burritoSource, ctxt); - - t.equal(burritoOutput, expectedOutput); - t.end(); -}); - -test('wrap calls', function (t) { - t.plan(20); - var src = burrito('f() && g(h())\nfoo()', function (node) { - if (node.name === 'call') node.wrap('qqq(%s)'); - if (node.name === 'binary') node.wrap('bbb(%s)'); - t.ok(node.state); - t.equal(this, node.state); - }); - - var times = { bbb : 0, qqq : 0 }; - - var res = []; - vm.runInNewContext(src, { - bbb : function (x) { - times.bbb ++; - res.push(x); - return x; - }, - qqq : function (x) { - times.qqq ++; - res.push(x); - return x; - }, - f : function () { return true }, - g : function (h) { - t.equal(h, 7); - return h !== 7 - }, - h : function () { return 7 }, - foo : function () { return 'foo!' }, - }); - - t.same(res, [ - true, // f() - 7, // h() - false, // g(h()) - false, // f() && g(h()) - 'foo!', // foo() - ]); - t.equal(times.bbb, 1); - t.equal(times.qqq, 4); - t.end(); -}); - -test('wrap fn', function (t) { - var src = burrito('f(g(h(5)))', function (node) { - if (node.name === 'call') { - node.wrap(function (s) { - return 'z(' + s + ')'; - }); - } - }); - - var times = 0; - t.equal( - vm.runInNewContext(src, { - f : function (x) { return x + 1 }, - g : function (x) { return x + 2 }, - h : function (x) { return x + 3 }, - z : function (x) { - times ++; - return x * 10; - }, - }), - (((((5 + 3) * 10) + 2) * 10) + 1) * 10 - ); - t.equal(times, 3); - t.end(); -}); - -test('binary string', function (t) { - var src = 'z(x + y)'; - var context = { - x : 3, - y : 4, - z : function (n) { return n * 10 }, - }; - - var res = burrito.microwave(src, context, function (node) { - if (node.name === 'binary') { - node.wrap('%a*2 - %b*2'); - } - }); - - t.equal(res, 10 * (3*2 - 4*2)); - t.end(); -}); - -test('binary fn', function (t) { - var src = 'z(x + y)'; - var context = { - x : 3, - y : 4, - z : function (n) { return n * 10 }, - }; - - var res = burrito.microwave(src, context, function (node) { - if (node.name === 'binary') { - node.wrap(function (expr, a, b) { - return '(' + a + ')*2 - ' + '(' + b + ')*2'; - }); - } - }); - - t.equal(res, 10 * (3*2 - 4*2)); - t.end(); -}); - -test('intersperse', function (t) { - var src = '(' + (function () { - f(); - g(); - }).toString() + ')()'; - - var times = { f : 0, g : 0, zzz : 0 }; - - var context = { - f : function () { times.f ++ }, - g : function () { times.g ++ }, - zzz : function () { times.zzz ++ }, - }; - - burrito.microwave(src, context, function (node) { - if (node.name === 'stat') node.wrap('{ zzz(); %s }'); - }); - - t.same(times, { f : 1, g : 1, zzz : 3 }); - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/package.json deleted file mode 100644 index 2721fdbcc..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "bunker", - "version": "0.1.2", - "description": "code coverage in native javascript", - "main": "index.js", - "directories": { - "lib": ".", - "example": "example", - "test": "test" - }, - "dependencies": { - "burrito": ">=0.2.5 <0.3" - }, - "devDependencies": { - "tap": "~0.2.4" - }, - "scripts": { - "test": "tap test/*.js" - }, - "repository": { - "type": "git", - "url": "http://github.com/substack/node-bunker.git" - }, - "keywords": [ - "code", - "coverage" - ], - "author": { - "name": "James Halliday", - "email": "mail@substack.net", - "url": "http://substack.net" - }, - "license": "MIT/X11", - "engine": { - "node": ">=0.4" - }, - "readme": "bunker\n======\n\nBunker is a module to calculate code coverage using native javascript\n[burrito](https://github.com/substack/node-burrito) AST trickery.\n\n[![build status](https://secure.travis-ci.org/substack/node-bunker.png)](http://travis-ci.org/substack/node-bunker)\n\n![code coverage](http://substack.net/images/code_coverage.png)\n\nexamples\n========\n\ntiny\n----\n\n````javascript\nvar bunker = require('bunker');\nvar b = bunker('var x = 0; for (var i = 0; i < 30; i++) { x++ }');\n\nvar counts = {};\n\nb.on('node', function (node) {\n if (!counts[node.id]) {\n counts[node.id] = { times : 0, node : node };\n }\n counts[node.id].times ++;\n});\n\nb.run();\n\nObject.keys(counts).forEach(function (key) {\n var count = counts[key];\n console.log(count.times + ' : ' + count.node.source());\n});\n````\n\noutput:\n\n $ node example/tiny.js \n 1 : var x=0;\n 31 : i<30\n 30 : i++\n 30 : x++;\n 30 : x++\n\nmethods\n=======\n\nvar bunker = require('bunker');\n\nvar b = bunker(src)\n-------------------\n\nCreate a new bunker code coverageifier with some source `src`.\n\nThe bunker object `b` is an `EventEmitter` that emits `'node'` events with two\nparameters:\n\n* `node` - the [burrito](https://github.com/substack/node-burrito) node object\n* `stack` - the stack, [stackedy](https://github.com/substack/node-stackedy) style\n\nb.include(src)\n--------------\n\nInclude some source into the bunker.\n\nb.compile()\n-----------\n\nReturn the source wrapped with burrito.\n\nb.assign(context={})\n--------------------\n\nAssign the statement-tracking functions into `context`.\n\nb.run(context={})\n-----------------\n\nRun the source using `vm.runInNewContext()` with some `context`.\nThe statement-tracking functions will be added to `context` by `assign()`.\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/substack/node-bunker/issues" - }, - "_id": "bunker@0.1.2", - "_from": "bunker@0.1.X" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/test/cover.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/test/cover.js deleted file mode 100644 index b04795d3f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/test/cover.js +++ /dev/null @@ -1,36 +0,0 @@ -var test = require('tap').test; -var bunker = require('../'); -var fs = require('fs'); - -var src = fs.readdirSync(__dirname + '/src').reduce(function (acc, file) { - acc[file] = fs.readFileSync(__dirname + '/src/' + file, 'utf8'); - return acc; -}, {}); - -test('cover', function (t) { - t.plan(1); - - var b = bunker(src['cover.js']); - var counts = {}; - - b.on('node', function (node) { - counts[node.name] = (counts[node.name] || 0) + 1; - }); - - b.run({ - setInterval : setInterval, - clearInterval : function () { - process.nextTick(function () { - t.same(counts, { - binary : 11, - 'unary-postfix' : 11, - 'var' : 2, - call : 2, // setInterval and clearInterval - stat : 1, // clearInterval - }); - }); - - return clearInterval.apply(this, arguments); - }, - }); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/test/return.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/test/return.js deleted file mode 100644 index 9be1700fe..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/test/return.js +++ /dev/null @@ -1,29 +0,0 @@ -var test = require('tap').test; -var bunker = require('../'); - -test('cover', function (t) { - t.plan(1); - - var b = bunker('(' + function () { - function foo () {} - function bar () {} - - (function () { - return foo(); - })(); - } + ')()'); - var counts = {}; - - b.on('node', function (node) { - counts[node.name] = (counts[node.name] || 0) + 1; - }); - b.run(); - - process.nextTick(function () { - t.same(counts, { - stat : 2, - call : 2, - return : 1, - }); - }); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/test/src/cover.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/test/src/cover.js deleted file mode 100644 index e64015149..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/node_modules/bunker/test/src/cover.js +++ /dev/null @@ -1,6 +0,0 @@ -var i = 0; -var iv = setInterval(function () { - if (i++ === 10) { - clearInterval(iv); - } -}, 10); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/package.json deleted file mode 100644 index 4d56f8058..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "runforcover", - "version": "0.0.2", - "description": "require plugin for js code coverage using bunker", - "main": "index.js", - "directories": { - "lib": ".", - "test": "test" - }, - "dependencies": { - "bunker": "0.1.X" - }, - "scripts": { - "test": "node test/index.js" - }, - "repository": { - "type": "git", - "url": "http://github.com/chrisdickinson/node-runforcover.git" - }, - "keywords": [ - "code", - "coverage", - "bunker" - ], - "author": { - "name": "Chris Dickinson", - "email": "chris@neversaw.us", - "url": "http://neversaw.us" - }, - "license": "new BSD", - "engine": { - "node": ">=0.4" - }, - "readme": "runforcover\n======\n\nRunforcover is a require-hook library that uses node-bunker to provide code coverage data\nfor your unit test library, whatever it might be.\n\nmethods\n=======\nvar runforcover = require('runforcover');\n\nvar coverage = runforcover.cover([RegExp | path]);\n-------\n\nAttach runforcover to the global `require` object and patch `require.extensions['.js']` to\nprovide coverage metadata for all files required after this point. Returns a function\nobject that can be called to obtain a object keying files to `CoverageData` objects, with \na method for releasing control back to vanilla `require`. Usage:\n\n````javascript\n\nvar coverage = runforcover.cover(/.*/g);\n\nrequire('some/library');\n\ncoverage(function(coverageData) {\n // coverageData is an object keyed by filename.\n var stats = coverageData['/full/path/to/file.js'].stats()\n\n // the percentage of lines run versus total lines in file\n console.log(stats.percentage);\n\n // the number of missing lines\n console.log(stats.missing);\n\n // the number of lines run (seen)\n console.log(stats.seen);\n\n // an array of line objects representing 'missed' lines\n stats.lines;\n\n stats.lines.forEach(function(line) {\n // the line number of the line:\n console.log(line.number);\n\n // returns a string containing the source data for the line:\n console.log(line.source()); \n }); \n \n // return control back to the original require function\n coverage.release(); \n});\n````\n\nlicense\n=======\nnew BSD.\n", - "readmeFilename": "README.markdown", - "bugs": { - "url": "https://github.com/chrisdickinson/node-runforcover/issues" - }, - "_id": "runforcover@0.0.2", - "_from": "runforcover@~0.0.2" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/test/index.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/test/index.js deleted file mode 100644 index ea59662c2..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/test/index.js +++ /dev/null @@ -1 +0,0 @@ -require('./interface').coverageInterface() diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/test/interface.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/test/interface.js deleted file mode 100644 index a6455ed82..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/test/interface.js +++ /dev/null @@ -1,50 +0,0 @@ -var assert = require('assert'); -var runforcover = require('../'); - -exports.coverageInterface = function() { - assert.ok(runforcover.cover); - - var originalRequire = require.extensions['.js']; - - var coverage = runforcover.cover(); - - assert.notEqual(originalRequire, require.extensions['.js']); - - var file = require('./src/coverage'); - - coverage(function(coverageData) { - assert.equal(Object.keys(coverageData).length, 1); - assert.equal(Object.keys(coverageData)[0], __dirname + '/src/coverage.js'); - - var fileCoverageData = coverageData[Object.keys(coverageData)[0]]; - - assert.ok(fileCoverageData.stats); - assert.ok(fileCoverageData.missing); - - var stats = fileCoverageData.stats(); - - assert.ok(stats.percentage !== undefined); - assert.ok(stats.lines !== undefined); - assert.ok(stats.missing !== undefined); - assert.ok(stats.seen !== undefined); - - assert.equal(stats.lines.length, 3); - assert.equal(stats.lines[0].source(), ' if(a > 0) {'); - assert.equal(stats.lines[1].source(), ' return a + 1;'); - assert.equal(stats.lines[2].source(), ' return a - 1;'); - - file.something(1); - stats = fileCoverageData.stats(); - - assert.equal(stats.lines.length, 1); - assert.equal(stats.lines[0].source(), ' return a - 1;'); - - file.something(-1); - stats = fileCoverageData.stats(); - - assert.equal(stats.lines.length, 0); - - coverage.release(); - assert.equal(require.extensions['.js'], originalRequire); - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/test/src/coverage.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/test/src/coverage.js deleted file mode 100644 index 5b88dfee7..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/runforcover/test/src/coverage.js +++ /dev/null @@ -1,7 +0,0 @@ -exports.something = function(a) { - if(a > 0) { - return a + 1; - } else { - return a - 1; - } -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/slide/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/slide/package.json deleted file mode 100644 index 4faccac02..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/slide/package.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "name": "slide", - "version": "1.1.4", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "contributors": [ - { - "name": "S. Sriram", - "email": "ssriram@gmail.com", - "url": "http://www.565labs.com" - } - ], - "description": "A flow control lib small enough to fit on in a slide presentation. Derived live at Oak.JS", - "main": "./lib/slide.js", - "dependencies": {}, - "devDependencies": {}, - "engines": { - "node": "*" - }, - "repository": { - "type": "git", - "url": "git://github.com/isaacs/slide-flow-control.git" - }, - "readme": "# Controlling Flow: callbacks are easy\n\n## What's actually hard?\n\n- Doing a bunch of things in a specific order.\n- Knowing when stuff is done.\n- Handling failures.\n- Breaking up functionality into parts (avoid nested inline callbacks)\n\n\n## Common Mistakes\n\n- Abandoning convention and consistency.\n- Putting all callbacks inline.\n- Using libraries without grokking them.\n- Trying to make async code look sync.\n\n## Define Conventions\n\n- Two kinds of functions: *actors* take action, *callbacks* get results.\n- Essentially the continuation pattern. Resulting code *looks* similar\n to fibers, but is *much* simpler to implement.\n- Node works this way in the lowlevel APIs already, and it's very flexible.\n\n## Callbacks\n\n- Simple responders\n- Must always be prepared to handle errors, that's why it's the first argument.\n- Often inline anonymous, but not always.\n- Can trap and call other callbacks with modified data, or pass errors upwards.\n\n## Actors\n\n- Last argument is a callback.\n- If any error occurs, and can't be handled, pass it to the callback and return.\n- Must not throw. Return value ignored.\n- return x ==> return cb(null, x)\n- throw er ==> return cb(er)\n\n```javascript\n// return true if a path is either\n// a symlink or a directory.\nfunction isLinkOrDir (path, cb) {\n fs.lstat(path, function (er, s) {\n if (er) return cb(er)\n return cb(null, s.isDirectory() || s.isSymbolicLink())\n })\n}\n```\n\n# asyncMap\n\n## Usecases\n\n- I have a list of 10 files, and need to read all of them, and then continue when they're all done.\n- I have a dozen URLs, and need to fetch them all, and then continue when they're all done.\n- I have 4 connected users, and need to send a message to all of them, and then continue when that's done.\n- I have a list of n things, and I need to dosomething with all of them, in parallel, and get the results once they're all complete.\n\n\n## Solution\n\n```javascript\nvar asyncMap = require(\"slide\").asyncMap\nfunction writeFiles (files, what, cb) {\n asyncMap(files, function (f, cb) {\n fs.writeFile(f, what, cb)\n }, cb)\n}\nwriteFiles([my, file, list], \"foo\", cb)\n```\n\n# chain\n\n## Usecases\n\n- I have to do a bunch of things, in order. Get db credentials out of a file,\n read the data from the db, write that data to another file.\n- If anything fails, do not continue.\n- I still have to provide an array of functions, which is a lot of boilerplate,\n and a pita if your functions take args like\n\n```javascript\nfunction (cb) {\n blah(a, b, c, cb)\n}\n```\n\n- Results are discarded, which is a bit lame.\n- No way to branch.\n\n## Solution\n\n- reduces boilerplate by converting an array of [fn, args] to an actor\n that takes no arguments (except cb)\n- A bit like Function#bind, but tailored for our use-case.\n- bindActor(obj, \"method\", a, b, c)\n- bindActor(fn, a, b, c)\n- bindActor(obj, fn, a, b, c)\n- branching, skipping over falsey arguments\n\n```javascript\nchain([\n doThing && [thing, a, b, c]\n, isFoo && [doFoo, \"foo\"]\n, subChain && [chain, [one, two]]\n], cb)\n```\n\n- tracking results: results are stored in an optional array passed as argument,\n last result is always in results[results.length - 1].\n- treat chain.first and chain.last as placeholders for the first/last\n result up until that point.\n\n\n## Non-trivial example\n\n- Read number files in a directory\n- Add the results together\n- Ping a web service with the result\n- Write the response to a file\n- Delete the number files\n\n```javascript\nvar chain = require(\"slide\").chain\nfunction myProgram (cb) {\n var res = [], last = chain.last, first = chain.first\n chain([\n [fs, \"readdir\", \"the-directory\"]\n , [readFiles, \"the-directory\", last]\n , [sum, last]\n , [ping, \"POST\", \"example.com\", 80, \"/foo\", last]\n , [fs, \"writeFile\", \"result.txt\", last]\n , [rmFiles, \"./the-directory\", first]\n ], res, cb)\n}\n```\n\n# Conclusion: Convention Profits\n\n- Consistent API from top to bottom.\n- Sneak in at any point to inject functionality. Testable, reusable, ...\n- When ruby and python users whine, you can smile condescendingly.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/slide-flow-control/issues" - }, - "_id": "slide@1.1.4", - "_from": "slide@*" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/yamlish/LICENSE b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/yamlish/LICENSE deleted file mode 100644 index 187e8db4c..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/yamlish/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011 Isaac Z. Schlueter - -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/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/yamlish/README.md b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/yamlish/README.md deleted file mode 100644 index 954d0636c..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/yamlish/README.md +++ /dev/null @@ -1,20 +0,0 @@ -This is a thingie to parse the "yamlish" format used to serialize -objects in the TAP format. - -It's like yaml, but just a tiny little bit smaller. - -Usage: - - var yamlish = require("yamlish") - // returns a string like: - /* - some: - object: - - full - - of - pretty: things - */ - yamlish.encode({some:{object:["full", "of"]}, pretty:"things"}) - - // returns the object - yamlish.decode(someYamlishString) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/yamlish/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/yamlish/package.json deleted file mode 100644 index 359300d64..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/yamlish/package.json +++ /dev/null @@ -1,9 +0,0 @@ -{ "name" : "yamlish" -, "description" : "Parser/encoder for the yamlish format" -, "repository":"https://github.com/isaacs/yamlish" -, "version" : "0.0.5" -, "main" : "yamlish.js" -, "keywords" : [ "yaml", "yamlish", "test", "anything", "protocol", "tap"] -, "license" : { "type" : "MIT" - , "url" : "http://github.com/isaacs/yamlish/raw/master/LICENSE" } -, "author" : "Isaac Z. Schlueter (http://blog.izs.me/)" } diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/yamlish/yamlish.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/yamlish/yamlish.js deleted file mode 100644 index dd8c3700a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/node_modules/yamlish/yamlish.js +++ /dev/null @@ -1,260 +0,0 @@ -exports.encode = encode -exports.decode = decode - -var seen = [] -function encode (obj, indent) { - var deep = arguments[2] - if (!indent) indent = " " - - if (obj instanceof String || - Object.prototype.toString.call(obj) === "[object String]") { - obj = obj.toString() - } - - if (obj instanceof Number || - Object.prototype.toString.call(obj) === "[object Number]") { - obj = obj.valueOf() - } - - // take out the easy ones. - switch (typeof obj) { - case "string": - obj = obj.trim() - if (obj.indexOf("\n") !== -1) { - return "|\n" + indent + obj.split(/\r?\n/).join("\n"+indent) - } else { - return (obj) - } - - case "number": - return obj.toString(10) - - case "function": - return encode(obj.toString(), indent, true) - - case "boolean": - return obj.toString() - - case "undefined": - // fallthrough - case "object": - // at this point we know it types as an object - if (!obj) return "~" - - if (obj instanceof Date || - Object.prototype.toString.call(obj) === "[object Date]") { - return JSON.stringify("[Date " + obj.toISOString() + "]") - } - - if (obj instanceof RegExp || - Object.prototype.toString.call(obj) === "[object RegExp]") { - return JSON.stringify(obj.toString()) - } - - if (obj instanceof Boolean || - Object.prototype.toString.call(obj) === "[object Boolean]") { - return obj.toString() - } - - if (seen.indexOf(obj) !== -1) { - return "[Circular]" - } - seen.push(obj) - - if (typeof Buffer === "function" && - typeof Buffer.isBuffer === "function" && - Buffer.isBuffer(obj)) return obj.inspect() - - if (obj instanceof Error) { - var o = { name: obj.name - , message: obj.message - , type: obj.type } - - if (obj.code) o.code = obj.code - if (obj.errno) o.errno = obj.errno - if (obj.type) o.type = obj.type - obj = o - } - - var out = "" - - if (Array.isArray(obj)) { - var out = "\n" + indent + "- " +obj.map(function (item) { - return encode(item, indent + " ", true) - }).join("\n"+indent + "- ") - break - } - - // an actual object - var keys = Object.keys(obj) - , niceKeys = keys.map(function (k) { - return (k.match(/^[a-zA-Z0-9_]+$/) ? k : JSON.stringify(k)) + ": " - }) - //console.error(keys, niceKeys, obj) - var maxLength = Math.max.apply(Math, niceKeys.map(function (k) { - return k.length - }).concat(0)) - //console.error(niceKeys, maxLength) - - var spaces = new Array(maxLength + 1).join(" ") - - if (!deep) indent += " " - out = "\n" + indent + keys.map(function (k, i) { - var niceKey = niceKeys[i] - return niceKey + spaces.substr(niceKey.length) - + encode(obj[k], indent + " ", true) - }).join("\n" + indent) - break - - default: return "" - } - if (!deep) seen.length = 0 - return out -} - -function decode (str) { - var v = str.trim() - , d - , dateRe = /^\[Date ([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(?::[0-9]{2})?(?:\.[0-9]{3})?(?:[A-Z]+)?)\]$/ - - if (v === "~") return null - - try { - var jp = JSON.parse(str) - } catch (e) { - var jp = "" - } - - if (jp && - typeof jp === "string" && - (d = jp.match(dateRe)) && - (d = Date.parse(d[1]))) { - return new Date(d) - } - - if (typeof jp === "boolean") return jp - if (v && !isNaN(v)) return parseInt(v, 10) - - // something interesting. - var lines = str.split(/\r?\n/) - // check if it's some kind of string or something. - // if the first line is > or | then it's a wrapping indented string. - // if the first line is blank, and there are many lines, - // then it's an array or object. - // otherwise, it's just "" - var first = lines.shift().trim() - if (lines.length) lines = undent(lines) - switch (first) { - case "|": - return lines.join("\n") - case ">": - return lines.join("\n").split(/\n{2,}/).map(function (l) { - return l.split(/\n/).join(" ") - }).join("\n") - default: - if (!lines.length) return first - // array or object. - // the first line will be either "- value" or "key: value" - return lines[0].charAt(0) === "-" ? decodeArr(lines) : decodeObj(lines) - } -} - -function decodeArr (lines) { - var out = [] - , key = 0 - , val = [] - for (var i = 0, l = lines.length; i < l; i ++) { - // if it starts with a -, then it's a new thing - var line = lines[i] - if (line.charAt(0) === "-") { - if (val.length) { - out[key ++] = decode(val.join("\n")) - val.length = 0 - } - val.push(line.substr(1).trim()) - } else if (line.charAt(0) === " ") { - val.push(line) - } else return [] - } - if (val.length) { - out[key ++] = decode(val.join("\n")) - } - return out -} - -function decodeObj (lines) { - var out = {} - , val = [] - , key = null - - for (var i = 0, l = lines.length; i < l; i ++) { - var line = lines[i] - if (line.charAt(0) === " ") { - val.push(line) - continue - } - // some key:val - if (val.length) { - out[key] = decode(val.join("\n")) - val.length = 0 - } - // parse out the quoted key - var first - if (line.charAt(0) === "\"") { - for (var ii = 1, ll = line.length, esc = false; ii < ll; ii ++) { - var c = line.charAt(ii) - if (c === "\\") { - esc = !esc - } else if (c === "\"" && !esc) { - break - } - } - key = JSON.parse(line.substr(0, ii + 1)) - line = line.substr(ii + 1) - first = line.substr(line.indexOf(":") + 1).trim() - } else { - var kv = line.split(":") - key = kv.shift() - first = kv.join(":").trim() - } - // now we've set a key, and "first" has the first line of the value. - val.push(first.trim()) - } - if (val.length) out[key] = decode(val.join("\n")) - return out -} - -function undent (lines) { - var i = lines[0].match(/^\s*/)[0].length - return lines.map(function (line) { - return line.substr(i) - }) -} - - -// XXX Turn this into proper tests. -if (require.main === module) { -var obj = [{"bigstring":new Error().stack} - ,{ar:[{list:"of"},{some:"objects"}]} - ,{date:new Date()} - ,{"super huge string":new Error().stack} - ] - -Date.prototype.toJSON = function (k, val) { - console.error(k, val, this) - return this.toISOString() + " (it's a date)" -} - -var enc = encode(obj) - , dec = decode(enc) - , encDec = encode(dec) - -console.error(JSON.stringify({ obj : obj - , enc : enc.split(/\n/) - , dec : dec }, null, 2), encDec === enc) - -var num = 100 - , encNum = encode(num) - , decEncNum = decode(encNum) -console.error([num, encNum, decEncNum]) -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/package.json b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/package.json deleted file mode 100644 index 066571cbc..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/package.json +++ /dev/null @@ -1,65 +0,0 @@ -{ - "name": "tap", - "version": "0.4.2", - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me" - }, - "description": "A Test-Anything-Protocol library", - "bin": { - "tap": "bin/tap.js" - }, - "main": "lib/main.js", - "dependencies": { - "inherits": "*", - "yamlish": "*", - "slide": "*", - "runforcover": "~0.0.2", - "nopt": "~2", - "mkdirp": "~0.3", - "difflet": "~0.2.0", - "deep-equal": "~0.0.0", - "buffer-equal": "~0.0.0", - "glob": "~3.2.1" - }, - "keywords": [ - "assert", - "test", - "tap" - ], - "contributors": [ - { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me" - }, - { - "name": "baudehlo", - "email": "helpme+github@gmail.com" - } - ], - "license": { - "type": "MIT", - "url": "https://github.com/isaacs/node-tap/raw/master/LICENSE" - }, - "repository": { - "type": "git", - "url": "git://github.com/isaacs/node-tap.git" - }, - "scripts": { - "test": "bin/tap.js test/*.js" - }, - "readme": "This is a mix-and-match set of utilities that you can use to write test\nharnesses and frameworks that communicate with one another using the\nTest Anything Protocol.\n\nIf you don't yet know what TAP is, [you better ask\nsomebody](http://testanything.org/).\n\nDefault Usage:\n\n1. Make a directory. Maybe call it 'test'. That'd be nice and obvious.\n2. Put a bunch of test scripts in there. If they're node programs, then\n they should be \".js\". Anything else is assumed to be some kind of shell\n script, which should have a shebang line.\n3. `npm install tap`\n4. Update package.json scripts.test to include `tap ./test` [example\n gist](https://gist.github.com/4469613)\n5. `npm test`\n\nThe output will be TAP-compliant.\n\nFor extra special bonus points, you can do something like this:\n\n var test = require(\"tap\").test\n test(\"make sure the thingie is a thing\", function (t) {\n t.equal(thingie, \"thing\", \"thingie should be thing\")\n t.type(thingie, \"string\", \"type of thingie is string\")\n t.ok(true, \"this is always true\")\n t.notOk(false, \"this is never true\")\n t.test(\"a child test\", function (t) {\n t.equal(this, superEasy, \"right!?\")\n t.similar(7, 2, \"ever notice 7 is kinda like 2?\", {todo: true})\n t.test(\"so skippable\", {skip: true}, function (t) {\n t.plan(1) // only one test in this block\n t.ok(true, \"but when the flag changes, it'll pass\")\n // no need to end, since we had a plan.\n })\n t.end()\n })\n t.ok(99, \"can also skip individual assertions\", {skip: true})\n // end lets it know it's over.\n t.end()\n })\n test(\"another one\", function (t) {\n t.plan(1)\n t.ok(true, \"It's ok to plan, and also end. Watch.\")\n t.end() // but it must match the plan!\n })\n\nNode-tap is actually a collection of several modules, any of which may be\nmixed and matched however you please.\n\nIf you don't like this test framework, and think you can do much much\nbetter, *I strongly encourage you to do so!* If you use this library,\nhowever, at least to output TAP-compliant results when `process.env.TAP`\nis set, then the data coming out of your framework will be much more\nconsumable by machines.\n\nYou can also use this to build programs that *consume* the TAP data, so\nthis is very useful for CI systems and such.\n\n* tap-assert: A collection of assert functions that return TAP result\n objects.\n* tap-consumer: A stream interface for consuming TAP data.\n* tap-producer: A class that produces a TAP stream by taking in result\n objects.\n* tap-results: A class for keeping track of TAP result objects as they\n pass by, counting up skips, passes, fails, and so on.\n* tap-runner: A program that runs through a directory running all the\n tests in it. (Tests which may or may not be TAP-outputting tests. But\n it's better if they are.)\n* tap-test: A class for actually running tests.\n* tap-harness: A class that runs tests. (Tests are also Harnesses,\n which is how sub-tests run.)\n* tap-global-harness: A default harness that provides the top-level\n support for running TAP tests.\n\n## Experimental Code Coverage with runforcover & bunker:\n\n```\nTAP_COV=1 tap ./test [--cover=./lib,foo.js] [--cover-dir=./coverage]\n```\n\nThis feature is experimental, and will most likely change somewhat\nbefore being finalized. Feedback welcome.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/node-tap/issues" - }, - "bundleDependencies": [ - "inherits", - "tap-consumer", - "yamlish" - ], - "_id": "tap@0.4.2", - "_from": "tap@>=0.2.3" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test-disabled/bailout.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test-disabled/bailout.js deleted file mode 100644 index 498035ce5..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test-disabled/bailout.js +++ /dev/null @@ -1,36 +0,0 @@ -var tap = require("tap") - , test = tap.test - -test("bailout test", { skip: false }, function (t) { - - // t.once("bailout", function () { - // console.error("bailout event")//, t) - // t.clear() - // }) - - // t.once("end", function () { - // console.error("end event") - // }) - - // simulate three tests where the second bails out. - t.test("first", function (t) { - t.pass("this is ok") - t.end() - }) - - t.test("bailout", function (t) { - console.error("bailout test") - t.pass("pass") - t.bailout("bail out message") - t.fail("fail") - t.end() - }) - - t.test("second (should not happen)", function (t) { - t.fail("this should not happen") - t.end() - }) - - t.end() - -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test-disabled/foo.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test-disabled/foo.js deleted file mode 100644 index 63601568b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test-disabled/foo.js +++ /dev/null @@ -1 +0,0 @@ -process.stdin diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test-disabled/t.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test-disabled/t.js deleted file mode 100644 index 581d24b6d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test-disabled/t.js +++ /dev/null @@ -1,16 +0,0 @@ -var test = require('tap').test; - -function foo() { - throw new Error('one'); -} - -test('demonstrate bug in t.throws', function (t) { - t.throws( - function () { - foo(); - }, - new Error('two')), - // "this should throw", - // {}); // not 'one'! - t.end(); -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/buffer_compare.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/buffer_compare.js deleted file mode 100644 index b1e150589..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/buffer_compare.js +++ /dev/null @@ -1,11 +0,0 @@ -var test = require("../").test - -test("same buffers", function (t) { - t.same(new Buffer([3,4,243]), new Buffer([3,4,243])) - t.end() -}) - -test("not same buffers", function (t) { - t.notSame(new Buffer([3,5,243]), new Buffer([3,4,243])) - t.end() -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/common.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/common.js deleted file mode 100644 index 7cc43c11b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/common.js +++ /dev/null @@ -1,32 +0,0 @@ -exports.taps = ["Tests for the foo module" - ,{ok:true, name:"test that the foo is fooish" - ,file:"foo.js", line:8, name:"fooish test" - ,stack:new Error("fooish").stack} - ,{ok:false, name:"a test that the bar is barish" - ,file:"bar.js", line:25 - ,expected:"bar\nbar\nbaz", actual:"rab\nrib\nzib" - ,hash:{more:"\nstuff\nhere\n",regexp:/asdf/}} - ,"Quux module tests" - ,"This is a longer comment" - ,{ok:true, name:"an easy one."} - ,{ok:false, name:"bloooooo" - ,expected:"blerggeyyy" - ,actual:"blorggeyy"} - ,{ok:false, name:"array test" - ,expected:[{ok:true},{ok:true},{stack:new Error().stack}] - ,actual:[1234567890,123456789,{error:new Error("yikes")}]} - ,{ok:true, name:"nulltest" - ,expected:undefined, actual:null} - ,{ok:true, name:"weird key test" - ,expected:"weird key" - ,actual:"weird key" - ,"this object":{"has a ":"weird key" - ,"and a looooooooonnnnnnnnnggg":"jacket"}} - ,{ok:true, name:"regexp test" - ,regexp:/asdf/,function:function (a,b) { return a + b }} - ] - -if (require.main === module) { - console.log("1..1") - console.log("ok 1 - just setup, nothing relevant") -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/deep.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/deep.js deleted file mode 100644 index 52b6110ab..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/deep.js +++ /dev/null @@ -1,43 +0,0 @@ -var tap = require("../") - , test = tap.test - -test("deepEquals shouldn't care about key order", function (t) { - t.deepEqual({ a : 1, b : 2 }, { b : 2, a : 1 }) - t.end() -}) - -test("deepEquals shouldn't care about key order recursively", function (t) { - t.deepEqual( - { x : { a : 1, b : 2 }, y : { c : 3, d : 4 } }, - { y : { d : 4, c : 3 }, x : { b : 2, a : 1 } } - ) - t.end() -}) - -test("deepEquals shoudn't care about key order but still might", function (t) { - t.deepEqual( - [ { foo: - { z: 100 - , y: 200 - , x: 300 } } - , "bar" - , 11 - , { baz: - { d : 4 - , a: 1 - , b: 2 - , c: 3 } } ] - , [ { foo : - { z: 100 - , y: 200 - , x: 300 } } - , "bar" - , 11 - , { baz: - { a: 1 - , b: 2 - , c: 3 - , d: 4 } } ] - ) - t.end() -}); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/end-exception/t.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/end-exception/t.js deleted file mode 100644 index eaa5b4672..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/end-exception/t.js +++ /dev/null @@ -1,12 +0,0 @@ -var test = require("../../").test - -test(function (t) { - t.plan(1) - - t.on('end', function () { - console.log('end()') - throw new Error('beep') - }) - - t.equal(3, 3) -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/executed.sh b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/executed.sh deleted file mode 100755 index 7300937f7..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/executed.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh - -echo "1..1" -echo "ok 1 File with executable bit should be executed" diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/expose-gc-test.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/expose-gc-test.js deleted file mode 100644 index 87377c1fa..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/expose-gc-test.js +++ /dev/null @@ -1,46 +0,0 @@ -var tap = require("../") - , fs = require("fs") - , cp = require("child_process") - -fs.writeFileSync("gc-script.js", "console.log(!!global.gc)", "utf8") - -tap.test("gc test when the gc isn't there", function (t) { - console.error("gc test") - t.plan(1) - console.error("t.plan="+t._plan) - - cp.exec("../bin/tap.js ./gc-script", function (err, stdo, stde) { - console.error("assert gc does not exist") - t.ok("false", stdo) - }) -}) - -tap.test("gc test when the gc should be there", function (t) { - console.error("gc test") - t.plan(2) - console.error("t.plan="+t._plan) - - t.test("test for gc using --gc", function (t) { - console.error("gc test using --gc") - t.plan(1) - console.error("t.plan="+t._plan) - - cp.exec("../bin/tap.js --gc ./gc-script", function (err, stdo, stde) { - console.error("assert gc exists") - t.ok("true", stdo) - }) - }) - - t.test("test for gc using --expose-gc", function (t) { - console.error("gc test using --expose-gc") - t.plan(1) - console.error("t.plan="+t._plan) - - cp.exec("../bin/tap.js --expose-gc ./gc-script", function (err, stdo) { - console.error("assert gc exists") - t.ok("true", stdo) - }) - }) -}) - -fs.unlinkSync("gc-script.js"); diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/independent-timeouts.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/independent-timeouts.js deleted file mode 100644 index 5a35e61d7..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/independent-timeouts.js +++ /dev/null @@ -1,16 +0,0 @@ -// https://github.com/isaacs/node-tap/issues/23 - -var tap = require("../") - , test = tap.test - -test("finishes in time", {timeout: 500}, function(t) { - setTimeout(function () { - t.end(); - }, 300); -}) -test("finishes in time too", {timeout: 500}, function(t) { - setTimeout(function () { - t.end(); - }, 300); -}) - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/isolated-conf-test.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/isolated-conf-test.js deleted file mode 100644 index d8bfae6a7..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/isolated-conf-test.js +++ /dev/null @@ -1,16 +0,0 @@ -// https://github.com/isaacs/node-tap/issues/24 - -var tap = require("../") - , test = tap.test - -var config = {foo: "bar"} -test("one", config, function(t) { - t.equal(t.conf.foo, "bar") - t.equal(t.conf.name, "one") // before fix this would be "two" - t.end() -}) -test("two", config, function(t) { - t.equal(t.conf.foo, "bar") - t.equal(t.conf.name, "two") - t.end() -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/meta-test.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/meta-test.js deleted file mode 100644 index 8f56f265a..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/meta-test.js +++ /dev/null @@ -1,73 +0,0 @@ -var tap = require("../") - , test = tap.test - -test("meta test", { skip: false }, function (t) { - - function thr0w() { throw new Error('raburt') } - function noop () {} - - // this also tests the ok/notOk functions - t.once("end", section2) - t.ok(true, "true is ok") - t.ok(noop, "function is ok") - t.ok({}, "object is ok") - t.ok(t, "t is ok") - t.ok(100, "number is ok") - t.ok("asdf", "string is ok") - t.notOk(false, "false is notOk") - t.notOk(0, "0 is notOk") - t.notOk(null, "null is notOk") - t.notOk(undefined, "undefined is notOk") - t.notOk(NaN, "NaN is notOk") - t.notOk("", "empty string is notOk") - t.throws(thr0w, "Thrower throws"); - t.doesNotThrow(noop, "noop does not throw"); - t.similar({foo:"bar", bar:"foo"}, {foo:"bar"}, "similar objects are ok"); - t.dissimilar({}, {mandatory:"value"}, "dissimilar objects are ok"); - t.dissimilar(null, {}, "null is dissimilar from an object, even with no keys"); - - // a few failures. - t.ifError(new Error("this is an error")) - t.ifError({ message: "this is a custom error" }) - t.ok(false, "false is not ok") - t.notOk(true, "true is not not ok") - t.similar(null, {}, "Null is not similar to an object, even with no keys"); - t.throws(noop, "noop does not throw"); - t.throws(noop, new Error("Whoops!"), "noop does not throw an Error"); - t.throws(noop, {name:"MyError", message:"Whoops!"}, "noop does not throw a MyError"); - t.doesNotThrow(thr0w, "thrower does throw"); - - // things that are like other things - t.like("asdf", "asdf") - t.like("asdf", /^a.*f$/) - t.like(100, 100) - t.like(100, '100') - t.like(100, 100.0) - t.unlike("asdf", "fdsa") - t.unlike("asdf", /^you jelly, bro?/) - t.unlike(100, 100.1) - t.like(true, 1) - t.like(null, undefined) - t.like(true, [1]) - t.like(false, []) - t.like('', []) - t.end() - - function section2 () { - var results = t.results - t.clear() - t.ok(true, "sanity check") - t.notOk(results.ok, "not ok") - t.equal(results.tests, 39, "total test count") - t.equal(results.passTotal, 30, "tests passed") - t.equal(results.fail, 9, "tests failed") - t.type(results.ok, "boolean", "ok is boolean") - t.type(results.skip, "number", "skip is number") - t.type(results, "Results", "results isa Results") - t.type(t, "Test", "test isa Test") - t.type(t, "Harness", "test isa Harness") - t.end() - } -}) - - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/nested-test.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/nested-test.js deleted file mode 100644 index 493f13a13..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/nested-test.js +++ /dev/null @@ -1,23 +0,0 @@ -var tap = require("../"), - test = tap.test, - util = require('util'); - -test("parent", function (t) { - // TODO: Make grandchildren tests count? - t.plan(3); - t.ok(true, 'p test'); - t.test("subtest", function (t) { - t.ok(true, 'ch test'); - t.test('nested subtest', function(t) { - t.ok(true, 'grch test'); - t.end(); - }); - t.end(); - }); - t.test('another subtest', function(t) { - t.ok(true, 'ch test 2'); - t.end(); - }); - t.end(); -}) - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/non-tap-output.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/non-tap-output.js deleted file mode 100644 index 929e9aa87..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/non-tap-output.js +++ /dev/null @@ -1,12 +0,0 @@ -console.log("everything is fine\n" - +"there are no errors\n" - +"this output is not haiku.\n\n" - +"is 8 ok?\n" - +"ok, 8 can stay.\n" - +"ok 100 might be confusing\n" - +" but: nevertheless, here we are\n" - +" this: is indented\n" - +" and: it\n" - +" might: ~\n" - +" be: yaml?\n" - +"ok done now, exiting") diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/not-executed.sh b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/not-executed.sh deleted file mode 100644 index de46caa9d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/not-executed.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh - -echo "1..1" -echo "not ok 1 File without executable bit should not be run" diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/output-childtest-description.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/output-childtest-description.js deleted file mode 100644 index e025ba81f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/output-childtest-description.js +++ /dev/null @@ -1,50 +0,0 @@ -var tap = require("../") - , fs = require("fs") - , path = require('path') - , cp = require("child_process") - , nestedTests = - [ "var test = require('..').test" - , "test('parent test description', function (t) {" - , " t.plan(2)" - , " t.ok(true, 'test in parent')" - , " t.test('child test description', function (t) {" - , " t.plan(1)" - , " t.ok(true, 'test in child') " - , " })" - , "})" - ].join("\n") - , nestedTestsFile = path.join(__dirname, "nested-tests-fixture.js") - -fs.writeFileSync(nestedTestsFile, nestedTests, "utf8") -console.log(nestedTestsFile); - -tap.test("nested tests, parent and child pass", function (t) { - /* - * Ensure the output includes the following lines in the right order: - * '# parent test description' - * 'ok 1 test in parent' - * '# child test description' - * 'ok 2 test in child' - */ - - t.plan(5) - - cp.exec("node " + nestedTestsFile, function (err, stdo, stde) { - var lines = stdo.split("\n") - , parentDes = lines.indexOf("# parent test description") - , parentRes = lines.indexOf("ok 1 test in parent") - , childDes = lines.indexOf("# child test description") - , childRes = lines.indexOf("ok 2 test in child") - - t.notEqual(parentDes, -1, "outputs parent description") - t.notEqual(childDes, -1, "outputs child description") - - t.ok(parentDes < parentRes , "outputs parent description before parent result") - t.ok(parentRes < childDes , "outputs parent result before child description") - t.ok(childDes < childRes , "outputs child description before child result") - - fs.unlinkSync(nestedTestsFile); - t.end() - }) -}) - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/result-trap.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/result-trap.js deleted file mode 100644 index 1ac600f97..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/result-trap.js +++ /dev/null @@ -1,25 +0,0 @@ -var tap = require("../") - -tap.test("trap result #TODO", function (t0) { - - console.log("not ok 1 result event trapping #TODO") - return t0.end() - - t0.plan(3) - - var t1 = new(tap.Harness)(tap.Test).test() - - t1.plan(1) - - t1.on("result", function (res) { - if (res.wanted === 4) { - t0.equal(res.found, 3) - t0.equal(res.wanted, 4) - - t0.end() - t1.end() - } - }) - - t1.equal(1 + 2, 4) -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/segv.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/segv.js deleted file mode 100644 index cb2c3713f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/segv.js +++ /dev/null @@ -1,62 +0,0 @@ -var test = require('../').test -var Runner = require('../lib/tap-runner.js') -var TC = require('../lib/tap-consumer.js') - -var fs = require('fs') -var spawn = require('child_process').spawn -var segv = - 'int main (void) {\n' + - ' char *s = "hello world";\n' + - ' *s = \'H\';\n' + - '}\n' -var compiled = false - -test('setup', function (t) { - fs.writeFile('segv.c', segv, 'utf8', function (er) { - if (er) - throw er - var cp = spawn('gcc', ['segv.c', '-o', 'segv']) - cp.on('exit', function (code, sig) { - if (code !== 0) { - t.bailout('failed to compile segv program') - return - } - t.pass('compiled seg faulter') - t.end() - }) - }) -}) - -test('segv', function (t) { - var r = new Runner({argv:{remain:['./segv']}}) - var tc = new TC() - var expect = - [ 'TAP version 13' - , './segv' - , { 'id': 1, - 'ok': false, - 'name': ' ././segv', - 'exit': null, - 'timedOut': true, - 'signal': 'SIGBUS', - 'command': '"./segv"' } - , 'tests 1' - , 'fail 1' ] - r.pipe(tc) - tc.on('data', function (d) { - t.same(d, expect.shift()) - }) - tc.on('end', function () { - t.equal(expect.length, 0) - t.end() - }) -}) - -test('cleanup', function (t) { - fs.unlink('segv.c', function () { - fs.unlink('segv', function () { - t.pass('cleaned up') - t.end() - }) - }) -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/simple-harness-test-with-plan.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/simple-harness-test-with-plan.js deleted file mode 100644 index 813c4cf94..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/simple-harness-test-with-plan.js +++ /dev/null @@ -1,16 +0,0 @@ -var tap = require("../") - , test = tap.test - , plan = tap.plan - -plan(2) - -test("trivial success", function (t) { - t.ok(true, "it works") - t.end() -}) - -test("two tests", function (t) { - t.equal(255, 0xFF, "math should work") - t.notOk(false, "false should not be ok") - t.end() -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/simple-harness-test.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/simple-harness-test.js deleted file mode 100644 index 64451ae16..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/simple-harness-test.js +++ /dev/null @@ -1,13 +0,0 @@ -var tap = require("../") - , test = tap.test - -test("trivial success", function (t) { - t.ok(true, "it works") - t.end() -}) - -test("two tests", function (t) { - t.equal(255, 0xFF, "math should work") - t.notOk(false, "false should not be ok") - t.end() -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/test-test.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/test-test.js deleted file mode 100644 index f3839415e..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/test-test.js +++ /dev/null @@ -1,91 +0,0 @@ -var tap = require("../") - , test = tap.test - , Test = require("../lib/tap-test") - , Harness = require("../lib/tap-harness") - -test("testing the test object", function (t) { - - t.isa(t, Test, "test object should be instanceof Test") - t.isa(t, Harness, "test object should be instanceof Harness") - t.is(t._Test, Test, "test._Test should be the Test class") - - // now test all the methods. - ; [ "isNotDeepEqual" - , "equals" - , "inequivalent" - , "threw" - , "strictEqual" - , "emit" - , "fail" - , "strictEquals" - , "notLike" - , "dissimilar" - , "true" - , "assert" - , "is" - , "ok" - , "isEqual" - , "isDeeply" - , "deepEqual" - , "deepEquals" - , "pass" - , "length" - , "skip" - , "isNotEqual" - , "looseEquals" - , "false" - , "notDeeply" - , "ifErr" - , "hasFields" - , "isNotDeeply" - , "like" - , "similar" - , "notOk" - , "isDissimilar" - , "isEquivalent" - , "doesNotEqual" - , "isSimilar" - , "notDeepEqual" - , "type" - , "notok" - , "isInequivalent" - , "isNot" - , "same" - , "isInequal" - , "_endNice" - , "ifError" - , "iferror" - , "clear" - , "has" - , "not" - , "timeout" - , "notSimilar" - , "isUnlike" - , "notEquals" - , "unsimilar" - , "result" - , "doesNotThrow" - , "error" - , "constructor" - , "notEqual" - , "throws" - , "isLike" - , "isNotSimilar" - , "isNotEquivalent" - , "inequal" - , "notEquivalent" - , "isNotLike" - , "equivalent" - , "looseEqual" - , "equal" - , "unlike" - , "doesNotHave" - , "comment" - , "isa" - ].forEach(function (method) { - t.ok(t[method], "should have "+method+" method") - t.isa(t[method], "function", method+" method should be a function") - }) - t.end() -}) - diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/timeout.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/timeout.js deleted file mode 100644 index 4ee409cb0..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/timeout.js +++ /dev/null @@ -1,33 +0,0 @@ -var tap = require("../") - -tap.test("timeout test with plan only", function (t) { - console.error("timeout test") - t.plan(2) - console.error("t.plan="+t._plan) - setTimeout(function () { - console.error("a assert") - t.ok(true, "a") - }, 1000) - setTimeout(function () { - console.error("b assert") - t.ok(true, "b") - }, 1000) -}) - -tap.test("timeout test with plan and end", function (t) { - console.error("timeout test") - t.plan(2) - - var tc = 2 - console.error("t.plan="+t._plan) - setTimeout(function () { - console.error("a assert") - t.ok(true, "a") - if (-- tc === 0) t.end() - }, 1000) - setTimeout(function () { - console.error("b assert") - t.ok(true, "b") - if (-- tc === 0) t.end() - }, 1000) -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/undefined_indented.js b/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/undefined_indented.js deleted file mode 100644 index 98abe026b..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/node_modules/tap/test/undefined_indented.js +++ /dev/null @@ -1,27 +0,0 @@ -var tap = require("../") - -tap.test("consume yaml", function (t) { - t.plan(1) - - var s = - [ "not ok 1 beep boop" - , " ---" - , " stack:" - , " - rawr" - , " - dinosaurs" - , " ..." - ].join("\n") - , c = tap.createConsumer() - - c.on("data", function (res) { - t.same(res, { - id: 1 - , ok: false - , name: " beep boop" // <-- should perhaps .trim() this? - , stack: [ "rawr", "dinosaurs" ] - }) - t.end() - }) - c.write(s) - c.end() -}) diff --git a/node/node_modules/grunt/node_modules/nodeunit/nodelint.cfg b/node/node_modules/grunt/node_modules/nodeunit/nodelint.cfg deleted file mode 100644 index d6a3aadaf..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/nodelint.cfg +++ /dev/null @@ -1,7 +0,0 @@ -//See: http://www.jslint.com/lint.html#options -var options = { - //white: false, // if false, strict whitespace rules should be enforced. - indent: 4, - onevar: false, - vars: true // allow multiple var statement per function. -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/package.json b/node/node_modules/grunt/node_modules/nodeunit/package.json deleted file mode 100644 index d25e3fa2d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/package.json +++ /dev/null @@ -1,97 +0,0 @@ -{ - "name": "nodeunit", - "description": "Easy unit testing for node.js and the browser.", - "maintainers": [ - { - "name": "Caolan McMahon", - "url": "https://github.com/caolan" - } - ], - "contributors": [ - { - "name": "Romain Beauxis", - "url": "https://github.com/toots" - }, - { - "name": "Alex Gorbatchev", - "url": "https://github.com/alexgorbatchev" - }, - { - "name": "Alex Wolfe", - "url": "https://github.com/alexkwolfe" - }, - { - "name": "Carl Fürstenberg", - "url": "https://github.com/azatoth" - }, - { - "name": "Gerad Suyderhoud", - "url": "https://github.com/gerad" - }, - { - "name": "Kadir Pekel", - "url": "https://github.com/coffeemate" - }, - { - "name": "Oleg Efimov", - "url": "https://github.com/Sannis" - }, - { - "name": "Orlando Vazquez", - "url": "https://github.com/orlandov" - }, - { - "name": "Ryan Dahl", - "url": "https://github.com/ry" - }, - { - "name": "Sam Stephenson", - "url": "https://github.com/sstephenson" - }, - { - "name": "Thomas Mayfield", - "url": "https://github.com/thegreatape" - }, - { - "name": "Elijah Insua", - "email": "tmpvar@gmail.com", - "url": "http://tmpvar.com" - } - ], - "version": "0.7.4", - "repository": { - "type": "git", - "url": "http://github.com/caolan/nodeunit.git" - }, - "devDependencies": { - "uglify-js": ">=1.1.0", - "should": ">=0.4.2" - }, - "bugs": { - "url": "http://github.com/caolan/nodeunit/issues" - }, - "licenses": [ - { - "type": "MIT", - "url": "http://github.com/caolan/nodeunit/raw/master/LICENSE" - } - ], - "directories": { - "lib": "./lib", - "doc": "./doc", - "man": "./man1" - }, - "bin": { - "nodeunit": "./bin/nodeunit" - }, - "dependencies": { - "tap": ">=0.2.3" - }, - "man": [ - "/home/jack/.npm/nodeunit/0.7.4/package/man1/nodeunit.1" - ], - "readme": "Nodeunit\n========\n\nSimple syntax, powerful tools. Nodeunit provides easy async unit testing for\nnode.js and the browser.\n\n* Simple to use\n* Just export the tests from a module\n* Works with node.js and in the browser.\n* Helps you avoid common pitfalls when testing asynchronous code\n* Easy to add test cases with setUp and tearDown functions if you wish\n* Flexible reporters for custom output, built-in support for HTML and jUnit XML\n* Allows the use of mocks and stubs\n\n__Contributors__\n\n* [alexgorbatchev](https://github.com/alexgorbatchev)\n* [alexkwolfe](https://github.com/alexkwolfe)\n* [azatoth](https://github.com/azatoth)\n* [kadirpekel](https://github.com/kadirpekel)\n* [lambdalisue](https://github.com/lambdalisue)\n* [luebken](https://github.com/luebken)\n* [orlandov](https://github.com/orlandov)\n* [Sannis](https://github.com/Sannis)\n* [sstephenson](https://github.com/sstephenson)\n* [thegreatape](https://github.com/thegreatape)\n* [mmalecki](https://github.com/mmalecki)\n* and thanks to [cjohansen](https://github.com/cjohansen) for input and advice\n on implementing setUp and tearDown functions. See\n [cjohansen's fork](https://github.com/cjohansen/nodeunit).\n\nAlso, check out gerad's [nodeunit-dsl](https://github.com/gerad/nodeunit-dsl)\nproject, which implements a 'pretty dsl on top of nodeunit'.\n\nMore contributor information can be found in the\n[CONTRIBUTORS.md](https://github.com/caolan/nodeunit/blob/master/CONTRIBUTORS.md)\nfile.\n\nUsage\n-----\n\nHere is an example unit test module:\n\n exports.testSomething = function(test){\n test.expect(1);\n test.ok(true, \"this assertion should pass\");\n test.done();\n };\n\n exports.testSomethingElse = function(test){\n test.ok(false, \"this assertion should fail\");\n test.done();\n };\n\nWhen run using the included test runner, this will output the following:\n\n\n\nInstallation\n------------\n\nThere are two options for installing nodeunit:\n\n1. Clone / download nodeunit from [github](https://github.com/caolan/nodeunit),\n then:\n\n make && sudo make install\n\n2. Install via npm:\n\n npm install nodeunit\n\nAPI Documentation\n-----------------\n\nNodeunit uses the functions available in the node.js\n[assert module](http://nodejs.org/docs/v0.4.2/api/assert.html):\n\n* __ok(value, [message])__ - Tests if value is a true value.\n* __equal(actual, expected, [message])__ - Tests shallow, coercive equality\n with the equal comparison operator ( == ).\n* __notEqual(actual, expected, [message])__ - Tests shallow, coercive\n non-equality with the not equal comparison operator ( != ).\n* __deepEqual(actual, expected, [message])__ - Tests for deep equality.\n* __notDeepEqual(actual, expected, [message])__ - Tests for any deep\n inequality.\n* __strictEqual(actual, expected, [message])__ - Tests strict equality, as\n determined by the strict equality operator ( === )\n* __notStrictEqual(actual, expected, [message])__ - Tests strict non-equality,\n as determined by the strict not equal operator ( !== )\n* __throws(block, [error], [message])__ - Expects block to throw an error.\n* __doesNotThrow(block, [error], [message])__ - Expects block not to throw an\n error.\n* __ifError(value)__ - Tests if value is not a false value, throws if it is a\n true value. Useful when testing the first argument, error in callbacks.\n\nNodeunit also provides the following functions within tests:\n\n* __expect(amount)__ - Specify how many assertions are expected to run within a\n test. Very useful for ensuring that all your callbacks and assertions are\n run.\n* __done()__ - Finish the current test function, and move on to the next. ALL\n tests should call this!\n\nNodeunit aims to be simple and easy to learn. This is achieved through using\nexisting structures (such as node.js modules) to maximum effect, and reducing\nthe API where possible, to make it easier to digest.\n\nTests are simply exported from a module, but they are still run in the order\nthey are defined.\n\n__Note:__ Users of old nodeunit versions may remember using ok, equals and same\nin the style of qunit, instead of the assert functions above. These functions\nstill exist for backwards compatibility, and are simply aliases to their assert\nmodule counterparts.\n\n\nAsynchronous Testing\n--------------------\n\nWhen testing asynchronous code, there are a number of sharp edges to watch out\nfor. Thankfully, nodeunit is designed to help you avoid as many of these\npitfalls as possible. For the most part, testing asynchronous code in nodeunit\n_just works_.\n\n\n### Tests run in series\n\nWhile running tests in parallel seems like a good idea for speeding up your\ntest suite, in practice I've found it means writing much more complicated\ntests. Because of node's module cache, running tests in parallel means mocking\nand stubbing is pretty much impossible. One of the nicest things about testing\nin javascript is the ease of doing stubs:\n\n var _readFile = fs.readFile;\n fs.readFile = function(path, callback){\n // its a stub!\n };\n // test function that uses fs.readFile\n\n // we're done\n fs.readFile = _readFile;\n\nYou cannot do this when running tests in parallel. In order to keep testing as\nsimple as possible, nodeunit avoids it. Thankfully, most unit-test suites run\nfast anyway.\n\n\n### Explicit ending of tests\n\nWhen testing async code its important that tests end at the correct point, not\njust after a given number of assertions. Otherwise your tests can run short,\nending before all assertions have completed. Its important to detect too\nmany assertions as well as too few. Combining explicit ending of tests with\nan expected number of assertions helps to avoid false test passes, so be sure\nto use the test.expect() method at the start of your test functions, and\ntest.done() when finished.\n\n\nGroups, setUp and tearDown\n--------------------------\n\nNodeunit allows the nesting of test functions:\n\n exports.test1 = function (test) {\n ...\n }\n\n exports.group = {\n test2: function (test) {\n ...\n },\n test3: function (test) {\n ...\n }\n }\n\nThis would be run as:\n\n test1\n group - test2\n group - test3\n\nUsing these groups, Nodeunit allows you to define a `setUp` function, which is\nrun before each test, and a `tearDown` function, which is run after each test\ncalls `test.done()`:\n\n module.exports = {\n setUp: function (callback) {\n this.foo = 'bar';\n callback();\n },\n tearDown: function (callback) {\n // clean up\n callback();\n },\n test1: function (test) {\n test.equals(this.foo, 'bar');\n test.done();\n }\n };\n\nIn this way, its possible to have multiple groups of tests in a module, each\ngroup with its own setUp and tearDown functions.\n\n\nRunning Tests\n-------------\n\nNodeunit comes with a basic command-line test runner, which can be installed\nusing 'sudo make install'. Example usage:\n\n nodeunit testmodule1.js testfolder [...]\n\nThe default test reporter uses color output, because I think that's more fun :) I\nintend to add a no-color option in future. To give you a feeling of the fun you'll\nbe having writing tests, lets fix the example at the start of the README:\n\n\n\nAhhh, Doesn't that feel better?\n\nWhen using the included test runner, it will exit using the failed number of\nassertions as the exit code. Exiting with 0 when all tests pass.\n\n\n### Command-line Options\n\n* __--reporter FILE__ - you can set the test reporter to a custom module or\non of the modules in nodeunit/lib/reporters, when omitted, the default test runner\nis used.\n* __--list-reporters__ - list available build-in reporters.\n* __--config FILE__ - load config options from a JSON file, allows\nthe customisation of color schemes for the default test reporter etc. See\nbin/nodeunit.json for current available options.\n* __--version__ or __-v__ - report nodeunit version\n* __--help__ - show nodeunit help\n\n\nRunning tests in the browser\n----------------------------\n\nNodeunit tests can also be run inside the browser. For example usage, see\nthe examples/browser folder. The basic syntax is as follows:\n\n__test.html__\n\n \n \n Example Test Suite\n \n \n \n \n \n \n

        Example Test Suite

        \n \n \n \n\nHere, suite1 and suite2 are just object literals containing test functions or\ngroups, as would be returned if you did require('test-suite') in node.js:\n\n__suite1.js__\n\n this.suite1 = {\n 'example test': function (test) {\n test.ok(true, 'everything is ok');\n test.done();\n }\n };\n\nIf you wish to use a commonjs format for your test suites (using exports), it is\nup to you to define the commonjs tools for the browser. There are a number of\nalternatives and its important it fits with your existing code, which is\nwhy nodeunit does not currently provide this out of the box.\n\nIn the example above, the tests will run when the page is loaded.\n\nThe browser-version of nodeunit.js is created in dist/browser when you do, 'make\nbrowser'. You'll need [UglifyJS](https://github.com/mishoo/UglifyJS) installed in\norder for it to automatically create nodeunit.min.js.\n\n\nAdding nodeunit to Your Projects\n--------------------------------\n\nIf you don't want people to have to install the nodeunit command-line tool,\nyou'll want to create a script that runs the tests for your project with the\ncorrect require paths set up. Here's an example test script, that assumes you\nhave nodeunit in a suitably located node_modules directory.\n\n #!/usr/bin/env node\n var reporter = require('nodeunit').reporters.default;\n reporter.run(['test']);\n\nIf you're using git, you might find it useful to include nodeunit as a\nsubmodule. Using submodules makes it easy for developers to download nodeunit\nand run your test suite, without cluttering up your repository with\nthe source code. To add nodeunit as a git submodule do the following:\n\n git submodule add git://github.com/caolan/nodeunit.git node_modules/nodeunit\n\nThis will add nodeunit to the node_modules folder of your project. Now, when\ncloning the repository, nodeunit can be downloaded by doing the following:\n\n git submodule init\n git submodule update\n\nLet's update the test script above with a helpful hint on how to get nodeunit,\nif its missing:\n\n #!/usr/bin/env node\n try {\n var reporter = require('nodeunit').reporters.default;\n }\n catch(e) {\n console.log(\"Cannot find nodeunit module.\");\n console.log(\"You can download submodules for this project by doing:\");\n console.log(\"\");\n console.log(\" git submodule init\");\n console.log(\" git submodule update\");\n console.log(\"\");\n process.exit();\n }\n\n process.chdir(__dirname);\n reporter.run(['test']);\n\nNow if someone attempts to run your test suite without nodeunit installed they\nwill be prompted to download the submodules for your project.\n\n\nBuilt-in Test Reporters\n-----------------------\n\n* __default__ - The standard reporter seen in the nodeunit screenshots\n* __minimal__ - Pretty, minimal output, shows errors and progress only\n* __html__ - Outputs a HTML report to stdout\n* __junit__ - Creates jUnit compatible XML reports, which can be used with\n continuous integration tools such as [Hudson](http://hudson-ci.org/).\n* __machineout__ - Simple reporter for machine analysis. There is [nodeunit.vim](https://github.com/lambdalisue/nodeunit.vim)\n which is useful for TDD on VIM\n\n\nWriting a Test Reporter\n---------------------\n\nNodeunit exports runTest(fn, options), runModule(mod, options) and\nrunFiles(paths, options). You'll most likely want to run test suites from\nfiles, which can be done using the latter function. The _options_ argument can\ncontain callbacks which run during testing. Nodeunit provides the following\ncallbacks:\n\n* __moduleStart(name)__ - called before a module is tested\n* __moduleDone(name, assertions)__ - called once all test functions within the\n module have completed (see assertions object reference below)\n ALL tests within the module\n* __testStart(name)__ - called before a test function is run\n* __testDone(name, assertions)__ - called once a test function has completed\n (by calling test.done())\n* __log(assertion)__ - called whenever an assertion is made (see assertion\n object reference below)\n* __done(assertions)__ - called after all tests/modules are complete\n\nThe __assertion__ object:\n\n* __passed()__ - did the assertion pass?\n* __failed()__ - did the assertion fail?\n* __error__ - the AssertionError if the assertion failed\n* __method__ - the nodeunit assertion method used (ok, same, equals...)\n* __message__ - the message the assertion method was called with (optional)\n\nThe __assertionList__ object:\n\n* An array-like object with the following new attributes:\n * __failures()__ - the number of assertions which failed\n * __duration__ - the time taken for the test to complete in msecs\n\nFor a reference implementation of a test reporter, see lib/reporters/default.js in\nthe nodeunit project directory.\n\n\nSandbox utility\n---------------\n\nThis is a function which evaluates JavaScript files in a sandbox and returns the\ncontext. The sandbox function can be used for testing client-side code or private\nun-exported functions within a module.\n\n var sandbox = require('nodeunit').utils.sandbox;\n var example = sandbox('example.js');\n\n__sandbox(files, sandbox)__ - Evaluates JavaScript files in a sandbox, returning\nthe context. The first argument can either be a single filename or an array of\nfilenames. If multiple filenames are given their contents are concatenated before\nevalution. The second argument is an optional context to use for the sandbox.\n\n\nRunning the nodeunit Tests\n--------------------------\n\nThe tests for nodeunit are written using nodeunit itself as the test framework.\nHowever, the module test-base.js first does some basic tests using the assert\nmodule to ensure that test functions are actually run, and a basic level of\nnodeunit functionality is available.\n\nTo run the nodeunit tests do:\n\n make test\n\n__Note:__ There was a bug in node v0.2.0 causing the tests to hang, upgrading\nto v0.2.1 fixes this.\n\n\n__machineout__ reporter\n----------------------------------------------\n\nThe default reporter is really readable for human but for machinally analysis. \nWhen you want to analyze the output of nodeunit, use __machineout__ reporter and you will get\n\n\n\n\nnodeunit with vim\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nThere is [nodeunit.vim](https://github.com/lambdalisue/nodeunit.vim) so you can use nodeunit with VIM.\nThat compiler use __machineout__ reporter and it is useful to use with [vim-makegreen](https://github.com/reinh/vim-makegreen)\n\n \n\nContributing\n------------\n\nContributions to the project are most welcome, so feel free to fork and improve.\nWhen submitting a pull request, please run 'make lint' first to ensure\nwe're following a consistent coding style.\n", - "readmeFilename": "README.md", - "_id": "nodeunit@0.7.4", - "_from": "nodeunit@~0.7.4" -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/share/junit.xml.ejs b/node/node_modules/grunt/node_modules/nodeunit/share/junit.xml.ejs deleted file mode 100644 index c1db5bbec..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/share/junit.xml.ejs +++ /dev/null @@ -1,19 +0,0 @@ - -<% for (var i=0; i < suites.length; i++) { %> - <% var suite=suites[i]; %> - - <% for (var j=0; j < suite.testcases.length; j++) { %> - <% var testcase=suites[i].testcases[j]; %> - - <% if (testcase.failure) { %> - - <% if (testcase.failure.backtrace) { %><%= testcase.failure.backtrace %><% } %> - - <% } %> - - <% } %> - -<% } %> diff --git a/node/node_modules/grunt/node_modules/nodeunit/share/license.js b/node/node_modules/grunt/node_modules/nodeunit/share/license.js deleted file mode 100644 index f0f326f33..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/share/license.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * Nodeunit - * https://github.com/caolan/nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * json2.js - * http://www.JSON.org/json2.js - * Public Domain. - * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - */ diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/coffee/mock_coffee_module.coffee b/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/coffee/mock_coffee_module.coffee deleted file mode 100644 index a1c069b57..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/coffee/mock_coffee_module.coffee +++ /dev/null @@ -1,4 +0,0 @@ -j = 0 -j += i for i in [0..5] - -exports.name = "mock_coffee_#{j}" diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/dir/mock_module3.js b/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/dir/mock_module3.js deleted file mode 100644 index 3021776c8..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/dir/mock_module3.js +++ /dev/null @@ -1 +0,0 @@ -exports.name = 'mock_module3'; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/dir/mock_module4.js b/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/dir/mock_module4.js deleted file mode 100644 index 876f9ca07..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/dir/mock_module4.js +++ /dev/null @@ -1 +0,0 @@ -exports.name = 'mock_module4'; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/mock_module1.js b/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/mock_module1.js deleted file mode 100644 index 4c093ad16..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/mock_module1.js +++ /dev/null @@ -1 +0,0 @@ -exports.name = 'mock_module1'; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/mock_module2.js b/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/mock_module2.js deleted file mode 100644 index a63d01226..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/mock_module2.js +++ /dev/null @@ -1 +0,0 @@ -exports.name = 'mock_module2'; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/raw_jscode1.js b/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/raw_jscode1.js deleted file mode 100644 index 2ef711524..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/raw_jscode1.js +++ /dev/null @@ -1,3 +0,0 @@ -function hello_world(arg) { - return "_" + arg + "_"; -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/raw_jscode2.js b/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/raw_jscode2.js deleted file mode 100644 index 55a764ef6..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/raw_jscode2.js +++ /dev/null @@ -1,3 +0,0 @@ -function get_a_variable() { - return typeof a_variable; -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/raw_jscode3.js b/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/raw_jscode3.js deleted file mode 100644 index 1fd1e7889..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/fixtures/raw_jscode3.js +++ /dev/null @@ -1 +0,0 @@ -var t=t?t+1:1; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/test-base.js b/node/node_modules/grunt/node_modules/nodeunit/test/test-base.js deleted file mode 100644 index 533504610..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/test-base.js +++ /dev/null @@ -1,239 +0,0 @@ -/* - * This module is not a plain nodeunit test suite, but instead uses the - * assert module to ensure a basic level of functionality is present, - * allowing the rest of the tests to be written using nodeunit itself. - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var assert = require('assert'), // @REMOVE_LINE_FOR_BROWSER - async = require('../deps/async'), // @REMOVE_LINE_FOR_BROWSER - nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER - - -// NOT A TEST - util function to make testing faster. -// retries the assertion until it passes or the timeout is reached, -// at which point it throws the assertion error -var waitFor = function (fn, timeout, callback, start) { - start = start || new Date().getTime(); - callback = callback || function () {}; - try { - fn(); - callback(); - } - catch (e) { - if (e instanceof assert.AssertionError) { - var now = new Date().getTime(); - if (now - start >= timeout) { - throw e; - } - else { - async.nextTick(function () { - waitFor(fn, timeout, callback, start); - }); - } - } - else { - throw e; - } - } -}; - - -// TESTS: - -// Are exported tests actually run? - store completed tests in this variable -// for checking later -var tests_called = {}; - -// most basic test that should run, the tests_called object is tested -// at the end of this module to ensure the tests were actually run by nodeunit -exports.testCalled = function (test) { - tests_called.testCalled = true; - test.done(); -}; - -// generates test functions for nodeunit assertions -var makeTest = function (method, args_pass, args_fail) { - return function (test) { - var test1_called = false; - var test2_called = false; - - // test pass - nodeunit.runTest( - 'testname', - function (test) { - test[method].apply(test, args_pass); - test.done(); - }, - {testDone: function (name, assertions) { - assert.equal(assertions.length, 1); - assert.equal(assertions.failures(), 0); - }}, - function () { - test1_called = true; - } - ); - - // test failure - nodeunit.runTest( - 'testname', - function (test) { - test[method].apply(test, args_fail); - test.done(); - }, - {testDone: function (name, assertions) { - assert.equal(assertions.length, 1); - assert.equal(assertions.failures(), 1); - }}, - function () { - test2_called = true; - } - ); - - // ensure tests were run - waitFor(function () { - assert.ok(test1_called); - assert.ok(test2_called); - tests_called[method] = true; - }, 500, test.done); - }; -}; - -// ensure basic assertions are working: -exports.testOk = makeTest('ok', [true], [false]); -exports.testEquals = makeTest('equals', [1, 1], [1, 2]); -exports.testSame = makeTest('same', - [{test: 'test'}, {test: 'test'}], - [{test: 'test'}, {monkey: 'penguin'}] -); - -// from the assert module: -exports.testEqual = makeTest('equal', [1, 1], [1, 2]); -exports.testNotEqual = makeTest('notEqual', [1, 2], [1, 1]); -exports.testDeepEqual = makeTest('deepEqual', - [{one: 1}, {one: 1}], [{one: 1}, {two: 2}] -); -exports.testNotDeepEqual = makeTest('notDeepEqual', - [{one: 1}, {two: 2}], [{one: 1}, {one: 1}] -); -exports.testStrictEqual = makeTest('strictEqual', [1, 1], [1, true]); -exports.testNotStrictEqual = makeTest('notStrictEqual', [true, 1], [1, 1]); -exports.testThrows = makeTest('throws', - [function () { - throw new Error('test'); - }], - [function () { - return; - }] -); -exports.testThrowsWithReGex = makeTest('throws', - [function () { - throw new Error('test'); - }, /test/], - [function () { - throw new Error('test'); - }, /fail/] -); -exports.testThrowsWithErrorValidation = makeTest('throws', - [function () { - throw new Error('test'); - }, function(err) { - return true; - }], - [function () { - throw new Error('test'); - }, function(err) { - return false; - }] -); -exports.testDoesNotThrows = makeTest('doesNotThrow', - [function () { - return; - }], - [function () { - throw new Error('test'); - }] -); -exports.testIfError = makeTest('ifError', [false], [new Error('test')]); - - -exports.testExpect = function (test) { - var test1_called = false, - test2_called = false, - test3_called = false; - - // correct number of tests run - nodeunit.runTest( - 'testname', - function (test) { - test.expect(2); - test.ok(true); - test.ok(true); - test.done(); - }, - {testDone: function (name, assertions) { - test.equals(assertions.length, 2); - test.equals(assertions.failures(), 0); - }}, - function () { - test1_called = true; - } - ); - - // no tests run - nodeunit.runTest( - 'testname', - function (test) { - test.expect(2); - test.done(); - }, - {testDone: function (name, assertions) { - test.equals(assertions.length, 1); - test.equals(assertions.failures(), 1); - }}, - function () { - test2_called = true; - } - ); - - // incorrect number of tests run - nodeunit.runTest( - 'testname', - function (test) { - test.expect(2); - test.ok(true); - test.ok(true); - test.ok(true); - test.done(); - }, - {testDone: function (name, assertions) { - test.equals(assertions.length, 4); - test.equals(assertions.failures(), 1); - }}, - function () { - test3_called = true; - } - ); - - // ensure callbacks fired - waitFor(function () { - assert.ok(test1_called); - assert.ok(test2_called); - assert.ok(test3_called); - tests_called.expect = true; - }, 1000, test.done); -}; - - -// tests are async, so wait for them to be called -waitFor(function () { - assert.ok(tests_called.testCalled); - assert.ok(tests_called.ok); - assert.ok(tests_called.equals); - assert.ok(tests_called.same); - assert.ok(tests_called.expect); -}, 10000); diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/test-bettererrors.js b/node/node_modules/grunt/node_modules/nodeunit/test/test-bettererrors.js deleted file mode 100644 index d20ca246d..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/test-bettererrors.js +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Test utils.betterErrors. utils.betterErrors should provide sensible error messages even when the error does not - * contain expected, actual or operator. - */ -var assert = require("../lib/assert"); -var should = require("should"); -var types = require("../lib/types"); -var util = require('util'); -var utils = require("../lib/utils"); - -function betterErrorStringFromError(error) { - var assertion = types.assertion({error: error}); - var better = utils.betterErrors(assertion); - return better.error.stack.toString(); -} - -function performBasicChecks(betterErrorString) { - betterErrorString.should.include("AssertionError"); - betterErrorString.should.include("test-bettererrors"); - betterErrorString.should.not.include("undefined"); -} - -/** - * Control test. Provide an AssertionError that contains actual, expected operator values. - * @param test the test object from nodeunit - */ -exports.testEqual = function (test) { - try { - assert.equal(true, false); - } catch (error) { - var betterErrorString = betterErrorStringFromError(error); - performBasicChecks(betterErrorString); - betterErrorString.should.include("true"); - betterErrorString.should.include("false"); - betterErrorString.should.include("=="); - test.done(); - } -}; - -/** - * Test an AssertionError that does not contain actual, expected or operator values. - * @param test the test object from nodeunit - */ -exports.testAssertThrows = function (test) { - try { - assert.throws(function () { - }); - } catch (error) { - var betterErrorString = betterErrorStringFromError(error); - performBasicChecks(betterErrorString); - test.done(); - } -}; - -/** - * Test with an error that is not an AssertionError. - * @param test the test object from nodeunit - */ -exports.testNonAssertionError = function (test) { - try { - throw new Error("test error"); - } catch (error) { - var betterErrorString = betterErrorStringFromError(error); - betterErrorString.should.not.include("AssertionError"); - betterErrorString.should.include("Error"); - betterErrorString.should.include("test error"); - betterErrorString.should.include("test-bettererrors"); - betterErrorString.should.not.include("undefined"); - test.done(); - } -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/test-failing-callbacks.js b/node/node_modules/grunt/node_modules/nodeunit/test/test-failing-callbacks.js deleted file mode 100644 index 08f7eb585..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/test-failing-callbacks.js +++ /dev/null @@ -1,114 +0,0 @@ -var nodeunit = require('../lib/nodeunit'); - - -exports.testFailingLog = function (test) { - test.expect(3); - - // this is meant to bubble to the top, and will be ignored for the purposes - // of testing: - var ignored_error = new Error('ignore this callback error'); - var err_handler = function (err) { - if (err && err.message !== ignored_error.message) { - throw err; - } - }; - process.addListener('uncaughtException', err_handler); - - // A failing callback should not affect the test outcome - var testfn = function (test) { - test.ok(true, 'test.ok'); - test.done(); - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.ok(true, 'log called'); - throw ignored_error; - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 1, 'total'); - process.removeListener('uncaughtException', err_handler); - } - }, test.done); -}; - -exports.testFailingTestDone = function (test) { - test.expect(2); - - var ignored_error = new Error('ignore this callback error'); - var err_handler = function (err) { - if (err && err.message !== ignored_error.message) { - throw err; - } - }; - process.addListener('uncaughtException', err_handler); - - // A failing callback should not affect the test outcome - var testfn = function (test) { - test.done(); - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.ok(false, 'log should not be called'); - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 0, 'total'); - process.nextTick(function () { - process.removeListener('uncaughtException', err_handler); - test.done(); - }); - throw ignored_error; - } - }, function () {}); -}; - -exports.testAssertionObj = function (test) { - test.expect(4); - var testfn = function (test) { - test.ok(true, 'ok true'); - test.done(); - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.ok(assertion.passed() === true, 'assertion.passed'); - test.ok(assertion.failed() === false, 'assertion.failed'); - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 1, 'total'); - } - }, test.done); -}; - -exports.testLogOptional = function (test) { - test.expect(2); - var testfn = function (test) { - test.ok(true, 'ok true'); - test.done(); - }; - nodeunit.runTest('testname', testfn, { - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 1, 'total'); - } - }, test.done); -}; - -exports.testExpectWithFailure = function (test) { - test.expect(3); - var testfn = function (test) { - test.expect(1); - test.ok(false, 'test.ok'); - test.done(); - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.equals(assertion.method, 'ok', 'assertion.method'); - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 1, 'failures'); - test.equals(assertions.length, 1, 'total'); - } - }, test.done); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/test-httputil.js b/node/node_modules/grunt/node_modules/nodeunit/test/test-httputil.js deleted file mode 100644 index e5ee25c64..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/test-httputil.js +++ /dev/null @@ -1,55 +0,0 @@ -var nodeunit = require('../lib/nodeunit'); -var httputil = require('../lib/utils').httputil; - -exports.testHttpUtilBasics = function (test) { - - test.expect(6); - - httputil(function (req, resp) { - test.equal(req.method, 'PUT'); - test.equal(req.url, '/newpair'); - test.equal(req.headers.foo, 'bar'); - - resp.writeHead(500, {'content-type': 'text/plain'}); - resp.end('failed'); - }, function (server, client) { - client.fetch('PUT', '/newpair', {'foo': 'bar'}, function (resp) { - test.equal(resp.statusCode, 500); - test.equal(resp.headers['content-type'], 'text/plain'); - test.equal(resp.body, 'failed'); - - server.close(); - test.done(); - }); - }); -}; - -exports.testHttpUtilJsonHandling = function (test) { - - test.expect(9); - - httputil(function (req, resp) { - test.equal(req.method, 'GET'); - test.equal(req.url, '/'); - test.equal(req.headers.foo, 'bar'); - - var testdata = {foo1: 'bar', foo2: 'baz'}; - - resp.writeHead(200, {'content-type': 'application/json'}); - resp.end(JSON.stringify(testdata)); - - }, function (server, client) { - client.fetch('GET', '/', {'foo': 'bar'}, function (resp) { - test.equal(resp.statusCode, 200); - test.equal(resp.headers['content-type'], 'application/json'); - - test.ok(resp.bodyAsObject); - test.equal(typeof resp.bodyAsObject, 'object'); - test.equal(resp.bodyAsObject.foo1, 'bar'); - test.equal(resp.bodyAsObject.foo2, 'baz'); - - server.close(); - test.done(); - }); - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/test-runfiles.js b/node/node_modules/grunt/node_modules/nodeunit/test/test-runfiles.js deleted file mode 100644 index ce1a4cd00..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/test-runfiles.js +++ /dev/null @@ -1,214 +0,0 @@ -var assert = require('assert'), - fs = require('fs'), - path = require('path'), - nodeunit = require('../lib/nodeunit'); - - -var setup = function (fn) { - return function (test) { - process.chdir(__dirname); - var env = { - mock_module1: require(__dirname + '/fixtures/mock_module1'), - mock_module2: require(__dirname + '/fixtures/mock_module2'), - mock_module3: require(__dirname + '/fixtures/dir/mock_module3'), - mock_module4: require(__dirname + '/fixtures/dir/mock_module4') - }; - fn.call(env, test); - }; -}; - - -exports.testRunFiles = setup(function (test) { - test.expect(24); - var runModule_copy = nodeunit.runModule; - - var runModule_calls = []; - var modules = []; - - var opts = { - moduleStart: function () { - return 'moduleStart'; - }, - testDone: function () { - return 'testDone'; - }, - testStart: function () { - return 'testStart'; - }, - log: function () { - return 'log'; - }, - done: function (assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 4, 'length'); - test.ok(typeof assertions.duration === "number"); - - var called_with = function (name) { - return runModule_calls.some(function (m) { - return m.name === name; - }); - }; - test.ok(called_with('mock_module1'), 'mock_module1 ran'); - test.ok(called_with('mock_module2'), 'mock_module2 ran'); - test.ok(called_with('mock_module3'), 'mock_module3 ran'); - test.ok(called_with('mock_module4'), 'mock_module4 ran'); - test.equals(runModule_calls.length, 4); - - nodeunit.runModule = runModule_copy; - test.done(); - } - }; - - nodeunit.runModule = function (name, mod, options, callback) { - test.equals(options.testDone, opts.testDone); - test.equals(options.testStart, opts.testStart); - test.equals(options.log, opts.log); - test.ok(typeof name === "string"); - runModule_calls.push(mod); - var m = [{failed: function () { - return false; - }}]; - modules.push(m); - callback(null, m); - }; - - nodeunit.runFiles( - [__dirname + '/fixtures/mock_module1.js', - __dirname + '/fixtures/mock_module2.js', - __dirname + '/fixtures/dir'], - opts - ); -}); - -exports.testRunFilesEmpty = function (test) { - test.expect(3); - nodeunit.runFiles([], { - moduleStart: function () { - test.ok(false, 'should not be called'); - }, - testDone: function () { - test.ok(false, 'should not be called'); - }, - testStart: function () { - test.ok(false, 'should not be called'); - }, - log: function () { - test.ok(false, 'should not be called'); - }, - done: function (assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 0, 'length'); - test.ok(typeof assertions.duration === "number"); - test.done(); - } - }); -}; - - -exports.testEmptyDir = function (test) { - var dir2 = __dirname + '/fixtures/dir2'; - - // git doesn't like empty directories, so we have to create one - path.exists(dir2, function (exists) { - if (!exists) { - fs.mkdirSync(dir2, 0777); - } - - // runFiles on empty directory: - nodeunit.runFiles([dir2], { - moduleStart: function () { - test.ok(false, 'should not be called'); - }, - testDone: function () { - test.ok(false, 'should not be called'); - }, - testStart: function () { - test.ok(false, 'should not be called'); - }, - log: function () { - test.ok(false, 'should not be called'); - }, - done: function (assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 0, 'length'); - test.ok(typeof assertions.duration === "number"); - test.done(); - } - }); - }); -}; - - -var CoffeeScript; -try { - CoffeeScript = require('coffee-script'); -} catch (e) { -} - -if (CoffeeScript) { - exports.testCoffeeScript = function (test) { - process.chdir(__dirname); - var env = { - mock_coffee_module: require(__dirname + - '/fixtures/coffee/mock_coffee_module') - }; - - test.expect(9); - var runModule_copy = nodeunit.runModule; - - var runModule_calls = []; - var modules = []; - - var opts = { - moduleStart: function () { - return 'moduleStart'; - }, - testDone: function () { - return 'testDone'; - }, - testStart: function () { - return 'testStart'; - }, - log: function () { - return 'log'; - }, - done: function (assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 1, 'length'); - test.ok(typeof assertions.duration === "number"); - - var called_with = function (name) { - return runModule_calls.some(function (m) { - return m.name === name; - }); - }; - test.ok( - called_with('mock_coffee_15'), - 'mock_coffee_module ran' - ); - test.equals(runModule_calls.length, 1); - - nodeunit.runModule = runModule_copy; - test.done(); - } - }; - - nodeunit.runModule = function (name, mod, options, callback) { - test.equals(options.testDone, opts.testDone); - test.equals(options.testStart, opts.testStart); - test.equals(options.log, opts.log); - test.ok(typeof name === "string"); - runModule_calls.push(mod); - var m = [{failed: function () { - return false; - }}]; - modules.push(m); - callback(null, m); - }; - - nodeunit.runFiles( - [__dirname + 'fixtures/coffee/mock_coffee_module.coffee'], - opts - ); - }; -} diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/test-runmodule.js b/node/node_modules/grunt/node_modules/nodeunit/test/test-runmodule.js deleted file mode 100644 index 19fe5c7f8..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/test-runmodule.js +++ /dev/null @@ -1,177 +0,0 @@ -/* THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER - - -exports.testRunModule = function (test) { - test.expect(11); - var call_order = []; - var testmodule = { - test1: function (test) { - call_order.push('test1'); - test.ok(true, 'ok true'); - test.done(); - }, - test2: function (test) { - call_order.push('test2'); - test.ok(false, 'ok false'); - test.ok(false, 'ok false'); - test.done(); - }, - test3: function (test) { - call_order.push('test3'); - test.done(); - } - }; - nodeunit.runModule('testmodule', testmodule, { - log: function (assertion) { - call_order.push('log'); - }, - testStart: function (name) { - call_order.push('testStart'); - test.ok( - name.toString() === 'test1' || - name.toString() === 'test2' || - name.toString() === 'test3', - 'testStart called with test name ' - ); - }, - testDone: function (name, assertions) { - call_order.push('testDone'); - test.ok( - name.toString() === 'test1' || - name.toString() === 'test2' || - name.toString() === 'test3', - 'testDone called with test name' - ); - }, - moduleDone: function (name, assertions) { - call_order.push('moduleDone'); - test.equals(assertions.length, 3); - test.equals(assertions.failures(), 2); - test.equals(name, 'testmodule'); - test.ok(typeof assertions.duration === "number"); - test.same(call_order, [ - 'testStart', 'test1', 'log', 'testDone', - 'testStart', 'test2', 'log', 'log', 'testDone', - 'testStart', 'test3', 'testDone', - 'moduleDone' - ]); - } - }, test.done); -}; - - -exports.testRunModuleTestSpec = function (test) { - test.expect(6); - var call_order = []; - var testmodule = { - test1: function (test) { - test.ok(true, 'ok true'); - test.done(); - }, - test2: function (test) { - call_order.push('test2'); - test.ok(false, 'ok false'); - test.ok(false, 'ok false'); - test.done(); - }, - test3: function (test) { - test.done(); - } - }; - nodeunit.runModule('testmodule', testmodule, { - testspec: "test2", - log: function (assertion) { - call_order.push('log'); - }, - testStart: function (name) { - call_order.push('testStart'); - test.equals( - name,'test2', - 'testStart called with test name ' - ); - }, - testDone: function (name, assertions) { - call_order.push('testDone'); - test.equal( - name, 'test2', - 'testDone called with test name' - ); - }, - moduleDone: function (name, assertions) { - call_order.push('moduleDone'); - test.equals(assertions.length, 2); - test.equals(name, 'testmodule'); - test.ok(typeof assertions.duration === "number"); - test.same(call_order, [ - 'testStart', 'test2', 'log', 'log', 'testDone', - 'moduleDone' - ]); - } - }, test.done); -}; - -exports.testRunModuleEmpty = function (test) { - nodeunit.runModule('module with no exports', {}, { - log: function (assertion) { - test.ok(false, 'log should not be called'); - }, - testStart: function (name) { - test.ok(false, 'testStart should not be called'); - }, - testDone: function (name, assertions) { - test.ok(false, 'testDone should not be called'); - }, - moduleDone: function (name, assertions) { - test.equals(assertions.length, 0); - test.equals(assertions.failures(), 0); - test.equals(name, 'module with no exports'); - test.ok(typeof assertions.duration === "number"); - } - }, test.done); -}; - - -exports.testNestedTests = function (test) { - var call_order = []; - var m = { - test1: function (test) { - test.done(); - }, - suite: { - t1: function (test) { - test.done(); - }, - t2: function (test) { - test.done(); - }, - another_suite: { - t3: function (test) { - test.done(); - } - } - } - }; - nodeunit.runModule('modulename', m, { - testStart: function (name) { - call_order.push(['testStart'].concat(name)); - }, - testDone: function (name, assertions) { - call_order.push(['testDone'].concat(name)); - } - }, function () { - test.same(call_order, [ - ['testStart', 'test1'], ['testDone', 'test1'], - ['testStart', 'suite', 't1'], ['testDone', 'suite', 't1'], - ['testStart', 'suite', 't2'], ['testDone', 'suite', 't2'], - ['testStart', 'suite', 'another_suite', 't3'], - ['testDone', 'suite', 'another_suite', 't3'] - ]); - test.done(); - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/test-runtest.js b/node/node_modules/grunt/node_modules/nodeunit/test/test-runtest.js deleted file mode 100644 index 8fc3d5209..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/test-runtest.js +++ /dev/null @@ -1,46 +0,0 @@ -/* THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER - - -exports.testArgs = function (test) { - test.ok(test.expect instanceof Function, 'test.expect'); - test.ok(test.done instanceof Function, 'test.done'); - test.ok(test.ok instanceof Function, 'test.ok'); - test.ok(test.same instanceof Function, 'test.same'); - test.ok(test.equals instanceof Function, 'test.equals'); - test.done(); -}; - -exports.testDoneCallback = function (test) { - test.expect(4); - nodeunit.runTest('testname', exports.testArgs, { - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 5, 'length'); - test.ok(typeof assertions.duration === "number"); - test.equals(name, 'testname'); - } - }, test.done); -}; - -exports.testThrowError = function (test) { - test.expect(3); - var err = new Error('test'); - var testfn = function (test) { - throw err; - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.same(assertion.error, err, 'assertion.error'); - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 1); - test.equals(assertions.length, 1); - } - }, test.done); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/test-sandbox.js b/node/node_modules/grunt/node_modules/nodeunit/test/test-sandbox.js deleted file mode 100644 index 1b249d7af..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/test-sandbox.js +++ /dev/null @@ -1,31 +0,0 @@ -var nodeunit = require('../lib/nodeunit'); -var sandbox = require('../lib/utils').sandbox; -var testCase = nodeunit.testCase; - -exports.testSimpleSandbox = function (test) { - var raw_jscode1 = sandbox(__dirname + '/fixtures/raw_jscode1.js'); - test.equal(raw_jscode1.hello_world('foo'), '_foo_', 'evaluation ok'); - test.done(); -}; - -exports.testSandboxContext = function (test) { - var a_variable = 42; // should not be visible in the sandbox - var raw_jscode2 = sandbox(__dirname + '/fixtures/raw_jscode2.js'); - a_variable = 42; // again for the win - test.equal( - raw_jscode2.get_a_variable(), - 'undefined', - 'the variable should not be defined' - ); - test.done(); -}; - -exports.testSandboxMultiple = function (test) { - var raw_jscode3 = sandbox([ - __dirname + '/fixtures/raw_jscode3.js', - __dirname + '/fixtures/raw_jscode3.js', - __dirname + '/fixtures/raw_jscode3.js' - ]); - test.equal(raw_jscode3.t, 3, 'two files loaded'); - test.done(); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/test-testcase-legacy.js b/node/node_modules/grunt/node_modules/nodeunit/test/test-testcase-legacy.js deleted file mode 100644 index 1dfd9a703..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/test-testcase-legacy.js +++ /dev/null @@ -1,257 +0,0 @@ -/* THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER -var testCase = nodeunit.testCase; - -exports.testTestCase = function (test) { - test.expect(7); - var call_order = []; - var s = testCase({ - setUp: function (callback) { - call_order.push('setUp'); - test.equals(this.one, undefined); - this.one = 1; - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - test.ok(true, 'tearDown called'); - callback(); - }, - test1: function (t) { - call_order.push('test1'); - test.equals(this.one, 1); - this.one = 2; - t.done(); - }, - test2: function (t) { - call_order.push('test2'); - test.equals(this.one, 1); - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function () { - test.same(call_order, [ - 'setUp', 'test1', 'tearDown', - 'setUp', 'test2', 'tearDown' - ]); - test.done(); - }); -}; - -exports.tearDownAfterError = function (test) { - test.expect(1); - var s = testCase({ - tearDown: function (callback) { - test.ok(true, 'tearDown called'); - callback(); - }, - test: function (t) { - throw new Error('some error'); - } - }); - nodeunit.runSuite(null, s, {}, function () { - test.done(); - }); -}; - -exports.catchSetUpError = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = testCase({ - setUp: function (callback) { - throw test_error; - }, - test: function (t) { - test.ok(false, 'test function should not be called'); - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.setUpErrorCallback = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = testCase({ - setUp: function (callback) { - callback(test_error); - }, - test: function (t) { - test.ok(false, 'test function should not be called'); - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.catchTearDownError = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = testCase({ - tearDown: function (callback) { - throw test_error; - }, - test: function (t) { - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.tearDownErrorCallback = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = testCase({ - tearDown: function (callback) { - callback(test_error); - }, - test: function (t) { - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.testErrorAndtearDownError = function (test) { - test.expect(3); - var error1 = new Error('test error one'); - var error2 = new Error('test error two'); - var s = testCase({ - tearDown: function (callback) { - callback(error2); - }, - test: function (t) { - t.done(error1); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 2); - test.equal(assertions[0].error, error1); - test.equal(assertions[1].error, error2); - test.done(); - }); -}; - -exports.testCaseGroups = function (test) { - var call_order = []; - var s = testCase({ - setUp: function (callback) { - call_order.push('setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - callback(); - }, - test1: function (test) { - call_order.push('test1'); - test.done(); - }, - group1: { - test2: function (test) { - call_order.push('group1.test2'); - test.done(); - } - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.same(call_order, [ - 'setUp', - 'test1', - 'tearDown', - 'setUp', - 'group1.test2', - 'tearDown' - ]); - test.done(); - }); -}; - -exports.nestedTestCases = function (test) { - var call_order = []; - var s = testCase({ - setUp: function (callback) { - call_order.push('setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - callback(); - }, - test1: function (test) { - call_order.push('test1'); - test.done(); - }, - group1: testCase({ - setUp: function (callback) { - call_order.push('group1.setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('group1.tearDown'); - callback(); - }, - test2: function (test) { - call_order.push('group1.test2'); - test.done(); - } - }) - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.same(call_order, [ - 'setUp', - 'test1', - 'tearDown', - 'setUp', - 'group1.setUp', - 'group1.test2', - 'group1.tearDown', - 'tearDown' - ]); - test.done(); - }); -}; - -exports.deepNestedTestCases = function (test) { - var val = 'foo'; - var s = testCase({ - setUp: function (callback) { - val = 'bar'; - callback(); - }, - group1: testCase({ - test: testCase({ - test2: function (test) { - test.equal(val, 'bar'); - test.done(); - } - }) - }) - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.ok(!assertions[0].failed()); - test.equal(assertions.length, 1); - test.done(); - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/test-testcase.js b/node/node_modules/grunt/node_modules/nodeunit/test/test-testcase.js deleted file mode 100644 index 5d33b0bf0..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/test-testcase.js +++ /dev/null @@ -1,256 +0,0 @@ -/* THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER - -exports.testTestCase = function (test) { - test.expect(7); - var call_order = []; - var s = { - setUp: function (callback) { - call_order.push('setUp'); - test.equals(this.one, undefined, 'in setUp, this.one not set'); - this.one = 1; - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - test.ok(true, 'tearDown called'); - callback(); - }, - test1: function (t) { - call_order.push('test1'); - test.equals(this.one, 1, 'in test1, this.one is 1'); - this.one = 2; - t.done(); - }, - test2: function (t) { - call_order.push('test2'); - test.equals(this.one, 1, 'in test2, this.one is still 1'); - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function () { - test.same(call_order, [ - 'setUp', 'test1', 'tearDown', - 'setUp', 'test2', 'tearDown' - ]); - test.done(); - }); -}; - -exports.tearDownAfterError = function (test) { - test.expect(1); - var s = { - tearDown: function (callback) { - test.ok(true, 'tearDown called'); - callback(); - }, - test: function (t) { - throw new Error('some error'); - } - }; - nodeunit.runSuite(null, s, {}, function () { - test.done(); - }); -}; - -exports.catchSetUpError = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = { - setUp: function (callback) { - throw test_error; - }, - test: function (t) { - test.ok(false, 'test function should not be called'); - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.setUpErrorCallback = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = { - setUp: function (callback) { - callback(test_error); - }, - test: function (t) { - test.ok(false, 'test function should not be called'); - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.catchTearDownError = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = { - tearDown: function (callback) { - throw test_error; - }, - test: function (t) { - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.tearDownErrorCallback = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = { - tearDown: function (callback) { - callback(test_error); - }, - test: function (t) { - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.testErrorAndtearDownError = function (test) { - test.expect(3); - var error1 = new Error('test error one'); - var error2 = new Error('test error two'); - var s = { - tearDown: function (callback) { - callback(error2); - }, - test: function (t) { - t.done(error1); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 2); - test.equal(assertions[0].error, error1); - test.equal(assertions[1].error, error2); - test.done(); - }); -}; - -exports.testCaseGroups = function (test) { - var call_order = []; - var s = { - setUp: function (callback) { - call_order.push('setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - callback(); - }, - test1: function (test) { - call_order.push('test1'); - test.done(); - }, - group1: { - test2: function (test) { - call_order.push('group1.test2'); - test.done(); - } - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.same(call_order, [ - 'setUp', - 'test1', - 'tearDown', - 'setUp', - 'group1.test2', - 'tearDown' - ]); - test.done(); - }); -}; - -exports.nestedTestCases = function (test) { - var call_order = []; - var s = { - setUp: function (callback) { - call_order.push('setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - callback(); - }, - test1: function (test) { - call_order.push('test1'); - test.done(); - }, - group1: { - setUp: function (callback) { - call_order.push('group1.setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('group1.tearDown'); - callback(); - }, - test2: function (test) { - call_order.push('group1.test2'); - test.done(); - } - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.same(call_order, [ - 'setUp', - 'test1', - 'tearDown', - 'setUp', - 'group1.setUp', - 'group1.test2', - 'group1.tearDown', - 'tearDown' - ]); - test.done(); - }); -}; - -exports.deepNestedTestCases = function (test) { - var val = 'foo'; - var s = { - setUp: function (callback) { - val = 'bar'; - callback(); - }, - group1: { - test: { - test2: function (test) { - test.equal(val, 'bar'); - test.done(); - } - } - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.ok(!assertions[0].failed()); - test.equal(assertions.length, 1); - test.done(); - }); -}; diff --git a/node/node_modules/grunt/node_modules/nodeunit/test/test.html b/node/node_modules/grunt/node_modules/nodeunit/test/test.html deleted file mode 100644 index e0826de3f..000000000 --- a/node/node_modules/grunt/node_modules/nodeunit/test/test.html +++ /dev/null @@ -1,28 +0,0 @@ - - - Nodeunit Test Suite - - - - - - - - - - -

        Nodeunit Test Suite

        - - - diff --git a/node/node_modules/grunt/node_modules/nopt/node_modules/abbrev/package.json b/node/node_modules/grunt/node_modules/nopt/node_modules/abbrev/package.json index 55ed011bf..3056f1e21 100644 --- a/node/node_modules/grunt/node_modules/nopt/node_modules/abbrev/package.json +++ b/node/node_modules/grunt/node_modules/nopt/node_modules/abbrev/package.json @@ -20,9 +20,6 @@ }, "readme": "# abbrev-js\n\nJust like [ruby's Abbrev](http://apidock.com/ruby/Abbrev).\n\nUsage:\n\n var abbrev = require(\"abbrev\");\n abbrev(\"foo\", \"fool\", \"folding\", \"flop\");\n \n // returns:\n { fl: 'flop'\n , flo: 'flop'\n , flop: 'flop'\n , fol: 'folding'\n , fold: 'folding'\n , foldi: 'folding'\n , foldin: 'folding'\n , folding: 'folding'\n , foo: 'foo'\n , fool: 'fool'\n }\n\nThis is handy for command-line scripts, or other cases where you want to be able to accept shorthands.\n", "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/abbrev-js/issues" - }, "_id": "abbrev@1.0.4", "_from": "abbrev@1" } diff --git a/node/node_modules/grunt/node_modules/nopt/package.json b/node/node_modules/grunt/node_modules/nopt/package.json index 35c8f64c1..6d4bc5ea5 100644 --- a/node/node_modules/grunt/node_modules/nopt/package.json +++ b/node/node_modules/grunt/node_modules/nopt/package.json @@ -27,9 +27,6 @@ }, "readme": "If you want to write an option parser, and have it be good, there are\ntwo ways to do it. The Right Way, and the Wrong Way.\n\nThe Wrong Way is to sit down and write an option parser. We've all done\nthat.\n\nThe Right Way is to write some complex configurable program with so many\noptions that you go half-insane just trying to manage them all, and put\nit off with duct-tape solutions until you see exactly to the core of the\nproblem, and finally snap and write an awesome option parser.\n\nIf you want to write an option parser, don't write an option parser.\nWrite a package manager, or a source control system, or a service\nrestarter, or an operating system. You probably won't end up with a\ngood one of those, but if you don't give up, and you are relentless and\ndiligent enough in your procrastination, you may just end up with a very\nnice option parser.\n\n## USAGE\n\n // my-program.js\n var nopt = require(\"nopt\")\n , Stream = require(\"stream\").Stream\n , path = require(\"path\")\n , knownOpts = { \"foo\" : [String, null]\n , \"bar\" : [Stream, Number]\n , \"baz\" : path\n , \"bloo\" : [ \"big\", \"medium\", \"small\" ]\n , \"flag\" : Boolean\n , \"pick\" : Boolean\n , \"many\" : [String, Array]\n }\n , shortHands = { \"foofoo\" : [\"--foo\", \"Mr. Foo\"]\n , \"b7\" : [\"--bar\", \"7\"]\n , \"m\" : [\"--bloo\", \"medium\"]\n , \"p\" : [\"--pick\"]\n , \"f\" : [\"--flag\"]\n }\n // everything is optional.\n // knownOpts and shorthands default to {}\n // arg list defaults to process.argv\n // slice defaults to 2\n , parsed = nopt(knownOpts, shortHands, process.argv, 2)\n console.log(parsed)\n\nThis would give you support for any of the following:\n\n```bash\n$ node my-program.js --foo \"blerp\" --no-flag\n{ \"foo\" : \"blerp\", \"flag\" : false }\n\n$ node my-program.js ---bar 7 --foo \"Mr. Hand\" --flag\n{ bar: 7, foo: \"Mr. Hand\", flag: true }\n\n$ node my-program.js --foo \"blerp\" -f -----p\n{ foo: \"blerp\", flag: true, pick: true }\n\n$ node my-program.js -fp --foofoo\n{ foo: \"Mr. Foo\", flag: true, pick: true }\n\n$ node my-program.js --foofoo -- -fp # -- stops the flag parsing.\n{ foo: \"Mr. Foo\", argv: { remain: [\"-fp\"] } }\n\n$ node my-program.js --blatzk 1000 -fp # unknown opts are ok.\n{ blatzk: 1000, flag: true, pick: true }\n\n$ node my-program.js --blatzk true -fp # but they need a value\n{ blatzk: true, flag: true, pick: true }\n\n$ node my-program.js --no-blatzk -fp # unless they start with \"no-\"\n{ blatzk: false, flag: true, pick: true }\n\n$ node my-program.js --baz b/a/z # known paths are resolved.\n{ baz: \"/Users/isaacs/b/a/z\" }\n\n# if Array is one of the types, then it can take many\n# values, and will always be an array. The other types provided\n# specify what types are allowed in the list.\n\n$ node my-program.js --many 1 --many null --many foo\n{ many: [\"1\", \"null\", \"foo\"] }\n\n$ node my-program.js --many foo\n{ many: [\"foo\"] }\n```\n\nRead the tests at the bottom of `lib/nopt.js` for more examples of\nwhat this puppy can do.\n\n## Types\n\nThe following types are supported, and defined on `nopt.typeDefs`\n\n* String: A normal string. No parsing is done.\n* path: A file system path. Gets resolved against cwd if not absolute.\n* url: A url. If it doesn't parse, it isn't accepted.\n* Number: Must be numeric.\n* Date: Must parse as a date. If it does, and `Date` is one of the options,\n then it will return a Date object, not a string.\n* Boolean: Must be either `true` or `false`. If an option is a boolean,\n then it does not need a value, and its presence will imply `true` as\n the value. To negate boolean flags, do `--no-whatever` or `--whatever\n false`\n* NaN: Means that the option is strictly not allowed. Any value will\n fail.\n* Stream: An object matching the \"Stream\" class in node. Valuable\n for use when validating programmatically. (npm uses this to let you\n supply any WriteStream on the `outfd` and `logfd` config options.)\n* Array: If `Array` is specified as one of the types, then the value\n will be parsed as a list of options. This means that multiple values\n can be specified, and that the value will always be an array.\n\nIf a type is an array of values not on this list, then those are\nconsidered valid values. For instance, in the example above, the\n`--bloo` option can only be one of `\"big\"`, `\"medium\"`, or `\"small\"`,\nand any other value will be rejected.\n\nWhen parsing unknown fields, `\"true\"`, `\"false\"`, and `\"null\"` will be\ninterpreted as their JavaScript equivalents, and numeric values will be\ninterpreted as a number.\n\nYou can also mix types and values, or multiple types, in a list. For\ninstance `{ blah: [Number, null] }` would allow a value to be set to\neither a Number or null.\n\nTo define a new type, add it to `nopt.typeDefs`. Each item in that\nhash is an object with a `type` member and a `validate` method. The\n`type` member is an object that matches what goes in the type list. The\n`validate` method is a function that gets called with `validate(data,\nkey, val)`. Validate methods should assign `data[key]` to the valid\nvalue of `val` if it can be handled properly, or return boolean\n`false` if it cannot.\n\nYou can also call `nopt.clean(data, types, typeDefs)` to clean up a\nconfig object and remove its invalid properties.\n\n## Error Handling\n\nBy default, nopt outputs a warning to standard error when invalid\noptions are found. You can change this behavior by assigning a method\nto `nopt.invalidHandler`. This method will be called with\nthe offending `nopt.invalidHandler(key, val, types)`.\n\nIf no `nopt.invalidHandler` is assigned, then it will console.error\nits whining. If it is assigned to boolean `false` then the warning is\nsuppressed.\n\n## Abbreviations\n\nYes, they are supported. If you define options like this:\n\n```javascript\n{ \"foolhardyelephants\" : Boolean\n, \"pileofmonkeys\" : Boolean }\n```\n\nThen this will work:\n\n```bash\nnode program.js --foolhar --pil\nnode program.js --no-f --pileofmon\n# etc.\n```\n\n## Shorthands\n\nShorthands are a hash of shorter option names to a snippet of args that\nthey expand to.\n\nIf multiple one-character shorthands are all combined, and the\ncombination does not unambiguously match any other option or shorthand,\nthen they will be broken up into their constituent parts. For example:\n\n```json\n{ \"s\" : [\"--loglevel\", \"silent\"]\n, \"g\" : \"--global\"\n, \"f\" : \"--force\"\n, \"p\" : \"--parseable\"\n, \"l\" : \"--long\"\n}\n```\n\n```bash\nnpm ls -sgflp\n# just like doing this:\nnpm ls --loglevel silent --global --force --long --parseable\n```\n\n## The Rest of the args\n\nThe config object returned by nopt is given a special member called\n`argv`, which is an object with the following fields:\n\n* `remain`: The remaining args after all the parsing has occurred.\n* `original`: The args as they originally appeared.\n* `cooked`: The args after flags and shorthands are expanded.\n\n## Slicing\n\nNode programs are called with more or less the exact argv as it appears\nin C land, after the v8 and node-specific options have been plucked off.\nAs such, `argv[0]` is always `node` and `argv[1]` is always the\nJavaScript program being run.\n\nThat's usually not very useful to you. So they're sliced off by\ndefault. If you want them, then you can pass in `0` as the last\nargument, or any other number that you'd like to slice off the start of\nthe list.\n", "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/nopt/issues" - }, "_id": "nopt@1.0.10", "_from": "nopt@~1.0.10" } diff --git a/node/node_modules/grunt/node_modules/prompt/.npmignore b/node/node_modules/grunt/node_modules/prompt/.npmignore deleted file mode 100644 index e3bc27506..000000000 --- a/node/node_modules/grunt/node_modules/prompt/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules/ -node_modules/* -npm-debug.log \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/.travis.yml b/node/node_modules/grunt/node_modules/prompt/.travis.yml deleted file mode 100644 index 63e4183e1..000000000 --- a/node/node_modules/grunt/node_modules/prompt/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 - -notifications: - email: - - travis@nodejitsu.com - irc: "irc.freenode.org#nodejitsu" - diff --git a/node/node_modules/grunt/node_modules/prompt/LICENSE b/node/node_modules/grunt/node_modules/prompt/LICENSE deleted file mode 100644 index 56217cac7..000000000 --- a/node/node_modules/grunt/node_modules/prompt/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Nodejitsu Inc. - -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/node_modules/grunt/node_modules/prompt/README.md b/node/node_modules/grunt/node_modules/prompt/README.md deleted file mode 100644 index e49fdcd06..000000000 --- a/node/node_modules/grunt/node_modules/prompt/README.md +++ /dev/null @@ -1,238 +0,0 @@ -# prompt [![Build Status](https://secure.travis-ci.org/flatiron/prompt.png)](http://travis-ci.org/flatiron/prompt) - -A beautiful command-line prompt for node.js - -## Features - -* prompts the user for input -* supports validation and defaults -* hides passwords - -## Installation - -### Installing npm (node package manager) -``` -curl http://npmjs.org/install.sh | sh -``` - -### Installing prompt -``` -[sudo] npm install prompt -``` - -## Usage -Using prompt is relatively straight forward. There are two core methods you should be aware of: `prompt.get()` and `prompt.addProperties()`. There methods take strings representing property names in addition to objects for complex property validation (and more). There are a number of [examples][0] that you should examine for detailed usage. - -### Getting Basic Prompt Information -Getting started with `prompt` is easy. Lets take a look at `examples/simple-prompt.js`: - -``` js -var prompt = require('prompt'); - -// -// Start the prompt -// -prompt.start(); - -// -// Get two properties from the user: username and email -// -prompt.get(['username', 'email'], function (err, result) { - // - // Log the results. - // - console.log('Command-line input received:'); - console.log(' username: ' + result.username); - console.log(' email: ' + result.email); -}) -``` - -This will result in the following command-line output: - -``` -$ node examples/simple-prompt.js -prompt: username: some-user -prompt: email: some-user@some-place.org -Command-line input received: - username: some-user - email: some-user@some-place.org -``` - -### Prompting with Validation, Default Values, and More (Complex Properties) -In addition to prompting the user with simple string prompts, there is a robust API for getting and validating complex information from a command-line prompt. Here's a quick sample: - -``` js -var properties = [ - { - name: 'name', - validator: /^[a-zA-Z\s\-]+$/, - warning: 'Name must be only letters, spaces, or dashes', - empty: false - }, - { - name: 'password', - hidden: true - } -]; - -// -// Start the prompt -// -prompt.start(); - -// -// Get two properties from the user: email, password -// -prompt.get(properties, function (err, result) { - // - // Log the results. - // - console.log('Command-line input received:'); - console.log(' name: ' + result.name); - console.log(' password: ' + result.password); -}); -``` - -Pretty easy right? The output from the above script is: - -``` -$ node examples/property-prompt.js -prompt: name: nodejitsu000 -error: Invalid input for name -error: Name must be only letters, spaces, or dashes -prompt: name: Nodejitsu Inc -prompt: password: -Command-line input received: - name: Nodejitsu Inc - password: some-password -``` - -## Valid Property Settings -`prompt` uses a simple property system for performing a couple of basic validation operations against input received from the command-line. The motivations here were speed and simplicity of implementation to integration of pseudo-standards like JSON-Schema were not feasible. - -Lets examine the anatomy of a prompt property: - -``` js -{ - message: 'Enter your password', // Prompt displayed to the user. If not supplied name will be used. - name: 'password' // Key in the JSON object returned from `.get()`. - validator: /^\w+$/ // Regular expression that input must be valid against. - warning: 'Password must be letters' // Warning message to display if validation fails. - hidden: true // If true, characters entered will not be output to console. - default: 'lamepassword' // Default value to use if no value is entered. - empty: false // If false, value entered must be non-empty. -} -``` -### skipping prompts - -Sometimes power users may wish to skip promts and specify all data as command line options. -if a value is set as a property of `prompt.override` prompt will use that instead of -prompting the user. - -``` js -//prompt-everride.js - -var prompt = require('prompt'), - optimist = require('optimist') - -// -// set the overrides -// -prompt.override = optimist.argv - -// -// Start the prompt -// -prompt.start(); - -// -// Get two properties from the user: username and email -// -prompt.get(['username', 'email'], function (err, result) { - // - // Log the results. - // - console.log('Command-line input received:'); - console.log(' username: ' + result.username); - console.log(' email: ' + result.email); -}) - -//: node prompt-everride.js --username USER --email EMAIL - -``` - - -### Adding Properties to an Object -A common use-case for prompting users for data from the command-line is to extend or create a configuration object that is passed onto the entry-point method for your CLI tool. `prompt` exposes a convenience method for doing just this: - -``` js -var obj = { - password: 'lamepassword', - mindset: 'NY' -} - -// -// Log the initial object. -// -console.log('Initial object to be extended:'); -console.dir(obj); - -// -// Add two properties to the empty object: username and email -// -prompt.addProperties(obj, ['username', 'email'], function (err) { - // - // Log the results. - // - console.log('Updated object received:'); - console.dir(obj); -}); -``` - -## Customizing your prompt -Aside from changing `property.message`, you can also change `prompt.message` -and `prompt.delimiter` to change the appearance of your prompt. - -The basic structure of a prompt is this: - -``` js -prompt.message + prompt.delimiter + property.message + prompt.delimiter; -``` - -The default `prompt.message` is "prompt," the default `prompt.delimiter` is -": ", and the default `property.message` is `property.name`. -Changing these allows you to customize the appearance of your prompts! In -addition, prompt supports ANSI color codes via the -[colors module](https://github.com/Marak/colors.js) for custom colors. For a -very colorful example: - -``` js -var prompt = require("prompt"); -// -// The colors module adds color properties to String.prototype -// -require("colors"); - -// -// Setting these properties customizes the prompt. -// -prompt.message = "Question!".rainbow; -prompt.delimiter = "><".green; - -prompt.start(); - -prompt.get([{ name: "name", - message: "What is your name?".magenta }], function (err, result) { - console.log("You said your name is: ".cyan + result.name.cyan); -}); -``` - -## Running tests -``` -vows test/*-test.js --spec -``` - -#### Author: [Charlie Robbins][1] - -[0]: https://github.com/flatiron/prompt/tree/master/examples -[1]: http://nodejitsu.com diff --git a/node/node_modules/grunt/node_modules/prompt/docs/docco.css b/node/node_modules/grunt/node_modules/prompt/docs/docco.css deleted file mode 100644 index bd5413433..000000000 --- a/node/node_modules/grunt/node_modules/prompt/docs/docco.css +++ /dev/null @@ -1,194 +0,0 @@ -/*--------------------- Layout and Typography ----------------------------*/ -body { - font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; - font-size: 15px; - line-height: 22px; - color: #252519; - margin: 0; padding: 0; -} -a { - color: #261a3b; -} - a:visited { - color: #261a3b; - } -p { - margin: 0 0 15px 0; -} -h4, h5, h6 { - color: #333; - margin: 6px 0 6px 0; - font-size: 13px; -} - h2, h3 { - margin-bottom: 0; - color: #000; - } - h1 { - margin-top: 40px; - margin-bottom: 15px; - color: #000; - } -#container { - position: relative; -} -#background { - position: fixed; - top: 0; left: 525px; right: 0; bottom: 0; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - z-index: -1; -} -#jump_to, #jump_page { - background: white; - -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; - -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; - font: 10px Arial; - text-transform: uppercase; - cursor: pointer; - text-align: right; -} -#jump_to, #jump_wrapper { - position: fixed; - right: 0; top: 0; - padding: 5px 10px; -} - #jump_wrapper { - padding: 0; - display: none; - } - #jump_to:hover #jump_wrapper { - display: block; - } - #jump_page { - padding: 5px 0 3px; - margin: 0 0 25px 25px; - } - #jump_page .source { - display: block; - padding: 5px 10px; - text-decoration: none; - border-top: 1px solid #eee; - } - #jump_page .source:hover { - background: #f5f5ff; - } - #jump_page .source:first-child { - } -table td { - border: 0; - outline: 0; -} - td.docs, th.docs { - max-width: 450px; - min-width: 450px; - min-height: 5px; - padding: 10px 25px 1px 50px; - overflow-x: hidden; - vertical-align: top; - text-align: left; - } - .docs pre { - margin: 15px 0 15px; - padding-left: 15px; - } - .docs p tt, .docs p code { - background: #f8f8ff; - border: 1px solid #dedede; - font-size: 12px; - padding: 0 0.2em; - } - .pilwrap { - position: relative; - } - .pilcrow { - font: 12px Arial; - text-decoration: none; - color: #454545; - position: absolute; - top: 3px; left: -20px; - padding: 1px 2px; - opacity: 0; - -webkit-transition: opacity 0.2s linear; - } - td.docs:hover .pilcrow { - opacity: 1; - } - td.code, th.code { - padding: 14px 15px 16px 25px; - width: 100%; - vertical-align: top; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - } - pre, tt, code { - font-size: 12px; line-height: 18px; - font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; - margin: 0; padding: 0; - } - - -/*---------------------- Syntax Highlighting -----------------------------*/ -td.linenos { background-color: #f0f0f0; padding-right: 10px; } -span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } -body .hll { background-color: #ffffcc } -body .c { color: #408080; font-style: italic } /* Comment */ -body .err { border: 1px solid #FF0000 } /* Error */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ -body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { color: #0000FF } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/docs/prompt.html b/node/node_modules/grunt/node_modules/prompt/docs/prompt.html deleted file mode 100644 index 7776f5bc4..000000000 --- a/node/node_modules/grunt/node_modules/prompt/docs/prompt.html +++ /dev/null @@ -1,296 +0,0 @@ - prompt.js

        prompt.js

        /*
        - * prompt.js: Simple prompt for prompting information from the command line 
        - *
        - * (C) 2010, Nodejitsu Inc.
        - *
        - */
        -
        -var events = require('events'),
        -    async = require('async'),
        -    colors = require('colors'),
        -    winston = require('winston'),
        -    stdio = process.binding('stdio');

        @private function capitalize (str)

        - -

        str {string} String to capitalize

        - -

        Capitalizes the string supplied.

        function capitalize(str) {
        -  return str.charAt(0).toUpperCase() + str.slice(1);
        -}
        -
        -var prompt = module.exports = Object.create(events.EventEmitter.prototype);
        -
        -var logger = prompt.logger = new winston.Logger({
        -  transports: [
        -    new (winston.transports.Console)()
        -  ]
        -});
        -    
        -prompt.started    = false;
        -prompt.paused     = false;
        -prompt.allowEmpty = false; 
        -
        -var stdin, stdout;

        Create an empty object for the properties -known to prompt

        prompt.properties = {};

        Setup the default winston logger to use -the cli levels and colors.

        logger.cli();

        function start (options)

        - -

        @options {Object} Optional Options to consume by prompt

        - -

        Starts the prompt by listening to the appropriate events on options.stdin -and options.stdout. If no streams are supplied, then process.stdin -and process.stdout are used, respectively.

        prompt.start = function (options) {
        -  if (prompt.started) {
        -    return;
        -  }
        -  
        -  options = options        || {};
        -  stdin   = options.stdin  || process.openStdin();
        -  stdout  = options.stdout || process.stdout;
        -  
        -  prompt.allowEmpty = options.allowEmpty || false;
        -  
        -  process.on('SIGINT', function () {
        -    stdout.write('\n');
        -    process.exit(1);
        -  })
        -  
        -  prompt.emit('start');
        -  prompt.started = true;
        -  return prompt;
        -};

        function pause ()

        - -

        Pauses input coming in from stdin

        prompt.pause = function () {
        -  if (!prompt.started || prompt.paused) {
        -    return;
        -  }
        -  
        -  stdin.pause();
        -  prompt.emit('pause');
        -  prompt.paused = true;
        -  return prompt;
        -};

        function resume ()

        - -

        Resumes input coming in from stdin

        prompt.resume = function () {
        -  if (!prompt.started || !prompt.paused) {
        -    return;
        -  }
        -  
        -  stdin.resume();
        -  prompt.emit('resume');
        -  prompt.paused = false;
        -  return prompt;
        -};

        function get (msg, [validator,] callback)

        - -

        @msg {Array|Object|string} Set of variables to get input for.

        - -

        @callback {function} Continuation to pass control to when complete.

        - -

        Gets input from the user via stdin for the specified message(s) msg.

        prompt.get = function (msg, callback) {
        -  var vars = !Array.isArray(msg) ? [msg] : msg,
        -      result = {};
        -  
        -  vars = vars.map(function (v) {
        -    if (typeof v === 'string') {
        -      v = v.toLowerCase();
        -    }
        -    
        -    return prompt.properties[v] || v;
        -  });
        -  
        -  function get(target, next) {
        -    prompt.getInput(target, function (err, line) {
        -      if (err) {
        -        return next(err);
        -      }
        -      
        -      var name = target.name || target;
        -      result[name] = line;
        -      next();
        -    });
        -  }
        -  
        -  async.forEachSeries(vars, get, function (err) {
        -    return err ? callback(err) : callback(null, result);
        -  });
        -  
        -  return prompt;
        -};

        function getInput (msg, validator, callback)

        - -

        @msg {Object|string} Variable to get input for.

        - -

        @callback {function} Continuation to pass control to when complete.

        - -

        Gets input from the user via stdin for the specified message msg.

        prompt.getInput = function (prop, callback) {
        -  var name   = prop.message || prop.name || prop,
        -      raw    = ['prompt', ': ' + name.grey, ': '.grey],
        -      read   = prop.hidden ? prompt.readLineHidden : prompt.readLine,
        -      length, msg;
        -  
        -  if (prop.default) {
        -    raw.splice(2, -1, ' (' + prop.default + ')');
        -  }
        -  

        Calculate the raw length and colorize the prompt

          length = raw.join('').length;
        -  raw[0] = raw[0];
        -  msg = raw.join('');
        -  
        -  if (prop.help) {
        -    prop.help.forEach(function (line) {
        -      logger.help(line);
        -    });
        -  }
        -  
        -  stdout.write(msg); 
        -  prompt.emit('prompt', prop);
        -  
        -  read.call(null, function (err, line) {
        -    if (err) {
        -      return callback(err);
        -    }
        -  
        -    if (!line || line === '') {
        -      line = prop.default || line;
        -    }
        -    
        -    if (prop.validator || prop.empty === false) {
        -      var valid;
        -      
        -      if (prop.validator) {
        -        valid = prop.validator.test 
        -         ? prop.validator.test(line)
        -         : prop.validator(line);
        -      }
        -      
        -      if (prop.empty === false && valid) {
        -        valid = line.length > 0;
        -        prop.warning = prop.warning || 'You must supply a value.';
        -      }
        -      
        -      if (!valid) {
        -        logger.error('Invalid input for ' + name.grey);
        -        if (prop.warning) {
        -          logger.error(prop.warning);
        -        }
        -        
        -        prompt.emit('invalid', prop, line);
        -        return prompt.getInput(prop, callback);
        -      }
        -    }
        -        
        -    logger.input(line.yellow);
        -    callback(null, line);
        -  });
        -
        -  return prompt;
        -};

        function addProperties (obj, properties, callback)

        - -

        @obj {Object} Object to add properties to

        - -

        @properties {Array} List of properties to get values for

        - -

        @callback {function} Continuation to pass control to when complete.

        - -

        Prompts the user for values each of the properties if obj does not already -have a value for the property. Responds with the modified object.

        prompt.addProperties = function (obj, properties, callback) {
        -  properties = properties.filter(function (prop) {
        -    return typeof obj[prop] === 'undefined';
        -  });
        -  
        -  if (properties.length === 0) {
        -    return callback(obj);
        -  }
        -  
        -  prompt.get(properties, function (err, results) {
        -    if (err) {
        -      return callback(err);
        -    }
        -    else if (!results) {
        -      return callback(null, obj);
        -    }
        -    
        -    function putNested (obj, path, value) {
        -      var last = obj, key; 
        -      
        -      while (path.length > 1) {
        -        key = path.shift();
        -        if (!last[key]) {
        -          last[key] = {};
        -        }
        -        
        -        last = last[key];
        -      }
        -      
        -      last[path.shift()] = value;
        -    }
        -    
        -    Object.keys(results).forEach(function (key) {
        -      putNested(obj, key.split('.'), results[key]);
        -    });
        -    
        -    callback(null, obj);
        -  });
        -  
        -  return prompt;
        -};

        function readLine (callback)

        - -

        @callback {function} Continuation to respond to when complete

        - -

        Gets a single line of input from the user.

        prompt.readLine = function (callback) {
        -  var value = '', buffer = '';
        -  prompt.resume();
        -  stdin.setEncoding('utf8');
        -  stdin.on('error', callback);
        -  stdin.on('data', function data (chunk) {
        -    value += buffer + chunk;
        -    buffer = '';
        -    value = value.replace(/\r/g, '');
        -    if (value.indexOf('\n') !== -1) {
        -      if (value !== '\n') {
        -        value = value.replace(/^\n+/, '');
        -      }
        -      
        -      buffer = value.substr(value.indexOf('\n'));
        -      val = value.substr(0, value.indexOf('\n'));
        -      prompt.pause();
        -      stdin.removeListener('data', data);
        -      stdin.removeListener('error', callback);
        -      value = value.trim();
        -      callback(null, value);
        -    }
        -  });
        -  
        -  return prompt;
        -};

        function readLineHidden (callback)

        - -

        @callback {function} Continuation to respond to when complete

        - -

        Gets a single line of hidden input (i.e. rawMode = true) from the user.

        prompt.readLineHidden = function (callback) {
        -  var value = '', buffer = '';
        -  stdio.setRawMode(true);
        -  prompt.resume();
        -  stdin.on('error', callback);
        -  stdin.on('data', function data (c) {
        -    c = '' + c;
        -    switch (c) {
        -      case '\n': case '\r': case '\r\n': case '\u0004':
        -        stdio.setRawMode(false);
        -        stdin.removeListener('data', data);
        -        stdin.removeListener('error', callback);
        -        value = value.trim();
        -        stdout.write('\n');
        -        stdout.flush();
        -        prompt.pause();
        -        return callback(null, value)
        -      case '\u0003': case '\0':
        -        stdout.write('\n');
        -        process.exit(1);
        -        break;
        -      default:
        -        value += buffer + c
        -        buffer = '';
        -        break;
        -    }
        -  });
        -  
        -  return prompt;
        -};
        -
        -
        diff --git a/node/node_modules/grunt/node_modules/prompt/examples/add-properties.js b/node/node_modules/grunt/node_modules/prompt/examples/add-properties.js deleted file mode 100644 index 71860ddbf..000000000 --- a/node/node_modules/grunt/node_modules/prompt/examples/add-properties.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * add-properties.js: Example of how to add properties to an object using prompt. - * - * (C) 2010, Nodejitsu Inc. - * - */ - -var prompt = require('../lib/prompt'); - -// -// Start the prompt -// -prompt.start(); - -var obj = { - password: 'lamepassword', - mindset: 'NY' -} - -// -// Log the initial object. -// -console.log('Initial object to be extended:'); -console.dir(obj); - -// -// Add two properties to the empty object: username and email -// -prompt.addProperties(obj, ['username', 'email'], function (err) { - // - // Log the results. - // - console.log('Updated object received:'); - console.dir(obj); -}); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/examples/existing-properties.js b/node/node_modules/grunt/node_modules/prompt/examples/existing-properties.js deleted file mode 100644 index b1d6621c1..000000000 --- a/node/node_modules/grunt/node_modules/prompt/examples/existing-properties.js +++ /dev/null @@ -1,37 +0,0 @@ -/* - * existing-properties.js: Example of using prompt with predefined properties. - * - * (C) 2010, Nodejitsu Inc. - * - */ - -var prompt = require('../lib/prompt'); - -prompt.properties = { - email: { - name: 'email', - validator: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, - warning: 'Must be a valid email address' - }, - password: { - name: 'password', - hidden: true - } -}; - -// -// Start the prompt -// -prompt.start(); - -// -// Get two properties from the user: email, password -// -prompt.get(['email', 'password'], function (err, result) { - // - // Log the results. - // - console.log('Command-line input received:'); - console.log(' email: ' + result.email); - console.log(' password: ' + result.password); -}); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/examples/history.js b/node/node_modules/grunt/node_modules/prompt/examples/history.js deleted file mode 100644 index e60e59dea..000000000 --- a/node/node_modules/grunt/node_modules/prompt/examples/history.js +++ /dev/null @@ -1,44 +0,0 @@ -/* - * history.js: Example of using the prompt history capabilities. - * - * (C) 2010, Nodejitsu Inc. - * - */ - -var prompt = require('../lib/prompt'); - -// -// Start the prompt -// -prompt.start(); - -var properties = [ - { - name: 'animal', - description: 'Enter an animal', - default: 'dog', - validator: /dog|cat/ - }, - { - name: 'sound', - description: 'What sound does this animal make?', - validator: function (value) { - var animal = prompt.history(0).value; - - return animal === 'dog' && value === 'woof' - || animal === 'cat' && value === 'meow'; - } - } -] - -// -// Get two properties from the user -// -prompt.get(properties, function (err, result) { - // - // Log the results. - // - console.log('Command-line input received:'); - console.log(' animal: ' + result.animal); - console.log(' sound: ' + result.sound); -}); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/examples/password.js b/node/node_modules/grunt/node_modules/prompt/examples/password.js deleted file mode 100644 index 90167eaa4..000000000 --- a/node/node_modules/grunt/node_modules/prompt/examples/password.js +++ /dev/null @@ -1,30 +0,0 @@ -/* - * simple-prompt.js: Simple example of using prompt. - * - * (C) 2010, Nodejitsu Inc. - * - */ - -var prompt = require('../lib/prompt'); - -// -// Start the prompt -// -prompt.start(); - -// -// Get two properties from the user: username and password -// -prompt.get([{ - name:'password', - hidden: true, - validator: function (value, next) { - setTimeout(next, 200); - } - }], function (err, result) { - // - // Log the results. - // - console.log('Command-line input received:'); - console.log(' password: ' + result.password); -}); diff --git a/node/node_modules/grunt/node_modules/prompt/examples/property-prompt.js b/node/node_modules/grunt/node_modules/prompt/examples/property-prompt.js deleted file mode 100644 index 7f3453e3f..000000000 --- a/node/node_modules/grunt/node_modules/prompt/examples/property-prompt.js +++ /dev/null @@ -1,45 +0,0 @@ -/* - * property-prompt.js: Example of using prompt with complex properties. - * - * (C) 2010, Nodejitsu Inc. - * - */ - -var prompt = require('../lib/prompt'); - -var properties = [ - { - name: 'name', - validator: /^[a-zA-Z\s-]+$/, - warning: 'Name must be only letters, spaces, or dashes', - empty: false - }, - { - name: 'email', - validator: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, - warning: 'Must be a valid email address' - }, - { - name: 'password', - empty: false, - hidden: true - } -]; - -// -// Start the prompt -// -prompt.start(); - -// -// Get two properties from the user: email, password -// -prompt.get(properties, function (err, result) { - // - // Log the results. - // - console.log('Command-line input received:'); - console.log(' name: ' + result.name); - console.log(' email: ' + result.email); - console.log(' password: ' + result.password); -}); diff --git a/node/node_modules/grunt/node_modules/prompt/examples/simple-prompt.js b/node/node_modules/grunt/node_modules/prompt/examples/simple-prompt.js deleted file mode 100644 index 6351656db..000000000 --- a/node/node_modules/grunt/node_modules/prompt/examples/simple-prompt.js +++ /dev/null @@ -1,25 +0,0 @@ -/* - * simple-prompt.js: Simple example of using prompt. - * - * (C) 2010, Nodejitsu Inc. - * - */ - -var prompt = require('../lib/prompt'); - -// -// Start the prompt -// -prompt.start(); - -// -// Get two properties from the user: username and email -// -prompt.get(['username', 'email'], function (err, result) { - // - // Log the results. - // - console.log('Command-line input received:'); - console.log(' username: ' + result.username); - console.log(' email: ' + result.email); -}); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/lib/prompt.js b/node/node_modules/grunt/node_modules/prompt/lib/prompt.js deleted file mode 100644 index d5a4e19e2..000000000 --- a/node/node_modules/grunt/node_modules/prompt/lib/prompt.js +++ /dev/null @@ -1,442 +0,0 @@ -/* - * prompt.js: Simple prompt for prompting information from the command line - * - * (C) 2010, Nodejitsu Inc. - * - */ - -var events = require('events'), - async = require('async'), - colors = require('colors'), - winston = require('winston'), - tty = require('tty'); - -// -// ### @private function capitalize (str) -// #### str {string} String to capitalize -// Capitalizes the string supplied. -// -function capitalize(str) { - return str.charAt(0).toUpperCase() + str.slice(1); -} - -// -// Expose version using `pkginfo` -// -require('pkginfo')(module, 'version'); - -var stdin, stdout, history = []; -var prompt = module.exports = Object.create(events.EventEmitter.prototype); -var logger = prompt.logger = new winston.Logger({ - transports: [new (winston.transports.Console)()] -}); - -prompt.started = false; -prompt.paused = false; -prompt.allowEmpty = false; -prompt.message = 'prompt'; -prompt.delimiter = ': '; - -// -// Create an empty object for the properties -// known to `prompt` -// -prompt.properties = {}; - -// -// Setup the default winston logger to use -// the `cli` levels and colors. -// -logger.cli(); - -// -// ### function start (options) -// #### @options {Object} **Optional** Options to consume by prompt -// Starts the prompt by listening to the appropriate events on `options.stdin` -// and `options.stdout`. If no streams are supplied, then `process.stdin` -// and `process.stdout` are used, respectively. -// -prompt.start = function (options) { - if (prompt.started) { - return; - } - - options = options || {}; - stdin = options.stdin || process.openStdin(); - stdout = options.stdout || process.stdout; - - // - // By default: Remeber the last `10` prompt property / - // answer pairs and don't allow empty responses globally. - // - prompt.memory = options.memory || 10; - prompt.allowEmpty = options.allowEmpty || false; - prompt.message = options.message || prompt.message; - prompt.delimiter = options.delimiter || prompt.delimiter; - - if (process.platform !== 'win32') { - // windows falls apart trying to deal with SIGINT - process.on('SIGINT', function () { - stdout.write('\n'); - process.exit(1); - }); - } - - prompt.emit('start'); - prompt.started = true; - return prompt; -}; - -// -// ### function pause () -// Pauses input coming in from stdin -// -prompt.pause = function () { - if (!prompt.started || prompt.paused) { - return; - } - - stdin.pause(); - prompt.emit('pause'); - prompt.paused = true; - return prompt; -}; - -// -// ### function resume () -// Resumes input coming in from stdin -// -prompt.resume = function () { - if (!prompt.started || !prompt.paused) { - return; - } - - stdin.resume(); - prompt.emit('resume'); - prompt.paused = false; - return prompt; -}; - -// -// ### function history (search) -// #### @search {Number|string} Index or property name to find. -// Returns the `property:value` pair from within the prompts -// `history` array. -// -prompt.history = function (search) { - if (typeof search === 'number') { - return history[search] || {}; - } - - var names = history.map(function (pair) { - return typeof pair.property === 'string' - ? pair.property - : pair.property.name; - }); - - if (~names.indexOf(search)) { - return null; - } - - return history.filter(function (name) { - return typeof pair.property === 'string' - ? pair.property === name - : pair.property.name === name; - })[0]; -}; - -// -// ### function get (msg, [validator,] callback) -// #### @msg {Array|Object|string} Set of variables to get input for. -// #### @callback {function} Continuation to pass control to when complete. -// Gets input from the user via stdin for the specified message(s) `msg`. -// -prompt.get = function (msg, callback) { - var vars = !Array.isArray(msg) ? [msg] : msg, - result = {}; - - vars = vars.map(function (v) { - if (typeof v === 'string') { - v = v.toLowerCase(); - } - - return prompt.properties[v] || v; - }); - - function get(target, next) { - prompt.getInput(target, function (err, line) { - if (err) { - return next(err); - } - - var name = target.name || target; - result[name] = line; - next(); - }); - } - - async.forEachSeries(vars, get, function (err) { - return err ? callback(err) : callback(null, result); - }); - - return prompt; -}; - -// -// ### function getInput (msg, validator, callback) -// #### @msg {Object|string} Variable to get input for. -// #### @callback {function} Continuation to pass control to when complete. -// Gets input from the user via stdin for the specified message `msg`. -// -prompt.getInput = function (prop, callback) { - var name = prop.message || prop.name || prop, - propName = prop.name || prop, - delim = prompt.delimiter, - raw = [prompt.message, delim + name.grey, delim.grey], - read = prop.hidden ? prompt.readLineHidden : prompt.readLine, - length, msg; - - if (prompt.override && prompt.override[propName]) { - return callback (null, prompt.override[propName]) - } - - if (prop.default) { - raw.splice(2, -1, ' (' + prop.default + ')'); - } - - // Calculate the raw length and colorize the prompt - length = raw.join('').length; - raw[0] = raw[0]; - msg = raw.join(''); - - if (prop.help) { - prop.help.forEach(function (line) { - logger.help(line); - }); - } - - stdout.write(msg); - prompt.emit('prompt', prop); - - read.call(null, function (err, line) { - if (err) { - return callback(err); - } - - if (!line || line === '') { - line = prop.default || line; - } - - if (!prop.validator && prop.empty !== false) { - logger.input(line.yellow); - return callback(null, line); - } - - var valid = true, - validator = prop.validator; - - function next(valid) { - if (arguments.length < 1) { - valid = true; - } - - if (prop.empty === false && valid) { - valid = line.length > 0; - if (!valid) { - prop.warning = prop.warning || 'You must supply a value.'; - } - } - - if (!valid) { - logger.error('Invalid input for ' + name.grey); - if (prop.warning) { - logger.error(prop.warning); - } - - prompt.emit('invalid', prop, line); - return prompt.getInput(prop, callback); - } - - // - // Log the resulting line, append this `property:value` - // pair to the history for `prompt` and respond to - // the callback. - // - logger.input(line.yellow); - prompt._remember(prop, line); - callback(null, line); - } - - if (validator) { - if (validator.test) { - valid = validator.test(line) - } - else if (typeof validator === 'function') { - return validator.length < 2 - ? next(validator(line)) - : validator(line, next); - } - else { - return callback(new Error('Invalid valiator: ' + typeof validator)); - } - } - - next(valid); - }); - - return prompt; -}; - -// -// ### function addProperties (obj, properties, callback) -// #### @obj {Object} Object to add properties to -// #### @properties {Array} List of properties to get values for -// #### @callback {function} Continuation to pass control to when complete. -// Prompts the user for values each of the `properties` if `obj` does not already -// have a value for the property. Responds with the modified object. -// -prompt.addProperties = function (obj, properties, callback) { - properties = properties.filter(function (prop) { - return typeof obj[prop] === 'undefined'; - }); - - if (properties.length === 0) { - return callback(obj); - } - - prompt.get(properties, function (err, results) { - if (err) { - return callback(err); - } - else if (!results) { - return callback(null, obj); - } - - function putNested (obj, path, value) { - var last = obj, key; - - while (path.length > 1) { - key = path.shift(); - if (!last[key]) { - last[key] = {}; - } - - last = last[key]; - } - - last[path.shift()] = value; - } - - Object.keys(results).forEach(function (key) { - putNested(obj, key.split('.'), results[key]); - }); - - callback(null, obj); - }); - - return prompt; -}; - -// -// ### function readLine (callback) -// #### @callback {function} Continuation to respond to when complete -// Gets a single line of input from the user. -// -prompt.readLine = function (callback) { - var value = '', buffer = ''; - prompt.resume(); - stdin.setEncoding('utf8'); - stdin.on('error', callback); - stdin.on('data', function data (chunk) { - value += buffer + chunk; - buffer = ''; - value = value.replace(/\r/g, ''); - if (value.indexOf('\n') !== -1) { - if (value !== '\n') { - value = value.replace(/^\n+/, ''); - } - - buffer = value.substr(value.indexOf('\n')); - value = value.substr(0, value.indexOf('\n')); - prompt.pause(); - stdin.removeListener('data', data); - stdin.removeListener('error', callback); - value = value.trim(); - callback(null, value); - } - }); - - return prompt; -}; - -// -// ### function readLineHidden (callback) -// #### @callback {function} Continuation to respond to when complete -// Gets a single line of hidden input (i.e. `rawMode = true`) from the user. -// -prompt.readLineHidden = function (callback) { - var value = ''; - - // - // Ignore errors from `.setRawMode()` so that `prompt` can - // be scripted in child processes. - // - try { tty.setRawMode(true) } - catch (ex) { } - - prompt.resume(); - stdin.on('error', callback); - stdin.on('data', function data (line) { - line = line + ''; - for(var i = 0; i < line.length; i++) { - c = line[i]; - switch (c) { - case '\n': case '\r': case '\r\n': case '\u0004': - try { tty.setRawMode(false) } - catch (ex) { } - stdin.removeListener('data', data); - stdin.removeListener('error', callback); - value = value.trim(); - stdout.write('\n'); - stdout.flush && stdout.flush(); - prompt.pause(); - return callback(null, value); - case '\x7f': case'\x08': - value = value.slice(0,-1); - break; - case '\u0003': case '\0': - stdout.write('\n'); - process.exit(1); - break; - default: - value = value + c; - break; - } - } - }); - - return prompt; -}; - -// -// ### @private function _remember (property, value) -// #### @property {Object|string} Property that the value is in response to. -// #### @value {string} User input captured by `prompt`. -// Prepends the `property:value` pair into the private `history` Array -// for `prompt` so that it can be accessed later. -// -prompt._remember = function (property, value) { - history.unshift({ - property: property, - value: value - }); - - // - // If the length of the `history` Array - // has exceeded the specified length to remember, - // `prompt.memory`, truncate it. - // - if (history.length > prompt.memory) { - history.splice(prompt.memory, history.length - prompt.memory); - } -}; diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/.npmignore b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/.npmignore deleted file mode 100644 index 9303c347e..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/LICENSE b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/LICENSE deleted file mode 100644 index ed4a4e701..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Charlie Robbins. - -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/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/README.md b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/README.md deleted file mode 100644 index 332704ef1..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/README.md +++ /dev/null @@ -1,86 +0,0 @@ -# node-pkginfo - -An easy way to expose properties on a module from a package.json - -## Installation - -### Installing npm (node package manager) -``` - curl http://npmjs.org/install.sh | sh -``` - -### Installing pkginfo -``` - [sudo] npm install pkginfo -``` - -## Motivation -How often when writing node.js modules have you written the following line(s) of code? - -* Hard code your version string into your code - -``` js - exports.version = '0.1.0'; -``` - -* Programmatically expose the version from the package.json - -``` js - exports.version = JSON.parse(fs.readFileSync('/path/to/package.json', 'utf8')).version; -``` - -In other words, how often have you wanted to expose basic information from your package.json onto your module programmatically? **WELL NOW YOU CAN!** - -## Usage - -Using `pkginfo` is idiot-proof, just require and invoke it. - -``` js - var pkginfo = require('pkginfo')(module); - - console.dir(module.exports); -``` - -By invoking the `pkginfo` module all of the properties in your `package.json` file will be automatically exposed on the callee module (i.e. the parent module of `pkginfo`). - -Here's a sample of the output: - -``` - { name: 'simple-app', - description: 'A test fixture for pkginfo', - version: '0.1.0', - author: 'Charlie Robbins ', - keywords: [ 'test', 'fixture' ], - main: './index.js', - scripts: { test: 'vows test/*-test.js --spec' }, - engines: { node: '>= 0.4.0' } } -``` - -### Expose specific properties -If you don't want to expose **all** properties on from your `package.json` on your module then simple pass those properties to the `pkginfo` function: - -``` js - var pkginfo = require('pkginfo')(module, 'version', 'author'); - - console.dir(module.exports); -``` - -``` - { version: '0.1.0', - author: 'Charlie Robbins ' } -``` - -If you're looking for further usage see the [examples][0] included in this repository. - -## Run Tests -Tests are written in [vows][1] and give complete coverage of all APIs. - -``` - vows test/*-test.js --spec -``` - -[0]: https://github.com/indexzero/node-pkginfo/tree/master/examples -[1]: http://vowsjs.org - -#### Author: [Charlie Robbins](http://nodejitsu.com) -#### License: MIT \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/docs/docco.css b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/docs/docco.css deleted file mode 100644 index bd5413433..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/docs/docco.css +++ /dev/null @@ -1,194 +0,0 @@ -/*--------------------- Layout and Typography ----------------------------*/ -body { - font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; - font-size: 15px; - line-height: 22px; - color: #252519; - margin: 0; padding: 0; -} -a { - color: #261a3b; -} - a:visited { - color: #261a3b; - } -p { - margin: 0 0 15px 0; -} -h4, h5, h6 { - color: #333; - margin: 6px 0 6px 0; - font-size: 13px; -} - h2, h3 { - margin-bottom: 0; - color: #000; - } - h1 { - margin-top: 40px; - margin-bottom: 15px; - color: #000; - } -#container { - position: relative; -} -#background { - position: fixed; - top: 0; left: 525px; right: 0; bottom: 0; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - z-index: -1; -} -#jump_to, #jump_page { - background: white; - -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; - -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; - font: 10px Arial; - text-transform: uppercase; - cursor: pointer; - text-align: right; -} -#jump_to, #jump_wrapper { - position: fixed; - right: 0; top: 0; - padding: 5px 10px; -} - #jump_wrapper { - padding: 0; - display: none; - } - #jump_to:hover #jump_wrapper { - display: block; - } - #jump_page { - padding: 5px 0 3px; - margin: 0 0 25px 25px; - } - #jump_page .source { - display: block; - padding: 5px 10px; - text-decoration: none; - border-top: 1px solid #eee; - } - #jump_page .source:hover { - background: #f5f5ff; - } - #jump_page .source:first-child { - } -table td { - border: 0; - outline: 0; -} - td.docs, th.docs { - max-width: 450px; - min-width: 450px; - min-height: 5px; - padding: 10px 25px 1px 50px; - overflow-x: hidden; - vertical-align: top; - text-align: left; - } - .docs pre { - margin: 15px 0 15px; - padding-left: 15px; - } - .docs p tt, .docs p code { - background: #f8f8ff; - border: 1px solid #dedede; - font-size: 12px; - padding: 0 0.2em; - } - .pilwrap { - position: relative; - } - .pilcrow { - font: 12px Arial; - text-decoration: none; - color: #454545; - position: absolute; - top: 3px; left: -20px; - padding: 1px 2px; - opacity: 0; - -webkit-transition: opacity 0.2s linear; - } - td.docs:hover .pilcrow { - opacity: 1; - } - td.code, th.code { - padding: 14px 15px 16px 25px; - width: 100%; - vertical-align: top; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - } - pre, tt, code { - font-size: 12px; line-height: 18px; - font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; - margin: 0; padding: 0; - } - - -/*---------------------- Syntax Highlighting -----------------------------*/ -td.linenos { background-color: #f0f0f0; padding-right: 10px; } -span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } -body .hll { background-color: #ffffcc } -body .c { color: #408080; font-style: italic } /* Comment */ -body .err { border: 1px solid #FF0000 } /* Error */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ -body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { color: #0000FF } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/docs/pkginfo.html b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/docs/pkginfo.html deleted file mode 100644 index bf615fa91..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/docs/pkginfo.html +++ /dev/null @@ -1,101 +0,0 @@ - pkginfo.js

        pkginfo.js

        /*
        - * pkginfo.js: Top-level include for the pkginfo module
        - *
        - * (C) 2011, Charlie Robbins
        - *
        - */
        - 
        -var fs = require('fs'),
        -    path = require('path');

        function pkginfo ([options, 'property', 'property' ..])

        - -

        @pmodule {Module} Parent module to read from.

        - -

        @options {Object|Array|string} Optional Options used when exposing properties.

        - -

        @arguments {string...} Optional Specified properties to expose.

        - -

        Exposes properties from the package.json file for the parent module on -it's exports. Valid usage:

        - -

        require('pkginfo')()

        - -

        require('pkginfo')('version', 'author');

        - -

        require('pkginfo')(['version', 'author']);

        - -

        require('pkginfo')({ include: ['version', 'author'] });

        var pkginfo = module.exports = function (pmodule, options) {
        -  var args = [].slice.call(arguments, 2).filter(function (arg) {
        -    return typeof arg === 'string';
        -  });
        -  

        Parse variable arguments

          if (Array.isArray(options)) {

        If the options passed in is an Array assume that -it is the Array of properties to expose from the -on the package.json file on the parent module.

            options = { include: options };
        -  }
        -  else if (typeof options === 'string') {

        Otherwise if the first argument is a string, then -assume that it is the first property to expose from -the package.json file on the parent module.

            options = { include: [options] };
        -  }
        -  

        Setup default options

          options = options || { include: [] };
        -  
        -  if (args.length > 0) {

        If additional string arguments have been passed in -then add them to the properties to expose on the -parent module.

            options.include = options.include.concat(args);
        -  }
        -  
        -  var pkg = pkginfo.read(pmodule, options.dir).package;
        -  Object.keys(pkg).forEach(function (key) {
        -    if (options.include.length > 0 && !~options.include.indexOf(key)) {
        -      return;
        -    }
        -    
        -    if (!pmodule.exports[key]) {
        -      pmodule.exports[key] = pkg[key];
        -    }
        -  });
        -  
        -  return pkginfo;
        -};

        function find (dir)

        - -

        @pmodule {Module} Parent module to read from.

        - -

        @dir {string} Optional Directory to start search from.

        - -

        Searches up the directory tree from dir until it finds a directory -which contains a package.json file.

        pkginfo.find = function (pmodule, dir) {
        -  dir = dir || pmodule.filename;
        -  dir = path.dirname(dir); 
        -  
        -  var files = fs.readdirSync(dir);
        -  
        -  if (~files.indexOf('package.json')) {
        -    return path.join(dir, 'package.json');
        -  }
        -  
        -  if (dir === '/') {
        -    throw new Error('Could not find package.json up from: ' + dir);
        -  }
        -  
        -  return pkginfo.find(dir);
        -};

        function read (pmodule, dir)

        - -

        @pmodule {Module} Parent module to read from.

        - -

        @dir {string} Optional Directory to start search from.

        - -

        Searches up the directory tree from dir until it finds a directory -which contains a package.json file and returns the package information.

        pkginfo.read = function (pmodule, dir) { 
        -  dir = pkginfo.find(pmodule, dir);
        -  
        -  var data = fs.readFileSync(dir).toString();
        -      
        -  return {
        -    dir: dir, 
        -    package: JSON.parse(data)
        -  };
        -};

        Call pkginfo on this module and expose version.

        pkginfo(module, {
        -  dir: __dirname,
        -  include: ['version'],
        -  target: pkginfo
        -});
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/all-properties.js b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/all-properties.js deleted file mode 100644 index fd1d831aa..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/all-properties.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * all-properties.js: Sample of including all properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/array-argument.js b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/array-argument.js deleted file mode 100644 index b1b684874..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/array-argument.js +++ /dev/null @@ -1,20 +0,0 @@ -/* - * array-argument.js: Sample of including specific properties from a package.json file - * using Array argument syntax. - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, ['version', 'author']); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/multiple-properties.js b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/multiple-properties.js deleted file mode 100644 index b4b5fd617..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/multiple-properties.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * multiple-properties.js: Sample of including multiple properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, 'version', 'author'); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/object-argument.js b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/object-argument.js deleted file mode 100644 index 28420c854..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/object-argument.js +++ /dev/null @@ -1,22 +0,0 @@ -/* - * object-argument.js: Sample of including specific properties from a package.json file - * using Object argument syntax. - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, { - include: ['version', 'author'] - }); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/package.json b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/package.json deleted file mode 100644 index 1f2f01c19..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "simple-app", - "description": "A test fixture for pkginfo", - "version": "0.1.0", - "author": "Charlie Robbins ", - "keywords": ["test", "fixture"], - "main": "./index.js", - "scripts": { "test": "vows test/*-test.js --spec" }, - "engines": { "node": ">= 0.4.0" } -} diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/single-property.js b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/single-property.js deleted file mode 100644 index 4f445614b..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/single-property.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * single-property.js: Sample of including a single specific properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, 'version'); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/subdir/package.json b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/subdir/package.json deleted file mode 100644 index aa8541022..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/subdir/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "simple-app-subdir", - "description": "A test fixture for pkginfo", - "version": "0.1.0", - "author": "Charlie Robbins ", - "keywords": ["test", "fixture"], - "main": "./index.js", - "scripts": { "test": "vows test/*-test.js --spec" }, - "engines": { "node": ">= 0.4.0" }, - "subdironly": "true" -} diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/target-dir.js b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/target-dir.js deleted file mode 100644 index 88770e6f5..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/examples/target-dir.js +++ /dev/null @@ -1,20 +0,0 @@ -/* - * multiple-properties.js: Sample of including multiple properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - path = require('path'), - pkginfo = require('../lib/pkginfo')(module, { dir: path.resolve(__dirname, 'subdir' )}); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/lib/pkginfo.js b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/lib/pkginfo.js deleted file mode 100644 index c5dc0203f..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/lib/pkginfo.js +++ /dev/null @@ -1,136 +0,0 @@ -/* - * pkginfo.js: Top-level include for the pkginfo module - * - * (C) 2011, Charlie Robbins - * - */ - -var fs = require('fs'), - path = require('path'); - -// -// ### function pkginfo ([options, 'property', 'property' ..]) -// #### @pmodule {Module} Parent module to read from. -// #### @options {Object|Array|string} **Optional** Options used when exposing properties. -// #### @arguments {string...} **Optional** Specified properties to expose. -// Exposes properties from the package.json file for the parent module on -// it's exports. Valid usage: -// -// `require('pkginfo')()` -// -// `require('pkginfo')('version', 'author');` -// -// `require('pkginfo')(['version', 'author']);` -// -// `require('pkginfo')({ include: ['version', 'author'] });` -// -var pkginfo = module.exports = function (pmodule, options) { - var args = [].slice.call(arguments, 2).filter(function (arg) { - return typeof arg === 'string'; - }); - - // - // **Parse variable arguments** - // - if (Array.isArray(options)) { - // - // If the options passed in is an Array assume that - // it is the Array of properties to expose from the - // on the package.json file on the parent module. - // - options = { include: options }; - } - else if (typeof options === 'string') { - // - // Otherwise if the first argument is a string, then - // assume that it is the first property to expose from - // the package.json file on the parent module. - // - options = { include: [options] }; - } - - // - // **Setup default options** - // - options = options || {}; - - // ensure that includes have been defined - options.include = options.include || []; - - if (args.length > 0) { - // - // If additional string arguments have been passed in - // then add them to the properties to expose on the - // parent module. - // - options.include = options.include.concat(args); - } - - var pkg = pkginfo.read(pmodule, options.dir).package; - Object.keys(pkg).forEach(function (key) { - if (options.include.length > 0 && !~options.include.indexOf(key)) { - return; - } - - if (!pmodule.exports[key]) { - pmodule.exports[key] = pkg[key]; - } - }); - - return pkginfo; -}; - -// -// ### function find (dir) -// #### @pmodule {Module} Parent module to read from. -// #### @dir {string} **Optional** Directory to start search from. -// Searches up the directory tree from `dir` until it finds a directory -// which contains a `package.json` file. -// -pkginfo.find = function (pmodule, dir) { - if (! dir) { - dir = path.dirname(pmodule.filename); - } - - var files = fs.readdirSync(dir); - - if (~files.indexOf('package.json')) { - return path.join(dir, 'package.json'); - } - - if (dir === '/') { - throw new Error('Could not find package.json up from: ' + dir); - } - else if (!dir || dir === '.') { - throw new Error('Cannot find package.json from unspecified directory'); - } - - return pkginfo.find(pmodule, path.dirname(dir)); -}; - -// -// ### function read (pmodule, dir) -// #### @pmodule {Module} Parent module to read from. -// #### @dir {string} **Optional** Directory to start search from. -// Searches up the directory tree from `dir` until it finds a directory -// which contains a `package.json` file and returns the package information. -// -pkginfo.read = function (pmodule, dir) { - dir = pkginfo.find(pmodule, dir); - - var data = fs.readFileSync(dir).toString(); - - return { - dir: dir, - package: JSON.parse(data) - }; -}; - -// -// Call `pkginfo` on this module and expose version. -// -pkginfo(module, { - dir: __dirname, - include: ['version'], - target: pkginfo -}); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/package.json b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/package.json deleted file mode 100644 index 173f799d7..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "pkginfo", - "version": "0.3.0", - "description": "An easy way to expose properties on a module from a package.json", - "author": { - "name": "Charlie Robbins", - "email": "charlie.robbins@gmail.com" - }, - "repository": { - "type": "git", - "url": "http://github.com/indexzero/node-pkginfo.git" - }, - "keywords": [ - "info", - "tools", - "package.json" - ], - "devDependencies": { - "vows": "0.7.x" - }, - "main": "./lib/pkginfo", - "scripts": { - "test": "vows test/*-test.js --spec" - }, - "engines": { - "node": ">= 0.4.0" - }, - "readme": "# node-pkginfo\n\nAn easy way to expose properties on a module from a package.json\n\n## Installation\n\n### Installing npm (node package manager)\n```\n curl http://npmjs.org/install.sh | sh\n```\n\n### Installing pkginfo\n```\n [sudo] npm install pkginfo\n```\n\n## Motivation\nHow often when writing node.js modules have you written the following line(s) of code? \n\n* Hard code your version string into your code\n\n``` js\n exports.version = '0.1.0';\n```\n\n* Programmatically expose the version from the package.json\n\n``` js\n exports.version = JSON.parse(fs.readFileSync('/path/to/package.json', 'utf8')).version;\n```\n\nIn other words, how often have you wanted to expose basic information from your package.json onto your module programmatically? **WELL NOW YOU CAN!**\n\n## Usage\n\nUsing `pkginfo` is idiot-proof, just require and invoke it. \n\n``` js\n var pkginfo = require('pkginfo')(module);\n \n console.dir(module.exports);\n```\n\nBy invoking the `pkginfo` module all of the properties in your `package.json` file will be automatically exposed on the callee module (i.e. the parent module of `pkginfo`). \n\nHere's a sample of the output:\n\n```\n { name: 'simple-app',\n description: 'A test fixture for pkginfo',\n version: '0.1.0',\n author: 'Charlie Robbins ',\n keywords: [ 'test', 'fixture' ],\n main: './index.js',\n scripts: { test: 'vows test/*-test.js --spec' },\n engines: { node: '>= 0.4.0' } }\n```\n\n### Expose specific properties\nIf you don't want to expose **all** properties on from your `package.json` on your module then simple pass those properties to the `pkginfo` function:\n\n``` js\n var pkginfo = require('pkginfo')(module, 'version', 'author');\n \n console.dir(module.exports);\n```\n\n```\n { version: '0.1.0',\n author: 'Charlie Robbins ' }\n```\n\nIf you're looking for further usage see the [examples][0] included in this repository. \n\n## Run Tests\nTests are written in [vows][1] and give complete coverage of all APIs.\n\n```\n vows test/*-test.js --spec\n```\n\n[0]: https://github.com/indexzero/node-pkginfo/tree/master/examples\n[1]: http://vowsjs.org\n\n#### Author: [Charlie Robbins](http://nodejitsu.com)\n#### License: MIT", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/indexzero/node-pkginfo/issues" - }, - "_id": "pkginfo@0.3.0", - "_from": "pkginfo@0.x.x" -} diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/test/pkginfo-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/test/pkginfo-test.js deleted file mode 100644 index a59f077e8..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/pkginfo/test/pkginfo-test.js +++ /dev/null @@ -1,83 +0,0 @@ -/* - * pkginfo-test.js: Tests for the pkginfo module. - * - * (C) 2011, Charlie Robbins - * - */ - -var assert = require('assert'), - exec = require('child_process').exec, - fs = require('fs'), - path = require('path'), - vows = require('vows'), - pkginfo = require('../lib/pkginfo'); - -function assertProperties (source, target) { - assert.lengthOf(source, target.length + 1); - target.forEach(function (prop) { - assert.isTrue(!!~source.indexOf(prop)); - }); -} - -function compareWithExample(targetPath) { - var examplePaths = ['package.json']; - - if (targetPath) { - examplePaths.unshift(targetPath); - } - - return function(exposed) { - var pkg = fs.readFileSync(path.join.apply(null, [__dirname, '..', 'examples'].concat(examplePaths))).toString(), - keys = Object.keys(JSON.parse(pkg)); - - assertProperties(exposed, keys); - }; -} - -function testExposes (options) { - return { - topic: function () { - exec('node ' + path.join(__dirname, '..', 'examples', options.script), this.callback); - }, - "should expose that property correctly": function (err, stdout, stderr) { - assert.isNull(err); - - var exposed = stderr.match(/'(\w+)'/ig).map(function (p) { - return p.substring(1, p.length - 1); - }); - - return !options.assert - ? assertProperties(exposed, options.properties) - : options.assert(exposed); - } - } -} - -vows.describe('pkginfo').addBatch({ - "When using the pkginfo module": { - "and passed a single `string` argument": testExposes({ - script: 'single-property.js', - properties: ['version'] - }), - "and passed multiple `string` arguments": testExposes({ - script: 'multiple-properties.js', - properties: ['version', 'author'] - }), - "and passed an `object` argument": testExposes({ - script: 'object-argument.js', - properties: ['version', 'author'] - }), - "and passed an `array` argument": testExposes({ - script: 'array-argument.js', - properties: ['version', 'author'] - }), - "and read from a specified directory": testExposes({ - script: 'target-dir.js', - assert: compareWithExample('subdir') - }), - "and passed no arguments": testExposes({ - script: 'all-properties.js', - assert: compareWithExample() - }) - } -}).export(module); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/.npmignore b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/.npmignore deleted file mode 100644 index 2c5c40a87..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/.npmignore +++ /dev/null @@ -1,6 +0,0 @@ -test/*.log -test/fixtures/*.json -test/fixtures/logs/*.log -node_modules/ -node_modules/* -npm-debug.log \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/.travis.yml b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/.travis.yml deleted file mode 100644 index c958222c4..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/.travis.yml +++ /dev/null @@ -1,11 +0,0 @@ -language: node_js -node_js: - - 0.4 - - 0.6 - - 0.7 - -notifications: - email: - - travis@nodejitsu.com - irc: "irc.freenode.org#nodejitsu" - diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/LICENSE b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/LICENSE deleted file mode 100644 index 948d80dd6..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Charlie Robbins - -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/node_modules/grunt/node_modules/prompt/node_modules/winston/README.md b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/README.md deleted file mode 100644 index ecf79f329..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/README.md +++ /dev/null @@ -1,732 +0,0 @@ -# winston [![Build Status](https://secure.travis-ci.org/flatiron/winston.png)](http://travis-ci.org/flatiron/winston) - -A multi-transport async logging library for node.js. "CHILL WINSTON! ... I put it in the logs." - -## Installation - -### Installing npm (node package manager) -``` - curl http://npmjs.org/install.sh | sh -``` - -### Installing winston -``` - [sudo] npm install winston -``` - -## Motivation -Winston is designed to be a simple and universal logging library with support for multiple transports. A transport is essentially a storage device for your logs. Each instance of a winston logger can have multiple transports configured at different levels. For example, one may want error logs to be stored in a persistent remote location (like a database), but all logs output to the console or a local file. - -There also seemed to be a lot of logging libraries out there that coupled their implementation of logging (i.e. how the logs are stored / indexed) to the API that they exposed to the programmer. This library aims to decouple those parts of the process to make it more flexible and extensible. - -## Usage -There are two different ways to use winston: directly via the default logger, or by instantiating your own Logger. The former is merely intended to be a convenient shared logger to use throughout your application if you so choose. - -### Using the Default Logger -The default logger is accessible through the winston module directly. Any method that you could call on an instance of a logger is available on the default logger: - -``` js - var winston = require('winston'); - - winston.log('info', 'Hello distributed log files!'); - winston.info('Hello again distributed logs'); -``` - -By default, only the Console transport is set on the default logger. You can add or remove transports via the add() and remove() methods: - -``` js - winston.add(winston.transports.File, { filename: 'somefile.log' }); - winston.remove(winston.transports.Console); -``` - -For more documenation about working with each individual transport supported by Winston see the "Working with Transports" section below. - -### Instantiating your own Logger -If you would prefer to manage the object lifetime of loggers you are free to instantiate them yourself: - -``` js - var logger = new (winston.Logger)({ - transports: [ - new (winston.transports.Console)(), - new (winston.transports.File)({ filename: 'somefile.log' }) - ] - }); -``` - -You can work with this logger in the same way that you work with the default logger: - -``` js - // - // Logging - // - logger.log('info', 'Hello distributed log files!'); - logger.info('Hello again distributed logs'); - - // - // Adding / Removing Transports - // (Yes It's chainable) - // - logger.add(winston.transports.File) - .remove(winston.transports.Console); -``` - -### Handling Uncaught Exceptions with winston - -With `winston`, it is possible to catch and log `uncaughtException` events from your process. There are two distinct ways of enabling this functionality either through the default winston logger or your own logger instance. - -If you want to use this feature with the default logger simply call `.handleExceptions()` with a transport instance. - -``` js - // - // You can add a separate exception logger by passing it to `.handleExceptions` - // - winston.handleExceptions(new winston.transports.File({ filename: 'path/to/exceptions.log' })) - - // - // Alternatively you can set `.handleExceptions` to true when adding transports to winston - // - winston.add(winston.transports.File, { - filename: 'path/to/all-logs.log', - handleExceptions: true - }); -``` - -## to exit or not to exit - -by default, winston will exit after logging an uncaughtException. if this is not the behavior you want, -set `exitOnError = false` - -``` js - var logger = new (winston.Logger)({ exitOnError: false }); - - // - // or, like this: - // - logger.exitOnError = false; -``` - -When working with custom logger instances, you can pass in separate transports to the `exceptionHandlers` property or set `.handleExceptions` on any transport. - -``` js - var logger = new (winston.Logger)({ - transports: [ - new winston.transports.File({ filename: 'path/to/all-logs.log' }) - ] - exceptionHandlers: [ - new winston.transports.File({ filename: 'path/to/exceptions.log' }) - ] - }); -``` - -The `exitOnError` option can also be a function to prevent exit on only certain types of errors: - -``` js - function ignoreEpipe(err) { - return err.code !== 'EPIPE'; - } - - var logger = new (winston.Logger)({ exitOnError: ignoreEpipe }); - - // - // or, like this: - // - logger.exitOnError = ignoreEpipe; -``` - -### Using Logging Levels -Setting the level for your logging message can be accomplished in one of two ways. You can pass a string representing the logging level to the log() method or use the level specified methods defined on every winston Logger. - -``` js - // - // Any logger instance - // - logger.log('info', "127.0.0.1 - there's no place like home"); - logger.info("127.0.0.1 - there's no place like home"); - - // - // Default logger - // - winston.log('info', "127.0.0.1 - there's no place like home"); - winston.info("127.0.0.1 - there's no place like home"); -``` - -As of 0.2.0, winston supports customizable logging levels, defaulting to [npm][0] style logging levels. Changing logging levels is easy: - -``` js - // - // Change levels on the default winston logger - // - winston.setLevels(winston.config.syslog.levels); - - // - // Change levels on an instance of a logger - // - logger.setLevels(winston.config.syslog.levels); -``` - -Calling `.setLevels` on a logger will remove all of the previous helper methods for the old levels and define helper methods for the new levels. Thus, you should be careful about the logging statements you use when changing levels. For example, if you ran this code after changing to the syslog levels: - -``` js - // - // Logger does not have 'silly' defined since that level is not in the syslog levels - // - logger.silly('some silly message'); -``` - -### Using Custom Logging Levels -In addition to the predefined `npm` and `syslog` levels available in Winston, you can also choose to define your own: - -``` js - var myCustomLevels = { - levels: { - foo: 0, - bar: 1, - baz: 2, - foobar: 3 - }, - colors: { - foo: 'blue', - bar: 'green', - baz: 'yellow', - foobar: 'red' - } - }; - - var customLevelLogger = new (winston.Logger)({ levels: myCustomLevels.levels }); - customLevelLogger.foobar('some foobar level-ed message'); -``` - -Although there is slight repetition in this data structure, it enables simple encapsulation if you not to have colors. If you do wish to have colors, in addition to passing the levels to the Logger itself, you must make winston aware of them: - -``` js - // - // Make winston aware of these colors - // - winston.addColors(myCustomLevels.colors); -``` - -This enables transports with the 'colorize' option set to appropriately color the output of custom levels. - -### Events and Callbacks in Winston -Each instance of winston.Logger is also an instance of an [EventEmitter][1]. A log event will be raised each time a transport successfully logs a message: - -``` js - logger.on('logging', function (transport, level, msg, meta) { - // [msg] and [meta] have now been logged at [level] to [transport] - }); - - logger.info('CHILL WINSTON!', { seriously: true }); -``` - -It is also worth mentioning that the logger also emits an 'error' event which you should handle or suppress if you don't want unhandled exceptions: - -``` js - // - // Handle errors - // - logger.on('error', function (err) { /* Do Something */ }); - - // - // Or just suppress them. - // - logger.emitErrs = false; -``` - -Every logging method described in the previous section also takes an optional callback which will be called only when all of the transports have logged the specified message. - -``` js - logger.info('CHILL WINSTON!', { seriously: true }, function (err, level, msg, meta) { - // [msg] and [meta] have now been logged at [level] to **every** transport. - }); -``` - -### Working with multiple Loggers in winston - -Often in larger, more complex applications it is necessary to have multiple logger instances with different settings. Each logger is responsible for a different feature area (or category). This is exposed in `winston` in two ways: through `winston.loggers` and instances of `winston.Container`. In fact, `winston.loggers` is just a predefined instance of `winston.Container`: - -``` js - var winston = require('winston'); - - // - // Configure the logger for `category1` - // - winston.loggers.add('category1', { - console: { - level: 'silly', - colorize: 'true' - }, - file: { - filename: '/path/to/some/file' - } - }); - - // - // Configure the logger for `category2` - // - winston.loggers.add('category2', { - couchdb: { - host: '127.0.0.1', - port: 5984 - } - }); -``` - -Now that your loggers are setup you can require winston _in any file in your application_ and access these pre-configured loggers: - -``` js - var winston = require('winston'); - - // - // Grab your preconfigured logger - // - var category1 = winston.loggers.get('category1'); - - category1.info('logging from your IoC container-based logger'); -``` - -If you prefer to manage the `Container` yourself you can simply instantiate one: - -``` js - var winston = require('winston'), - container = new winston.Container(); - - container.add('category1', { - console: { - level: 'silly', - colorize: 'true' - }, - file: { - filename: '/path/to/some/file' - } - }); -``` - -### Sharing transports between Loggers in winston - -``` js - var winston = require('winston'); - - // - // Setup transports to be shared across all loggers - // in three ways: - // - // 1. By setting it on the default Container - // 2. By passing `transports` into the constructor function of winston.Container - // 3. By passing `transports` into the `.get()` or `.add()` methods - // - - // - // 1. By setting it on the default Container - // - winston.loggers.options.transports = [ - // Setup your shared transports here - ]; - - // - // 2. By passing `transports` into the constructor function of winston.Container - // - var container = new winston.Container({ - transports: [ - // Setup your shared transports here - ] - }); - - // - // 3. By passing `transports` into the `.get()` or `.add()` methods - // - winston.loggers.add('some-category', { - transports: [ - // Setup your shared transports here - ] - }); - - container.add('some-category', { - transports: [ - // Setup your shared transports here - ] - }); -``` - -### Logging with Metadata -In addition to logging string messages, winston will also optionally log additional JSON metadata objects. Adding metadata is simple: - -``` js - winston.log('info', 'Test Log Message', { anything: 'This is metadata' }); -``` - -The way these objects is stored varies from transport to transport (to best support the storage mechanisms offered). Here's a quick summary of how each transports handles metadata: - -1. __Console:__ Logged via util.inspect(meta) -2. __File:__ Logged via util.inspect(meta) -3. __Loggly:__ Logged in suggested [Loggly format][2] - -### Profiling with Winston -In addition to logging messages and metadata, winston also has a simple profiling mechanism implemented for any logger: - -``` js - // - // Start profile of 'test' - // Remark: Consider using Date.now() with async operations - // - winston.profile('test'); - - setTimeout(function () { - // - // Stop profile of 'test'. Logging will now take place: - // "17 Jan 21:00:00 - info: test duration=1000ms" - // - winston.profile('test'); - }, 1000); -``` - -All profile messages are set to the 'info' by default and both message and metadata are optional There are no plans in the Roadmap to make this configurable, but I'm open to suggestions / issues. - -### Using winston in a CLI tool -A common use-case for logging is output to a CLI tool. Winston has a special helper method which will pretty print output from your CLI tool. Here's an example from the [require-analyzer][15] written by [Nodejitsu][5]: - -``` - info: require-analyzer starting in /Users/Charlie/Nodejitsu/require-analyzer - info: Found existing dependencies - data: { - data: colors: '0.x.x', - data: eyes: '0.1.x', - data: findit: '0.0.x', - data: npm: '1.0.x', - data: optimist: '0.2.x', - data: semver: '1.0.x', - data: winston: '0.2.x' - data: } - info: Analyzing dependencies... - info: Done analyzing raw dependencies - info: Retrieved packages from npm - warn: No additional dependencies found -``` - -Configuring output for this style is easy, just use the `.cli()` method on `winston` or an instance of `winston.Logger`: - -``` js - var winston = require('winston'); - - // - // Configure CLI output on the default logger - // - winston.cli(); - - // - // Configure CLI on an instance of winston.Logger - // - var logger = new winston.Logger({ - transports: [ - new (winston.transports.Console)() - ] - }); - - logger.cli(); -``` - -### Extending another object with Logging functionality -Often in a given code base with lots of Loggers it is useful to add logging methods a different object so that these methods can be called with less syntax. Winston exposes this functionality via the 'extend' method: - -``` js - var myObject = {}; - - logger.extend(myObject); - - // - // You can now call logger methods on 'myObject' - // - myObject.info('127.0.0.1 - there's no place like home'); -``` - -## Working with Transports -Right now there are four transports supported by winston core. If you have a transport you would like to add either open an issue or fork and submit a pull request. Commits are welcome, but I'll give you extra street cred if you __add tests too :D__ - -1. __Console:__ Output to the terminal -2. __Files:__ Append to a file -3. __Loggly:__ Log to Logging-as-a-Service platform Loggly - -### Console Transport -``` js - winston.add(winston.transports.Console, options) -``` - -The Console transport takes two simple options: - -* __level:__ Level of messages that this transport should log (default 'debug'). -* __silent:__ Boolean flag indicating whether to suppress output (default false). -* __colorize:__ Boolean flag indicating if we should colorize output (default false). -* __timestamp:__ Boolean flag indicating if we should prepend output with timestamps (default false). If function is specified, its return value will be used instead of timestamps. - -*Metadata:* Logged via util.inspect(meta); - -### File Transport -``` js - winston.add(winston.transports.File, options) -``` - -The File transport should really be the 'Stream' transport since it will accept any [WritableStream][14]. It is named such because it will also accept filenames via the 'filename' option: - -* __level:__ Level of messages that this transport should log. -* __silent:__ Boolean flag indicating whether to suppress output. -* __colorize:__ Boolean flag indicating if we should colorize output. -* __timestamp:__ Boolean flag indicating if we should prepend output with timestamps (default false). If function is specified, its return value will be used instead of timestamps. -* __filename:__ The filename of the logfile to write output to. -* __maxsize:__ Max size in bytes of the logfile, if the size is exceeded then a new file is created. -* __maxFiles:__ Limit the number of files created when the size of the logfile is exceeded. -* __stream:__ The WriteableStream to write output to. -* __json:__ If true, messages will be logged as JSON (default true). - -*Metadata:* Logged via util.inspect(meta); - -### Loggly Transport -``` js - winston.add(winston.transports.Loggly, options); -``` - -The Loggly transport is based on [Nodejitsu's][5] [node-loggly][6] implementation of the [Loggly][7] API. If you haven't heard of Loggly before, you should probably read their [value proposition][8]. The Loggly transport takes the following options. Either 'inputToken' or 'inputName' is required: - -* __level:__ Level of messages that this transport should log. -* __subdomain:__ The subdomain of your Loggly account. *[required]* -* __auth__: The authentication information for your Loggly account. *[required with inputName]* -* __inputName:__ The name of the input this instance should log to. -* __inputToken:__ The input token of the input this instance should log to. -* __json:__ If true, messages will be sent to Loggly as JSON. - -*Metadata:* Logged in suggested [Loggly format][2] - -### Riak Transport -As of `0.3.0` the Riak transport has been broken out into a new module: [winston-riak][17]. Using it is just as easy: - -``` js - var Riak = require('winston-riak').Riak; - winston.add(Riak, options); -``` - -In addition to the options accepted by the [riak-js][3] [client][4], the Riak transport also accepts the following options. It is worth noting that the riak-js debug option is set to *false* by default: - -* __level:__ Level of messages that this transport should log. -* __bucket:__ The name of the Riak bucket you wish your logs to be in or a function to generate bucket names dynamically. - -``` js - // Use a single bucket for all your logs - var singleBucketTransport = new (Riak)({ bucket: 'some-logs-go-here' }); - - // Generate a dynamic bucket based on the date and level - var dynamicBucketTransport = new (Riak)({ - bucket: function (level, msg, meta, now) { - var d = new Date(now); - return level + [d.getDate(), d.getMonth(), d.getFullYear()].join('-'); - } - }); -``` - -*Metadata:* Logged as JSON literal in Riak - -### MongoDB Transport -As of `0.3.0` the MongoDB transport has been broken out into a new module: [winston-mongodb][16]. Using it is just as easy: - -``` js - var MongoDB = require('winston-mongodb').MongoDB; - winston.add(MongoDB, options); -``` - -The MongoDB transport takes the following options. 'db' is required: - -* __level:__ Level of messages that this transport should log. -* __silent:__ Boolean flag indicating whether to suppress output. -* __db:__ The name of the database you want to log to. *[required]* -* __collection__: The name of the collection you want to store log messages in, defaults to 'log'. -* __safe:__ Boolean indicating if you want eventual consistency on your log messages, if set to true it requires an extra round trip to the server to ensure the write was committed, defaults to true. -* __host:__ The host running MongoDB, defaults to localhost. -* __port:__ The port on the host that MongoDB is running on, defaults to MongoDB's default port. - -*Metadata:* Logged as a native JSON object. - -### SimpleDB Transport - -The [winston-simpledb][18] transport is just as easy: - -``` js - var SimpleDB = require('winston-simpledb').SimpleDB; - winston.add(SimpleDB, options); -``` - -The SimpleDB transport takes the following options. All items marked with an asterisk are required: - -* __awsAccessKey__:* your AWS Access Key -* __secretAccessKey__:* your AWS Secret Access Key -* __awsAccountId__:* your AWS Account Id -* __domainName__:* a string or function that returns the domain name to log to -* __region__:* the region your domain resides in -* __itemName__: a string ('uuid', 'epoch', 'timestamp') or function that returns the item name to log - -*Metadata:* Logged as a native JSON object to the 'meta' attribute of the item. - -### Mail Transport - -The [winston-mail][19] is an email transport: - -``` js - var Mail = require('winston-mail').Mail; - winston.add(Mail, options); -``` - -The Mail transport uses [node-mail][20] behind the scenes. Options are the following, `to` and `host` are required: - -* __to:__ The address(es) you want to send to. *[required]* -* __from:__ The address you want to send from. (default: `winston@[server-host-name]`) -* __host:__ SMTP server hostname -* __port:__ SMTP port (default: 587 or 25) -* __secure:__ Use secure -* __username__ User for server auth -* __password__ Password for server auth -* __level:__ Level of messages that this transport should log. -* __silent:__ Boolean flag indicating whether to suppress output. - -*Metadata:* Stringified as JSON in email. - -### Amazon SNS (Simple Notification System) Transport - -The [winston-sns][21] transport uses amazon SNS to send emails, texts, or a bunch of other notifications. - -``` js - require('winston-sns').SNS; - winston.add(winston.transports.SNS, options); -``` - -Options: - -* __aws_key:__ Your Amazon Web Services Key. *[required]* -* __aws_secret:__ Your Amazon Web Services Secret. *[required]* -* __subscriber:__ Subscriber number - found in your SNS AWS Console, after clicking on a topic. Same as AWS Account ID. *[required]* -* __topic_arn:__ Also found in SNS AWS Console - listed under a topic as Topic ARN. *[required]* -* __region:__ AWS Region to use. Can be one of: `us-east-1`,`us-west-1`,`eu-west-1`,`ap-southeast-1`,`ap-northeast-1`,`us-gov-west-1`,`sa-east-1`. (default: `us-east-1`) -* __subject:__ Subject for notifications. (default: "Winston Error Report") -* __message:__ Message of notifications. Uses placeholders for level (%l), error message (%e), and metadata (%m). (default: "Level '%l' Error:\n%e\n\nMetadata:\n%m") -* __level:__ lowest level this transport will log. (default: `info`) - -### Graylog2 Transport - -[winston-graylog2][22] is a Graylog2 transport: - -``` js - var Graylog2 = require('winston-graylog2').Graylog2; - winston.add(Graylog2, options); -``` - -The Graylog2 transport connects to a Graylog2 server over UDP using the following options: - -* __level:__ Level of messages this transport should log. (default: info) -* __silent:__ Boolean flag indicating whether to suppress output. (default: false) - -* __graylogHost:__ IP address or hostname of the graylog2 server. (default: localhost) -* __graylogPort:__ Port to send messages to on the graylog2 server. (default: 12201) -* __graylogHostname:__ The hostname associated with graylog2 messages. (default: require('os').hostname()) -* __graylogFacility:__ The graylog2 facility to send log messages.. (default: nodejs) - -*Metadata:* Stringified as JSON in the full message GELF field. - -### Adding Custom Transports -Adding a custom transport (say for one of the datastore on the Roadmap) is actually pretty easy. All you need to do is accept a couple of options, set a name, implement a log() method, and add it to the set of transports exposed by winston. - -``` js - var util = require('util'), - winston = require('winston'); - - var CustomLogger = winston.transports.CustomerLogger = function (options) { - // - // Name this logger - // - this.name = 'customLogger'; - - // - // Set the level from your options - // - this.level = options.level || 'info'; - - // - // Configure your storage backing as you see fit - // - }; - - // - // Inherit from `winston.Transport` so you can take advantage - // of the base functionality and `.handleExceptions()`. - // - util.inherits(CustomLogger, winston.Transport); - - CustomLogger.prototype.log = function (level, msg, meta, callback) { - // - // Store this message and metadata, maybe use some custom logic - // then callback indicating success. - // - callback(null, true); - }; -``` - -## What's Next? -Winston is stable and under active development. It is supported by and used at [Nodejitsu][5]. - -### Inspirations -1. [npm][0] -2. [log.js][9] -3. [socket.io][10] -4. [node-rlog][11] -5. [BigBrother][12] -6. [Loggly][7] - -### Road Map -1. Improve support for adding custom Transports not defined in Winston core. -2. Create API for reading from logs across all transports. -3. Add more transports: Redis - -## Run Tests -All of the winston tests are written in [vows][13], and cover all of the use cases described above. You will need to add valid credentials for the various transports included to test/fixtures/test-config.json before running tests: - -``` js - { - "transports": { - "loggly": { - "subdomain": "your-subdomain", - "inputToken": "really-long-token-you-got-from-loggly", - "auth": { - "username": "your-username", - "password": "your-password" - } - } - } - } -``` - -Once you have valid configuration and credentials you can run tests with [vows][13]: - -``` - vows --spec --isolate -``` - -#### Author: [Charlie Robbins](http://twitter.com/indexzero) -#### Contributors: [Matthew Bergman](http://github.com/fotoverite), [Marak Squires](http://github.com/marak) - -[0]: https://github.com/isaacs/npm/blob/master/lib/utils/log.js -[1]: http://nodejs.org/docs/v0.3.5/api/events.html#events.EventEmitter -[2]: http://wiki.loggly.com/loggingfromcode -[3]: http://riakjs.org -[4]: https://github.com/frank06/riak-js/blob/master/src/http_client.coffee#L10 -[5]: http://nodejitsu.com -[6]: http://github.com/nodejitsu/node-loggly -[7]: http://loggly.com -[8]: http://www.loggly.com/product/ -[9]: https://github.com/visionmedia/log.js -[10]: http://socket.io -[11]: https://github.com/jbrisbin/node-rlog -[12]: https://github.com/feisty/BigBrother -[13]: http://vowsjs.org -[14]: http://nodejs.org/docs/v0.3.5/api/streams.html#writable_Stream -[15]: http://github.com/nodejitsu/require-analyzer -[16]: http://github.com/indexzero/winston-mongodb -[17]: http://github.com/indexzero/winston-riak -[18]: http://github.com/appsattic/winston-simpledb -[19]: http://github.com/wavded/winston-mail -[20]: https://github.com/weaver/node-mail -[21]: https://github.com/jesseditson/winston-sns -[22]: https://github.com/flite/winston-graylog2 diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/docco.css b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/docco.css deleted file mode 100644 index bd5413433..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/docco.css +++ /dev/null @@ -1,194 +0,0 @@ -/*--------------------- Layout and Typography ----------------------------*/ -body { - font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; - font-size: 15px; - line-height: 22px; - color: #252519; - margin: 0; padding: 0; -} -a { - color: #261a3b; -} - a:visited { - color: #261a3b; - } -p { - margin: 0 0 15px 0; -} -h4, h5, h6 { - color: #333; - margin: 6px 0 6px 0; - font-size: 13px; -} - h2, h3 { - margin-bottom: 0; - color: #000; - } - h1 { - margin-top: 40px; - margin-bottom: 15px; - color: #000; - } -#container { - position: relative; -} -#background { - position: fixed; - top: 0; left: 525px; right: 0; bottom: 0; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - z-index: -1; -} -#jump_to, #jump_page { - background: white; - -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; - -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; - font: 10px Arial; - text-transform: uppercase; - cursor: pointer; - text-align: right; -} -#jump_to, #jump_wrapper { - position: fixed; - right: 0; top: 0; - padding: 5px 10px; -} - #jump_wrapper { - padding: 0; - display: none; - } - #jump_to:hover #jump_wrapper { - display: block; - } - #jump_page { - padding: 5px 0 3px; - margin: 0 0 25px 25px; - } - #jump_page .source { - display: block; - padding: 5px 10px; - text-decoration: none; - border-top: 1px solid #eee; - } - #jump_page .source:hover { - background: #f5f5ff; - } - #jump_page .source:first-child { - } -table td { - border: 0; - outline: 0; -} - td.docs, th.docs { - max-width: 450px; - min-width: 450px; - min-height: 5px; - padding: 10px 25px 1px 50px; - overflow-x: hidden; - vertical-align: top; - text-align: left; - } - .docs pre { - margin: 15px 0 15px; - padding-left: 15px; - } - .docs p tt, .docs p code { - background: #f8f8ff; - border: 1px solid #dedede; - font-size: 12px; - padding: 0 0.2em; - } - .pilwrap { - position: relative; - } - .pilcrow { - font: 12px Arial; - text-decoration: none; - color: #454545; - position: absolute; - top: 3px; left: -20px; - padding: 1px 2px; - opacity: 0; - -webkit-transition: opacity 0.2s linear; - } - td.docs:hover .pilcrow { - opacity: 1; - } - td.code, th.code { - padding: 14px 15px 16px 25px; - width: 100%; - vertical-align: top; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - } - pre, tt, code { - font-size: 12px; line-height: 18px; - font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; - margin: 0; padding: 0; - } - - -/*---------------------- Syntax Highlighting -----------------------------*/ -td.linenos { background-color: #f0f0f0; padding-right: 10px; } -span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } -body .hll { background-color: #ffffcc } -body .c { color: #408080; font-style: italic } /* Comment */ -body .err { border: 1px solid #FF0000 } /* Error */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ -body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { color: #0000FF } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston.html deleted file mode 100644 index 0c7f087f6..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston.html +++ /dev/null @@ -1,86 +0,0 @@ - winston.js

        winston.js

        /*
        - * winston.js: Top-level include defining Winston.
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        -
        -var winston = exports;

        Expose version using pkginfo

        require('pkginfo')(module, 'version');

        Include transports defined by default by winston

        winston.transports = require('./winston/transports');
        -
        -var common           = require('./winston/common');
        -winston.hash           = common.hash;
        -winston.clone          = common.clone;
        -winston.longestElement = common.longestElement;
        -winston.exception      = require('./winston/exception');
        -winston.config         = require('./winston/config');
        -winston.addColors      = winston.config.addColors; 
        -winston.Logger         = require('./winston/logger').Logger;
        -winston.Transport      = require('./winston/transports/transport').Transport;

        We create and expose a 'defaultLogger' so that the programmer may do the -following without the need to create an instance of winston.Logger directly:

        - -
        var winston = require('winston');
        -winston.log('info', 'some message');
        -winston.error('some error'); 
        -
        var defaultLogger = new winston.Logger({ 
        -  transports: [new winston.transports.Console()] 
        -});

        Pass through the target methods onto `winston.

        var methods = [
        -  'log', 
        -  'add', 
        -  'remove', 
        -  'profile', 
        -  'extend', 
        -  'cli', 
        -  'handleExceptions', 
        -  'unhandleExceptions'
        -];
        -common.setLevels(winston, null, defaultLogger.levels);
        -methods.forEach(function (method) {
        -  winston[method] = function () {
        -    return defaultLogger[method].apply(defaultLogger, arguments);
        -  };
        -});

        function cli ()

        - -

        Configures the default winston logger to have the -settings for command-line interfaces: no timestamp, -colors enabled, padded output, and additional levels.

        winston.cli = function () {
        -  winston.padLevels = true;
        -  common.setLevels(winston, defaultLogger.levels, winston.config.cli.levels);
        -  defaultLogger.setLevels(winston.config.cli.levels);
        -  winston.config.addColors(winston.config.cli.colors);
        -  
        -  if (defaultLogger.transports.console) {
        -    defaultLogger.transports.console.colorize = true;
        -    defaultLogger.transports.console.timestamp = false;
        -  }
        -  
        -  return winston;
        -};

        function setLevels (target)

        - -

        @target {Object} Target levels to use

        - -

        Sets the target levels specified on the default winston logger.

        winston.setLevels = function (target) {
        -  common.setLevels(winston, defaultLogger.levels, target);
        -  defaultLogger.setLevels(target);
        -};

        Define getters / setters for appropriate properties of the -default logger which need to be exposed by winston.

        ['emitErrs', 'padLevels', 'levelLength'].forEach(function (prop) {
        -  Object.defineProperty(winston, prop, {
        -    get: function () {
        -      return defaultLogger[prop];
        -    },
        -    set: function (val) {
        -      defaultLogger[prop] = val;
        -    }
        -  });
        -});

        @default {Object} -The default transports and exceptionHandlers for -the default winston logger.

        Object.defineProperty(winston, 'default', {
        -  get: function () {
        -    return {
        -      transports: defaultLogger.transports,
        -      exceptionHandlers: defaultLogger.exceptionHandlers
        -    };
        -  }
        -});
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/common.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/common.html deleted file mode 100644 index 1ab139c07..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/common.html +++ /dev/null @@ -1,140 +0,0 @@ - common.js

        common.js

        /*
        - * common.js: Internal helper and utility functions for winston
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        -
        -var util = require('util'),
        -    crypto = require('crypto'),
        -    loggly = require('loggly'),
        -    config = require('./config');

        function setLevels (target, past, current)

        - -

        @target {Object} Object on which to set levels.

        - -

        @past {Object} Previous levels set on target.

        - -

        @current {Object} Current levels to set on target.

        - -

        Create functions on the target objects for each level -in current.levels. If past is defined, remove functions -for each of those levels.

        exports.setLevels = function (target, past, current, isDefault) {
        -  if (past) {
        -    Object.keys(past).forEach(function (level) {
        -      delete target[level];
        -    });
        -  }
        -
        -  target.levels = current || config.npm.levels;
        -  if (target.padLevels) {
        -    target.levelLength = exports.longestElement(Object.keys(target.levels));
        -  }
        -  

        Define prototype methods for each log level - e.g. target.log('info', msg) <=> target.info(msg)

          Object.keys(target.levels).forEach(function (level) {
        -    target[level] = function (msg) {
        -      var args     = Array.prototype.slice.call(arguments),
        -          callback = typeof args[args.length - 1] === 'function' ? args.pop() : null,
        -          meta     = args.length === 2 ? args.pop() : null;
        -
        -      return target.log(level, msg, meta, callback);
        -    };
        -  });
        -  
        -  return target;
        -};

        function longestElement

        - -

        @xs {Array} Array to calculate against

        - -

        Returns the longest element in the xs array.

        exports.longestElement = function (xs) {
        -  return Math.max.apply(
        -    null,
        -    xs.map(function (x) { return x.length })
        -  );
        -};

        function clone (obj)

        - -

        @obj {Object} Object to clone.

        - -

        Helper method for deep cloning pure JSON objects -i.e. JSON objects that are either literals or objects (no Arrays, etc)

        exports.clone = function (obj) {
        -  var copy = {};
        -  for (var i in obj) {
        -    if (Array.isArray(obj[i])) {
        -      copy[i] = obj[i].slice(0);
        -    }
        -    else {
        -      copy[i] = obj[i] instanceof Object ? exports.clone(obj[i]) : obj[i];
        -    }
        -  }
        -
        -  return copy;
        -};

        function log (options)

        - -

        @options {Object} All information about the log serialization.

        - -

        Generic logging function for returning timestamped strings -with the following options:

        - -

        { - level: 'level to add to serialized message', - message: 'message to serialize', - meta: 'additional logging metadata to serialize', - colorize: false, // Colorizes output (only if .json is false) - timestamp: true // Adds a timestamp to the serialized message - }

        exports.log = function (options) {
        -  var timestampFn = typeof options.timestamp === 'function' ? options.timestamp : exports.timestamp,
        -      timestamp   = options.timestamp ? timestampFn() : null,
        -      meta        = options.meta ? exports.clone(options.meta) : null,
        -      output;
        -
        -  if (options.json) {
        -    output         = meta || {};
        -    output.level   = options.level;
        -    output.message = options.message;
        -    
        -    if (timestamp) {
        -      output.timestamp = timestamp;
        -    }
        -    
        -    return JSON.stringify(output);
        -  }
        -
        -  output = timestamp ? timestamp + ' - ' : '';
        -  output += options.colorize ? config.colorize(options.level) : options.level;
        -  output += (': ' + options.message);
        -
        -  if (meta && typeof meta === 'object' && Object.keys(meta).length > 0) {
        -    output += ' ' + loggly.serialize(meta);
        -  }
        -
        -  return output;
        -};

        function hash (str)

        - -

        @str {string} String to hash.

        - -

        Utility function for creating unique ids -e.g. Profiling incoming HTTP requests on the same tick

        exports.hash = function (str) {
        -  return crypto.createHash('sha1').update(str).digest('hex');
        -};

        Borrowed from node.js core

        - -

        I wanted a universal lowercase header message, as opposed to the DEBUG -(i.e. all uppercase header) used only in util.debug()

        var months = ['Jan', 'Feb', 'Mar', 'Apr', 
        -              'May', 'Jun', 'Jul', 'Aug', 
        -              'Sep', 'Oct', 'Nov', 'Dec'];

        function pad (n)

        - -

        Returns a padded string if n < 10.

        exports.pad = function (n) {
        -  return n < 10 ? '0' + n.toString(10) : n.toString(10);
        -};

        function timestamp ()

        - -

        Returns a timestamp string for the current time.

        exports.timestamp = function () {
        -  var d = new Date();
        -  var time = [
        -    exports.pad(d.getHours()),
        -    exports.pad(d.getMinutes()),
        -    exports.pad(d.getSeconds())
        -  ].join(':');
        -              
        -  return [d.getDate(), months[d.getMonth()], time].join(' ');
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/config.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/config.html deleted file mode 100644 index c623d649c..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/config.html +++ /dev/null @@ -1,37 +0,0 @@ - config.js

        config.js

        /*
        - * config.js: Default settings for all levels that winston knows about 
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        -
        -var colors = require('colors');
        -
        -var config = exports, 
        -    allColors = exports.allColors = {};
        -
        -config.addColors = function (colors) {
        -  mixin(allColors, colors);
        -};
        -
        -config.colorize = function (level) {
        -  return level[allColors[level]];
        -};

        Export config sets

        config.cli    = require('./config/cli-config');
        -config.npm    = require('./config/npm-config');
        -config.syslog = require('./config/syslog-config');

        Add colors for pre-defined config sets

        config.addColors(config.npm.colors);
        -config.addColors(config.syslog.colors);
        -
        -function mixin (target) {
        -  var args = Array.prototype.slice.call(arguments, 1);
        -
        -  args.forEach(function (a) {
        -    var keys = Object.keys(a);
        -    for (var i = 0; i < keys.length; i++) {
        -      target[keys[i]] = a[keys[i]];
        -    }
        -  });
        -  return target;
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/config/cli-config.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/config/cli-config.html deleted file mode 100644 index 075edd0e6..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/config/cli-config.html +++ /dev/null @@ -1,37 +0,0 @@ - cli-config.js

        cli-config.js

        /*
        - * cli-config.js: Config that conform to commonly used CLI logging levels. 
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        - 
        -var cliConfig = exports;
        -
        -cliConfig.levels = {
        -  silly: 0,
        -  input: 1,
        -  verbose: 2,
        -  prompt: 3,
        -  info: 4,
        -  data: 5,
        -  help: 6,
        -  warn: 7,
        -  debug: 8,
        -  error: 9
        -};
        -
        -cliConfig.colors = {
        -  silly: 'magenta',
        -  input: 'grey',
        -  verbose: 'cyan',
        -  prompt: 'grey',
        -  info: 'green',
        -  data: 'grey',
        -  help: 'cyan',
        -  warn: 'yellow',
        -  debug: 'blue',
        -  error: 'red'
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/config/npm-config.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/config/npm-config.html deleted file mode 100644 index 851743071..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/config/npm-config.html +++ /dev/null @@ -1,29 +0,0 @@ - npm-config.js

        npm-config.js

        /*
        - * npm-config.js: Config that conform to npm logging levels. 
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        - 
        -var npmConfig = exports;
        -
        -npmConfig.levels = {
        -  silly: 0, 
        -  verbose: 1, 
        -  info: 2, 
        -  warn: 3,
        -  debug: 4, 
        -  error: 5
        -};
        -
        -npmConfig.colors = {
        -  silly: 'magenta',
        -  verbose: 'cyan',
        -  info: 'green',
        -  warn: 'yellow',
        -  debug: 'blue',
        -  error: 'red'
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/config/syslog-config.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/config/syslog-config.html deleted file mode 100644 index 6da0993f2..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/config/syslog-config.html +++ /dev/null @@ -1,33 +0,0 @@ - syslog-config.js

        syslog-config.js

        /*
        - * syslog-config.js: Config that conform to syslog logging levels. 
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        - 
        -var syslogConfig = exports;
        -
        -syslogConfig.levels = {
        -  debug: 0, 
        -  info: 1, 
        -  notice: 2, 
        -  warning: 3,
        -  error: 4, 
        -  crit: 5,
        -  alert: 6,
        -  emerg: 7
        -};
        -
        -syslogConfig.colors = {
        -  debug: 'blue',
        -  info: 'green',
        -  notice: 'yellow',
        -  warning: 'red',
        -  error: 'red', 
        -  crit: 'red',
        -  alert: 'yellow',
        -  emerg: 'red'
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/exception.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/exception.html deleted file mode 100644 index f6a4a6c1f..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/exception.html +++ /dev/null @@ -1,56 +0,0 @@ - exception.js

        exception.js

        /*
        - * exception.js: Utility methods for gathing information about uncaughtExceptions.
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        - 
        -var os = require('os'),
        -    stackTrace = require('stack-trace');
        -    
        -var exception = exports;
        -
        -exception.getAllInfo = function (err) {
        -  return {
        -    process: exception.getProcessInfo(),
        -    os:      exception.getOsInfo(),
        -    trace:   exception.getTrace(err)
        -  };
        -};
        -
        -exception.getProcessInfo = function () {
        -  return {
        -    pid:         process.pid,
        -    uid:         process.getuid(),
        -    gid:         process.getgid(),
        -    cwd:         process.cwd(),
        -    execPath:    process.execPath,
        -    version:     process.version,
        -    argv:        process.argv,
        -    memoryUsage: process.memoryUsage()
        -  };
        -};
        -
        -exception.getOsInfo = function () {
        -  return {
        -    loadavg: os.loadavg(),
        -    uptime:  os.uptime()
        -  };
        -};
        -
        -exception.getTrace = function (err) {
        -  var trace = err ? stackTrace.parse(err) : stackTrace.get();
        -  return trace.map(function (site) {
        -    return {
        -      column:   site.getColumnNumber(),
        -      file:     site.getFileName(),
        -      function: site.getFunctionName(),
        -      line:     site.getLineNumber(),
        -      method:   site.getMethodName(),
        -      native:   site.isNative(),
        -    }
        -  });
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/logger.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/logger.html deleted file mode 100644 index de7038a7f..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/logger.html +++ /dev/null @@ -1,344 +0,0 @@ - logger.js

        logger.js

        /*
        - * logger.js: Core logger object used by winston.
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        - 
        -var events = require('events'),
        -    util = require('util'),
        -    async = require('async'),
        -    config = require('./config'),
        -    common = require('./common'),
        -    exception = require('./exception');
        -
        -function capitalize(str) {
        -  return str && str[0].toUpperCase() + str.slice(1);
        -}

        Time constants

        var ticksPerMillisecond = 10000;

        function Logger (options)

        - -

        @options {Object} Options for this instance.

        - -

        Constructor function for the Logger object responsible -for persisting log messages and metadata to one or more transports.

        var Logger = exports.Logger = function (options) {
        -  events.EventEmitter.call(this);
        -  options = options || {};
        -  
        -  var self = this,
        -      handleExceptions = false;
        -  

        Set Levels and default logging level

          this.padLevels = options.padLevels || false;
        -  this.setLevels(options.levels);
        -  

        Setup other intelligent default settings.

          this.level             = options.level || 'info';
        -  this.emitErrs          = options.emitErrs || false;
        -  this.stripColors       = options.stripColors || false;
        -  this.transports        = {};
        -  this.exceptionHandlers = {};
        -  this.profilers         = {};
        -  this._names            = [];
        -  this._hnames           = [];
        -  
        -  if (options.transports) {
        -    options.transports.forEach(function (transport) {
        -      self.add(transport, null, true);
        -      
        -      if (transport.handleExceptions) {
        -        handleExceptions = true;
        -      }
        -    });
        -  }
        -  
        -  if (options.exceptionHandlers) {
        -    options.exceptionHandlers.forEach(function (handler) {
        -      self._hnames.push(handler.name);
        -      self.exceptionHandlers[handler.name] = handler;
        -    });
        -  }
        -  
        -  if (options.handleExceptions || handleExceptions) {
        -    this.handleExceptions();
        -  }
        -};

        Inherit from events.EventEmitter.

        util.inherits(Logger, events.EventEmitter);

        function extend (target)

        - -

        @target {Object} Target to extend.

        - -

        Extends the target object with a 'log' method -along with a method for each level in this instance.

        Logger.prototype.extend = function (target) {
        -  var self = this;
        -  ['log', 'profile'].concat(Object.keys(this.levels)).forEach(function (method) {
        -    target[method] = function () {
        -      return self[method].apply(self, arguments);
        -    };
        -  });
        -  
        -  return this;
        -};

        function log (level, msg, [meta], callback)

        - -

        @level {string} Level at which to log the message.

        - -

        @msg {string} Message to log

        - -

        @meta {Object} Optional Additional metadata to attach

        - -

        @callback {function} Continuation to respond to when complete.

        - -

        Core logging method exposed to Winston. Metadata is optional.

        Logger.prototype.log = function (level, msg) {
        -  var self = this, 
        -      callback,
        -      meta;
        -  
        -  if (arguments.length === 3) {
        -    if (typeof arguments[2] === 'function') {
        -      meta = {};
        -      callback = arguments[2];
        -    }
        -    else if (typeof arguments[2] === 'object') {
        -      meta = arguments[2];
        -    }
        -  }
        -  else if (arguments.length === 4) {
        -    meta = arguments[2];
        -    callback = arguments[3];
        -  }

        If we should pad for levels, do so

          if (this.padLevels) {
        -    msg = new Array(this.levelLength - level.length).join(' ') + msg;
        -  }
        -
        -  function onError (err) {
        -    if (callback) {
        -      callback(err);
        -    }
        -    else if (self.emitErrs) {
        -      self.emit('error', err);
        -    };
        -  }
        -  
        -  if (this.transports.length === 0) {
        -    return onError(new Error('Cannot log with no transports.'));
        -  }
        -  else if (typeof self.levels[level] === 'undefined') {
        -    return onError(new Error('Unknown log level: ' + level));
        -  }
        -  

        For consideration of terminal 'color" programs like colors.js, -which can add ANSI escape color codes to strings, we destyle the -ANSI color escape codes when this.stripColors is set.

        - -

        see: http://en.wikipedia.org/wiki/ANSIescapecode

          if (this.stripColors) {
        -    var code = /\u001b\[\d+m/g;
        -    msg = ('' + msg).replace(code, '');
        -  }
        -  
        -  for (var i = 0, l = this._names.length; i < l; i++) {
        -    var transport = this.transports[this._names[i]];
        -    if ((transport.level && self.levels[transport.level] <= self.levels[level])
        -      || (!transport.level && self.levels[self.level] <= self.levels[level])) {
        -      transport.log(level, msg, meta, function (err) {
        -        self.emit('logging', transport, level, msg, meta);
        -      });
        -    }
        -  }
        -  

        Immediately respond to the callback

          if (callback) {
        -    callback(null, level, msg, meta);    
        -  }
        -  
        -  return this;
        -};

        function handleExceptions ()

        - -

        Handles uncaughtException events for the current process

        Logger.prototype.handleExceptions = function () {
        -  var args = Array.prototype.slice.call(arguments),
        -      handlers = [],
        -      self = this;
        -      
        -  args.forEach(function (a) {
        -    if (Array.isArray(a)) {
        -      handlers = handlers.concat(a);
        -    }
        -    else {
        -      handlers.push(a);
        -    }
        -  });
        -  
        -  handlers.forEach(function (handler) {
        -    self.exceptionHandlers[handler.name] = handler;
        -  });
        -  
        -  this._hnames = Object.keys(self.exceptionHandlers);
        -    
        -  if (!this.catchExceptions) {
        -    this.catchExceptions = this._uncaughtException.bind(this);
        -    process.on('uncaughtException', this.catchExceptions);
        -  }
        -};

        function unhandleExceptions ()

        - -

        Removes any handlers to uncaughtException events -for the current process

        Logger.prototype.unhandleExceptions = function () {
        -  var self = this;
        -  
        -  if (this.catchExceptions) {
        -    Object.keys(this.exceptionHandlers).forEach(function (name) {
        -      if (handler.close) {
        -        handler.close();
        -      }
        -    });
        -    
        -    this.exceptionHandlers = {};
        -    Object.keys(this.transports).forEach(function (name) {
        -      var transport = self.transports[name];
        -      if (transport.handleExceptions) {
        -        transport.handleExceptions = false;
        -      }
        -    })
        -    
        -    process.removeListener('uncaughtException', this.catchExceptions);
        -    this.catchExceptions = false;    
        -  }
        -};

        function add (transport, [options])

        - -

        @transport {Transport} Prototype of the Transport object to add.

        - -

        @options {Object} Optional Options for the Transport to add.

        - -

        @instance {Boolean} Optional Value indicating if transport is already instantiated.

        - -

        Adds a transport of the specified type to this instance.

        Logger.prototype.add = function (transport, options, created) {
        -  var instance = created ? transport : (new (transport)(options));
        -  
        -  if (!instance.name && !instance.log) {
        -    throw new Error('Unknown transport with no log() method');
        -  }
        -  else if (this.transports[instance.name]) {
        -    throw new Error('Transport already attached: ' + instance.name);
        -  }
        -  
        -  this.transports[instance.name] = instance;
        -  this._names = Object.keys(this.transports);
        -  

        Listen for the error event on the new Transport

          instance._onError = this._onError.bind(this, instance)
        -  instance.on('error', instance._onError);
        -
        -  return this;
        -};

        function remove (transport)

        - -

        @transport {Transport} Transport to remove.

        - -

        Removes a transport of the specified type from this instance.

        Logger.prototype.remove = function (transport) {
        -  var name = transport.name || transport.prototype.name;
        -    
        -  if (!this.transports[name]) {
        -    throw new Error('Transport ' + name + ' not attached to this instance');
        -  }
        -  
        -  var instance = this.transports[name];
        -  delete this.transports[name];
        -  this._names = Object.keys(this.transports);
        -  
        -  if (instance.close) {
        -    instance.close();
        -  }
        -  
        -  instance.removeListener('error', instance._onError);
        -  return this;
        -};

        function profile (id, [msg, meta, callback])

        - -

        @id {string} Unique id of the profiler

        - -

        @msg {string} Optional Message to log

        - -

        @meta {Object} Optional Additional metadata to attach

        - -

        @callback {function} Optional Continuation to respond to when complete.

        - -

        Tracks the time inbetween subsequent calls to this method -with the same id parameter. The second call to this method -will log the difference in milliseconds along with the message.

        Logger.prototype.profile = function (id) {
        -  var now = Date.now(), then, args,
        -      msg, meta, callback;
        -  
        -  if (this.profilers[id] && arguments.length !== 1) {
        -    then = this.profilers[id];
        -    delete this.profilers[id];
        -    

        Support variable arguments: msg, meta, callback

            args     = Array.prototype.slice.call(arguments);
        -    callback = typeof args[args.length - 1] === 'function' ? args.pop() : null;
        -    meta     = typeof args[args.length - 1] === 'object' ? args.pop() : {};
        -    msg      = args.length === 2 ? args[1] : id; 
        -    

        Set the duration property of the metadata

            meta.duration = now - then + 'ms'; 
        -    return this.info(msg, meta, callback);
        -  }
        -  else {
        -    this.profilers[id] = now;
        -  }
        -  
        -  return this;
        -};

        function setLevels (target)

        - -

        @target {Object} Target levels to use on this instance

        - -

        Sets the target levels specified on this instance.

        Logger.prototype.setLevels = function (target) {
        -  return common.setLevels(this, this.levels, target);
        -};

        function cli ()

        - -

        Configures this instance to have the default -settings for command-line interfaces: no timestamp, -colors enabled, padded output, and additional levels.

        Logger.prototype.cli = function () {
        -  this.padLevels = true;
        -  this.setLevels(config.cli.levels);
        -  config.addColors(config.cli.colors);
        -  
        -  if (this.transports.console) {
        -    this.transports.console.colorize = true;
        -    this.transports.console.timestamp = false;
        -  }
        -  
        -  return this;
        -};

        @private function _uncaughtException (err)

        - -

        @err {Error} Error to handle

        - -

        Logs all relevant information around the err and -exits the current process.

        Logger.prototype._uncaughtException = function (err) {
        -  var self = this,
        -      responded = false,
        -      info = exception.getAllInfo(err),
        -      handlers = this._getExceptionHandlers(),
        -      timeout;
        -  
        -  function logAndWait (transport, next) {
        -    transport.logException('uncaughtException', info, next);
        -  }
        -  
        -  function gracefulExit () {
        -    if (!responded) {

        Remark: Currently ignoring any exceptions from transports - when catching uncaught exceptions.

              clearTimeout(timeout);
        -      responded = true;
        -      process.exit(1);
        -    }
        -  }
        -  
        -  if (!handlers || handlers.length === 0) {
        -    return gracefulExit();
        -  }
        -  

        Log to all transports and allow the operation to take -only up to 3000ms.

          async.forEach(handlers, logAndWait, gracefulExit);
        -  timeout = setTimeout(gracefulExit, 3000);
        -};

        @private function _getExceptionHandlers ()

        - -

        Returns the list of transports and exceptionHandlers -for this instance.

        Logger.prototype._getExceptionHandlers = function () {
        -  var self = this;
        -
        -  return this._hnames.map(function (name) {
        -    return self.exceptionHandlers[name];
        -  }).concat(this._names.map(function (name) {
        -    return self.transports[name].handleExceptions && self.transports[name];
        -  })).filter(Boolean);
        -};

        @private function _onError (transport, err)

        - -

        @transport {Object} Transport on which the error occured

        - -

        @err {Error} Error that occurred on the transport

        - -

        Bubbles the error, err, that occured on the specified transport -up from this instance if emitErrs has been set.

        Logger.prototype._onError = function (transport, err) {
        -  if (self.emitErrs) {
        -    self.emit('error', err, transport);
        -  }
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports.html deleted file mode 100644 index bc92fc8e2..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports.html +++ /dev/null @@ -1,29 +0,0 @@ - transports.js

        transports.js

        /*
        - * transports.js: Set of all transports Winston knows about
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        -
        -var fs = require('fs'),
        -    path = require('path');
        -
        -var transports = exports;
        -
        -function capitalize (str) {
        -  return str && str[0].toUpperCase() + str.slice(1);
        -};

        Setup all transports as lazy-loaded getters.

        fs.readdirSync(path.join(__dirname, 'transports')).forEach(function (file) {
        -  var transport = file.replace('.js', ''),
        -      name  = capitalize(transport);
        -  
        -  if (transport === 'transport') {
        -    return;
        -  }
        -  
        -  transports.__defineGetter__(name, function () {
        -    return require('./transports/' + transport)[name];
        -  });
        -});
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/console.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/console.html deleted file mode 100644 index 3d45f3682..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/console.html +++ /dev/null @@ -1,59 +0,0 @@ - console.js

        console.js

        /*
        - * console.js: Transport for outputting to the console
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        -
        -var events = require('events'),
        -    util = require('util'),
        -    colors = require('colors'),
        -    common = require('../common'),
        -    Transport = require('./transport').Transport;

        function Console (options)

        - -

        @options {Object} Options for this instance.

        - -

        Constructor function for the Console transport object responsible -for persisting log messages and metadata to a terminal or TTY.

        var Console = exports.Console = function (options) {
        -  Transport.call(this, options);
        -  options = options || {};
        -  
        -  this.name      = 'console';
        -  this.json      = options.json     || false;
        -  this.colorize  = options.colorize || false;
        -  this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false;
        -};

        Inherit from winston.Transport.

        util.inherits(Console, Transport);

        Expose the name of this Transport on the prototype

        Console.prototype.name = 'console';

        function log (level, msg, [meta], callback)

        - -

        @level {string} Level at which to log the message.

        - -

        @msg {string} Message to log

        - -

        @meta {Object} Optional Additional metadata to attach

        - -

        @callback {function} Continuation to respond to when complete.

        - -

        Core logging method exposed to Winston. Metadata is optional.

        Console.prototype.log = function (level, msg, meta, callback) {
        -  if (this.silent) {
        -    return callback(null, true);
        -  }
        -    
        -  var self = this, output = common.log({
        -    level:     level,
        -    message:   msg,
        -    meta:      meta,
        -    colorize:  this.colorize, 
        -    timestamp: this.timestamp
        -  });
        -  
        -  if (level === 'error' || level === 'debug') {
        -    util.error(output);
        -  }
        -  else {
        -    util.puts(output);
        -  }

        Emit the logged event immediately because the event loop -will not exit until process.stdout has drained anyway.

          self.emit('logged');
        -  callback(null, true);
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/couchdb.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/couchdb.html deleted file mode 100644 index b7690def7..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/couchdb.html +++ /dev/null @@ -1,84 +0,0 @@ - couchdb.js

        couchdb.js

        /*
        - * Couchdb.js: Transport for logging to Couchdb
        - *
        - * (C) 2011 Max Ogden
        - * MIT LICENSE
        - *
        - */
        -
        -var events = require('events'),
        -    http = require('http'),
        -    util = require('util'),
        -    common = require('../common'),
        -    Transport = require('./transport').Transport; 

        function Couchdb (options)

        - -

        @options {Object} Options for this instance.

        - -

        Constructor function for the Console transport object responsible -for making arbitrary HTTP requests whenever log messages and metadata -are received.

        var Couchdb = exports.Couchdb = function (options) {
        -  Transport.call(this, options);
        -
        -  this.name   = 'Couchdb'; 
        -  this.db     = options.db;
        -  this.user   = options.user;
        -  this.pass   = options.pass;
        -  this.host   = options.host   || 'localhost';
        -  this.port   = options.port   || 5984;
        -
        -  if (options.auth) {

        TODO: add http basic auth options for outgoing HTTP requests

          }
        -  
        -  if (options.ssl) {

        TODO: add ssl support for outgoing HTTP requests

          }  
        -};

        Inherit from winston.Transport.

        util.inherits(Couchdb, Transport);

        Expose the name of this Transport on the prototype

        Couchdb.prototype.name = 'Couchdb';

        function log (level, msg, [meta], callback)

        - -

        @level {string} Level at which to log the message.

        - -

        @msg {string} Message to log

        - -

        @meta {Object} Optional Additional metadata to attach

        - -

        @callback {function} Continuation to respond to when complete.

        - -

        Core logging method exposed to Winston. Metadata is optional.

        Couchdb.prototype.log = function (level, msg, meta, callback) {
        -  if (this.silent) {
        -    return callback(null, true);
        -  }
        -  
        -  var self = this,
        -      message = common.clone(meta),
        -      options,
        -      req;
        -      
        -  message.level = level;
        -  message.message = msg;

        Prepare options for outgoing HTTP request

          options = {
        -    host: this.host,
        -    port: this.port,
        -    path: "/" + this.db,
        -    method: "POST",
        -    headers: {"content-type": "application/json"}
        -  };
        -  
        -  if (options.user && options.pass) {
        -    options.headers["Authorization"] = "Basic " + new Buffer(options.user + ":" + options.pass).toString('base64');
        -  }
        -  

        Perform HTTP logging request

          req = http.request(options, function (res) { 

        No callback on request, fire and forget about the response

            self.emit('logged', res);
        -  }); 
        -
        -  req.on('error', function (err) {

        Propagate the error back up to the Logger that this -instance belongs to.

            self.emit('error', err);
        -  });
        -  

        Write logging event to the outgoing request body

          req.write(JSON.stringify({ 
        -    method: 'log', 
        -    params: { 
        -      timestamp: new Date(), // RFC3339/ISO8601 format instead of common.timestamp()
        -      msg: msg, 
        -      level: level, 
        -      meta: meta 
        -    } 
        -  }));
        -  
        -  req.end();
        -  

        Always return true, regardless of any errors

          callback(null, true);
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/file.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/file.html deleted file mode 100644 index bba8459b4..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/file.html +++ /dev/null @@ -1,211 +0,0 @@ - file.js

        file.js

        /*
        - * file.js: Transport for outputting to a local log file
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        -
        -var events = require('events'),
        -    fs = require('fs'),
        -    path = require('path'),
        -    util = require('util'),
        -    colors = require('colors'),
        -    common = require('../common'),
        -    Transport = require('./transport').Transport;
        -    

        function File (options)

        - -

        @options {Object} Options for this instance.

        - -

        Constructor function for the File transport object responsible -for persisting log messages and metadata to one or more files.

        var File = exports.File = function (options) {
        -  Transport.call(this, options);
        -  

        Helper function which throws an Error in the event -that any of the rest of the arguments is present in options.

          function throwIf (target /*, illegal... */) {
        -    Array.prototype.slice.call(arguments, 1).forEach(function (name) {
        -      if (options[name]) {
        -        throw new Error('Cannot set ' + name + ' and ' + target + 'together');
        -      }
        -    });
        -  }
        -  
        -  if (options.filename || options.dirname) {
        -    throwIf('filename or dirname', 'stream');
        -    this._basename = this.filename = path.basename(options.filename) || 'winston.log';
        -    this.dirname   = options.dirname || path.dirname(options.filename);
        -    this.options   = options.options || { flags: 'a' };    
        -  }
        -  else if (options.stream) {
        -    throwIf('stream', 'filename', 'maxsize');
        -    this.stream = options.stream;
        -  }
        -  else {
        -    throw new Error('Cannot log to file without filename or stream.');
        -  }
        -    
        -  this.json      = options.json !== false;
        -  this.colorize  = options.colorize  || false;
        -  this.maxsize   = options.maxsize   || null;
        -  this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false;

        Internal state variables representing the number -of files this instance has created and the current -size (in bytes) of the current logfile.

          this._size    = 0;
        -  this._created = 0;
        -  this._buffer  = [];
        -};

        Inherit from winston.Transport.

        util.inherits(File, Transport);

        Expose the name of this Transport on the prototype

        File.prototype.name = 'file';

        function log (level, msg, [meta], callback)

        - -

        @level {string} Level at which to log the message.

        - -

        @msg {string} Message to log

        - -

        @meta {Object} Optional Additional metadata to attach

        - -

        @callback {function} Continuation to respond to when complete.

        - -

        Core logging method exposed to Winston. Metadata is optional.

        File.prototype.log = function (level, msg, meta, callback) {
        -  if (this.silent) {
        -    return callback(null, true);
        -  }
        -
        -  var self = this, output = common.log({
        -    level:     level,
        -    message:   msg,
        -    meta:      meta,
        -    json:      this.json,
        -    colorize:  this.colorize,
        -    timestamp: this.timestamp
        -  }) + '\n';
        -  
        -  this._size += output.length;
        -  
        -  function onDrain () {
        -    self.emit('logged');
        -  }
        -  
        -  if (!this.filename) {

        If there is no filename on this instance then it was configured -with a raw WriteableStream instance and we should not perform any -size restrictions.

            this.stream.write(output);
        -    this.stream.once('drain', onDrain);
        -  }
        -  else {
        -    this.open(function (err) {
        -      if (err) {

        If there was an error enqueue the message

                return self._buffer.push(output);
        -      }
        -      
        -      self.stream.write(output);
        -      self.stream.once('drain', onDrain);
        -    });
        -  }
        -
        -  callback(null, true);
        -};

        function open (callback)

        - -

        @callback {function} Continuation to respond to when complete

        - -

        Checks to see if a new file needs to be created based on the maxsize -(if any) and the current size of the file used.

        File.prototype.open = function (callback) {
        -  if (this.opening) {

        If we are already attempting to open the next -available file then respond with a value indicating -that the message should be buffered.

            return callback(true);
        -  }
        -  else if (!this.stream || (this.maxsize && this._size >= this.maxsize)) {

        If we dont have a stream or have exceeded our size, then create -the next stream and respond with a value indicating that -the message should be buffered.

            callback(true);
        -    return this._createStream();
        -  }
        -  

        Otherwise we have a valid (and ready) stream.

          callback();
        -};

        function close ()

        - -

        Closes the stream associated with this instance.

        File.prototype.close = function() {
        -  var self = this;
        -
        -  if (this.stream) {
        -    this.stream.end();
        -    this.stream.destroySoon();
        -    
        -    this.stream.once('drain', function () {
        -      self.emit('flush');
        -      self.emit('closed');
        -    });
        -  }
        -};

        function flush ()

        - -

        Flushes any buffered messages to the current stream -used by this instance.

        File.prototype.flush = function () {
        -  var self = this;

        Iterate over the _buffer of enqueued messaged -and then write them to the newly created stream.

          this._buffer.forEach(function (str) {
        -    process.nextTick(function () {
        -      self.stream.write(str);
        -      self._size += str.length;
        -    });
        -  });
        -  

        Quickly truncate the _buffer once the write operations -have been started

          self._buffer.length = 0;
        -  

        When the stream has drained we have flushed -our buffer.

          self.stream.once('drain', function () {
        -    self.emit('flush');
        -    self.emit('logged');
        -  });
        -};

        @private function _createStream ()

        - -

        Attempts to open the next appropriate file for this instance -based on the common state (such as maxsize and _basename).

        File.prototype._createStream = function () {
        -  var self = this;
        -  this.opening = true;
        -    
        -  (function checkFile (target) {
        -    var fullname = path.join(self.dirname, target);
        -    

        Creates the WriteStream and then flushes any -buffered messages.

            function createAndFlush (size) {
        -      if (self.stream) {
        -        self.stream.end();
        -        self.stream.destroySoon();
        -      }
        -      
        -      self._size = size;
        -      self.filename = target;
        -      self.stream = fs.createWriteStream(fullname, self.options);
        -      

        When the current stream has finished flushing -then we can be sure we have finished opening -and thus can emit the open event.

              self.once('flush', function () {
        -        self.opening = false;
        -        self.emit('open', fullname);
        -      });

        Remark: It is possible that in the time it has taken to find the -next logfile to be written more data than maxsize has been buffered, -but for sensible limits (10s - 100s of MB) this seems unlikely in less -than one second.

              self.flush();
        -    }
        -
        -    fs.stat(fullname, function (err, stats) {
        -      if (err) {
        -        if (err.code !== 'ENOENT') {
        -          return self.emit('error', err);
        -        }
        -        
        -        return createAndFlush(0);
        -      }
        -      
        -      if (!stats || (self.maxsize && stats.size >= self.maxsize)) {

        If stats.size is greater than the maxsize for -this instance then try again

                return checkFile(self._getFile(true));
        -      }
        -      
        -      createAndFlush(stats.size);
        -    });
        -  })(this._getFile());  
        -};

        @private function _getFile ()

        - -

        Gets the next filename to use for this instance -in the case that log filesizes are being capped.

        File.prototype._getFile = function (inc) {
        -  var self = this,
        -      ext = path.extname(this._basename),
        -      basename = path.basename(this._basename, ext);
        -  
        -  if (inc) {

        Increment the number of files created or -checked by this instance.

            this._created += 1;
        -  }
        -  
        -  return this._created 
        -    ? basename + this._created + ext
        -    : basename + ext;
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/loggly.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/loggly.html deleted file mode 100644 index 76523181f..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/loggly.html +++ /dev/null @@ -1,118 +0,0 @@ - loggly.js

        loggly.js

        /*
        - * loggly.js: Transport for logginh to remote Loggly API
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        -
        -var events = require('events'),
        -    loggly = require('loggly'),
        -    util = require('util'),
        -    async = require('async'),
        -    common = require('../common'),
        -    Transport = require('./transport').Transport; 

        function Loggly (options)

        - -

        @options {Object} Options for this instance.

        - -

        Constructor function for the Loggly transport object responsible -for persisting log messages and metadata to Loggly; 'LaaS'.

        var Loggly = exports.Loggly = function (options) {
        -  Transport.call(this, options);
        -
        -  if (!options.subdomain) {
        -    throw new Error('Loggly Subdomain is required');
        -  }
        -  
        -  if (!options.inputToken && !options.inputName) {
        -    throw new Error('Target input token or name is required.');
        -  }
        -  
        -  if (!options.auth && options.inputName) {
        -    throw new Error('Loggly authentication is required');
        -  }
        -  
        -  this.name = 'loggly'; 
        -  this.logBuffer = [];
        -  
        -  this.client = loggly.createClient({
        -    subdomain: options.subdomain,
        -    auth: options.auth || null,
        -    json: options.json || false
        -  });
        -  
        -  if (options.inputToken) {
        -    this.inputToken = options.inputToken;
        -    this.ready = true;
        -  }
        -  else if (options.inputName) {
        -    this.ready = false;
        -    this.inputName = options.inputName;
        -    
        -    var self = this;
        -    this.client.getInput(this.inputName, function (err, input) {
        -      if (err) {
        -        throw err;
        -      }
        -      
        -      self.inputToken = input.input_token;
        -      self.ready = true;
        -    });
        -  }
        -};

        Inherit from winston.Transport.

        util.inherits(Loggly, Transport);

        Expose the name of this Transport on the prototype

        Loggly.prototype.name = 'loggly';

        function log (level, msg, [meta], callback)

        - -

        @level {string} Level at which to log the message.

        - -

        @msg {string} Message to log

        - -

        @meta {Object} Optional Additional metadata to attach

        - -

        @callback {function} Continuation to respond to when complete.

        - -

        Core logging method exposed to Winston. Metadata is optional.

        Loggly.prototype.log = function (level, msg, meta, callback) {
        -  if (this.silent) {
        -    return callback(null, true);
        -  }
        -
        -  var self = this,
        -      message = common.clone(meta);
        -      
        -  message.level = level;
        -  message.message = msg;
        -  
        -  if (!this.ready) {

        If we haven't gotten the input token yet -add this message to the log buffer.

            this.logBuffer.push(message);
        -  }
        -  else if (this.ready && this.logBuffer.length > 0) {

        Otherwise if we have buffered messages -add this message to the buffer and flush them.

            this.logBuffer.push(message);
        -    this.flush();
        -  }
        -  else {

        Otherwise just log the message as normal

            this.client.log(this.inputToken, message, function () {
        -      self.emit('logged');
        -    });
        -  }
        -  
        -  callback(null, true);
        -};

        function flush ()

        - -

        Flushes any buffered messages to the current stream -used by this instance.

        Loggly.prototype.flush = function () {
        -  var self = this;
        -  
        -  function logMsg (msg, next) {
        -    self.client.log(self.inputToken, msg, function (err) {
        -      if (err) {
        -        self.emit('error', err);
        -      }
        -      
        -      next();
        -    });
        -  }
        -  

        Initiate calls to loggly for each message in the buffer

          async.forEach(this.logBuffer, logMsg, function () {
        -    self.emit('logged');
        -  });
        -  
        -  process.nextTick(function () {

        Then quickly truncate the list

            self.logBuffer.length = 0;
        -  });
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/transport.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/transport.html deleted file mode 100644 index f0cc4b9eb..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/transport.html +++ /dev/null @@ -1,50 +0,0 @@ - transport.js

        transport.js

        /*
        - * transport.js: Base Transport object for all Winston transports.
        - *
        - * (C) 2010 Charlie Robbins
        - * MIT LICENCE
        - *
        - */
        -
        -var events = require('events'),
        -    util = require('util'); 

        function Transport (options)

        - -

        @options {Object} Options for this instance.

        - -

        Constructor function for the Tranport object responsible -base functionality for all winston transports.

        var Transport = exports.Transport = function (options) {
        -  events.EventEmitter.call(this);
        -  
        -  options               = options        || {};  
        -  this.level            = options.level  || 'info';
        -  this.silent           = options.silent || false;
        -  this.handleExceptions = options.handleExceptions || false;
        -};

        Inherit from events.EventEmitter.

        util.inherits(Transport, events.EventEmitter);

        function logException (msg, meta, callback)

        - -

        @msg {string} Message to log

        - -

        @meta {Object} Optional Additional metadata to attach

        - -

        @callback {function} Continuation to respond to when complete.

        - -

        Logs the specified msg, meta and responds to the callback once the log -operation is complete to ensure that the event loop will not exit before -all logging has completed.

        Transport.prototype.logException = function (msg, meta, callback) {
        -  var self = this;
        -  
        -  function onLogged () {
        -    self.removeListener('error', onError);
        -    callback();
        -  }
        -  
        -  function onError () {
        -    self.removeListener('logged', onLogged);
        -    callback();
        -  }
        -  
        -  this.once('logged', onLogged);
        -  this.once('error', onError);  
        -  this.log('error', msg, meta, function () { });
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/webhook.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/webhook.html deleted file mode 100644 index 719149537..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/docs/winston/transports/webhook.html +++ /dev/null @@ -1,82 +0,0 @@ - webhook.js

        webhook.js

        /*
        - * webhook.js: Transport for logging to remote http endpoints ( POST / RECEIVE webhooks )
        - *
        - * (C) 2011 Marak Squires
        - * MIT LICENCE
        - *
        - */
        -
        -var events = require('events'),
        -    http = require('http'),
        -    util = require('util'),
        -    common = require('../common'),
        -    Transport = require('./transport').Transport; 

        function WebHook (options)

        - -

        @options {Object} Options for this instance.

        - -

        Constructor function for the Console transport object responsible -for making arbitrary HTTP requests whenever log messages and metadata -are received.

        var Webhook = exports.Webhook = function (options) {
        -  Transport.call(this, options);
        -
        -  this.name   = 'webhook'; 
        -  this.host   = options.host   || 'localhost';
        -  this.port   = options.port   || 8080;
        -  this.method = options.method || 'POST';
        -  this.path   = options.path   || '/winston-log';
        -
        -  if (options.auth) {

        TODO: add http basic auth options for outgoing HTTP requests

          }
        -  
        -  if (options.ssl) {

        TODO: add ssl support for outgoing HTTP requests

          }  
        -};

        Inherit from winston.Transport.

        util.inherits(Webhook, Transport);

        Expose the name of this Transport on the prototype

        Webhook.prototype.name = 'webhook';

        function log (level, msg, [meta], callback)

        - -

        @level {string} Level at which to log the message.

        - -

        @msg {string} Message to log

        - -

        @meta {Object} Optional Additional metadata to attach

        - -

        @callback {function} Continuation to respond to when complete.

        - -

        Core logging method exposed to Winston. Metadata is optional.

        Webhook.prototype.log = function (level, msg, meta, callback) {
        -  if (this.silent) {
        -    return callback(null, true);
        -  }
        -  
        -  var self = this,
        -      message = common.clone(meta),
        -      options,
        -      req;
        -      
        -  message.level = level;
        -  message.message = msg;

        Prepare options for outgoing HTTP request

          options = {
        -    host: this.host,
        -    port: this.port,
        -    path: this.path,
        -    method: this.method
        -  };
        -  

        Perform HTTP logging request

          req = http.request(options, function (res) { 

        No callback on request, fire and forget about the response

            self.emit('logged');
        -  }); 
        -
        -  req.on('error', function (err) {

        Propagate the error back up to the Logger that this -instance belongs to.

            self.emit('error', err);
        -  });
        -  

        Write logging event to the outgoing request body

        - -

        jsonMessage is currently conforming to JSON-RPC v1.0, -but without the unique id since there is no anticipated response -see: http://en.wikipedia.org/wiki/JSON-RPC

          req.write(JSON.stringify({ 
        -    method: 'log', 
        -    params: { 
        -      timestamp: common.timestamp(), 
        -      msg: msg, 
        -      level: level, 
        -      meta: meta 
        -    } 
        -  }));
        -  
        -  req.end();
        -  

        Always return true, regardless of any errors

          callback(null, true);
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/examples/couchdb.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/examples/couchdb.js deleted file mode 100644 index ce2d96073..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/examples/couchdb.js +++ /dev/null @@ -1,18 +0,0 @@ -var winston = require('../lib/winston'); - -// -// Create a new winston logger instance with two tranports: Console, and Couchdb -// -// -// The Console transport will simply output to the console screen -// The Couchdb tranport will perform an HTTP POST request to the specified CouchDB instance -// -var logger = new (winston.Logger)({ - transports: [ - new (winston.transports.Console)(), - new (winston.transports.Couchdb)({ 'host': 'localhost', 'db': 'logs' }) - // if you need auth do this: new (winston.transports.Couchdb)({ 'user': 'admin', 'pass': 'admin', 'host': 'localhost', 'db': 'logs' }) - ] -}); - -logger.log('info', 'Hello webhook log files!', { 'foo': 'bar' }); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/examples/raw-mode.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/examples/raw-mode.js deleted file mode 100644 index 89e070da3..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/examples/raw-mode.js +++ /dev/null @@ -1,10 +0,0 @@ -var winston = require('../lib/winston'); - -var logger = new (winston.Logger)({ - transports: [ - new (winston.transports.Console)({ raw: true }), - ] -}); - -logger.log('info', 'Hello, this is a raw logging event', { 'foo': 'bar' }); -logger.log('info', 'Hello, this is a raw logging event 2', { 'foo': 'bar' }); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/examples/webhook-post.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/examples/webhook-post.js deleted file mode 100644 index 0fa1c8dae..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/examples/webhook-post.js +++ /dev/null @@ -1,17 +0,0 @@ -var winston = require('../lib/winston'); - -// -// Create a new winston logger instance with two tranports: Console, and Webhook -// -// -// The Console transport will simply output to the console screen -// The Webhook tranports will perform an HTTP POST request to an abritrary end-point ( for post/recieve webhooks ) -// -var logger = new (winston.Logger)({ - transports: [ - new (winston.transports.Console)(), - new (winston.transports.Webhook)({ 'host': 'localhost', 'port': 8080, 'path': '/collectdata' }) - ] -}); - -logger.log('info', 'Hello webhook log files!', { 'foo': 'bar' }); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston.js deleted file mode 100644 index 51bfb45fb..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston.js +++ /dev/null @@ -1,143 +0,0 @@ -/* - * winston.js: Top-level include defining Winston. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var winston = exports; - -// -// Expose version using `pkginfo` -// -require('pkginfo')(module, 'version'); - -// -// Include transports defined by default by winston -// -winston.transports = require('./winston/transports'); - -// -// Expose utility methods -// -var common = require('./winston/common'); -winston.hash = common.hash; -winston.clone = common.clone; -winston.longestElement = common.longestElement; -winston.exception = require('./winston/exception'); -winston.config = require('./winston/config'); -winston.addColors = winston.config.addColors; - -// -// Expose core Logging-related prototypes. -// -winston.Container = require('./winston/container').Container; -winston.Logger = require('./winston/logger').Logger; -winston.Transport = require('./winston/transports/transport').Transport; - -// -// We create and expose a default `Container` to `winston.loggers` so that the -// programmer may manage multiple `winston.Logger` instances without any additional overhead. -// -// ### some-file1.js -// -// var logger = require('winston').loggers.get('something'); -// -// ### some-file2.js -// -// var logger = require('winston').loggers.get('something'); -// -winston.loggers = new winston.Container(); - -// -// We create and expose a 'defaultLogger' so that the programmer may do the -// following without the need to create an instance of winston.Logger directly: -// -// var winston = require('winston'); -// winston.log('info', 'some message'); -// winston.error('some error'); -// -var defaultLogger = new winston.Logger({ - transports: [new winston.transports.Console()] -}); - -// -// Pass through the target methods onto `winston. -// -var methods = [ - 'log', - 'add', - 'remove', - 'profile', - 'startTimer', - 'extend', - 'cli', - 'handleExceptions', - 'unhandleExceptions' -]; -common.setLevels(winston, null, defaultLogger.levels); -methods.forEach(function (method) { - winston[method] = function () { - return defaultLogger[method].apply(defaultLogger, arguments); - }; -}); - -// -// ### function cli () -// Configures the default winston logger to have the -// settings for command-line interfaces: no timestamp, -// colors enabled, padded output, and additional levels. -// -winston.cli = function () { - winston.padLevels = true; - common.setLevels(winston, defaultLogger.levels, winston.config.cli.levels); - defaultLogger.setLevels(winston.config.cli.levels); - winston.config.addColors(winston.config.cli.colors); - - if (defaultLogger.transports.console) { - defaultLogger.transports.console.colorize = true; - defaultLogger.transports.console.timestamp = false; - } - - return winston; -}; - -// -// ### function setLevels (target) -// #### @target {Object} Target levels to use -// Sets the `target` levels specified on the default winston logger. -// -winston.setLevels = function (target) { - common.setLevels(winston, defaultLogger.levels, target); - defaultLogger.setLevels(target); -}; - -// -// Define getters / setters for appropriate properties of the -// default logger which need to be exposed by winston. -// -['emitErrs', 'exitOnError', 'padLevels', 'level', 'levelLength', 'stripColors'].forEach(function (prop) { - Object.defineProperty(winston, prop, { - get: function () { - return defaultLogger[prop]; - }, - set: function (val) { - defaultLogger[prop] = val; - } - }); -}); - -// -// @default {Object} -// The default transports and exceptionHandlers for -// the default winston logger. -// -Object.defineProperty(winston, 'default', { - get: function () { - return { - transports: defaultLogger.transports, - exceptionHandlers: defaultLogger.exceptionHandlers - }; - } -}); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/common.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/common.js deleted file mode 100644 index 9b8abebeb..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/common.js +++ /dev/null @@ -1,264 +0,0 @@ -/* - * common.js: Internal helper and utility functions for winston - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var util = require('util'), - crypto = require('crypto'), - config = require('./config'); - -// -// ### function setLevels (target, past, current) -// #### @target {Object} Object on which to set levels. -// #### @past {Object} Previous levels set on target. -// #### @current {Object} Current levels to set on target. -// Create functions on the target objects for each level -// in current.levels. If past is defined, remove functions -// for each of those levels. -// -exports.setLevels = function (target, past, current, isDefault) { - if (past) { - Object.keys(past).forEach(function (level) { - delete target[level]; - }); - } - - target.levels = current || config.npm.levels; - if (target.padLevels) { - target.levelLength = exports.longestElement(Object.keys(target.levels)); - } - - // - // Define prototype methods for each log level - // e.g. target.log('info', msg) <=> target.info(msg) - // - Object.keys(target.levels).forEach(function (level) { - target[level] = function (msg) { - var args = Array.prototype.slice.call(arguments), - callback = typeof args[args.length - 1] === 'function' || !args[args.length - 1] ? args.pop() : null, - meta = args.length === 2 ? args.pop() : null; - - return target.log(level, msg, meta, callback); - }; - }); - - return target; -}; - -// -// ### function longestElement -// #### @xs {Array} Array to calculate against -// Returns the longest element in the `xs` array. -// -exports.longestElement = function (xs) { - return Math.max.apply( - null, - xs.map(function (x) { return x.length; }) - ); -}; - -// -// ### function clone (obj) -// #### @obj {Object} Object to clone. -// Helper method for deep cloning pure JSON objects -// i.e. JSON objects that are either literals or objects (no Arrays, etc) -// -exports.clone = function (obj) { - // we only need to clone refrence types (Object) - if (!(obj instanceof Object)) { - return obj; - } - else if (obj instanceof Date) { - return obj; - } - - var copy = {}; - for (var i in obj) { - if (Array.isArray(obj[i])) { - copy[i] = obj[i].slice(0); - } - else if (obj[i] instanceof Buffer) { - copy[i] = obj[i].slice(0); - } - else if (typeof obj[i] != 'function') { - copy[i] = obj[i] instanceof Object ? exports.clone(obj[i]) : obj[i]; - } - } - - return copy; -}; - -// -// ### function log (options) -// #### @options {Object} All information about the log serialization. -// Generic logging function for returning timestamped strings -// with the following options: -// -// { -// level: 'level to add to serialized message', -// message: 'message to serialize', -// meta: 'additional logging metadata to serialize', -// colorize: false, // Colorizes output (only if `.json` is false) -// timestamp: true // Adds a timestamp to the serialized message -// } -// -exports.log = function (options) { - var timestampFn = typeof options.timestamp === 'function' ? options.timestamp : exports.timestamp, - timestamp = options.timestamp ? timestampFn() : null, - meta = options.meta ? exports.clone(options.meta) : null, - output; - - // - // raw mode is intended for outputing winston as streaming JSON to STDOUT - // - if (options.raw) { - output = meta || {}; - output.level = options.level; - output.message = options.message.stripColors; - return JSON.stringify(output); - } - - // - // json mode is intended for pretty printing multi-line json to the terminal - // - if (options.json) { - output = meta || {}; - output.level = options.level; - output.message = options.message; - - if (timestamp) { - output.timestamp = timestamp; - } - - return typeof options.stringify === 'function' - ? options.stringify(output) - : JSON.stringify(output, function(key, value) { - if (value instanceof Buffer) { - return value.toString('base64'); - } - return value; - }); - } - - output = timestamp ? timestamp + ' - ' : ''; - output += options.colorize ? config.colorize(options.level) : options.level; - output += (': ' + options.message); - - if (meta) { - if (typeof meta !== 'object') { - output += ' ' + meta; - } - else if (Object.keys(meta).length > 0) { - output += ' ' + exports.serialize(meta); - } - } - - return output; -}; - -exports.capitalize = function (str) { - return str && str[0].toUpperCase() + str.slice(1); -}; - -// -// ### function hash (str) -// #### @str {string} String to hash. -// Utility function for creating unique ids -// e.g. Profiling incoming HTTP requests on the same tick -// -exports.hash = function (str) { - return crypto.createHash('sha1').update(str).digest('hex'); -}; - -// -// ## Borrowed from node.js core -// I wanted a universal lowercase header message, as opposed to the `DEBUG` -// (i.e. all uppercase header) used only in `util.debug()` -// -var months = ['Jan', 'Feb', 'Mar', 'Apr', - 'May', 'Jun', 'Jul', 'Aug', - 'Sep', 'Oct', 'Nov', 'Dec']; - -// -// ### function pad (n) -// Returns a padded string if `n < 10`. -// -exports.pad = function (n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -}; - -// -// ### function timestamp () -// Returns a timestamp string for the current time. -// -exports.timestamp = function () { - var d = new Date(); - var time = [ - exports.pad(d.getHours()), - exports.pad(d.getMinutes()), - exports.pad(d.getSeconds()) - ].join(':'); - - return [d.getDate(), months[d.getMonth()], time].join(' '); -}; - -// -// ### function serialize (obj, key) -// #### @obj {Object|literal} Object to serialize -// #### @key {string} **Optional** Optional key represented by obj in a larger object -// Performs simple comma-separated, `key=value` serialization for Loggly when -// logging to non-JSON inputs. -// -exports.serialize = function (obj, key) { - if (obj === null) { - obj = 'null'; - } - else if (obj === undefined) { - obj = 'undefined'; - } - else if (obj === false) { - obj = 'false'; - } - - if (typeof obj !== 'object') { - return key ? key + '=' + obj : obj; - } - - if (obj instanceof Buffer) { - return key ? key + '=' + obj.toString('base64') : obj.toString('base64'); - } - - var msg = '', - keys = Object.keys(obj), - length = keys.length; - - for (var i = 0; i < length; i++) { - if (Array.isArray(obj[keys[i]])) { - msg += keys[i] + '=['; - - for (var j = 0, l = obj[keys[i]].length; j < l; j++) { - msg += exports.serialize(obj[keys[i]][j]); - if (j < l - 1) { - msg += ', '; - } - } - - msg += ']'; - } - else if (obj[keys[i]] instanceof Date) { - msg += keys[i] + '=' + obj[keys[i]]; - } - else { - msg += exports.serialize(obj[keys[i]], keys[i]); - } - - if (i < length - 1) { - msg += ', '; - } - } - - return msg; -}; diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/config.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/config.js deleted file mode 100644 index 45e92837b..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/config.js +++ /dev/null @@ -1,45 +0,0 @@ -/* - * config.js: Default settings for all levels that winston knows about - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var colors = require('colors'); - -var config = exports, - allColors = exports.allColors = {}; - -config.addColors = function (colors) { - mixin(allColors, colors); -}; - -config.colorize = function (level) { - return level[allColors[level]]; -}; - -// -// Export config sets -// -config.cli = require('./config/cli-config'); -config.npm = require('./config/npm-config'); -config.syslog = require('./config/syslog-config'); - -// -// Add colors for pre-defined config sets -// -config.addColors(config.npm.colors); -config.addColors(config.syslog.colors); - -function mixin (target) { - var args = Array.prototype.slice.call(arguments, 1); - - args.forEach(function (a) { - var keys = Object.keys(a); - for (var i = 0; i < keys.length; i++) { - target[keys[i]] = a[keys[i]]; - } - }); - return target; -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/config/cli-config.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/config/cli-config.js deleted file mode 100644 index 9798ddca1..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/config/cli-config.js +++ /dev/null @@ -1,35 +0,0 @@ -/* - * cli-config.js: Config that conform to commonly used CLI logging levels. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var cliConfig = exports; - -cliConfig.levels = { - silly: 0, - input: 1, - verbose: 2, - prompt: 3, - info: 4, - data: 5, - help: 6, - warn: 7, - debug: 8, - error: 9 -}; - -cliConfig.colors = { - silly: 'magenta', - input: 'grey', - verbose: 'cyan', - prompt: 'grey', - info: 'green', - data: 'grey', - help: 'cyan', - warn: 'yellow', - debug: 'blue', - error: 'red' -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/config/npm-config.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/config/npm-config.js deleted file mode 100644 index 464f73558..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/config/npm-config.js +++ /dev/null @@ -1,27 +0,0 @@ -/* - * npm-config.js: Config that conform to npm logging levels. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var npmConfig = exports; - -npmConfig.levels = { - silly: 0, - verbose: 1, - info: 2, - warn: 3, - debug: 4, - error: 5 -}; - -npmConfig.colors = { - silly: 'magenta', - verbose: 'cyan', - info: 'green', - warn: 'yellow', - debug: 'blue', - error: 'red' -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/config/syslog-config.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/config/syslog-config.js deleted file mode 100644 index a198abca1..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/config/syslog-config.js +++ /dev/null @@ -1,31 +0,0 @@ -/* - * syslog-config.js: Config that conform to syslog logging levels. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var syslogConfig = exports; - -syslogConfig.levels = { - debug: 0, - info: 1, - notice: 2, - warning: 3, - error: 4, - crit: 5, - alert: 6, - emerg: 7 -}; - -syslogConfig.colors = { - debug: 'blue', - info: 'green', - notice: 'yellow', - warning: 'red', - error: 'red', - crit: 'red', - alert: 'yellow', - emerg: 'red' -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/container.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/container.js deleted file mode 100644 index 0e67b20a2..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/container.js +++ /dev/null @@ -1,101 +0,0 @@ -/* - * container.js: Inversion of control container for winston logger instances - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var common = require('./common'), - winston = require('../winston'); - -// -// ### function Container (options) -// #### @options {Object} Default pass-thru options for Loggers -// Constructor function for the Container object responsible for managing -// a set of `winston.Logger` instances based on string ids. -// -var Container = exports.Container = function (options) { - this.loggers = {}; - this.options = options || {}; - this.default = { - transports: [ - new winston.transports.Console({ - level: 'silly', - colorize: false - }) - ] - } -}; - -// -// ### function get / add (id, options) -// #### @id {string} Id of the Logger to get -// #### @options {Object} **Optional** Options for the Logger instance -// Retreives a `winston.Logger` instance for the specified `id`. If -// an instance does not exist, one is created. -// -Container.prototype.get = Container.prototype.add = function (id, options) { - if (!this.loggers[id]) { - options = common.clone(options || this.options || this.default); - options.transports = options.transports || []; - - if (options.transports.length === 0 && (!options || !options['console'])) { - options.transports.push(this.default.transports[0]); - } - - Object.keys(options).forEach(function (key) { - if (key === 'transports') { - return; - } - - var name = common.capitalize(key); - - if (!winston.transports[name]) { - throw new Error('Cannot add unknown transport: ' + name); - } - - var namedOptions = options[key]; - namedOptions.id = id; - options.transports.push(new (winston.transports[name])(namedOptions)); - }); - - this.loggers[id] = new winston.Logger(options); - } - - return this.loggers[id]; -}; - -// -// ### function close (id) -// #### @id {string} **Optional** Id of the Logger instance to find -// Returns a boolean value indicating if this instance -// has a logger with the specified `id`. -// -Container.prototype.has = function (id) { - return !!this.loggers[id]; -}; - -// -// ### function close (id) -// #### @id {string} **Optional** Id of the Logger instance to close -// Closes a `Logger` instance with the specified `id` if it exists. -// If no `id` is supplied then all Loggers are closed. -// -Container.prototype.close = function (id) { - var self = this; - - function _close (id) { - if (!self.loggers[id]) { - return; - } - - self.loggers[id].close(); - delete self.loggers[id]; - } - - return id ? _close(id) : Object.keys(this.loggers).forEach(function (id) { - _close(id); - }); -}; - diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/exception.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/exception.js deleted file mode 100644 index 2a01e91c7..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/exception.js +++ /dev/null @@ -1,55 +0,0 @@ -/* - * exception.js: Utility methods for gathing information about uncaughtExceptions. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var os = require('os'), - stackTrace = require('stack-trace'); - -var exception = exports; - -exception.getAllInfo = function (err) { - return { - process: exception.getProcessInfo(), - os: exception.getOsInfo(), - trace: exception.getTrace(err), - stack: err.stack.split('\n') - }; -}; - -exception.getProcessInfo = function () { - return { - pid: process.pid, - uid: process.getuid(), - gid: process.getgid(), - cwd: process.cwd(), - execPath: process.execPath, - version: process.version, - argv: process.argv, - memoryUsage: process.memoryUsage() - }; -}; - -exception.getOsInfo = function () { - return { - loadavg: os.loadavg(), - uptime: os.uptime() - }; -}; - -exception.getTrace = function (err) { - var trace = err ? stackTrace.parse(err) : stackTrace.get(); - return trace.map(function (site) { - return { - column: site.getColumnNumber(), - file: site.getFileName(), - function: site.getFunctionName(), - line: site.getLineNumber(), - method: site.getMethodName(), - native: site.isNative(), - } - }); -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/logger.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/logger.js deleted file mode 100644 index baaa05754..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/logger.js +++ /dev/null @@ -1,515 +0,0 @@ -/* - * logger.js: Core logger object used by winston. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var events = require('events'), - util = require('util'), - async = require('async'), - config = require('./config'), - common = require('./common'), - exception = require('./exception'); - -// -// Time constants -// -var ticksPerMillisecond = 10000; - -// -// ### function Logger (options) -// #### @options {Object} Options for this instance. -// Constructor function for the Logger object responsible -// for persisting log messages and metadata to one or more transports. -// -var Logger = exports.Logger = function (options) { - events.EventEmitter.call(this); - options = options || {}; - - var self = this, - handleExceptions = false; - - // - // Set Levels and default logging level - // - this.padLevels = options.padLevels || false; - this.setLevels(options.levels); - if (options.colors) { - config.addColors(options.colors); - } - - // - // Hoist other options onto this instance. - // - this.level = options.level || 'info'; - this.emitErrs = options.emitErrs || false; - this.stripColors = options.stripColors || false; - this.exitOnError = typeof options.exitOnError !== 'undefined' - ? options.exitOnError - : true; - - // - // Setup other intelligent default settings. - // - this.transports = {}; - this.rewriters = []; - this.exceptionHandlers = {}; - this.profilers = {}; - this._names = []; - this._hnames = []; - - if (options.transports) { - options.transports.forEach(function (transport) { - self.add(transport, null, true); - - if (transport.handleExceptions) { - handleExceptions = true; - } - }); - } - - if (options.rewriters) { - options.rewriters.forEach(function(rewriter) { - self.addRewriter(rewriter); - }); - } - - if (options.exceptionHandlers) { - handleExceptions = true; - options.exceptionHandlers.forEach(function (handler) { - self._hnames.push(handler.name); - self.exceptionHandlers[handler.name] = handler; - }); - } - - if (options.handleExceptions || handleExceptions) { - this.handleExceptions(); - } -}; - -// -// Inherit from `events.EventEmitter`. -// -util.inherits(Logger, events.EventEmitter); - -// -// ### function extend (target) -// #### @target {Object} Target to extend. -// Extends the target object with a 'log' method -// along with a method for each level in this instance. -// -Logger.prototype.extend = function (target) { - var self = this; - ['log', 'profile', 'startTimer'].concat(Object.keys(this.levels)).forEach(function (method) { - target[method] = function () { - return self[method].apply(self, arguments); - }; - }); - - return this; -}; - -// -// ### function log (level, msg, [meta], callback) -// #### @level {string} Level at which to log the message. -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Core logging method exposed to Winston. Metadata is optional. -// -Logger.prototype.log = function (level, msg) { - var self = this, - callback, - meta; - - if (arguments.length === 3) { - if (typeof arguments[2] === 'function') { - meta = {}; - callback = arguments[2]; - } - else if (typeof arguments[2] === 'object') { - meta = arguments[2]; - } - } - else if (arguments.length === 4) { - meta = arguments[2]; - callback = arguments[3]; - } - - // If we should pad for levels, do so - if (this.padLevels) { - msg = new Array(this.levelLength - level.length).join(' ') + msg; - } - - function onError (err) { - if (callback) { - callback(err); - } - else if (self.emitErrs) { - self.emit('error', err); - }; - } - - if (this.transports.length === 0) { - return onError(new Error('Cannot log with no transports.')); - } - else if (typeof self.levels[level] === 'undefined') { - return onError(new Error('Unknown log level: ' + level)); - } - - this.rewriters.forEach(function(rewriter) { - meta = rewriter(level, msg, meta); - }); - - // - // For consideration of terminal 'color" programs like colors.js, - // which can add ANSI escape color codes to strings, we destyle the - // ANSI color escape codes when `this.stripColors` is set. - // - // see: http://en.wikipedia.org/wiki/ANSI_escape_code - // - if (this.stripColors) { - var code = /\u001b\[\d+m/g; - msg = ('' + msg).replace(code, ''); - } - - for (var i = 0, l = this._names.length; i < l; i++) { - var transport = this.transports[this._names[i]]; - if ((transport.level && self.levels[transport.level] <= self.levels[level]) - || (!transport.level && self.levels[self.level] <= self.levels[level])) { - transport.log(level, msg, meta, function (err) { - self.emit('logging', transport, level, msg, meta); - }); - } - } - - // - // Immediately respond to the callback - // - if (callback) { - callback(null, level, msg, meta); - } - - return this; -}; - -// -// ### function close () -// Cleans up resources (streams, event listeners) for all -// transports associated with this instance (if necessary). -// -Logger.prototype.close = function () { - var self = this; - - this._names.forEach(function (name) { - var transport = self.transports[name]; - if (transport && transport.close) { - transport.close(); - } - }); -}; - -// -// ### function handleExceptions () -// Handles `uncaughtException` events for the current process -// -Logger.prototype.handleExceptions = function () { - var args = Array.prototype.slice.call(arguments), - handlers = [], - self = this; - - args.forEach(function (a) { - if (Array.isArray(a)) { - handlers = handlers.concat(a); - } - else { - handlers.push(a); - } - }); - - handlers.forEach(function (handler) { - self.exceptionHandlers[handler.name] = handler; - }); - - this._hnames = Object.keys(self.exceptionHandlers); - - if (!this.catchExceptions) { - this.catchExceptions = this._uncaughtException.bind(this); - process.on('uncaughtException', this.catchExceptions); - } -}; - -// -// ### function unhandleExceptions () -// Removes any handlers to `uncaughtException` events -// for the current process -// -Logger.prototype.unhandleExceptions = function () { - var self = this; - - if (this.catchExceptions) { - Object.keys(this.exceptionHandlers).forEach(function (name) { - if (handler.close) { - handler.close(); - } - }); - - this.exceptionHandlers = {}; - Object.keys(this.transports).forEach(function (name) { - var transport = self.transports[name]; - if (transport.handleExceptions) { - transport.handleExceptions = false; - } - }) - - process.removeListener('uncaughtException', this.catchExceptions); - this.catchExceptions = false; - } -}; - -// -// ### function add (transport, [options]) -// #### @transport {Transport} Prototype of the Transport object to add. -// #### @options {Object} **Optional** Options for the Transport to add. -// #### @instance {Boolean} **Optional** Value indicating if `transport` is already instantiated. -// Adds a transport of the specified type to this instance. -// -Logger.prototype.add = function (transport, options, created) { - var instance = created ? transport : (new (transport)(options)); - - if (!instance.name && !instance.log) { - throw new Error('Unknown transport with no log() method'); - } - else if (this.transports[instance.name]) { - throw new Error('Transport already attached: ' + instance.name); - } - - this.transports[instance.name] = instance; - this._names = Object.keys(this.transports); - - // - // Listen for the `error` event on the new Transport - // - instance._onError = this._onError.bind(this, instance) - instance.on('error', instance._onError); - - // - // If this transport has `handleExceptions` set to `true` - // and we are not already handling exceptions, do so. - // - if (transport.handleExceptions && !this.catchExceptions) { - this.handleExceptions(); - } - - return this; -}; - -// -// ### function addRewriter (transport, [options]) -// #### @transport {Transport} Prototype of the Transport object to add. -// #### @options {Object} **Optional** Options for the Transport to add. -// #### @instance {Boolean} **Optional** Value indicating if `transport` is already instantiated. -// Adds a transport of the specified type to this instance. -// -Logger.prototype.addRewriter = function(rewriter) { - this.rewriters.push(rewriter); -} - -// -// ### function clear () -// Remove all transports from this instance -// -Logger.prototype.clear = function () { - for (var name in this.transports) { - this.remove({ name: name }); - } -}; - -// -// ### function remove (transport) -// #### @transport {Transport} Transport to remove. -// Removes a transport of the specified type from this instance. -// -Logger.prototype.remove = function (transport) { - var name = transport.name || transport.prototype.name; - - if (!this.transports[name]) { - throw new Error('Transport ' + name + ' not attached to this instance'); - } - - var instance = this.transports[name]; - delete this.transports[name]; - this._names = Object.keys(this.transports); - - if (instance.close) { - instance.close(); - } - - instance.removeListener('error', instance._onError); - return this; -}; - -var ProfileHandler = function (logger) { - this.logger = logger; - - this.start = Date.now(); - - this.done = function (msg) { - var args, callback, meta; - args = Array.prototype.slice.call(arguments); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : null; - meta = typeof args[args.length - 1] === 'object' ? args.pop() : {}; - - meta.duration = (Date.now()) - this.start + 'ms'; - - return this.logger.info(msg, meta, callback); - } -} - -Logger.prototype.startTimer = function () { - return new ProfileHandler(this); -} - -// -// ### function profile (id, [msg, meta, callback]) -// #### @id {string} Unique id of the profiler -// #### @msg {string} **Optional** Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} **Optional** Continuation to respond to when complete. -// Tracks the time inbetween subsequent calls to this method -// with the same `id` parameter. The second call to this method -// will log the difference in milliseconds along with the message. -// -Logger.prototype.profile = function (id) { - var now = Date.now(), then, args, - msg, meta, callback; - - if (this.profilers[id]) { - then = this.profilers[id]; - delete this.profilers[id]; - - // Support variable arguments: msg, meta, callback - args = Array.prototype.slice.call(arguments); - callback = typeof args[args.length - 1] === 'function' ? args.pop() : null; - meta = typeof args[args.length - 1] === 'object' ? args.pop() : {}; - msg = args.length === 2 ? args[1] : id; - - // Set the duration property of the metadata - meta.duration = now - then + 'ms'; - return this.info(msg, meta, callback); - } - else { - this.profilers[id] = now; - } - - return this; -}; - -// -// ### function setLevels (target) -// #### @target {Object} Target levels to use on this instance -// Sets the `target` levels specified on this instance. -// -Logger.prototype.setLevels = function (target) { - return common.setLevels(this, this.levels, target); -}; - -// -// ### function cli () -// Configures this instance to have the default -// settings for command-line interfaces: no timestamp, -// colors enabled, padded output, and additional levels. -// -Logger.prototype.cli = function () { - this.padLevels = true; - this.setLevels(config.cli.levels); - config.addColors(config.cli.colors); - - if (this.transports.console) { - this.transports.console.colorize = true; - this.transports.console.timestamp = false; - } - - return this; -}; - -// -// ### @private function _uncaughtException (err) -// #### @err {Error} Error to handle -// Logs all relevant information around the `err` and -// exits the current process. -// -Logger.prototype._uncaughtException = function (err) { - var self = this, - responded = false, - info = exception.getAllInfo(err), - handlers = this._getExceptionHandlers(), - timeout, - doExit; - - // - // Calculate if we should exit on this error - // - doExit = typeof this.exitOnError === 'function' - ? this.exitOnError(err) - : this.exitOnError; - - function logAndWait(transport, next) { - transport.logException('uncaughtException', info, next, err); - } - - function gracefulExit() { - if (doExit && !responded) { - // - // Remark: Currently ignoring any exceptions from transports - // when catching uncaught exceptions. - // - clearTimeout(timeout); - responded = true; - process.exit(1); - } - } - - if (!handlers || handlers.length === 0) { - return gracefulExit(); - } - - // - // Log to all transports and allow the operation to take - // only up to `3000ms`. - // - async.forEach(handlers, logAndWait, gracefulExit); - if (doExit) { - timeout = setTimeout(gracefulExit, 3000); - } -}; - -// -// ### @private function _getExceptionHandlers () -// Returns the list of transports and exceptionHandlers -// for this instance. -// -Logger.prototype._getExceptionHandlers = function () { - var self = this; - - return this._hnames.map(function (name) { - return self.exceptionHandlers[name]; - }).concat(this._names.map(function (name) { - return self.transports[name].handleExceptions && self.transports[name]; - })).filter(Boolean); -}; - -// -// ### @private function _onError (transport, err) -// #### @transport {Object} Transport on which the error occured -// #### @err {Error} Error that occurred on the transport -// Bubbles the error, `err`, that occured on the specified `transport` -// up from this instance if `emitErrs` has been set. -// -Logger.prototype._onError = function (transport, err) { - if (this.emitErrs) { - this.emit('error', err, transport); - } -}; diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports.js deleted file mode 100644 index 508063440..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports.js +++ /dev/null @@ -1,29 +0,0 @@ -/* - * transports.js: Set of all transports Winston knows about - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var fs = require('fs'), - path = require('path'), - common = require('./common'); - -var transports = exports; - -// -// Setup all transports as lazy-loaded getters. -// -fs.readdirSync(path.join(__dirname, 'transports')).forEach(function (file) { - var transport = file.replace('.js', ''), - name = common.capitalize(transport); - - if (transport === 'transport') { - return; - } - - transports.__defineGetter__(name, function () { - return require('./transports/' + transport)[name]; - }); -}); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/console.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/console.js deleted file mode 100644 index 835d0755b..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/console.js +++ /dev/null @@ -1,87 +0,0 @@ -/* - * console.js: Transport for outputting to the console - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var events = require('events'), - util = require('util'), - colors = require('colors'), - common = require('../common'), - Transport = require('./transport').Transport; - -// -// ### function Console (options) -// #### @options {Object} Options for this instance. -// Constructor function for the Console transport object responsible -// for persisting log messages and metadata to a terminal or TTY. -// -var Console = exports.Console = function (options) { - Transport.call(this, options); - options = options || {}; - - this.name = 'console'; - this.json = options.json || false; - this.colorize = options.colorize || false; - this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false; - - if (this.json) { - this.stringify = options.stringify || function (obj) { - return JSON.stringify(obj, null, 2); - }; - } -}; - -// -// Inherit from `winston.Transport`. -// -util.inherits(Console, Transport); - -// -// Expose the name of this Transport on the prototype -// -Console.prototype.name = 'console'; - -// -// ### function log (level, msg, [meta], callback) -// #### @level {string} Level at which to log the message. -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Core logging method exposed to Winston. Metadata is optional. -// -Console.prototype.log = function (level, msg, meta, callback) { - if (this.silent) { - return callback(null, true); - } - - var self = this, - output; - - output = common.log({ - colorize: this.colorize, - json: this.json, - level: level, - message: msg, - meta: meta, - stringify: this.stringify, - timestamp: this.timestamp, - raw: this.raw - }); - - if (level === 'error' || level === 'debug') { - util.error(output); - } - else { - util.puts(output); - } - - // - // Emit the `logged` event immediately because the event loop - // will not exit until `process.stdout` has drained anyway. - // - self.emit('logged'); - callback(null, true); -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/couchdb.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/couchdb.js deleted file mode 100644 index 61ad74abe..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/couchdb.js +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Couchdb.js: Transport for logging to Couchdb - * - * (C) 2011 Max Ogden - * MIT LICENSE - * - */ - -var events = require('events'), - http = require('http'), - util = require('util'), - common = require('../common'), - Transport = require('./transport').Transport; - -// -// ### function Couchdb (options) -// #### @options {Object} Options for this instance. -// Constructor function for the Console transport object responsible -// for making arbitrary HTTP requests whenever log messages and metadata -// are received. -// -var Couchdb = exports.Couchdb = function (options) { - Transport.call(this, options); - - this.name = 'Couchdb'; - this.db = options.db; - this.user = options.user; - this.pass = options.pass; - this.host = options.host || 'localhost'; - this.port = options.port || 5984; - - if (options.auth) { - // - // TODO: add http basic auth options for outgoing HTTP requests - // - } - - if (options.ssl) { - // - // TODO: add ssl support for outgoing HTTP requests - // - } -}; - -// -// Inherit from `winston.Transport`. -// -util.inherits(Couchdb, Transport); - -// -// Expose the name of this Transport on the prototype -// -Couchdb.prototype.name = 'Couchdb'; - -// -// ### function log (level, msg, [meta], callback) -// #### @level {string} Level at which to log the message. -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Core logging method exposed to Winston. Metadata is optional. -// -Couchdb.prototype.log = function (level, msg, meta, callback) { - if (this.silent) { - return callback(null, true); - } - - var self = this, - message = common.clone(meta || {}), - options, - req; - - message.level = level; - message.message = msg; - - // Prepare options for outgoing HTTP request - options = { - host: this.host, - port: this.port, - path: "/" + this.db, - method: "POST", - headers: {"content-type": "application/json"} - }; - - if (options.user && options.pass) { - options.headers["Authorization"] = "Basic " + new Buffer(options.user + ":" + options.pass).toString('base64'); - } - - // Perform HTTP logging request - req = http.request(options, function (res) { - // - // No callback on request, fire and forget about the response - // - self.emit('logged', res); - }); - - req.on('error', function (err) { - // - // Propagate the `error` back up to the `Logger` that this - // instance belongs to. - // - self.emit('error', err); - }); - - // - // Write logging event to the outgoing request body - // - req.write(JSON.stringify({ - method: 'log', - params: { - timestamp: new Date(), // RFC3339/ISO8601 format instead of common.timestamp() - msg: msg, - level: level, - meta: meta - } - })); - - req.end(); - - // Always return true, regardless of any errors - callback(null, true); -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/file.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/file.js deleted file mode 100644 index 0a96c012b..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/file.js +++ /dev/null @@ -1,332 +0,0 @@ -/* - * file.js: Transport for outputting to a local log file - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var events = require('events'), - fs = require('fs'), - path = require('path'), - util = require('util'), - colors = require('colors'), - common = require('../common'), - Transport = require('./transport').Transport; - -// -// ### function File (options) -// #### @options {Object} Options for this instance. -// Constructor function for the File transport object responsible -// for persisting log messages and metadata to one or more files. -// -var File = exports.File = function (options) { - Transport.call(this, options); - - // - // Helper function which throws an `Error` in the event - // that any of the rest of the arguments is present in `options`. - // - function throwIf (target /*, illegal... */) { - Array.prototype.slice.call(arguments, 1).forEach(function (name) { - if (options[name]) { - throw new Error('Cannot set ' + name + ' and ' + target + 'together'); - } - }); - } - - if (options.filename || options.dirname) { - throwIf('filename or dirname', 'stream'); - this._basename = this.filename = path.basename(options.filename) || 'winston.log'; - this.dirname = options.dirname || path.dirname(options.filename); - this.options = options.options || { flags: 'a' }; - } - else if (options.stream) { - throwIf('stream', 'filename', 'maxsize'); - this.stream = options.stream; - } - else { - throw new Error('Cannot log to file without filename or stream.'); - } - - this.json = options.json !== false; - this.colorize = options.colorize || false; - this.maxsize = options.maxsize || null; - this.maxFiles = options.maxFiles || null; - this.timestamp = typeof options.timestamp !== 'undefined' ? options.timestamp : false; - - // - // Internal state variables representing the number - // of files this instance has created and the current - // size (in bytes) of the current logfile. - // - this._size = 0; - this._created = 0; - this._buffer = []; - this._draining = false; -}; - -// -// Inherit from `winston.Transport`. -// -util.inherits(File, Transport); - -// -// Expose the name of this Transport on the prototype -// -File.prototype.name = 'file'; - -// -// ### function log (level, msg, [meta], callback) -// #### @level {string} Level at which to log the message. -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Core logging method exposed to Winston. Metadata is optional. -// -File.prototype.log = function (level, msg, meta, callback) { - if (this.silent) { - return callback(null, true); - } - - var self = this, output = common.log({ - level: level, - message: msg, - meta: meta, - json: this.json, - colorize: this.colorize, - timestamp: this.timestamp - }) + '\n'; - - this._size += output.length; - - if (!this.filename) { - // - // If there is no `filename` on this instance then it was configured - // with a raw `WriteableStream` instance and we should not perform any - // size restrictions. - // - this.stream.write(output); - self._lazyDrain(); - } - else { - this.open(function (err) { - if (err) { - // - // If there was an error enqueue the message - // - return self._buffer.push(output); - } - - self.stream.write(output); - self._lazyDrain(); - }); - } - - callback(null, true); -}; - -// -// ### function open (callback) -// #### @callback {function} Continuation to respond to when complete -// Checks to see if a new file needs to be created based on the `maxsize` -// (if any) and the current size of the file used. -// -File.prototype.open = function (callback) { - if (this.opening) { - // - // If we are already attempting to open the next - // available file then respond with a value indicating - // that the message should be buffered. - // - return callback(true); - } - else if (!this.stream || (this.maxsize && this._size >= this.maxsize)) { - // - // If we dont have a stream or have exceeded our size, then create - // the next stream and respond with a value indicating that - // the message should be buffered. - // - callback(true); - return this._createStream(); - } - - // - // Otherwise we have a valid (and ready) stream. - // - callback(); -}; - -// -// ### function close () -// Closes the stream associated with this instance. -// -File.prototype.close = function () { - var self = this; - - if (this.stream) { - this.stream.end(); - this.stream.destroySoon(); - - this.stream.once('drain', function () { - self.emit('flush'); - self.emit('closed'); - }); - } -}; - -// -// ### function flush () -// Flushes any buffered messages to the current `stream` -// used by this instance. -// -File.prototype.flush = function () { - var self = this; - - // - // Iterate over the `_buffer` of enqueued messaged - // and then write them to the newly created stream. - // - this._buffer.forEach(function (str) { - process.nextTick(function () { - self.stream.write(str); - self._size += str.length; - }); - }); - - // - // Quickly truncate the `_buffer` once the write operations - // have been started - // - self._buffer.length = 0; - - // - // When the stream has drained we have flushed - // our buffer. - // - self.stream.once('drain', function () { - self.emit('flush'); - self.emit('logged'); - }); -}; - -// -// ### @private function _createStream () -// Attempts to open the next appropriate file for this instance -// based on the common state (such as `maxsize` and `_basename`). -// -File.prototype._createStream = function () { - var self = this; - this.opening = true; - - (function checkFile (target) { - var fullname = path.join(self.dirname, target); - - // - // Creates the `WriteStream` and then flushes any - // buffered messages. - // - function createAndFlush (size) { - if (self.stream) { - self.stream.end(); - self.stream.destroySoon(); - } - - self._size = size; - self.filename = target; - self.stream = fs.createWriteStream(fullname, self.options); - - // - // When the current stream has finished flushing - // then we can be sure we have finished opening - // and thus can emit the `open` event. - // - self.once('flush', function () { - self.opening = false; - self.emit('open', fullname); - }); - - // - // Remark: It is possible that in the time it has taken to find the - // next logfile to be written more data than `maxsize` has been buffered, - // but for sensible limits (10s - 100s of MB) this seems unlikely in less - // than one second. - // - self.flush(); - } - - fs.stat(fullname, function (err, stats) { - if (err) { - if (err.code !== 'ENOENT') { - return self.emit('error', err); - } - - return createAndFlush(0); - } - - if (!stats || (self.maxsize && stats.size >= self.maxsize)) { - // - // If `stats.size` is greater than the `maxsize` for - // this instance then try again - // - return checkFile(self._getFile(true)); - } - - createAndFlush(stats.size); - }); - })(this._getFile()); -}; - -// -// ### @private function _getFile () -// Gets the next filename to use for this instance -// in the case that log filesizes are being capped. -// -File.prototype._getFile = function (inc) { - var self = this, - ext = path.extname(this._basename), - basename = path.basename(this._basename, ext), - remaining; - - if (inc) { - // - // Increment the number of files created or - // checked by this instance. - // - // Check for maxFiles option and delete file - if (this.maxFiles && (this._created >= (this.maxFiles - 1))) { - remaining = this._created - (this.maxFiles - 1); - if (remaining === 0) { - fs.unlinkSync(path.join(this.dirname, basename + ext)); - } - else { - fs.unlinkSync(path.join(this.dirname, basename + remaining + ext)); - } - } - - this._created += 1; - } - - return this._created - ? basename + this._created + ext - : basename + ext; -}; - -// -// ### @private function _lazyDrain () -// Lazily attempts to emit the `logged` event when `this.stream` has -// drained. This is really just a simple mutex that only works because -// Node.js is single-threaded. -// -File.prototype._lazyDrain = function () { - var self = this; - - if (!this._draining && this.stream) { - this._draining = true; - - this.stream.once('drain', function () { - this._draining = false; - self.emit('logged'); - }); - } -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/loggly.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/loggly.js deleted file mode 100644 index dd5762b51..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/loggly.js +++ /dev/null @@ -1,161 +0,0 @@ -/* - * loggly.js: Transport for logginh to remote Loggly API - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var events = require('events'), - loggly = require('loggly'), - util = require('util'), - async = require('async'), - common = require('../common'), - Transport = require('./transport').Transport; - -// -// ### function Loggly (options) -// #### @options {Object} Options for this instance. -// Constructor function for the Loggly transport object responsible -// for persisting log messages and metadata to Loggly; 'LaaS'. -// -var Loggly = exports.Loggly = function (options) { - Transport.call(this, options); - - function valid() { - return options.inputToken - || options.inputName && options.auth - || options.inputName && options.inputs && options.inputs[options.inputName] - || options.id && options.inputs && options.inputs[options.id]; - } - - if (!options.subdomain) { - throw new Error('Loggly Subdomain is required'); - } - - if (!valid()) { - throw new Error('Target input token or name is required.'); - } - - this.name = 'loggly'; - this.logBuffer = []; - - this.client = loggly.createClient({ - subdomain: options.subdomain, - auth: options.auth || null, - json: options.json || false - }); - - if (options.inputToken) { - this.inputToken = options.inputToken; - this.ready = true; - } - else if (options.inputs && (options.inputs[options.inputName] - || options.inputs[options.id])) { - this.inputToken = options.inputs[options.inputName] || options.inputs[options.id]; - this.ready = true; - } - else if (options.inputName) { - this.ready = false; - this.inputName = options.inputName; - - var self = this; - this.client.getInput(this.inputName, function (err, input) { - if (err) { - throw err; - } - - self.inputToken = input.input_token; - self.ready = true; - }); - } -}; - -// -// Inherit from `winston.Transport`. -// -util.inherits(Loggly, Transport); - -// -// Expose the name of this Transport on the prototype -// -Loggly.prototype.name = 'loggly'; - -// -// ### function log (level, msg, [meta], callback) -// #### @level {string} Level at which to log the message. -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Core logging method exposed to Winston. Metadata is optional. -// -Loggly.prototype.log = function (level, msg, meta, callback) { - if (this.silent) { - return callback(null, true); - } - - var self = this, - message = common.clone(meta || {}); - - message.level = level; - message.message = msg; - - if (!this.ready) { - // - // If we haven't gotten the input token yet - // add this message to the log buffer. - // - this.logBuffer.push(message); - } - else if (this.ready && this.logBuffer.length > 0) { - // - // Otherwise if we have buffered messages - // add this message to the buffer and flush them. - // - this.logBuffer.push(message); - this.flush(); - } - else { - // - // Otherwise just log the message as normal - // - this.client.log(this.inputToken, message, function () { - self.emit('logged'); - }); - } - - callback(null, true); -}; - -// -// ### function flush () -// Flushes any buffered messages to the current `stream` -// used by this instance. -// -Loggly.prototype.flush = function () { - var self = this; - - function logMsg (msg, next) { - self.client.log(self.inputToken, msg, function (err) { - if (err) { - self.emit('error', err); - } - - next(); - }); - } - - // - // Initiate calls to loggly for each message in the buffer - // - async.forEach(this.logBuffer, logMsg, function () { - self.emit('logged'); - }); - - process.nextTick(function () { - // - // Then quickly truncate the list - // - self.logBuffer.length = 0; - }); -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/transport.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/transport.js deleted file mode 100644 index 1489cb5a4..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/transport.js +++ /dev/null @@ -1,59 +0,0 @@ -/* - * transport.js: Base Transport object for all Winston transports. - * - * (C) 2010 Charlie Robbins - * MIT LICENCE - * - */ - -var events = require('events'), - util = require('util'); - -// -// ### function Transport (options) -// #### @options {Object} Options for this instance. -// Constructor function for the Tranport object responsible -// base functionality for all winston transports. -// -var Transport = exports.Transport = function (options) { - events.EventEmitter.call(this); - - options = options || {}; - this.level = options.level || 'info'; - this.silent = options.silent || false; - this.raw = options.raw || false; - - this.handleExceptions = options.handleExceptions || false; -}; - -// -// Inherit from `events.EventEmitter`. -// -util.inherits(Transport, events.EventEmitter); - -// -// ### function logException (msg, meta, callback) -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Logs the specified `msg`, `meta` and responds to the callback once the log -// operation is complete to ensure that the event loop will not exit before -// all logging has completed. -// -Transport.prototype.logException = function (msg, meta, callback) { - var self = this; - - function onLogged () { - self.removeListener('error', onError); - callback(); - } - - function onError () { - self.removeListener('logged', onLogged); - callback(); - } - - this.once('logged', onLogged); - this.once('error', onError); - this.log('error', msg, meta, function () { }); -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/webhook.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/webhook.js deleted file mode 100644 index bf8eb2727..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/lib/winston/transports/webhook.js +++ /dev/null @@ -1,136 +0,0 @@ -/* - * webhook.js: Transport for logging to remote http endpoints ( POST / RECEIVE webhooks ) - * - * (C) 2011 Marak Squires - * MIT LICENCE - * - */ - -var events = require('events'), - http = require('http'), - https = require('https'), - util = require('util'), - common = require('../common'), - Transport = require('./transport').Transport; - -// -// ### function WebHook (options) -// #### @options {Object} Options for this instance. -// Constructor function for the Console transport object responsible -// for making arbitrary HTTP requests whenever log messages and metadata -// are received. -// -var Webhook = exports.Webhook = function (options) { - Transport.call(this, options); - - this.name = 'webhook'; - this.host = options.host || 'localhost'; - this.port = options.port || 8080; - this.method = options.method || 'POST'; - this.path = options.path || '/winston-log'; - - if (options.auth) { - this.auth = {}; - this.auth.username = options.auth.username || ''; - this.auth.password = options.auth.password || ''; - } - - if (options.ssl) { - this.ssl = {}; - this.ssl.key = options.ssl.key || null; - this.ssl.cert = options.ssl.cert || null; - this.ssl.ca = options.ssl.ca; - } -}; - -// -// Inherit from `winston.Transport`. -// -util.inherits(Webhook, Transport); - -// -// Expose the name of this Transport on the prototype -// -Webhook.prototype.name = 'webhook'; - -// -// ### function log (level, msg, [meta], callback) -// #### @level {string} Level at which to log the message. -// #### @msg {string} Message to log -// #### @meta {Object} **Optional** Additional metadata to attach -// #### @callback {function} Continuation to respond to when complete. -// Core logging method exposed to Winston. Metadata is optional. -// -Webhook.prototype.log = function (level, msg, meta, callback) { - if (this.silent) { - return callback(null, true); - } - - var self = this, - message = common.clone(meta), - options, - req; - - message.level = level; - message.message = msg; - - // Prepare options for outgoing HTTP request - options = { - host: this.host, - port: this.port, - path: this.path, - method: this.method, - headers: { 'Content-Type': 'application/json' } - }; - - if (this.ssl) { - options.ca = this.ssl.ca; - options.key = this.ssl.key; - options.cert = this.ssl.cert; - } - - if (this.auth) { - // Encode `Authorization` header used by Basic Auth - options.headers['Authorization'] = 'Basic ' + new Buffer( - this.auth.username + ':' + this.auth.password, 'utf8' - ).toString('base64'); - } - - // Perform HTTP logging request - req = (self.ssl ? https : http).request(options, function (res) { - // - // No callback on request, fire and forget about the response - // - self.emit('logged'); - }); - - req.on('error', function (err) { - // - // Propagate the `error` back up to the `Logger` that this - // instance belongs to. - // - self.emit('error', err); - }); - - // - // Write logging event to the outgoing request body - // - // jsonMessage is currently conforming to JSON-RPC v1.0, - // but without the unique id since there is no anticipated response - // see: http://en.wikipedia.org/wiki/JSON-RPC - // - req.write(JSON.stringify({ - method: 'log', - params: { - timestamp: new Date(), - msg: msg, - level: level, - meta: meta - } - })); - - req.end(); - - // Always return true, regardless of any errors - callback(null, true); -}; diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/LICENSE b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/LICENSE deleted file mode 100644 index a1edd93b5..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2009 cloudhead - -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/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/Makefile b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/Makefile deleted file mode 100644 index a121deaf0..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/Makefile +++ /dev/null @@ -1,4 +0,0 @@ -test: - @@node test/eyes-test.js - -.PHONY: test diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/README.md b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/README.md deleted file mode 100644 index c4f6f769e..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/README.md +++ /dev/null @@ -1,73 +0,0 @@ -eyes -==== - -a customizable value inspector for Node.js - -synopsis --------- - -I was tired of looking at cluttered output in the console -- something needed to be done, -`sys.inspect()` didn't display regexps correctly, and was too verbose, and I had an hour or two to spare. -So I decided to have some fun. _eyes_ were born. - -![eyes-ss](http://dl.dropbox.com/u/251849/eyes-js-ss.gif) - -_example of the output of a user-customized eyes.js inspector_ - -*eyes* also deals with circular objects in an intelligent way, and can pretty-print object literals. - -usage ------ - - var inspect = require('eyes').inspector({styles: {all: 'magenta'}}); - - inspect(something); // inspect with the settings passed to `inspector` - -or - - var eyes = require('eyes'); - - eyes.inspect(something); // inspect with the default settings - -you can pass a _label_ to `inspect()`, to keep track of your inspections: - - eyes.inspect(something, "a random value"); - -If you want to return the output of eyes without printing it, you can set it up this way: - - var inspect = require('eyes').inspector({ stream: null }); - - sys.puts(inspect({ something: 42 })); - -customization -------------- - -These are the default styles and settings used by _eyes_. - - styles: { // Styles applied to stdout - all: 'cyan', // Overall style applied to everything - label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]` - other: 'inverted', // Objects which don't have a literal representation, such as functions - key: 'bold', // The keys in object literals, like 'a' in `{a: 1}` - special: 'grey', // null, undefined... - string: 'green', - number: 'magenta', - bool: 'blue', // true false - regexp: 'green', // /\d+/ - }, - - pretty: true, // Indent object literals - hideFunctions: false, // Don't output functions at all - stream: process.stdout, // Stream to write to, or null - maxLength: 2048 // Truncate output if longer - -You can overwrite them with your own, by passing a similar object to `inspector()` or `inspect()`. - - var inspect = require('eyes').inspector({ - styles: { - all: 'magenta', - special: 'bold' - }, - maxLength: 512 - }); - diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/lib/eyes.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/lib/eyes.js deleted file mode 100644 index 10d964b96..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/lib/eyes.js +++ /dev/null @@ -1,236 +0,0 @@ -// -// Eyes.js - a customizable value inspector for Node.js -// -// usage: -// -// var inspect = require('eyes').inspector({styles: {all: 'magenta'}}); -// inspect(something); // inspect with the settings passed to `inspector` -// -// or -// -// var eyes = require('eyes'); -// eyes.inspect(something); // inspect with the default settings -// -var eyes = exports, - stack = []; - -eyes.defaults = { - styles: { // Styles applied to stdout - all: 'cyan', // Overall style applied to everything - label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]` - other: 'inverted', // Objects which don't have a literal representation, such as functions - key: 'bold', // The keys in object literals, like 'a' in `{a: 1}` - special: 'grey', // null, undefined... - string: 'green', - number: 'magenta', - bool: 'blue', // true false - regexp: 'green', // /\d+/ - }, - pretty: true, // Indent object literals - hideFunctions: false, - showHidden: false, - stream: process.stdout, - maxLength: 2048 // Truncate output if longer -}; - -// Return a curried inspect() function, with the `options` argument filled in. -eyes.inspector = function (options) { - var that = this; - return function (obj, label, opts) { - return that.inspect.call(that, obj, label, - merge(options || {}, opts || {})); - }; -}; - -// If we have a `stream` defined, use it to print a styled string, -// if not, we just return the stringified object. -eyes.inspect = function (obj, label, options) { - options = merge(this.defaults, options || {}); - - if (options.stream) { - return this.print(stringify(obj, options), label, options); - } else { - return stringify(obj, options) + (options.styles ? '\033[39m' : ''); - } -}; - -// Output using the 'stream', and an optional label -// Loop through `str`, and truncate it after `options.maxLength` has been reached. -// Because escape sequences are, at this point embeded within -// the output string, we can't measure the length of the string -// in a useful way, without separating what is an escape sequence, -// versus a printable character (`c`). So we resort to counting the -// length manually. -eyes.print = function (str, label, options) { - for (var c = 0, i = 0; i < str.length; i++) { - if (str.charAt(i) === '\033') { i += 4 } // `4` because '\033[25m'.length + 1 == 5 - else if (c === options.maxLength) { - str = str.slice(0, i - 1) + '…'; - break; - } else { c++ } - } - return options.stream.write.call(options.stream, (label ? - this.stylize(label, options.styles.label, options.styles) + ': ' : '') + - this.stylize(str, options.styles.all, options.styles) + '\033[0m' + "\n"); -}; - -// Apply a style to a string, eventually, -// I'd like this to support passing multiple -// styles. -eyes.stylize = function (str, style, styles) { - var codes = { - 'bold' : [1, 22], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'cyan' : [36, 39], - 'magenta' : [35, 39], - 'blue' : [34, 39], - 'yellow' : [33, 39], - 'green' : [32, 39], - 'red' : [31, 39], - 'grey' : [90, 39] - }, endCode; - - if (style && codes[style]) { - endCode = (codes[style][1] === 39 && styles.all) ? codes[styles.all][0] - : codes[style][1]; - return '\033[' + codes[style][0] + 'm' + str + - '\033[' + endCode + 'm'; - } else { return str } -}; - -// Convert any object to a string, ready for output. -// When an 'array' or an 'object' are encountered, they are -// passed to specialized functions, which can then recursively call -// stringify(). -function stringify(obj, options) { - var that = this, stylize = function (str, style) { - return eyes.stylize(str, options.styles[style], options.styles) - }, index, result; - - if ((index = stack.indexOf(obj)) !== -1) { - return stylize(new(Array)(stack.length - index + 1).join('.'), 'special'); - } - stack.push(obj); - - result = (function (obj) { - switch (typeOf(obj)) { - case "string" : obj = stringifyString(obj.indexOf("'") === -1 ? "'" + obj + "'" - : '"' + obj + '"'); - return stylize(obj, 'string'); - case "regexp" : return stylize('/' + obj.source + '/', 'regexp'); - case "number" : return stylize(obj + '', 'number'); - case "function" : return options.stream ? stylize("Function", 'other') : '[Function]'; - case "null" : return stylize("null", 'special'); - case "undefined": return stylize("undefined", 'special'); - case "boolean" : return stylize(obj + '', 'bool'); - case "date" : return stylize(obj.toUTCString()); - case "array" : return stringifyArray(obj, options, stack.length); - case "object" : return stringifyObject(obj, options, stack.length); - } - })(obj); - - stack.pop(); - return result; -}; - -// Escape invisible characters in a string -function stringifyString (str, options) { - return str.replace(/\\/g, '\\\\') - .replace(/\n/g, '\\n') - .replace(/[\u0001-\u001F]/g, function (match) { - return '\\0' + match[0].charCodeAt(0).toString(8); - }); -} - -// Convert an array to a string, such as [1, 2, 3]. -// This function calls stringify() for each of the elements -// in the array. -function stringifyArray(ary, options, level) { - var out = []; - var pretty = options.pretty && (ary.length > 4 || ary.some(function (o) { - return (o !== null && typeof(o) === 'object' && Object.keys(o).length > 0) || - (Array.isArray(o) && o.length > 0); - })); - var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' '; - - for (var i = 0; i < ary.length; i++) { - out.push(stringify(ary[i], options)); - } - - if (out.length === 0) { - return '[]'; - } else { - return '[' + ws - + out.join(',' + (pretty ? ws : ' ')) - + (pretty ? ws.slice(0, -4) : ws) + - ']'; - } -}; - -// Convert an object to a string, such as {a: 1}. -// This function calls stringify() for each of its values, -// and does not output functions or prototype values. -function stringifyObject(obj, options, level) { - var out = []; - var pretty = options.pretty && (Object.keys(obj).length > 2 || - Object.keys(obj).some(function (k) { return typeof(obj[k]) === 'object' })); - var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' '; - - var keys = options.showHidden ? Object.keys(obj) : Object.getOwnPropertyNames(obj); - keys.forEach(function (k) { - if (Object.prototype.hasOwnProperty.call(obj, k) - && !(obj[k] instanceof Function && options.hideFunctions)) { - out.push(eyes.stylize(k, options.styles.key, options.styles) + ': ' + - stringify(obj[k], options)); - } - }); - - if (out.length === 0) { - return '{}'; - } else { - return "{" + ws - + out.join(',' + (pretty ? ws : ' ')) - + (pretty ? ws.slice(0, -4) : ws) + - "}"; - } -}; - -// A better `typeof` -function typeOf(value) { - var s = typeof(value), - types = [Object, Array, String, RegExp, Number, Function, Boolean, Date]; - - if (s === 'object' || s === 'function') { - if (value) { - types.forEach(function (t) { - if (value instanceof t) { s = t.name.toLowerCase() } - }); - } else { s = 'null' } - } - return s; -} - -function merge(/* variable args */) { - var objs = Array.prototype.slice.call(arguments); - var target = {}; - - objs.forEach(function (o) { - Object.keys(o).forEach(function (k) { - if (k === 'styles') { - if (! o.styles) { - target.styles = false; - } else { - target.styles = {} - for (var s in o.styles) { - target.styles[s] = o.styles[s]; - } - } - } else { - target[k] = o[k]; - } - }); - }); - return target; -} - diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/package.json b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/package.json deleted file mode 100644 index 4f3d45911..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/package.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "name": "eyes", - "description": "a customizable value inspector", - "url": "http://github.com/cloudhead/eyes.js", - "keywords": [ - "inspector", - "debug", - "inspect", - "print" - ], - "author": { - "name": "Alexis Sellier", - "email": "self@cloudhead.net" - }, - "contributors": [ - { - "name": "Charlie Robbins", - "email": "charlie@nodejitsu.com" - } - ], - "licenses": [ - "MIT" - ], - "main": "./lib/eyes", - "version": "0.1.8", - "scripts": { - "test": "node test/*-test.js" - }, - "directories": { - "lib": "./lib", - "test": "./test" - }, - "engines": { - "node": "> 0.1.90" - }, - "readme": "eyes\n====\n\na customizable value inspector for Node.js\n\nsynopsis\n--------\n\nI was tired of looking at cluttered output in the console -- something needed to be done,\n`sys.inspect()` didn't display regexps correctly, and was too verbose, and I had an hour or two to spare. \nSo I decided to have some fun. _eyes_ were born.\n\n![eyes-ss](http://dl.dropbox.com/u/251849/eyes-js-ss.gif)\n\n_example of the output of a user-customized eyes.js inspector_\n\n*eyes* also deals with circular objects in an intelligent way, and can pretty-print object literals.\n\nusage\n-----\n\n var inspect = require('eyes').inspector({styles: {all: 'magenta'}});\n\n inspect(something); // inspect with the settings passed to `inspector`\n\nor\n\n var eyes = require('eyes');\n\n eyes.inspect(something); // inspect with the default settings\n\nyou can pass a _label_ to `inspect()`, to keep track of your inspections:\n\n eyes.inspect(something, \"a random value\");\n\nIf you want to return the output of eyes without printing it, you can set it up this way:\n\n var inspect = require('eyes').inspector({ stream: null });\n\n sys.puts(inspect({ something: 42 }));\n\ncustomization\n-------------\n\nThese are the default styles and settings used by _eyes_.\n\n styles: { // Styles applied to stdout\n all: 'cyan', // Overall style applied to everything\n label: 'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]`\n other: 'inverted', // Objects which don't have a literal representation, such as functions\n key: 'bold', // The keys in object literals, like 'a' in `{a: 1}`\n special: 'grey', // null, undefined...\n string: 'green',\n number: 'magenta',\n bool: 'blue', // true false\n regexp: 'green', // /\\d+/\n },\n \n pretty: true, // Indent object literals\n hideFunctions: false, // Don't output functions at all\n stream: process.stdout, // Stream to write to, or null\n maxLength: 2048 // Truncate output if longer\n\nYou can overwrite them with your own, by passing a similar object to `inspector()` or `inspect()`.\n\n var inspect = require('eyes').inspector({\n styles: {\n all: 'magenta',\n special: 'bold'\n },\n maxLength: 512\n });\n\n", - "readmeFilename": "README.md", - "_id": "eyes@0.1.8", - "_from": "eyes@0.1.x" -} diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/test/eyes-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/test/eyes-test.js deleted file mode 100644 index 1f9606a2d..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/eyes/test/eyes-test.js +++ /dev/null @@ -1,56 +0,0 @@ -var util = require('util'); -var eyes = require('../lib/eyes'); - -eyes.inspect({ - number: 42, - string: "John Galt", - regexp: /[a-z]+/, - array: [99, 168, 'x', {}], - func: function () {}, - bool: false, - nil: null, - undef: undefined, - object: {attr: []} -}, "native types"); - -eyes.inspect({ - number: new(Number)(42), - string: new(String)("John Galt"), - regexp: new(RegExp)(/[a-z]+/), - array: new(Array)(99, 168, 'x', {}), - bool: new(Boolean)(false), - object: new(Object)({attr: []}), - date: new(Date) -}, "wrapped types"); - -var obj = {}; -obj.that = { self: obj }; -obj.self = obj; - -eyes.inspect(obj, "circular object"); -eyes.inspect({hello: 'moto'}, "small object"); -eyes.inspect({hello: new(Array)(6) }, "big object"); -eyes.inspect(["hello 'world'", 'hello "world"'], "quotes"); -eyes.inspect({ - recommendations: [{ - id: 'a7a6576c2c822c8e2bd81a27e41437d8', - key: [ 'spree', 3.764316258020699 ], - value: { - _id: 'a7a6576c2c822c8e2bd81a27e41437d8', - _rev: '1-2e2d2f7fd858c4a5984bcf809d22ed98', - type: 'domain', - domain: 'spree', - weight: 3.764316258020699, - product_id: 30 - } - }] -}, 'complex'); - -eyes.inspect([null], "null in array"); - -var inspect = eyes.inspector({ stream: null }); - -util.puts(inspect('something', "something")); -util.puts(inspect("something else")); - -util.puts(inspect(["no color"], null, { styles: false })); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/.npmignore b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/.npmignore deleted file mode 100644 index 8f08029c6..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -test/data -test/data/* -node_modules -npm-debug.log \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/README.md b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/README.md deleted file mode 100644 index 926cb63f1..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/README.md +++ /dev/null @@ -1,227 +0,0 @@ -# node-loggly - -A client implementation for Loggly in node.js - -## Installation - -### Installing npm (node package manager) -``` bash - $ curl http://npmjs.org/install.sh | sh -``` - -### Installing node-loggly -``` bash - $ [sudo] npm install loggly -``` - -## Usage - -The node-loggly library is compliant with the [Loggly API][0]. Using node-loggly is easy for a variety of scenarios: logging, working with devices and inputs, searching, and facet searching. - -### Getting Started -Before we can do anything with Loggly, we have to create a client with valid credentials. We will authenticate for you automatically: - -``` js - var loggly = require('loggly'); - var config = { - subdomain: "your-subdomain", - auth: { - username: "your-username", - password: "your-password" - } - }; - var client = loggly.createClient(config); -``` - -### Logging -There are two ways to send log information to Loggly via node-loggly. The first is to simply call client.log with an appropriate input token: - -``` js - client.log('your-really-long-input-token', '127.0.0.1 - Theres no place like home', function (err, result) { - // Do something once you've logged - }); -``` - -Note that the callback in the above example is optional, if you prefer the 'fire and forget' method of logging: - -``` js - client.log('your-really-long-input-token', '127.0.0.1 - Theres no place like home'); -``` - -The second way to send log information to Loggly is to do so once you've retrieved an input directly from Loggly: - -``` js - client.getInput('your-input-name', function (err, input) { - input.log('127.0.0.1 - Theres no place like home'); - }); -``` - -Again the callback in the above example is optional and you can pass it if you'd like to. - -### Logging Shallow JSON Object Literals as a String -In addition to logging pure strings it is also possible to pass shallow JSON object literals (i.e. no nested objects) to client.log(..) or input.log(..) methods, which will get converted into the [Loggly recommended string representation][1]. So - -``` js - var source = { - foo: 1, - bar: 2, - buzz: 3 - }; - - input.log(source); -``` - -will be logged as: - -``` - foo=1,bar=2,buzz=3 -``` - -### Logging Objects to JSON Enabled Loggly Inputs -It is also possible to log complex objects using the new JSON capabilities of Loggly. To enable JSON functionality in the client simply add 'json: true' to the configuration: - -``` js - var config = { - subdomain: "your-subdomain", - auth: { - username: "your-username", - password: "your-password" - }, - json: true - }; -``` - -When the json flag is enabled, objects will be converted to JSON using JSON.stringify before being transmitted to Loggly. So - -``` js - var source = { - foo: 1, - bar: 2, - buzz: { - sheep: 'jumped', - times: 10 - } - }; - - input.log(source); -``` - -will be logged as: - -``` json - { "foo": 1, "bar": 2, "buzz": {"sheep": "jumped", "times": 10 }} -``` - -### Searching -[Searching][3] with node-loggly is easy. All you have to do is use the search() method defined on each Loggly client: - -``` js - var util = require('util'); - - client.search('404', function (err, results) { - // Inspect the result set - util.inspect(results.data); - }); -``` - -The search() exposes a chainable interface that allows you to set additional search parameters such as: ip, input name, rows, start, end, etc. - -``` js - var util = require('util'); - - client.search('404') - .meta({ ip: '127.0.0.1', inputname: test }) - .context({ rows: 10 }) - .run(function (err, results) { - // Inspect the result set - util.inspect(results.data); - }); -``` - -The context of the search (set using the `.context()` method) represents additional parameters in the Loggly API besides the search query itself. See the [Search API documentation][9] for a list of all options. - -Metadata set using the `.meta()` method is data that is set in the query parameter of your Loggly search, but `:` delimited. For more information about search queries in Loggly, check out the [Search Language Guide][4] on the [Loggly Wiki][5]. - -### Facet Searching -Loggly also exposes searches that can return counts of events over a time range. These are called [facets][6]. The valid facets are 'ip', 'date', and 'input'. Performing a facet search is very similar to a normal search: - -``` js - var util = require('util'); - - client.facet('ip', '404') - .context({ buckets: 10 }) - .run(function (err, results) { - // Inspect the result set - util.inspect(results.data); - }); -``` - -The chaining and options for the facet method(s) are the same as the search method above. - -### Working with Devices and Inputs -Loggly exposes several entities that are available through node-loggly: inputs and devices. For more information about these terms, checkout the [Loggly Jargon][7] on the wiki. There are several methods available in node-loggly to work with these entities: - -``` js - // - // Returns all inputs associated with your account - // - client.getInputs(function (err, inputs) { /* ... */ }); - - // - // Returns an input with the specified name - // - client.getInput('input-name', function (err, input) { /* ... */ }); - - // - // Returns all devices associated with your account - // - client.getDevices(function (err, devices) { /* ... */ }); -``` - -## Run Tests -All of the node-loggly tests are written in [vows][8], and cover all of the use cases described above. You will need to add your Loggly username, password, subdomain, and a two test inputs to test/data/test-config.json before running tests. When configuring the test inputs on Loggly, the first test input should be named 'test' using the HTTP service. The second input should be name 'test_json' using the HTTP service with the JSON logging option enabled: - -``` js - { - "subdomain": "your-subdomain", - "auth": { - "username": "your-username", - "password": "your-password" - }, - "inputs": { - "test": { - // - // Token and ID of your plain-text input. - // - "token": "your-really-long-token-you-got-when-you-created-an-http-input", - "id": 000 - }, - "test_json": { - // - // Token and ID of your JSON input. - // - "token": "your-really-long-token-you-got-when-you-created-an-http-input", - "id": 001 - }, - } - } -``` - -Once you have valid Loggly credentials you can run tests with [vows][8]: - -``` bash - $ npm test -``` - -#### Author: [Charlie Robbins](http://www.github.com/indexzero) -#### Contributors: [Marak Squires](http://github.com/marak), [hij1nx](http://github.com/hij1nx), [Kord Campbell](http://loggly.com), [Erik Hedenström](http://github.com/ehedenst), - -[0]: http://wiki.loggly.com/apidocumentation -[1]: http://wiki.loggly.com/loggingfromcode -[3]: http://wiki.loggly.com/retrieve_events#search_uri -[4]: http://wiki.loggly.com/searchguide -[5]: http://wiki.loggly.com/ -[6]: http://wiki.loggly.com/retrieve_events#facet_uris -[7]: http://wiki.loggly.com/loggingjargon -[8]: http://vowsjs.org -[9]: http://wiki.loggly.com/retrieve_events#optional diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/docco.css b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/docco.css deleted file mode 100644 index bd5413433..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/docco.css +++ /dev/null @@ -1,194 +0,0 @@ -/*--------------------- Layout and Typography ----------------------------*/ -body { - font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; - font-size: 15px; - line-height: 22px; - color: #252519; - margin: 0; padding: 0; -} -a { - color: #261a3b; -} - a:visited { - color: #261a3b; - } -p { - margin: 0 0 15px 0; -} -h4, h5, h6 { - color: #333; - margin: 6px 0 6px 0; - font-size: 13px; -} - h2, h3 { - margin-bottom: 0; - color: #000; - } - h1 { - margin-top: 40px; - margin-bottom: 15px; - color: #000; - } -#container { - position: relative; -} -#background { - position: fixed; - top: 0; left: 525px; right: 0; bottom: 0; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - z-index: -1; -} -#jump_to, #jump_page { - background: white; - -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; - -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; - font: 10px Arial; - text-transform: uppercase; - cursor: pointer; - text-align: right; -} -#jump_to, #jump_wrapper { - position: fixed; - right: 0; top: 0; - padding: 5px 10px; -} - #jump_wrapper { - padding: 0; - display: none; - } - #jump_to:hover #jump_wrapper { - display: block; - } - #jump_page { - padding: 5px 0 3px; - margin: 0 0 25px 25px; - } - #jump_page .source { - display: block; - padding: 5px 10px; - text-decoration: none; - border-top: 1px solid #eee; - } - #jump_page .source:hover { - background: #f5f5ff; - } - #jump_page .source:first-child { - } -table td { - border: 0; - outline: 0; -} - td.docs, th.docs { - max-width: 450px; - min-width: 450px; - min-height: 5px; - padding: 10px 25px 1px 50px; - overflow-x: hidden; - vertical-align: top; - text-align: left; - } - .docs pre { - margin: 15px 0 15px; - padding-left: 15px; - } - .docs p tt, .docs p code { - background: #f8f8ff; - border: 1px solid #dedede; - font-size: 12px; - padding: 0 0.2em; - } - .pilwrap { - position: relative; - } - .pilcrow { - font: 12px Arial; - text-decoration: none; - color: #454545; - position: absolute; - top: 3px; left: -20px; - padding: 1px 2px; - opacity: 0; - -webkit-transition: opacity 0.2s linear; - } - td.docs:hover .pilcrow { - opacity: 1; - } - td.code, th.code { - padding: 14px 15px 16px 25px; - width: 100%; - vertical-align: top; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - } - pre, tt, code { - font-size: 12px; line-height: 18px; - font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; - margin: 0; padding: 0; - } - - -/*---------------------- Syntax Highlighting -----------------------------*/ -td.linenos { background-color: #f0f0f0; padding-right: 10px; } -span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } -body .hll { background-color: #ffffcc } -body .c { color: #408080; font-style: italic } /* Comment */ -body .err { border: 1px solid #FF0000 } /* Error */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ -body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { color: #0000FF } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly.html deleted file mode 100644 index 7afcf684c..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly.html +++ /dev/null @@ -1,16 +0,0 @@ - loggly.js

        loggly.js

        /*
        - * loggly.js: Wrapper for node-loggly object
        - *
        - * (C) 2010 Nodejitsu Inc.
        - * MIT LICENSE
        - *
        - */
        -
        -var loggly = exports;

        Export node-loggly core client APIs

        loggly.createClient  = require('./loggly/core').createClient;
        -loggly.Loggly        = require('./loggly/core').Loggly;
        -loggly.Config        = require('./loggly/config').Config;

        Export Resources for node-loggly

        loggly.Input  = require('./loggly/input').Input;
        -loggly.Facet  = require('./loggly/facet').Facet;
        -loggly.Device = require('./loggly/device').Device;
        -loggly.Search = require('./loggly/search').Search;
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/common.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/common.html deleted file mode 100644 index 94336be01..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/common.html +++ /dev/null @@ -1,126 +0,0 @@ - common.js

        common.js

        /*
        - * common.js: Common utility functions for requesting against Loggly APIs
        - *
        - * (C) 2010 Nodejitsu Inc.
        - * MIT LICENSE
        - *
        - */
        -
        -var request = require('request'),
        -    loggly = require('../loggly');
        -
        -var common = exports;

        Failure HTTP Response codes based -off Loggly specification.

        var failCodes = common.failCodes = {
        -  400: "Bad Request",
        -  401: "Unauthorized",
        -  403: "Forbidden",
        -  404: "Not Found",
        -  409: "Conflict / Duplicate",
        -  410: "Gone",
        -  500: "Internal Server Error",
        -  501: "Not Implemented",
        -  503: "Throttled"
        -};

        Success HTTP Response codes based -off Loggly specification.

        var successCodes = common.successCodes = {
        -  200: "OK",
        -  201: "Created", 
        -  202: "Accepted",
        -  203: "Non-authoritative information",
        -  204: "Deleted",
        -};

        Core method that actually sends requests to Loggly. -This method is designed to be flexible w.r.t. arguments -and continuation passing given the wide range of different -requests required to fully implement the Loggly API.

        - -

        Continuations: - 1. 'callback': The callback passed into every node-loggly method - 2. 'success': A callback that will only be called on successful requests. - This is used throughout node-loggly to conditionally - do post-request processing such as JSON parsing.

        - -

        Possible Arguments (1 & 2 are equivalent): - 1. common.loggly('some-fully-qualified-url', auth, callback, success) - 2. common.loggly('GET', 'some-fully-qualified-url', auth, callback, success) - 3. common.loggly('DELETE', 'some-fully-qualified-url', auth, callback, success) - 4. common.loggly({ method: 'POST', uri: 'some-url', body: { some: 'body'} }, callback, success)

        common.loggly = function () {
        -  var args = Array.prototype.slice.call(arguments),
        -      success = args.pop(),
        -      callback = args.pop(),
        -      requestBody, 
        -      headers,
        -      method, 
        -      auth, 
        -      uri;
        -  

        Now that we've popped off the two callbacks -We can make decisions about other arguments

          if (args.length == 1) {
        -    if (typeof args[0] === 'string') {

        If we got a string assume that it's the URI

              method = 'GET';
        -      uri    = args[0];
        -    }
        -    else {
        -      method      = args[0]['method'] || 'GET',
        -      uri         = args[0]['uri'];
        -      requestBody = args[0]['body'];
        -      auth        = args[0]['auth'];
        -      headers     = args[0]['headers'];
        -    }
        -  }
        -  else if (args.length == 2) {
        -    method = 'GET';
        -    uri    = args[0];
        -    auth   = args[1];
        -  }
        -  else {
        -    method = args[0];
        -    uri    = args[1];
        -    auth   = args[2];
        -  }
        -  
        -  function onError (err) {
        -    if (callback) {
        -      callback(err);
        -    }
        -  }
        -  
        -  var requestOptions = {
        -    uri: uri,
        -    method: method,
        -    headers: headers || {}
        -  };
        -  
        -  if (auth) {
        -    requestOptions.headers['authorization'] = 'Basic ' + new Buffer(auth.username + ':' + auth.password).toString('base64');
        -  }
        -  
        -  if (requestBody) {
        -    requestOptions.body = requestBody;
        -  }
        -  
        -  try {
        -    request(requestOptions, function (err, res, body) {
        -      if (err) {
        -        return onError(err);
        -      }
        -
        -      var statusCode = res.statusCode.toString();
        -      if (Object.keys(failCodes).indexOf(statusCode) !== -1) {
        -        return onError((new Error('Loggly Error (' + statusCode + '): ' + failCodes[statusCode])));
        -      }
        -
        -      success(res, body);
        -    });
        -  }
        -  catch (ex) {
        -    onError(ex);
        -  }
        -};

        function clone (obj) - Helper method for deep cloning pure JSON objects - i.e. JSON objects that are either literals or objects (no Arrays, etc)

        common.clone = function (obj) {
        -  var clone = {};
        -  for (var i in obj) {
        -    clone[i] = obj[i] instanceof Object ? common.clone(obj[i]) : obj[i];
        -  }
        -
        -  return clone;
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/config.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/config.html deleted file mode 100644 index 0f39f4a21..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/config.html +++ /dev/null @@ -1,41 +0,0 @@ - config.js

        config.js

        /*
        - * config.js: Configuration information for your Loggly account.
        - *            This information is only used for require('loggly')./\.+/ methods
        - *
        - * (C) 2010 Nodejitsu Inc.
        - * MIT LICENSE
        - *
        - */

        function createConfig (defaults) - Creates a new instance of the configuration - object based on default values

        exports.createConfig = function (defaults) {
        -  return new Config(defaults);
        -};

        Config (defaults) - Constructor for the Config object

        var Config = exports.Config = function (defaults) {
        -  if (!defaults.subdomain) {
        -    throw new Error('Subdomain is required to create an instance of Config');
        -  }
        -  
        -  this.subdomain = defaults.subdomain;
        -  this.json = defaults.json || null;
        -  this.auth = defaults.auth || null;
        -};
        - 
        -Config.prototype = {
        -  get subdomain () {
        -   return this._subdomain; 
        -  },
        -
        -  set subdomain (value) {
        -    this._subdomain = value;
        -  },
        -  
        -  get logglyUrl () {
        -    return 'https://' + [this._subdomain, 'loggly', 'com'].join('.') + '/api';
        -  },
        -  
        -  get inputUrl () {
        -    return 'https://logs.loggly.com/inputs/';
        -  }
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/core.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/core.html deleted file mode 100644 index 7d1a4bf24..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/core.html +++ /dev/null @@ -1,150 +0,0 @@ - core.js

        core.js

        /*
        - * core.js: Core functions for accessing Loggly
        - *
        - * (C) 2010 Nodejitsu Inc.
        - * MIT LICENSE
        - *
        - */
        -
        -var events = require('events'),
        -    qs = require('querystring'),
        -    config = require('./config'),
        -    common = require('./common'),
        -    Search = require('./search').Search,
        -    Facet = require('./facet').Facet,
        -    loggly = require('../loggly');

        function createClient (options) - Creates a new instance of a Loggly client.

        exports.createClient = function (options) {
        -  return new Loggly(config.createConfig(options));
        -};

        Loggly (config) - Constructor for the Loggly object

        var Loggly = exports.Loggly = function (config) {
        -  this.config = config;
        -};

        function log (callback) - logs args to input device

        Loggly.prototype.log = function (inputId, msg, callback) {
        -  var emitter = new (events.EventEmitter)(),
        -      message;
        -      
        -  if (msg instanceof Object) {
        -    message = this.config.json ? JSON.stringify(msg) : qs.unescape(qs.stringify(msg, ','));
        -  } else {
        -    message = this.config.json ? JSON.stringify({ message : msg }) : msg;
        -  }
        -
        -  var logOptions = {
        -    uri: this.config.inputUrl + inputId,
        -    method: 'POST', 
        -    body: message,
        -    headers: {
        -      'Content-Type': this.config.json ? 'application/json' : 'text/plain'
        -    }
        -  };
        -
        -  common.loggly(logOptions, callback, function (res, body) {
        -    try {
        -      var result = JSON.parse(body);
        -      if (callback) {
        -        callback(null, result);
        -      }
        -      
        -      emitter.emit('log', result);
        -    }
        -    catch (ex) {
        -      if (callback) {
        -        callback(new Error('Unspecified error from Loggly: ' + ex));
        -      }
        -    }
        -  }); 
        -  
        -  return emitter; 
        -};

        function search (query, callback) - Returns a new search object which can be chained - with options or called directly if @callback is passed - initially.

        - -

        Sample Usage:

        - -

        client.search('404') - .meta({ ip: '127.0.0.1' }) - .context({ rows: 100 }) - .run(function () { /* ... */ });

        Loggly.prototype.search = function (query, callback) {
        -  return new Search(query, this, callback);
        -};

        function facet (facet, query, [options], callback) - Performs a facet search against loggly with the - specified facet, query and options.

        Loggly.prototype.facet = function (facet, query, callback) {
        -  return new Facet(facet, query, this, callback);
        -};

        function getInputs ([raw], callback) - Returns a list of all inputs for the authenicated account

        Loggly.prototype.getInputs = function () {
        -  var self = this,
        -      args = Array.prototype.slice.call(arguments),
        -      callback = args.pop(),
        -      raw = args.length > 0 ? args[0] : false;
        -  
        -  common.loggly(this.logglyUrl('inputs'), this.config.auth, callback, function (res, body) {
        -    var inputs = [], 
        -        results = JSON.parse(body);
        -        
        -    if (!raw) {
        -      results.forEach(function (result) {
        -        inputs.push(new (loggly.Input)(self, result));
        -      });
        -      
        -      return callback(null, inputs);
        -    }
        -    
        -    callback(null, results);
        -  });
        -};

        function getInput (name, callback) - Returns the input with the specified name

        Loggly.prototype.getInput = function (name, callback) {
        -  var self = this;
        -  this.getInputs(true, function (err, results) {
        -    if (err) {
        -      return callback(err);
        -    }
        -    
        -    var matches = results.filter(function (r) { return r.name === name }),
        -        input = null;
        -        
        -    if (matches.length > 0) {
        -      input = new (loggly.Input)(self, matches[0]);
        -    }
        -    
        -    callback(null, input);
        -  });
        -};

        function addDevice (inputId, address, callback) - Adds the device at address to the input specified by inputId

        Loggly.prototype.addDeviceToInput = function (inputId, address, callback) {
        -  var addOptions = {
        -    uri: this.logglyUrl('devices'),
        -    auth: this.config.auth,
        -    method: 'POST', 
        -    headers: {
        -      'Content-Type': 'application/x-www-form-urlencoded'
        -    },
        -    body: qs.stringify({ 'input_id': inputId, 'ip': address }).replace('"', '')
        -  };
        -
        -  common.loggly(addOptions, callback, function (res, body) {
        -    callback(null, res);
        -  });
        -};

        function addDevice (inputId, callback) - Adds the calling device to the input

        Loggly.prototype.addDevice = function (inputId, callback) {

        Remark: This is not fully implemented yet

          callback(new Error('Not Implemented Yet...'));
        -  

        common.loggly(this.logglyUrl('inputs', inputId, 'adddevice'), this.config.auth, callback, function (res, body) { -});

        };

        function getDevices (callback) - Returns a list of all devices for the authenicated account

        Loggly.prototype.getDevices = function (callback) {
        -  var self = this;
        -  common.loggly(this.logglyUrl('devices'), this.config.auth, callback, function (res, body) {
        -    var results = JSON.parse(body),
        -        devices = [];
        -        
        -    results.forEach(function (result) {
        -      devices.push(new (loggly.Device)(self, result));
        -    });
        -    
        -    callback(null, devices);
        -  });
        -};

        function logglyUrl ([path, to, resource]) - Helper method that concats the string params into a url - to request against a loggly serverUrl.

        Loggly.prototype.logglyUrl = function (/* path, to, resource */) {
        -  var args = Array.prototype.slice.call(arguments);
        -  return [this.config.logglyUrl].concat(args).join('/');
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/device.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/device.html deleted file mode 100644 index 3cc7fc502..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/device.html +++ /dev/null @@ -1,26 +0,0 @@ - device.js

        device.js

        /*
        - * device.js: Instance of a single Loggly device
        - *
        - * (C) 2010 Nodejitsu Inc.
        - * MIT LICENSE
        - *
        - */
        - 
        -var Device = exports.Device = function (client, details) {
        -  if (!details) throw new Error("Device must be constructed with at least basic details.")
        -
        -  this.client = client;
        -  this._setProperties(details);
        -};
        -
        -Device.prototype.addToInput = function (inputId, callback) {
        -  this.client.addDeviceToInput(inputId, this.id, callback);
        -};
        -  

        Sets the properties for this instance -Parameters: details

        Device.prototype._setProperties = function (details) {

        Copy the properties to this instance

          var self = this;
        -  Object.keys(details).forEach(function (key) {
        -    self[key] = details[key];
        -  });
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/facet.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/facet.html deleted file mode 100644 index 39fe2b3ff..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/facet.html +++ /dev/null @@ -1,26 +0,0 @@ - facet.js

        facet.js

        /*
        - * facet.js: Chainable search functions for Loggly facet searches.
        - *
        - * (C) 2010 Nodejitsu Inc.
        - * MIT LICENSE
        - *
        - */
        -
        -var util = require('util'),
        -    Search = require('./search').Search;

        function Facet (facet, query, client, callback) - Chainable facet search object for Loggly API

        var Facet = exports.Facet = function (facet, query, client, callback) {
        -  if (['date', 'ip', 'input'].indexOf(facet) === -1) {
        -    var error = new Error('Cannot search with unknown facet: ' + facet); 
        -    
        -    if (callback) {
        -      return callback(error);
        -    }
        -    else {
        -      throw error;
        -    }
        -  }
        -  

        Set the baseUrl to be facet/:facet?

          this.baseUrl = ['facets', facet + '?'].join('/');
        -  

        Call the base constructor.

          Search.call(this, query, client, callback);
        -};

        Inherit from loggly.Search.

        util.inherits(Facet, Search);
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/input.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/input.html deleted file mode 100644 index 22bcac22d..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/input.html +++ /dev/null @@ -1,32 +0,0 @@ - input.js

        input.js

        /*
        - * input.js: Instance of a single Loggly input
        - *
        - * (C) 2010 Nodejitsu Inc.
        - * MIT LICENSE
        - *
        - */
        - 
        -var Input = exports.Input = function (client, details) {
        -  if (!details) {
        -    throw new Error("Input must be constructed with at least basic details.");
        -  }
        -  
        -  this.client = client;
        -  this._setProperties(details);
        -};
        -
        -Input.prototype.log = function (msg, callback) {
        -  return this.client.log(this.input_token, msg, callback);
        -};
        -  
        -Input.prototype.addDevice = function (address, callback) {
        -  this.client.addDeviceToInput(this.id, address, callback);
        -};
        -  

        Sets the properties for this instance -Parameters: details

        Input.prototype._setProperties = function (details) {

        Copy the properties to this instance

          var self = this;
        -  Object.keys(details).forEach(function (key) {
        -    self[key] = details[key];
        -  });
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/search.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/search.html deleted file mode 100644 index 0a13c0e26..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/docs/loggly/search.html +++ /dev/null @@ -1,89 +0,0 @@ - search.js

        search.js

        /*
        - * search.js: chainable search functions for Loggly
        - *
        - * (C) 2010 Nodejitsu Inc.
        - * MIT LICENSE
        - *
        - */
        -
        -var qs = require('querystring'),
        -    timespan = require('timespan'),
        -    common = require('./common');

        function Search (query, client, callback) - Chainable search object for Loggly API

        var Search = exports.Search = function (query, client, callback) {
        -  this.query = query;
        -  this.client = client;
        -  
        -  if (!this.baseUrl) {
        -    this.baseUrl = 'search?';
        -  }
        -  

        If we're passed a callback, run immediately.

          if (callback) {
        -    this.callback = callback;
        -    this.run();
        -  }
        -};

        function meta (meta) - Sets the appropriate metadata for this search query: - e.g. ip, inputname

        Search.prototype.meta = function (meta) {
        -  this._meta = meta;
        -  return this;
        -};

        function context (context) - Sets the appropriate context for this search query: - e.g. rows, start, from, until, order, format, fields

        Search.prototype.context = function (context) {
        -  this._context = context;
        -  return this;
        -};

        function run (callback)

        - -

        @callback {function} Continuation to respond to when complete

        - -

        Runs the search query for for this instance with the query, metadata, -context, and other parameters that have been configured on it.

        Search.prototype.run = function (callback) {
        -  var rangeError;
        -  

        Trim the search query

          this.query.trim();
        -  

        Update the callback for this instance if it's passed

          this.callback = callback || this.callback;
        -  if (!this.callback) {
        -    throw new Error('Cannot run search without a callback function.');
        -  }
        -  

        If meta was passed, update the search query appropriately

          if (this._meta) {
        -    this.query += ' ' + qs.unescape(qs.stringify(this._meta, ' ', ':'));
        -  }

        Set the context for the query string

          this._context = this._context || {};
        -  this._context.q = this.query;
        -  this._checkRange();
        -
        -  var self = this, searchOptions = {
        -    uri: this.client.logglyUrl(this.baseUrl + qs.stringify(this._context)),
        -    auth: this.client.config.auth
        -  };
        -  
        -  common.loggly(searchOptions, this.callback, function (res, body) {
        -    self.callback(null, JSON.parse(body));
        -  });
        -  
        -  return this;
        -};

        function _checkRange ()

        - -

        Checks if the range that has been configured for this -instance is valid and updates if it is not.

        Search.prototype._checkRange = function () {
        -  if (!this._context || (!this._context.until && !this._context.from)) {
        -    return;
        -  }
        -  
        -  this._context.until = this._context.until || 'NOW';
        -  this._context.from  = this._context.from  || 'NOW-24HOURS';
        -  
        -  if (!timespan.parseDate(this._context.until)) {
        -    this._context.until = 'NOW';
        -  }
        -  
        -  if (!timespan.parseDate(this._context.from)) {
        -    this._context.from = 'NOW-24HOURS';
        -  }
        -  
        -  if (timespan.fromDates(this._context.from, this._context.until) < 0
        -    || this._context.until === this._context.from) {

        If the length of the timespan for this Search instance is -negative then set it to default values

            this._context.until = 'NOW';
        -    this._context.from = 'NOW-24HOURS';
        -  }
        -  
        -  return this;
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly.js deleted file mode 100644 index e55d2c27a..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly.js +++ /dev/null @@ -1,25 +0,0 @@ -/* - * loggly.js: Wrapper for node-loggly object - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var loggly = exports; - -// -// Export node-loggly core client APIs -// -loggly.createClient = require('./loggly/core').createClient; -loggly.serialize = require('./loggly/common').serialize; -loggly.Loggly = require('./loggly/core').Loggly; -loggly.Config = require('./loggly/config').Config; - -// -// Export Resources for node-loggly -// -loggly.Input = require('./loggly/input').Input; -loggly.Facet = require('./loggly/facet').Facet; -loggly.Device = require('./loggly/device').Device; -loggly.Search = require('./loggly/search').Search; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/common.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/common.js deleted file mode 100644 index dae938ecb..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/common.js +++ /dev/null @@ -1,204 +0,0 @@ -/* - * common.js: Common utility functions for requesting against Loggly APIs - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var util = require('util'), - request = require('request'), - loggly = require('../loggly'); - -var common = exports; - -// -// Failure HTTP Response codes based -// off Loggly specification. -// -var failCodes = common.failCodes = { - 400: "Bad Request", - 401: "Unauthorized", - 403: "Forbidden", - 404: "Not Found", - 409: "Conflict / Duplicate", - 410: "Gone", - 500: "Internal Server Error", - 501: "Not Implemented", - 503: "Throttled" -}; - -// -// Success HTTP Response codes based -// off Loggly specification. -// -var successCodes = common.successCodes = { - 200: "OK", - 201: "Created", - 202: "Accepted", - 203: "Non-authoritative information", - 204: "Deleted", -}; - -// -// Core method that actually sends requests to Loggly. -// This method is designed to be flexible w.r.t. arguments -// and continuation passing given the wide range of different -// requests required to fully implement the Loggly API. -// -// Continuations: -// 1. 'callback': The callback passed into every node-loggly method -// 2. 'success': A callback that will only be called on successful requests. -// This is used throughout node-loggly to conditionally -// do post-request processing such as JSON parsing. -// -// Possible Arguments (1 & 2 are equivalent): -// 1. common.loggly('some-fully-qualified-url', auth, callback, success) -// 2. common.loggly('GET', 'some-fully-qualified-url', auth, callback, success) -// 3. common.loggly('DELETE', 'some-fully-qualified-url', auth, callback, success) -// 4. common.loggly({ method: 'POST', uri: 'some-url', body: { some: 'body'} }, callback, success) -// -common.loggly = function () { - var args = Array.prototype.slice.call(arguments), - success = args.pop(), - callback = args.pop(), - requestBody, - headers, - method, - auth, - uri; - - // - // Now that we've popped off the two callbacks - // We can make decisions about other arguments - // - if (args.length == 1) { - if (typeof args[0] === 'string') { - // - // If we got a string assume that it's the URI - // - method = 'GET'; - uri = args[0]; - } - else { - method = args[0]['method'] || 'GET', - uri = args[0]['uri']; - requestBody = args[0]['body']; - auth = args[0]['auth']; - headers = args[0]['headers']; - } - } - else if (args.length == 2) { - method = 'GET'; - uri = args[0]; - auth = args[1]; - } - else { - method = args[0]; - uri = args[1]; - auth = args[2]; - } - - function onError (err) { - if (callback) { - callback(err); - } - } - - var requestOptions = { - uri: uri, - method: method, - headers: headers || {} - }; - - if (auth) { - requestOptions.headers['authorization'] = 'Basic ' + new Buffer(auth.username + ':' + auth.password).toString('base64'); - } - - if (requestBody) { - requestOptions.body = requestBody; - } - - try { - request(requestOptions, function (err, res, body) { - if (err) { - return onError(err); - } - - var statusCode = res.statusCode.toString(); - if (Object.keys(failCodes).indexOf(statusCode) !== -1) { - return onError((new Error('Loggly Error (' + statusCode + '): ' + failCodes[statusCode]))); - } - - success(res, body); - }); - } - catch (ex) { - onError(ex); - } -}; - -// -// ### function serialize (obj, key) -// #### @obj {Object|literal} Object to serialize -// #### @key {string} **Optional** Optional key represented by obj in a larger object -// Performs simple comma-separated, `key=value` serialization for Loggly when -// logging to non-JSON inputs. -// -common.serialize = function (obj, key) { - if (obj === null) { - obj = 'null'; - } - else if (obj === undefined) { - obj = 'undefined'; - } - else if (obj === false) { - obj = 'false'; - } - - if (typeof obj !== 'object') { - return key ? key + '=' + obj : obj; - } - - var msg = '', - keys = Object.keys(obj), - length = keys.length; - - for (var i = 0; i < length; i++) { - if (Array.isArray(obj[keys[i]])) { - msg += keys[i] + '=[' - - for (var j = 0, l = obj[keys[i]].length; j < l; j++) { - msg += common.serialize(obj[keys[i]][j]); - if (j < l - 1) { - msg += ', '; - } - } - - msg += ']'; - } - else { - msg += common.serialize(obj[keys[i]], keys[i]); - } - - if (i < length - 1) { - msg += ', '; - } - } - - return msg; -}; - -// -// function clone (obj) -// Helper method for deep cloning pure JSON objects -// i.e. JSON objects that are either literals or objects (no Arrays, etc) -// -common.clone = function (obj) { - var clone = {}; - for (var i in obj) { - clone[i] = obj[i] instanceof Object ? common.clone(obj[i]) : obj[i]; - } - - return clone; -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/config.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/config.js deleted file mode 100644 index 2156ceb76..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/config.js +++ /dev/null @@ -1,49 +0,0 @@ -/* - * config.js: Configuration information for your Loggly account. - * This information is only used for require('loggly')./\.+/ methods - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -// -// function createConfig (defaults) -// Creates a new instance of the configuration -// object based on default values -// -exports.createConfig = function (defaults) { - return new Config(defaults); -}; - -// -// Config (defaults) -// Constructor for the Config object -// -var Config = exports.Config = function (defaults) { - if (!defaults.subdomain) { - throw new Error('Subdomain is required to create an instance of Config'); - } - - this.subdomain = defaults.subdomain; - this.json = defaults.json || null; - this.auth = defaults.auth || null; -}; - -Config.prototype = { - get subdomain () { - return this._subdomain; - }, - - set subdomain (value) { - this._subdomain = value; - }, - - get logglyUrl () { - return 'https://' + [this._subdomain, 'loggly', 'com'].join('.') + '/api'; - }, - - get inputUrl () { - return 'https://logs.loggly.com/inputs/'; - } -}; diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/core.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/core.js deleted file mode 100644 index 9be1553ad..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/core.js +++ /dev/null @@ -1,211 +0,0 @@ -/* - * core.js: Core functions for accessing Loggly - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var events = require('events'), - qs = require('querystring'), - config = require('./config'), - common = require('./common'), - Search = require('./search').Search, - Facet = require('./facet').Facet, - loggly = require('../loggly'); - -// -// function createClient (options) -// Creates a new instance of a Loggly client. -// -exports.createClient = function (options) { - return new Loggly(config.createConfig(options)); -}; - -// -// Loggly (config) -// Constructor for the Loggly object -// -var Loggly = exports.Loggly = function (config) { - this.config = config; -}; - -// -// function log (callback) -// logs args to input device -// -Loggly.prototype.log = function (inputId, msg, callback) { - var emitter = new (events.EventEmitter)(), - message; - - if (msg instanceof Object) { - message = this.config.json ? JSON.stringify(msg) : common.serialize(msg); - } - else { - message = this.config.json ? JSON.stringify({ message : msg }) : msg; - } - - var logOptions = { - uri: this.config.inputUrl + inputId, - method: 'POST', - body: message, - headers: { - 'Content-Type': this.config.json ? 'application/json' : 'text/plain' - } - }; - - common.loggly(logOptions, callback, function (res, body) { - try { - var result = JSON.parse(body); - if (callback) { - callback(null, result); - } - - emitter.emit('log', result); - } - catch (ex) { - if (callback) { - callback(new Error('Unspecified error from Loggly: ' + ex)); - } - } - }); - - return emitter; -}; - -// -// function search (query, callback) -// Returns a new search object which can be chained -// with options or called directly if @callback is passed -// initially. -// -// Sample Usage: -// -// client.search('404') -// .meta({ ip: '127.0.0.1' }) -// .context({ rows: 100 }) -// .run(function () { /* ... */ }); -// -Loggly.prototype.search = function (query, callback) { - return new Search(query, this, callback); -}; - -// -// function facet (facet, query, [options], callback) -// Performs a facet search against loggly with the -// specified facet, query and options. -// -Loggly.prototype.facet = function (facet, query, callback) { - return new Facet(facet, query, this, callback); -}; - - -// -// function getInputs ([raw], callback) -// Returns a list of all inputs for the authenicated account -// -Loggly.prototype.getInputs = function () { - var self = this, - args = Array.prototype.slice.call(arguments), - callback = args.pop(), - raw = args.length > 0 ? args[0] : false; - - common.loggly(this.logglyUrl('inputs'), this.config.auth, callback, function (res, body) { - var inputs = [], - results = JSON.parse(body); - - if (!raw) { - results.forEach(function (result) { - inputs.push(new (loggly.Input)(self, result)); - }); - - return callback(null, inputs); - } - - callback(null, results); - }); -}; - -// -// function getInput (name, callback) -// Returns the input with the specified name -// -Loggly.prototype.getInput = function (name, callback) { - var self = this; - this.getInputs(true, function (err, results) { - if (err) { - return callback(err); - } - - var matches = results.filter(function (r) { return r.name === name }), - input = null; - - if (matches.length > 0) { - input = new (loggly.Input)(self, matches[0]); - } - - callback(null, input); - }); -}; - -// -// function addDevice (inputId, address, callback) -// Adds the device at address to the input specified by inputId -// -Loggly.prototype.addDeviceToInput = function (inputId, address, callback) { - var addOptions = { - uri: this.logglyUrl('devices'), - auth: this.config.auth, - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded' - }, - body: qs.stringify({ 'input_id': inputId, 'ip': address }).replace('"', '') - }; - - common.loggly(addOptions, callback, function (res, body) { - callback(null, res); - }); -}; - -// -// function addDevice (inputId, callback) -// Adds the calling device to the input -// -Loggly.prototype.addDevice = function (inputId, callback) { - // - // Remark: This is not fully implemented yet - // - callback(new Error('Not Implemented Yet...')); - - //common.loggly(this.logglyUrl('inputs', inputId, 'adddevice'), this.config.auth, callback, function (res, body) { - //}); -}; - -// -// function getDevices (callback) -// Returns a list of all devices for the authenicated account -// -Loggly.prototype.getDevices = function (callback) { - var self = this; - common.loggly(this.logglyUrl('devices'), this.config.auth, callback, function (res, body) { - var results = JSON.parse(body), - devices = []; - - results.forEach(function (result) { - devices.push(new (loggly.Device)(self, result)); - }); - - callback(null, devices); - }); -}; - -// -// function logglyUrl ([path, to, resource]) -// Helper method that concats the string params into a url -// to request against a loggly serverUrl. -// -Loggly.prototype.logglyUrl = function (/* path, to, resource */) { - var args = Array.prototype.slice.call(arguments); - return [this.config.logglyUrl].concat(args).join('/'); -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/device.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/device.js deleted file mode 100644 index a06d74ac4..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/device.js +++ /dev/null @@ -1,30 +0,0 @@ -/* - * device.js: Instance of a single Loggly device - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var Device = exports.Device = function (client, details) { - if (!details) throw new Error("Device must be constructed with at least basic details.") - - this.client = client; - this._setProperties(details); -}; - -Device.prototype.addToInput = function (inputId, callback) { - this.client.addDeviceToInput(inputId, this.id, callback); -}; - -// -// Sets the properties for this instance -// Parameters: details -// -Device.prototype._setProperties = function (details) { - // Copy the properties to this instance - var self = this; - Object.keys(details).forEach(function (key) { - self[key] = details[key]; - }); -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/facet.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/facet.js deleted file mode 100644 index a17abf964..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/facet.js +++ /dev/null @@ -1,42 +0,0 @@ -/* - * facet.js: Chainable search functions for Loggly facet searches. - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var util = require('util'), - Search = require('./search').Search; - -// -// function Facet (facet, query, client, callback) -// Chainable facet search object for Loggly API -// -var Facet = exports.Facet = function (facet, query, client, callback) { - if (['date', 'ip', 'input'].indexOf(facet) === -1) { - var error = new Error('Cannot search with unknown facet: ' + facet); - - if (callback) { - return callback(error); - } - else { - throw error; - } - } - - // - // Set the baseUrl to be facet/:facet? - // - this.baseUrl = ['facets', facet + '?'].join('/'); - - // - // Call the base constructor. - // - Search.call(this, query, client, callback); -}; - -// -// Inherit from `loggly.Search`. -// -util.inherits(Facet, Search); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/input.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/input.js deleted file mode 100644 index 1e02b8596..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/input.js +++ /dev/null @@ -1,36 +0,0 @@ -/* - * input.js: Instance of a single Loggly input - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var Input = exports.Input = function (client, details) { - if (!details) { - throw new Error("Input must be constructed with at least basic details."); - } - - this.client = client; - this._setProperties(details); -}; - -Input.prototype.log = function (msg, callback) { - return this.client.log(this.input_token, msg, callback); -}; - -Input.prototype.addDevice = function (address, callback) { - this.client.addDeviceToInput(this.id, address, callback); -}; - -// -// Sets the properties for this instance -// Parameters: details -// -Input.prototype._setProperties = function (details) { - // Copy the properties to this instance - var self = this; - Object.keys(details).forEach(function (key) { - self[key] = details[key]; - }); -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/search.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/search.js deleted file mode 100644 index 09dd437fd..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/lib/loggly/search.js +++ /dev/null @@ -1,130 +0,0 @@ -/* - * search.js: chainable search functions for Loggly - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var qs = require('querystring'), - timespan = require('timespan'), - common = require('./common'); - -// -// function Search (query, client, callback) -// Chainable search object for Loggly API -// -var Search = exports.Search = function (query, client, callback) { - this.query = query; - this.client = client; - - if (!this.baseUrl) { - this.baseUrl = 'search?'; - } - - // - // If we're passed a callback, run immediately. - // - if (callback) { - this.callback = callback; - this.run(); - } -}; - -// -// function meta (meta) -// Sets the appropriate metadata for this search query: -// e.g. ip, inputname -// -Search.prototype.meta = function (meta) { - this._meta = meta; - return this; -}; - -// -// function context (context) -// Sets the appropriate context for this search query: -// e.g. rows, start, from, until, order, format, fields -// -Search.prototype.context = function (context) { - this._context = context; - return this; -}; - -// -// ### function run (callback) -// #### @callback {function} Continuation to respond to when complete -// Runs the search query for for this instance with the query, metadata, -// context, and other parameters that have been configured on it. -// -Search.prototype.run = function (callback) { - var rangeError; - - // - // Trim the search query - // - this.query.trim(); - - // - // Update the callback for this instance if it's passed - // - this.callback = callback || this.callback; - if (!this.callback) { - throw new Error('Cannot run search without a callback function.'); - } - - // If meta was passed, update the search query appropriately - if (this._meta) { - this.query += ' ' + qs.unescape(qs.stringify(this._meta, ' ', ':')); - } - - // Set the context for the query string - this._context = this._context || {}; - this._context.q = this.query; - this._checkRange(); - - var self = this, searchOptions = { - uri: this.client.logglyUrl(this.baseUrl + qs.stringify(this._context)), - auth: this.client.config.auth - }; - - common.loggly(searchOptions, this.callback, function (res, body) { - self.callback(null, JSON.parse(body)); - }); - - return this; -}; - -// -// ### function _checkRange () -// Checks if the range that has been configured for this -// instance is valid and updates if it is not. -// -Search.prototype._checkRange = function () { - if (!this._context || (!this._context.until && !this._context.from)) { - return; - } - - this._context.until = this._context.until || 'NOW'; - this._context.from = this._context.from || 'NOW-24HOURS'; - - if (!timespan.parseDate(this._context.until)) { - this._context.until = 'NOW'; - } - - if (!timespan.parseDate(this._context.from)) { - this._context.from = 'NOW-24HOURS'; - } - - if (timespan.fromDates(this._context.from, this._context.until) < 0 - || this._context.until === this._context.from) { - // - // If the length of the timespan for this Search instance is - // negative then set it to default values - // - this._context.until = 'NOW'; - this._context.from = 'NOW-24HOURS'; - } - - return this; -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/README.md b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/README.md deleted file mode 100644 index 8713a807c..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/README.md +++ /dev/null @@ -1,287 +0,0 @@ -# Request -- Simplified HTTP request method - -## Install - -
        -  npm install request
        -
        - -Or from source: - -
        -  git clone git://github.com/mikeal/request.git 
        -  cd request
        -  npm link
        -
        - -## Super simple to use - -Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default. - -```javascript -var request = require('request'); -request('http://www.google.com', function (error, response, body) { - if (!error && response.statusCode == 200) { - console.log(body) // Print the google web page. - } -}) -``` - -## Streaming - -You can stream any response to a file stream. - -```javascript -request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')) -``` - -You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types, in this case `application/json`, and use the proper content-type in the PUT request if one is not already provided in the headers. - -```javascript -fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json')) -``` - -Request can also pipe to itself. When doing so the content-type and content-length will be preserved in the PUT headers. - -```javascript -request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png')) -``` - -Now let's get fancy. - -```javascript -http.createServer(function (req, resp) { - if (req.url === '/doodle.png') { - if (req.method === 'PUT') { - req.pipe(request.put('http://mysite.com/doodle.png')) - } else if (req.method === 'GET' || req.method === 'HEAD') { - request.get('http://mysite.com/doodle.png').pipe(resp) - } - } -}) -``` - -You can also pipe() from a http.ServerRequest instance and to a http.ServerResponse instance. The HTTP method and headers will be sent as well as the entity-body data. Which means that, if you don't really care about security, you can do: - -```javascript -http.createServer(function (req, resp) { - if (req.url === '/doodle.png') { - var x = request('http://mysite.com/doodle.png') - req.pipe(x) - x.pipe(resp) - } -}) -``` - -And since pipe() returns the destination stream in node 0.5.x you can do one line proxying :) - -```javascript -req.pipe(request('http://mysite.com/doodle.png')).pipe(resp) -``` - -Also, none of this new functionality conflicts with requests previous features, it just expands them. - -```javascript -var r = request.defaults({'proxy':'http://localproxy.com'}) - -http.createServer(function (req, resp) { - if (req.url === '/doodle.png') { - r.get('http://google.com/doodle.png').pipe(resp) - } -}) -``` - -You can still use intermediate proxies, the requests will still follow HTTP forwards, etc. - -## OAuth Signing - -```javascript -// Twitter OAuth -var qs = require('querystring') - , oauth = - { callback: 'http://mysite.com/callback/' - , consumer_key: CONSUMER_KEY - , consumer_secret: CONSUMER_SECRET - } - , url = 'https://api.twitter.com/oauth/request_token' - ; -request.post({url:url, oauth:oauth}, function (e, r, body) { - // Assume by some stretch of magic you aquired the verifier - var access_token = qs.parse(body) - , oauth = - { consumer_key: CONSUMER_KEY - , consumer_secret: CONSUMER_SECRET - , token: access_token.oauth_token - , verifier: VERIFIER - , token_secret: access_token.oauth_token_secret - } - , url = 'https://api.twitter.com/oauth/access_token' - ; - request.post({url:url, oauth:oauth}, function (e, r, body) { - var perm_token = qs.parse(body) - , oauth = - { consumer_key: CONSUMER_KEY - , consumer_secret: CONSUMER_SECRET - , token: perm_token.oauth_token - , token_secret: perm_token.oauth_token_secret - } - , url = 'https://api.twitter.com/1/users/show.json?' - , params = - { screen_name: perm_token.screen_name - , user_id: perm_token.user_id - } - ; - url += qs.stringify(params) - request.get({url:url, oauth:oauth, json:true}, function (e, r, user) { - console.log(user) - }) - }) -}) -``` - - - -### request(options, callback) - -The first argument can be either a url or an options object. The only required option is uri, all others are optional. - -* `uri` || `url` - fully qualified uri or a parsed url object from url.parse() -* `qs` - object containing querystring values to be appended to the uri -* `method` - http method, defaults to GET -* `headers` - http headers, defaults to {} -* `body` - entity body for POST and PUT requests. Must be buffer or string. -* `form` - sets `body` but to querystring representation of value and adds `Content-type: application/x-www-form-urlencoded; charset=utf-8` header. -* `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header. -* `multipart` - (experimental) array of objects which contains their own headers and `body` attribute. Sends `multipart/related` request. See example below. -* `followRedirect` - follow HTTP 3xx responses as redirects. defaults to true. -* `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects. defaults to false. -* `maxRedirects` - the maximum number of redirects to follow, defaults to 10. -* `encoding` - Encoding to be used on `setEncoding` of response data. If set to `null`, the body is returned as a Buffer. -* `pool` - A hash object containing the agents for these requests. If omitted this request will use the global pool which is set to node's default maxSockets. -* `pool.maxSockets` - Integer containing the maximum amount of sockets in the pool. -* `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request -* `proxy` - An HTTP proxy to be used. Support proxy Auth with Basic Auth the same way it's supported with the `url` parameter by embedding the auth info in the uri. -* `oauth` - Options for OAuth HMAC-SHA1 signing, see documentation above. -* `strictSSL` - Set to `true` to require that SSL certificates be valid. Note: to use your own certificate authority, you need to specify an agent that was created with that ca as an option. -* `jar` - Set to `false` if you don't want cookies to be remembered for future use or define your custom cookie jar (see examples section) - - -The callback argument gets 3 arguments. The first is an error when applicable (usually from the http.Client option not the http.ClientRequest object). The second in an http.ClientResponse object. The third is the response body String or Buffer. - -## Convenience methods - -There are also shorthand methods for different HTTP METHODs and some other conveniences. - -### request.defaults(options) - -This method returns a wrapper around the normal request API that defaults to whatever options you pass in to it. - -### request.put - -Same as request() but defaults to `method: "PUT"`. - -```javascript -request.put(url) -``` - -### request.post - -Same as request() but defaults to `method: "POST"`. - -```javascript -request.post(url) -``` - -### request.head - -Same as request() but defaults to `method: "HEAD"`. - -```javascript -request.head(url) -``` - -### request.del - -Same as request() but defaults to `method: "DELETE"`. - -```javascript -request.del(url) -``` - -### request.get - -Alias to normal request method for uniformity. - -```javascript -request.get(url) -``` -### request.cookie - -Function that creates a new cookie. - -```javascript -request.cookie('cookie_string_here') -``` -### request.jar - -Function that creates a new cookie jar. - -```javascript -request.jar() -``` - - -## Examples: - -```javascript - var request = require('request') - , rand = Math.floor(Math.random()*100000000).toString() - ; - request( - { method: 'PUT' - , uri: 'http://mikeal.iriscouch.com/testjs/' + rand - , multipart: - [ { 'content-type': 'application/json' - , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) - } - , { body: 'I am an attachment' } - ] - } - , function (error, response, body) { - if(response.statusCode == 201){ - console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand) - } else { - console.log('error: '+ response.statusCode) - console.log(body) - } - } - ) -``` -Cookies are enabled by default (so they can be used in subsequent requests). To disable cookies set jar to false (either in defaults or in the options sent). - -```javascript -var request = request.defaults({jar: false}) -request('http://www.google.com', function () { - request('http://images.google.com') -}) -``` - -If you to use a custom cookie jar (instead of letting request use its own global cookie jar) you do so by setting the jar default or by specifying it as an option: - -```javascript -var j = request.jar() -var request = request.defaults({jar:j}) -request('http://www.google.com', function () { - request('http://images.google.com') -}) -``` -OR - -```javascript -var j = request.jar() -var cookie = request.cookie('your_cookie_here') -j.add(cookie) -request({url: 'http://www.google.com', jar: j}, function () { - request('http://images.google.com') -}) -``` diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/aws2.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/aws2.js deleted file mode 100644 index eb683f765..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/aws2.js +++ /dev/null @@ -1,128 +0,0 @@ -var crypto = require('crypto') - -// The Authentication Header -// -// The Amazon S3 REST API uses the standard HTTPAuthorization header to pass authentication information. (The name of the standard header is unfortunate because it carries authentication information, not authorization).Under the Amazon S3 authentication scheme, the Authorization header has the following form. -// -// Authorization: AWS AWSAccessKeyId:Signature -// -// Developers are issued an AWS Access Key ID and AWS SecretAccess Key when they register. For request authentication, theAWSAccessKeyId element identifies the secret key that was used to compute the signature, and (indirectly) the developer making the request. -// -// The Signature element is the RFC 2104HMAC-SHA1 of selected elements from the request, and so theSignature part of the Authorization header will vary from request to request. If the request signature calculated by the system matches theSignature included with the request, then the requester will have demonstrated possession to the AWSSecret Access Key. The request will then be processed under the identity, and with the authority, of the developer to whom the key was issued. -// -// Following is pseudo-grammar that illustrates the construction of the Authorization request header (\nmeans the Unicode code point U+000A commonly called newline). - -function authorizationHeader (accessKey) { - // Authorization = "AWS" + " " + AWSAccessKeyId + ":" + Signature; - - var authorization = 'AWS' + " " + accessKey + ":" + signature() - - return authorization -} - -// - -function signature (secret, verb, md5, contenttype, date, amzheaders, bucket, path) { - // Signature = Base64( HMAC-SHA1( UTF-8-Encoding-Of( YourSecretAccessKeyID, StringToSign ) ) ); - - function encodeSignature (stringToSign) { - return crypto.createHash('sha1').update(stringToSign).digest('base64') - } - - // - // StringToSign = HTTP-Verb + "\n" + - // Content-MD5 + "\n" + - // Content-Type + "\n" + - // Date + "\n" + - // CanonicalizedAmzHeaders + - // CanonicalizedResource; - - function compileStringToSign () { - var s = - verb + '\n' - (md5 || '') + '\n' - (contenttype || '') + '\n' - date.toUTCString() + '\n' - canonicalizeAmzHeaders(amzheaders) + - canonicalizeResource() - return s - } - - // - // CanonicalizedResource = [ "/" + Bucket ] + - // + - // [ sub-resource, if present. For example "?acl", "?location", "?logging", or "?torrent"]; - - function canonicalizeResource () { - return '/' + bucket + path - } - - // - // CanonicalizedAmzHeaders = - // - // HMAC-SHA1 is an algorithm defined by RFC 2104 (go to RFC 2104 - Keyed-Hashing for Message Authentication ). The algorithm takes as input two byte-strings: a key and a message. For Amazon S3 Request authentication, use your AWS Secret Access Key (YourSecretAccessKeyID) as the key, and the UTF-8 encoding of the StringToSign as the message. The output of HMAC-SHA1 is also a byte string, called the digest. The Signature request parameter is constructed by Base64 encoding this digest. - // Request Canonicalization for Signing - // - // Recall that when the system receives an authenticated request, it compares the computed request signature with the signature provided in the request in StringToSign. For that reason, you must compute the signature using the same method used by Amazon S3. We call the process of putting a request in an agreed-upon form for signing "canonicalization". - -} - - - -// Constructing the CanonicalizedResource Element -// -// CanonicalizedResource represents the Amazon S3 resource targeted by the request. Construct it for a REST request as follows: -// -// Launch Process -// -// 1 -// -// -// Start with the empty string (""). -// -// 2 -// -// -// If the request specifies a bucket using the HTTP Host header (virtual hosted-style), append the bucket name preceded by a "/" (e.g., "/bucketname"). For path-style requests and requests that don't address a bucket, do nothing. For more information on virtual hosted-style requests, see Virtual Hosting of Buckets. -// -// 3 -// -// -// Append the path part of the un-decoded HTTP Request-URI, up-to but not including the query string. -// -// 4 -// -// -// If the request addresses a sub-resource, like ?versioning, ?location, ?acl, ?torrent, ?lifecycle, or ?versionid append the sub-resource, its value if it has one, and the question mark. Note that in case of multiple sub-resources, sub-resources must be lexicographically sorted by sub-resource name and separated by '&'. e.g. ?acl&versionId=value. -// -// The list of sub-resources that must be included when constructing the CanonicalizedResource Element are: acl, lifecycle, location, logging, notification, partNumber, policy, requestPayment, torrent, uploadId, uploads, versionId, versioning, versions and website. -// -// If the request specifies query string parameters overriding the response header values (see Get Object), append the query string parameters, and its values. When signing you do not encode these values. However, when making the request, you must encode these parameter values. The query string parameters in a GET request include response-content-type, response-content-language, response-expires, response-cache-control, response-content-disposition, response-content-encoding. -// -// The delete query string parameter must be including when creating the CanonicalizedResource for a Multi-Object Delete request. -// -// Elements of the CanonicalizedResource that come from the HTTP Request-URI should be signed literally as they appear in the HTTP request, including URL-Encoding meta characters. -// -// The CanonicalizedResource might be different than the HTTP Request-URI. In particular, if your request uses the HTTP Host header to specify a bucket, the bucket does appear in the HTTP Request-URI. However, the CanonicalizedResource continues to include the bucket. Query string parameters might also appear in the Request-URI but are not included in CanonicalizedResource. For more information, see Virtual Hosting of Buckets. -// Constructing the CanonicalizedAmzHeaders Element -// -// To construct the CanonicalizedAmzHeaders part of StringToSign, select all HTTP request headers that start with 'x-amz-' (using a case-insensitive comparison) and use the following process. -// -// CanonicalizedAmzHeaders Process -// 1 Convert each HTTP header name to lower-case. For example, 'X-Amz-Date' becomes 'x-amz-date'. -// 2 Sort the collection of headers lexicographically by header name. -// 3 Combine header fields with the same name into one "header-name:comma-separated-value-list" pair as prescribed by RFC 2616, section 4.2, without any white-space between values. For example, the two metadata headers 'x-amz-meta-username: fred' and 'x-amz-meta-username: barney' would be combined into the single header 'x-amz-meta-username: fred,barney'. -// 4 "Unfold" long headers that span multiple lines (as allowed by RFC 2616, section 4.2) by replacing the folding white-space (including new-line) by a single space. -// 5 Trim any white-space around the colon in the header. For example, the header 'x-amz-meta-username: fred,barney' would become 'x-amz-meta-username:fred,barney' -// 6 Finally, append a new-line (U+000A) to each canonicalized header in the resulting list. Construct the CanonicalizedResource element by concatenating all headers in this list into a single string. -// -// Positional versus Named HTTP Header StringToSign Elements -// -// The first few header elements of StringToSign (Content-Type, Date, and Content-MD5) are positional in nature. StringToSign does not include the names of these headers, only their values from the request. In contrast, the 'x-amz-' elements are named; Both the header names and the header values appear in StringToSign. -// -// If a positional header called for in the definition of StringToSign is not present in your request, (Content-Type or Content-MD5, for example, are optional for PUT requests, and meaningless for GET requests), substitute the empty string ("") in for that position. -// Time Stamp Requirement -// -// A valid time stamp (using either the HTTP Date header or an x-amz-date alternative) is mandatory for authenticated requests. Furthermore, the client time-stamp included with an authenticated request must be within 15 minutes of the Amazon S3 system time when the request is received. If not, the request will fail with the RequestTimeTooSkewed error status code. The intention of these restrictions is to limit the possibility that intercepted requests could be replayed by an adversary. For stronger protection against eavesdropping, use the HTTPS transport for authenticated requests. -// -// Some HTTP client libraries do not expose the ability to set the Date header for a request. If you have trouble including the value of the 'Date' header in the canonicalized headers, you can set the time-stamp for the request using an 'x-amz-date' header instead. The value of the x-amz-date header must be in one of the RFC 2616 formats (http://www.ietf.org/rfc/rfc2616.txt). When an x-amz-date header is present in a request, the system will ignore any Date header when computing the request signature. Therefore, if you include the x-amz-date header, use the empty string for the Date when constructing the StringToSign. See the next section for an example. diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/main.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/main.js deleted file mode 100644 index 2407a9349..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/main.js +++ /dev/null @@ -1,974 +0,0 @@ -// Copyright 2010-2012 Mikeal Rogers -// -// 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. - -var http = require('http') - , https = false - , tls = false - , url = require('url') - , util = require('util') - , stream = require('stream') - , qs = require('querystring') - , mimetypes = require('./mimetypes') - , oauth = require('./oauth') - , uuid = require('./uuid') - , ForeverAgent = require('./forever') - , Cookie = require('./vendor/cookie') - , CookieJar = require('./vendor/cookie/jar') - , cookieJar = new CookieJar - , tunnel = require('./tunnel') - , aws = require('./aws') - ; - -if (process.logging) { - var log = process.logging('request') -} - -try { - https = require('https') -} catch (e) {} - -try { - tls = require('tls') -} catch (e) {} - -function toBase64 (str) { - return (new Buffer(str || "", "ascii")).toString("base64") -} - -// Hacky fix for pre-0.4.4 https -if (https && !https.Agent) { - https.Agent = function (options) { - http.Agent.call(this, options) - } - util.inherits(https.Agent, http.Agent) - https.Agent.prototype._getConnection = function (host, port, cb) { - var s = tls.connect(port, host, this.options, function () { - // do other checks here? - if (cb) cb() - }) - return s - } -} - -function isReadStream (rs) { - if (rs.readable && rs.path && rs.mode) { - return true - } -} - -function copy (obj) { - var o = {} - Object.keys(obj).forEach(function (i) { - o[i] = obj[i] - }) - return o -} - -var isUrl = /^https?:/ - -var globalPool = {} - -function Request (options) { - stream.Stream.call(this) - this.readable = true - this.writable = true - - if (typeof options === 'string') { - options = {uri:options} - } - - var reserved = Object.keys(Request.prototype) - for (var i in options) { - if (reserved.indexOf(i) === -1) { - this[i] = options[i] - } else { - if (typeof options[i] === 'function') { - delete options[i] - } - } - } - options = copy(options) - - this.init(options) -} -util.inherits(Request, stream.Stream) -Request.prototype.init = function (options) { - var self = this - - if (!options) options = {} - - if (!self.pool && self.pool !== false) self.pool = globalPool - self.dests = [] - self.__isRequestRequest = true - - // Protect against double callback - if (!self._callback && self.callback) { - self._callback = self.callback - self.callback = function () { - if (self._callbackCalled) return // Print a warning maybe? - self._callback.apply(self, arguments) - self._callbackCalled = true - } - self.on('error', self.callback.bind()) - self.on('complete', self.callback.bind(self, null)) - } - - if (self.url) { - // People use this property instead all the time so why not just support it. - self.uri = self.url - delete self.url - } - - if (!self.uri) { - throw new Error("options.uri is a required argument") - } else { - if (typeof self.uri == "string") self.uri = url.parse(self.uri) - } - if (self.proxy) { - if (typeof self.proxy == 'string') self.proxy = url.parse(self.proxy) - - // do the HTTP CONNECT dance using koichik/node-tunnel - if (http.globalAgent && self.uri.protocol === "https:") { - self.tunnel = true - var tunnelFn = self.proxy.protocol === "http:" - ? tunnel.httpsOverHttp : tunnel.httpsOverHttps - - var tunnelOptions = { proxy: { host: self.proxy.hostname - , port: +self.proxy.port - , proxyAuth: self.proxy.auth } - , ca: this.ca } - - self.agent = tunnelFn(tunnelOptions) - self.tunnel = true - } - } - - if (!self.uri.host || !self.uri.pathname) { - // Invalid URI: it may generate lot of bad errors, like "TypeError: Cannot call method 'indexOf' of undefined" in CookieJar - // Detect and reject it as soon as possible - var faultyUri = url.format(self.uri) - var message = 'Invalid URI "' + faultyUri + '"' - if (Object.keys(options).length === 0) { - // No option ? This can be the sign of a redirect - // As this is a case where the user cannot do anything (he didn't call request directly with this URL) - // he should be warned that it can be caused by a redirection (can save some hair) - message += '. This can be caused by a crappy redirection.' - } - self.emit('error', new Error(message)) - return // This error was fatal - } - - self._redirectsFollowed = self._redirectsFollowed || 0 - self.maxRedirects = (self.maxRedirects !== undefined) ? self.maxRedirects : 10 - self.followRedirect = (self.followRedirect !== undefined) ? self.followRedirect : true - self.followAllRedirects = (self.followAllRedirects !== undefined) ? self.followAllRedirects : false; - if (self.followRedirect || self.followAllRedirects) - self.redirects = self.redirects || [] - - self.headers = self.headers ? copy(self.headers) : {} - - self.setHost = false - if (!self.headers.host) { - self.headers.host = self.uri.hostname - if (self.uri.port) { - if ( !(self.uri.port === 80 && self.uri.protocol === 'http:') && - !(self.uri.port === 443 && self.uri.protocol === 'https:') ) - self.headers.host += (':'+self.uri.port) - } - self.setHost = true - } - - self.jar(self._jar || options.jar) - - if (!self.uri.pathname) {self.uri.pathname = '/'} - if (!self.uri.port) { - if (self.uri.protocol == 'http:') {self.uri.port = 80} - else if (self.uri.protocol == 'https:') {self.uri.port = 443} - } - - if (self.proxy && !self.tunnel) { - self.port = self.proxy.port - self.host = self.proxy.hostname - } else { - self.port = self.uri.port - self.host = self.uri.hostname - } - - self.clientErrorHandler = function (error) { - if (self._aborted) return - - if (self.setHost) delete self.headers.host - if (self.req._reusedSocket && error.code === 'ECONNRESET' - && self.agent.addRequestNoreuse) { - self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) } - self.start() - self.req.end() - return - } - if (self.timeout && self.timeoutTimer) { - clearTimeout(self.timeoutTimer) - self.timeoutTimer = null - } - self.emit('error', error) - } - - if (options.form) { - self.form(options.form) - } - - if (options.oauth) { - self.oauth(options.oauth) - } - - if (options.aws) { - self.aws(options.aws) - } - - if (self.uri.auth && !self.headers.authorization) { - self.headers.authorization = "Basic " + toBase64(self.uri.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':')) - } - if (self.proxy && self.proxy.auth && !self.headers['proxy-authorization'] && !self.tunnel) { - self.headers['proxy-authorization'] = "Basic " + toBase64(self.proxy.auth.split(':').map(function(item){ return qs.unescape(item)}).join(':')) - } - - if (options.qs) self.qs(options.qs) - - if (self.uri.path) { - self.path = self.uri.path - } else { - self.path = self.uri.pathname + (self.uri.search || "") - } - - if (self.path.length === 0) self.path = '/' - - if (self.proxy && !self.tunnel) self.path = (self.uri.protocol + '//' + self.uri.host + self.path) - - if (options.json) { - self.json(options.json) - } else if (options.multipart) { - self.boundary = uuid() - self.multipart(options.multipart) - } - - if (self.body) { - var length = 0 - if (!Buffer.isBuffer(self.body)) { - if (Array.isArray(self.body)) { - for (var i = 0; i < self.body.length; i++) { - length += self.body[i].length - } - } else { - self.body = new Buffer(self.body) - length = self.body.length - } - } else { - length = self.body.length - } - if (length) { - self.headers['content-length'] = length - } else { - throw new Error('Argument error, options.body.') - } - } - - var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol - , defaultModules = {'http:':http, 'https:':https} - , httpModules = self.httpModules || {} - ; - self.httpModule = httpModules[protocol] || defaultModules[protocol] - - if (!self.httpModule) throw new Error("Invalid protocol") - - if (options.ca) self.ca = options.ca - - if (!self.agent) { - if (options.agentOptions) self.agentOptions = options.agentOptions - - if (options.agentClass) { - self.agentClass = options.agentClass - } else if (options.forever) { - self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL - } else { - self.agentClass = self.httpModule.Agent - } - } - - if (self.pool === false) { - self.agent = false - } else { - self.agent = self.agent || self.getAgent() - if (self.maxSockets) { - // Don't use our pooling if node has the refactored client - self.agent.maxSockets = self.maxSockets - } - if (self.pool.maxSockets) { - // Don't use our pooling if node has the refactored client - self.agent.maxSockets = self.pool.maxSockets - } - } - - self.once('pipe', function (src) { - if (self.ntick) throw new Error("You cannot pipe to this stream after the first nextTick() after creation of the request stream.") - self.src = src - if (isReadStream(src)) { - if (!self.headers['content-type'] && !self.headers['Content-Type']) - self.headers['content-type'] = mimetypes.lookup(src.path.slice(src.path.lastIndexOf('.')+1)) - } else { - if (src.headers) { - for (var i in src.headers) { - if (!self.headers[i]) { - self.headers[i] = src.headers[i] - } - } - } - if (src.method && !self.method) { - self.method = src.method - } - } - - self.on('pipe', function () { - console.error("You have already piped to this stream. Pipeing twice is likely to break the request.") - }) - }) - - process.nextTick(function () { - if (self._aborted) return - - if (self.body) { - if (Array.isArray(self.body)) { - self.body.forEach(function (part) { - self.write(part) - }) - } else { - self.write(self.body) - } - self.end() - } else if (self.requestBodyStream) { - console.warn("options.requestBodyStream is deprecated, please pass the request object to stream.pipe.") - self.requestBodyStream.pipe(self) - } else if (!self.src) { - if (self.method !== 'GET' && typeof self.method !== 'undefined') { - self.headers['content-length'] = 0; - } - self.end(); - } - self.ntick = true - }) -} - -Request.prototype.getAgent = function () { - var Agent = this.agentClass - var options = {} - if (this.agentOptions) { - for (var i in this.agentOptions) { - options[i] = this.agentOptions[i] - } - } - if (this.ca) options.ca = this.ca - - var poolKey = '' - - // different types of agents are in different pools - if (Agent !== this.httpModule.Agent) { - poolKey += Agent.name - } - - if (!this.httpModule.globalAgent) { - // node 0.4.x - options.host = this.host - options.port = this.port - if (poolKey) poolKey += ':' - poolKey += this.host + ':' + this.port - } - - if (options.ca) { - if (poolKey) poolKey += ':' - poolKey += options.ca - } - - if (!poolKey && Agent === this.httpModule.Agent && this.httpModule.globalAgent) { - // not doing anything special. Use the globalAgent - return this.httpModule.globalAgent - } - - // already generated an agent for this setting - if (this.pool[poolKey]) return this.pool[poolKey] - - return this.pool[poolKey] = new Agent(options) -} - -Request.prototype.start = function () { - var self = this - - if (self._aborted) return - - self._started = true - self.method = self.method || 'GET' - self.href = self.uri.href - if (log) log('%method %href', self) - - if (self.src && self.src.stat && self.src.stat.size) { - self.headers['content-length'] = self.src.stat.size - } - if (self._aws) { - self.aws(self._aws, true) - } - - self.req = self.httpModule.request(self, function (response) { - if (self._aborted) return - if (self._paused) response.pause() - - self.response = response - response.request = self - response.toJSON = toJSON - - if (self.httpModule === https && - self.strictSSL && - !response.client.authorized) { - var sslErr = response.client.authorizationError - self.emit('error', new Error('SSL Error: '+ sslErr)) - return - } - - if (self.setHost) delete self.headers.host - if (self.timeout && self.timeoutTimer) { - clearTimeout(self.timeoutTimer) - self.timeoutTimer = null - } - - var addCookie = function (cookie) { - if (self._jar) self._jar.add(new Cookie(cookie)) - else cookieJar.add(new Cookie(cookie)) - } - - if (response.headers['set-cookie'] && (!self._disableCookies)) { - if (Array.isArray(response.headers['set-cookie'])) response.headers['set-cookie'].forEach(addCookie) - else addCookie(response.headers['set-cookie']) - } - - if (response.statusCode >= 300 && response.statusCode < 400 && - (self.followAllRedirects || - (self.followRedirect && (self.method !== 'PUT' && self.method !== 'POST' && self.method !== 'DELETE'))) && - response.headers.location) { - if (self._redirectsFollowed >= self.maxRedirects) { - self.emit('error', new Error("Exceeded maxRedirects. Probably stuck in a redirect loop.")) - return - } - self._redirectsFollowed += 1 - - if (!isUrl.test(response.headers.location)) { - response.headers.location = url.resolve(self.uri.href, response.headers.location) - } - self.uri = response.headers.location - self.redirects.push( - { statusCode : response.statusCode - , redirectUri: response.headers.location - } - ) - if (self.followAllRedirects) self.method = 'GET' - // self.method = 'GET'; // Force all redirects to use GET || commented out fixes #215 - delete self.req - delete self.agent - delete self._started - delete self.body - if (self.headers) { - delete self.headers.host - } - if (log) log('Redirect to %uri', self) - self.init() - return // Ignore the rest of the response - } else { - self._redirectsFollowed = self._redirectsFollowed || 0 - // Be a good stream and emit end when the response is finished. - // Hack to emit end on close because of a core bug that never fires end - response.on('close', function () { - if (!self._ended) self.response.emit('end') - }) - - if (self.encoding) { - if (self.dests.length !== 0) { - console.error("Ingoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.") - } else { - response.setEncoding(self.encoding) - } - } - - self.dests.forEach(function (dest) { - self.pipeDest(dest) - }) - - response.on("data", function (chunk) { - self._destdata = true - self.emit("data", chunk) - }) - response.on("end", function (chunk) { - self._ended = true - self.emit("end", chunk) - }) - response.on("close", function () {self.emit("close")}) - - self.emit('response', response) - - if (self.callback) { - var buffer = [] - var bodyLen = 0 - self.on("data", function (chunk) { - buffer.push(chunk) - bodyLen += chunk.length - }) - self.on("end", function () { - if (self._aborted) return - - if (buffer.length && Buffer.isBuffer(buffer[0])) { - var body = new Buffer(bodyLen) - var i = 0 - buffer.forEach(function (chunk) { - chunk.copy(body, i, 0, chunk.length) - i += chunk.length - }) - if (self.encoding === null) { - response.body = body - } else { - response.body = body.toString() - } - } else if (buffer.length) { - response.body = buffer.join('') - } - - if (self._json) { - try { - response.body = JSON.parse(response.body) - } catch (e) {} - } - - self.emit('complete', response, response.body) - }) - } - } - }) - - if (self.timeout && !self.timeoutTimer) { - self.timeoutTimer = setTimeout(function () { - self.req.abort() - var e = new Error("ETIMEDOUT") - e.code = "ETIMEDOUT" - self.emit("error", e) - }, self.timeout) - - // Set additional timeout on socket - in case if remote - // server freeze after sending headers - if (self.req.setTimeout) { // only works on node 0.6+ - self.req.setTimeout(self.timeout, function () { - if (self.req) { - self.req.abort() - var e = new Error("ESOCKETTIMEDOUT") - e.code = "ESOCKETTIMEDOUT" - self.emit("error", e) - } - }) - } - } - - self.req.on('error', self.clientErrorHandler) - self.req.on('drain', function() { - self.emit('drain') - }) - - self.emit('request', self.req) -} - -Request.prototype.abort = function () { - this._aborted = true; - - if (this.req) { - this.req.abort() - } - else if (this.response) { - this.response.abort() - } - - this.emit("abort") -} - -Request.prototype.pipeDest = function (dest) { - var response = this.response - // Called after the response is received - if (dest.headers) { - dest.headers['content-type'] = response.headers['content-type'] - if (response.headers['content-length']) { - dest.headers['content-length'] = response.headers['content-length'] - } - } - if (dest.setHeader) { - for (var i in response.headers) { - dest.setHeader(i, response.headers[i]) - } - dest.statusCode = response.statusCode - } - if (this.pipefilter) this.pipefilter(response, dest) -} - -// Composable API -Request.prototype.setHeader = function (name, value, clobber) { - if (clobber === undefined) clobber = true - if (clobber || !this.headers.hasOwnProperty(name)) this.headers[name] = value - else this.headers[name] += ',' + value - return this -} -Request.prototype.setHeaders = function (headers) { - for (var i in headers) {this.setHeader(i, headers[i])} - return this -} -Request.prototype.qs = function (q, clobber) { - var base - if (!clobber && this.uri.query) base = qs.parse(this.uri.query) - else base = {} - - for (var i in q) { - base[i] = q[i] - } - - this.uri = url.parse(this.uri.href.split('?')[0] + '?' + qs.stringify(base)) - this.url = this.uri - - return this -} -Request.prototype.form = function (form) { - this.headers['content-type'] = 'application/x-www-form-urlencoded; charset=utf-8' - this.body = qs.stringify(form).toString('utf8') - return this -} -Request.prototype.multipart = function (multipart) { - var self = this - self.body = [] - - if (!self.headers['content-type']) { - self.headers['content-type'] = 'multipart/related; boundary=' + self.boundary; - } else { - self.headers['content-type'] = self.headers['content-type'].split(';')[0] + '; boundary=' + self.boundary; - } - - console.log('boundary >> ' + self.boundary) - - if (!multipart.forEach) throw new Error('Argument error, options.multipart.') - - multipart.forEach(function (part) { - var body = part.body - if(body == null) throw Error('Body attribute missing in multipart.') - delete part.body - var preamble = '--' + self.boundary + '\r\n' - Object.keys(part).forEach(function (key) { - preamble += key + ': ' + part[key] + '\r\n' - }) - preamble += '\r\n' - self.body.push(new Buffer(preamble)) - self.body.push(new Buffer(body)) - self.body.push(new Buffer('\r\n')) - }) - self.body.push(new Buffer('--' + self.boundary + '--')) - return self -} -Request.prototype.json = function (val) { - this.setHeader('content-type', 'application/json') - this.setHeader('accept', 'application/json') - this._json = true - if (typeof val === 'boolean') { - if (typeof this.body === 'object') this.body = JSON.stringify(this.body) - } else { - this.body = JSON.stringify(val) - } - return this -} -Request.prototype.aws = function (opts, now) { - if (!now) { - this._aws = opts - return this - } - var date = new Date() - this.setHeader('date', date.toUTCString()) - this.setHeader('authorization', aws.authorization( - { key: opts.key - , secret: opts.secret - , verb: this.method - , date: date - , resource: aws.canonicalizeResource('/' + opts.bucket + this.path) - , contentType: this.headers['content-type'] || '' - , md5: this.headers['content-md5'] || '' - , amazonHeaders: aws.canonicalizeHeaders(this.headers) - } - )) - - return this -} - -Request.prototype.oauth = function (_oauth) { - var form - if (this.headers['content-type'] && - this.headers['content-type'].slice(0, 'application/x-www-form-urlencoded'.length) === - 'application/x-www-form-urlencoded' - ) { - form = qs.parse(this.body) - } - if (this.uri.query) { - form = qs.parse(this.uri.query) - } - if (!form) form = {} - var oa = {} - for (var i in form) oa[i] = form[i] - for (var i in _oauth) oa['oauth_'+i] = _oauth[i] - if (!oa.oauth_version) oa.oauth_version = '1.0' - if (!oa.oauth_timestamp) oa.oauth_timestamp = Math.floor( (new Date()).getTime() / 1000 ).toString() - if (!oa.oauth_nonce) oa.oauth_nonce = uuid().replace(/-/g, '') - - oa.oauth_signature_method = 'HMAC-SHA1' - - var consumer_secret = oa.oauth_consumer_secret - delete oa.oauth_consumer_secret - var token_secret = oa.oauth_token_secret - delete oa.oauth_token_secret - - var baseurl = this.uri.protocol + '//' + this.uri.host + this.uri.pathname - var signature = oauth.hmacsign(this.method, baseurl, oa, consumer_secret, token_secret) - - // oa.oauth_signature = signature - for (var i in form) { - if ( i.slice(0, 'oauth_') in _oauth) { - // skip - } else { - delete oa['oauth_'+i] - } - } - this.headers.Authorization = - 'OAuth '+Object.keys(oa).sort().map(function (i) {return i+'="'+oauth.rfc3986(oa[i])+'"'}).join(',') - this.headers.Authorization += ',oauth_signature="'+oauth.rfc3986(signature)+'"' - return this -} -Request.prototype.jar = function (jar) { - var cookies - - if (this._redirectsFollowed === 0) { - this.originalCookieHeader = this.headers.cookie - } - - if (jar === false) { - // disable cookies - cookies = false; - this._disableCookies = true; - } else if (jar) { - // fetch cookie from the user defined cookie jar - cookies = jar.get({ url: this.uri.href }) - } else { - // fetch cookie from the global cookie jar - cookies = cookieJar.get({ url: this.uri.href }) - } - - if (cookies && cookies.length) { - var cookieString = cookies.map(function (c) { - return c.name + "=" + c.value - }).join("; ") - - if (this.originalCookieHeader) { - // Don't overwrite existing Cookie header - this.headers.cookie = this.originalCookieHeader + '; ' + cookieString - } else { - this.headers.cookie = cookieString - } - } - this._jar = jar - return this -} - - -// Stream API -Request.prototype.pipe = function (dest, opts) { - if (this.response) { - if (this._destdata) { - throw new Error("You cannot pipe after data has been emitted from the response.") - } else if (this._ended) { - throw new Error("You cannot pipe after the response has been ended.") - } else { - stream.Stream.prototype.pipe.call(this, dest, opts) - this.pipeDest(dest) - return dest - } - } else { - this.dests.push(dest) - stream.Stream.prototype.pipe.call(this, dest, opts) - return dest - } -} -Request.prototype.write = function () { - if (!this._started) this.start() - return this.req.write.apply(this.req, arguments) -} -Request.prototype.end = function (chunk) { - if (chunk) this.write(chunk) - if (!this._started) this.start() - this.req.end() -} -Request.prototype.pause = function () { - if (!this.response) this._paused = true - else this.response.pause.apply(this.response, arguments) -} -Request.prototype.resume = function () { - if (!this.response) this._paused = false - else this.response.resume.apply(this.response, arguments) -} -Request.prototype.destroy = function () { - if (!this._ended) this.end() -} - -// organize params for post, put, head, del -function initParams(uri, options, callback) { - if ((typeof options === 'function') && !callback) callback = options; - if (options && typeof options === 'object') { - options.uri = uri; - } else if (typeof uri === 'string') { - options = {uri:uri}; - } else { - options = uri; - uri = options.uri; - } - return { uri: uri, options: options, callback: callback }; -} - -function request (uri, options, callback) { - if (typeof uri === 'undefined') throw new Error('undefined is not a valid uri or options object.') - if ((typeof options === 'function') && !callback) callback = options; - if (options && typeof options === 'object') { - options.uri = uri; - } else if (typeof uri === 'string') { - options = {uri:uri}; - } else { - options = uri; - } - - if (callback) options.callback = callback; - var r = new Request(options) - return r -} - -module.exports = request - -request.defaults = function (options) { - var def = function (method) { - var d = function (uri, opts, callback) { - var params = initParams(uri, opts, callback); - for (var i in options) { - if (params.options[i] === undefined) params.options[i] = options[i] - } - return method(params.options, params.callback) - } - return d - } - var de = def(request) - de.get = def(request.get) - de.post = def(request.post) - de.put = def(request.put) - de.head = def(request.head) - de.del = def(request.del) - de.cookie = def(request.cookie) - de.jar = def(request.jar) - return de -} - -request.forever = function (agentOptions, optionsArg) { - var options = {} - if (optionsArg) { - for (option in optionsArg) { - options[option] = optionsArg[option] - } - } - if (agentOptions) options.agentOptions = agentOptions - options.forever = true - return request.defaults(options) -} - -request.get = request -request.post = function (uri, options, callback) { - var params = initParams(uri, options, callback); - params.options.method = 'POST'; - return request(params.uri || null, params.options, params.callback) -} -request.put = function (uri, options, callback) { - var params = initParams(uri, options, callback); - params.options.method = 'PUT' - return request(params.uri || null, params.options, params.callback) -} -request.head = function (uri, options, callback) { - var params = initParams(uri, options, callback); - params.options.method = 'HEAD' - if (params.options.body || - params.options.requestBodyStream || - (params.options.json && typeof params.options.json !== 'boolean') || - params.options.multipart) { - throw new Error("HTTP HEAD requests MUST NOT include a request body.") - } - return request(params.uri || null, params.options, params.callback) -} -request.del = function (uri, options, callback) { - var params = initParams(uri, options, callback); - params.options.method = 'DELETE' - return request(params.uri || null, params.options, params.callback) -} -request.jar = function () { - return new CookieJar -} -request.cookie = function (str) { - if (str && str.uri) str = str.uri - if (typeof str !== 'string') throw new Error("The cookie function only accepts STRING as param") - return new Cookie(str) -} - -// Safe toJSON - -function getSafe (self, uuid) { - if (typeof self === 'object' || typeof self === 'function') var safe = {} - if (Array.isArray(self)) var safe = [] - - var recurse = [] - - Object.defineProperty(self, uuid, {}) - - var attrs = Object.keys(self).filter(function (i) { - if (i === uuid) return false - if ( (typeof self[i] !== 'object' && typeof self[i] !== 'function') || self[i] === null) return true - return !(Object.getOwnPropertyDescriptor(self[i], uuid)) - }) - - - for (var i=0;i= 0.3.6" - ], - "main": "./main", - "scripts": { - "test": "node tests/run.js" - }, - "readme": "# Request -- Simplified HTTP request method\n\n## Install\n\n
        \n  npm install request\n
        \n\nOr from source:\n\n
        \n  git clone git://github.com/mikeal/request.git \n  cd request\n  npm link\n
        \n\n## Super simple to use\n\nRequest is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default.\n\n```javascript\nvar request = require('request');\nrequest('http://www.google.com', function (error, response, body) {\n if (!error && response.statusCode == 200) {\n console.log(body) // Print the google web page.\n }\n})\n```\n\n## Streaming\n\nYou can stream any response to a file stream.\n\n```javascript\nrequest('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))\n```\n\nYou can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types, in this case `application/json`, and use the proper content-type in the PUT request if one is not already provided in the headers.\n\n```javascript\nfs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json'))\n```\n\nRequest can also pipe to itself. When doing so the content-type and content-length will be preserved in the PUT headers.\n\n```javascript\nrequest.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))\n```\n\nNow let's get fancy.\n\n```javascript\nhttp.createServer(function (req, resp) {\n if (req.url === '/doodle.png') {\n if (req.method === 'PUT') {\n req.pipe(request.put('http://mysite.com/doodle.png'))\n } else if (req.method === 'GET' || req.method === 'HEAD') {\n request.get('http://mysite.com/doodle.png').pipe(resp)\n } \n }\n})\n```\n\nYou can also pipe() from a http.ServerRequest instance and to a http.ServerResponse instance. The HTTP method and headers will be sent as well as the entity-body data. Which means that, if you don't really care about security, you can do:\n\n```javascript\nhttp.createServer(function (req, resp) {\n if (req.url === '/doodle.png') {\n var x = request('http://mysite.com/doodle.png')\n req.pipe(x)\n x.pipe(resp)\n }\n})\n```\n\nAnd since pipe() returns the destination stream in node 0.5.x you can do one line proxying :)\n\n```javascript\nreq.pipe(request('http://mysite.com/doodle.png')).pipe(resp)\n```\n\nAlso, none of this new functionality conflicts with requests previous features, it just expands them.\n\n```javascript\nvar r = request.defaults({'proxy':'http://localproxy.com'})\n\nhttp.createServer(function (req, resp) {\n if (req.url === '/doodle.png') {\n r.get('http://google.com/doodle.png').pipe(resp)\n }\n})\n```\n\nYou can still use intermediate proxies, the requests will still follow HTTP forwards, etc.\n\n## OAuth Signing\n\n```javascript\n// Twitter OAuth\nvar qs = require('querystring')\n , oauth =\n { callback: 'http://mysite.com/callback/'\n , consumer_key: CONSUMER_KEY\n , consumer_secret: CONSUMER_SECRET\n }\n , url = 'https://api.twitter.com/oauth/request_token'\n ;\nrequest.post({url:url, oauth:oauth}, function (e, r, body) {\n // Assume by some stretch of magic you aquired the verifier\n var access_token = qs.parse(body)\n , oauth = \n { consumer_key: CONSUMER_KEY\n , consumer_secret: CONSUMER_SECRET\n , token: access_token.oauth_token\n , verifier: VERIFIER\n , token_secret: access_token.oauth_token_secret\n }\n , url = 'https://api.twitter.com/oauth/access_token'\n ;\n request.post({url:url, oauth:oauth}, function (e, r, body) {\n var perm_token = qs.parse(body)\n , oauth = \n { consumer_key: CONSUMER_KEY\n , consumer_secret: CONSUMER_SECRET\n , token: perm_token.oauth_token\n , token_secret: perm_token.oauth_token_secret\n }\n , url = 'https://api.twitter.com/1/users/show.json?'\n , params = \n { screen_name: perm_token.screen_name\n , user_id: perm_token.user_id\n }\n ;\n url += qs.stringify(params)\n request.get({url:url, oauth:oauth, json:true}, function (e, r, user) {\n console.log(user)\n })\n })\n})\n```\n\n\n\n### request(options, callback)\n\nThe first argument can be either a url or an options object. The only required option is uri, all others are optional.\n\n* `uri` || `url` - fully qualified uri or a parsed url object from url.parse()\n* `qs` - object containing querystring values to be appended to the uri\n* `method` - http method, defaults to GET\n* `headers` - http headers, defaults to {}\n* `body` - entity body for POST and PUT requests. Must be buffer or string.\n* `form` - sets `body` but to querystring representation of value and adds `Content-type: application/x-www-form-urlencoded; charset=utf-8` header.\n* `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header.\n* `multipart` - (experimental) array of objects which contains their own headers and `body` attribute. Sends `multipart/related` request. See example below.\n* `followRedirect` - follow HTTP 3xx responses as redirects. defaults to true.\n* `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects. defaults to false.\n* `maxRedirects` - the maximum number of redirects to follow, defaults to 10.\n* `encoding` - Encoding to be used on `setEncoding` of response data. If set to `null`, the body is returned as a Buffer.\n* `pool` - A hash object containing the agents for these requests. If omitted this request will use the global pool which is set to node's default maxSockets.\n* `pool.maxSockets` - Integer containing the maximum amount of sockets in the pool.\n* `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request\t\n* `proxy` - An HTTP proxy to be used. Support proxy Auth with Basic Auth the same way it's supported with the `url` parameter by embedding the auth info in the uri.\n* `oauth` - Options for OAuth HMAC-SHA1 signing, see documentation above.\n* `strictSSL` - Set to `true` to require that SSL certificates be valid. Note: to use your own certificate authority, you need to specify an agent that was created with that ca as an option.\n* `jar` - Set to `false` if you don't want cookies to be remembered for future use or define your custom cookie jar (see examples section)\n\n\nThe callback argument gets 3 arguments. The first is an error when applicable (usually from the http.Client option not the http.ClientRequest object). The second in an http.ClientResponse object. The third is the response body String or Buffer.\n\n## Convenience methods\n\nThere are also shorthand methods for different HTTP METHODs and some other conveniences.\n\n### request.defaults(options) \n \nThis method returns a wrapper around the normal request API that defaults to whatever options you pass in to it.\n\n### request.put\n\nSame as request() but defaults to `method: \"PUT\"`.\n\n```javascript\nrequest.put(url)\n```\n\n### request.post\n\nSame as request() but defaults to `method: \"POST\"`.\n\n```javascript\nrequest.post(url)\n```\n\n### request.head\n\nSame as request() but defaults to `method: \"HEAD\"`.\n\n```javascript\nrequest.head(url)\n```\n\n### request.del\n\nSame as request() but defaults to `method: \"DELETE\"`.\n\n```javascript\nrequest.del(url)\n```\n\n### request.get\n\nAlias to normal request method for uniformity.\n\n```javascript\nrequest.get(url)\n```\n### request.cookie\n\nFunction that creates a new cookie.\n\n```javascript\nrequest.cookie('cookie_string_here')\n```\n### request.jar\n\nFunction that creates a new cookie jar.\n\n```javascript\nrequest.jar()\n```\n\n\n## Examples:\n\n```javascript\n var request = require('request')\n , rand = Math.floor(Math.random()*100000000).toString()\n ;\n request(\n { method: 'PUT'\n , uri: 'http://mikeal.iriscouch.com/testjs/' + rand\n , multipart: \n [ { 'content-type': 'application/json'\n , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}})\n }\n , { body: 'I am an attachment' }\n ] \n }\n , function (error, response, body) {\n if(response.statusCode == 201){\n console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand)\n } else {\n console.log('error: '+ response.statusCode)\n console.log(body)\n }\n }\n )\n```\nCookies are enabled by default (so they can be used in subsequent requests). To disable cookies set jar to false (either in defaults or in the options sent).\n\n```javascript\nvar request = request.defaults({jar: false})\nrequest('http://www.google.com', function () {\n request('http://images.google.com')\n})\n```\n\nIf you to use a custom cookie jar (instead of letting request use its own global cookie jar) you do so by setting the jar default or by specifying it as an option:\n\n```javascript\nvar j = request.jar()\nvar request = request.defaults({jar:j})\nrequest('http://www.google.com', function () {\n request('http://images.google.com')\n})\n```\nOR\n\n```javascript\nvar j = request.jar()\nvar cookie = request.cookie('your_cookie_here')\nj.add(cookie)\nrequest({url: 'http://www.google.com', jar: j}, function () {\n request('http://images.google.com')\n})\n```\n", - "readmeFilename": "README.md", - "_id": "request@2.9.203", - "_from": "request@2.9.x" -} diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/run.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/run.js deleted file mode 100644 index f3a30d354..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/run.js +++ /dev/null @@ -1,39 +0,0 @@ -var spawn = require('child_process').spawn - , exitCode = 0 - ; - -var tests = [ - 'test-body.js' - , 'test-cookie.js' - , 'test-cookiejar.js' - , 'test-defaults.js' - , 'test-errors.js' - , 'test-headers.js' - , 'test-httpModule.js' - , 'test-https.js' - , 'test-https-strict.js' - , 'test-oauth.js' - , 'test-pipes.js' - , 'test-pool.js' - , 'test-proxy.js' - , 'test-qs.js' - , 'test-redirect.js' - , 'test-timeout.js' - , 'test-toJSON.js' - , 'test-tunnel.js' -] - -var next = function () { - if (tests.length === 0) process.exit(exitCode); - - var file = tests.shift() - console.log(file) - var proc = spawn('node', [ 'tests/' + file ]) - proc.stdout.pipe(process.stdout) - proc.stderr.pipe(process.stderr) - proc.on('exit', function (code) { - exitCode += code || 0 - next() - }) -} -next() diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/server.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/server.js deleted file mode 100644 index 921f51204..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/server.js +++ /dev/null @@ -1,82 +0,0 @@ -var fs = require('fs') - , http = require('http') - , path = require('path') - , https = require('https') - , events = require('events') - , stream = require('stream') - , assert = require('assert') - ; - -exports.createServer = function (port) { - port = port || 6767 - var s = http.createServer(function (req, resp) { - s.emit(req.url, req, resp); - }) - s.port = port - s.url = 'http://localhost:'+port - return s; -} - -exports.createSSLServer = function(port, opts) { - port = port || 16767 - - var options = { 'key' : path.join(__dirname, 'ssl', 'test.key') - , 'cert': path.join(__dirname, 'ssl', 'test.crt') - } - if (opts) { - for (var i in opts) options[i] = opts[i] - } - - for (var i in options) { - options[i] = fs.readFileSync(options[i]) - } - - var s = https.createServer(options, function (req, resp) { - s.emit(req.url, req, resp); - }) - s.port = port - s.url = 'https://localhost:'+port - return s; -} - -exports.createPostStream = function (text) { - var postStream = new stream.Stream(); - postStream.writeable = true; - postStream.readable = true; - setTimeout(function () {postStream.emit('data', new Buffer(text)); postStream.emit('end')}, 0); - return postStream; -} -exports.createPostValidator = function (text) { - var l = function (req, resp) { - var r = ''; - req.on('data', function (chunk) {r += chunk}) - req.on('end', function () { - if (r !== text) console.log(r, text); - assert.equal(r, text) - resp.writeHead(200, {'content-type':'text/plain'}) - resp.write('OK') - resp.end() - }) - } - return l; -} -exports.createGetResponse = function (text, contentType) { - var l = function (req, resp) { - contentType = contentType || 'text/plain' - resp.writeHead(200, {'content-type':contentType}) - resp.write(text) - resp.end() - } - return l; -} -exports.createChunkResponse = function (chunks, contentType) { - var l = function (req, resp) { - contentType = contentType || 'text/plain' - resp.writeHead(200, {'content-type':contentType}) - chunks.forEach(function (chunk) { - resp.write(chunk) - }) - resp.end() - } - return l; -} diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-body.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-body.js deleted file mode 100644 index e3fc75d97..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-body.js +++ /dev/null @@ -1,80 +0,0 @@ -var server = require('./server') - , events = require('events') - , stream = require('stream') - , assert = require('assert') - , request = require('../main.js') - ; - -var s = server.createServer(); - -var tests = - { testGet : - { resp : server.createGetResponse("TESTING!") - , expectBody: "TESTING!" - } - , testGetChunkBreak : - { resp : server.createChunkResponse( - [ new Buffer([239]) - , new Buffer([163]) - , new Buffer([191]) - , new Buffer([206]) - , new Buffer([169]) - , new Buffer([226]) - , new Buffer([152]) - , new Buffer([131]) - ]) - , expectBody: "Ω☃" - } - , testGetBuffer : - { resp : server.createGetResponse(new Buffer("TESTING!")) - , encoding: null - , expectBody: new Buffer("TESTING!") - } - , testGetJSON : - { resp : server.createGetResponse('{"test":true}', 'application/json') - , json : true - , expectBody: {"test":true} - } - , testPutString : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : "PUTTINGDATA" - } - , testPutBuffer : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : new Buffer("PUTTINGDATA") - } - , testPutJSON : - { resp : server.createPostValidator(JSON.stringify({foo: 'bar'})) - , method: "PUT" - , json: {foo: 'bar'} - } - - } - -s.listen(s.port, function () { - - var counter = 0 - - for (i in tests) { - (function () { - var test = tests[i] - s.on('/'+i, test.resp) - test.uri = s.url + '/' + i - request(test, function (err, resp, body) { - if (err) throw err - if (test.expectBody) { - assert.deepEqual(test.expectBody, body) - } - counter = counter - 1; - if (counter === 0) { - console.log(Object.keys(tests).length+" tests passed.") - s.close() - } - }) - counter++ - })() - } -}) - diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-defaults.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-defaults.js deleted file mode 100644 index 6c8b58fa6..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-defaults.js +++ /dev/null @@ -1,68 +0,0 @@ -var server = require('./server') - , assert = require('assert') - , request = require('../main.js') - ; - -var s = server.createServer(); - -s.listen(s.port, function () { - var counter = 0; - s.on('/get', function (req, resp) { - assert.equal(req.headers.foo, 'bar'); - assert.equal(req.method, 'GET') - resp.writeHead(200, {'Content-Type': 'text/plain'}); - resp.end('TESTING!'); - }); - - // test get(string, function) - request.defaults({headers:{foo:"bar"}})(s.url + '/get', function (e, r, b){ - if (e) throw e; - assert.deepEqual("TESTING!", b); - counter += 1; - }); - - s.on('/post', function (req, resp) { - assert.equal(req.headers.foo, 'bar'); - assert.equal(req.headers['content-type'], 'application/json'); - assert.equal(req.method, 'POST') - resp.writeHead(200, {'Content-Type': 'application/json'}); - resp.end(JSON.stringify({foo:'bar'})); - }); - - // test post(string, object, function) - request.defaults({headers:{foo:"bar"}}).post(s.url + '/post', {json: true}, function (e, r, b){ - if (e) throw e; - assert.deepEqual('bar', b.foo); - counter += 1; - }); - - s.on('/del', function (req, resp) { - assert.equal(req.headers.foo, 'bar'); - assert.equal(req.method, 'DELETE') - resp.writeHead(200, {'Content-Type': 'application/json'}); - resp.end(JSON.stringify({foo:'bar'})); - }); - - // test .del(string, function) - request.defaults({headers:{foo:"bar"}, json:true}).del(s.url + '/del', function (e, r, b){ - if (e) throw e; - assert.deepEqual('bar', b.foo); - counter += 1; - }); - - s.on('/head', function (req, resp) { - assert.equal(req.headers.foo, 'bar'); - assert.equal(req.method, 'HEAD') - resp.writeHead(200, {'Content-Type': 'text/plain'}); - resp.end(); - }); - - // test head.(object, function) - request.defaults({headers:{foo:"bar"}}).head({uri: s.url + '/head'}, function (e, r, b){ - if (e) throw e; - counter += 1; - console.log(counter.toString() + " tests passed.") - s.close() - }); - -}) diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-https-strict.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-https-strict.js deleted file mode 100644 index f53fc14a8..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-https-strict.js +++ /dev/null @@ -1,97 +0,0 @@ -// a test where we validate the siguature of the keys -// otherwise exactly the same as the ssl test - -var server = require('./server') - , assert = require('assert') - , request = require('../main.js') - , fs = require('fs') - , path = require('path') - , opts = { key: path.resolve(__dirname, 'ssl/ca/server.key') - , cert: path.resolve(__dirname, 'ssl/ca/server.crt') } - , s = server.createSSLServer(null, opts) - , caFile = path.resolve(__dirname, 'ssl/ca/ca.crt') - , ca = fs.readFileSync(caFile) - -var tests = - { testGet : - { resp : server.createGetResponse("TESTING!") - , expectBody: "TESTING!" - } - , testGetChunkBreak : - { resp : server.createChunkResponse( - [ new Buffer([239]) - , new Buffer([163]) - , new Buffer([191]) - , new Buffer([206]) - , new Buffer([169]) - , new Buffer([226]) - , new Buffer([152]) - , new Buffer([131]) - ]) - , expectBody: "Ω☃" - } - , testGetJSON : - { resp : server.createGetResponse('{"test":true}', 'application/json') - , json : true - , expectBody: {"test":true} - } - , testPutString : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : "PUTTINGDATA" - } - , testPutBuffer : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : new Buffer("PUTTINGDATA") - } - , testPutJSON : - { resp : server.createPostValidator(JSON.stringify({foo: 'bar'})) - , method: "PUT" - , json: {foo: 'bar'} - } - , testPutMultipart : - { resp: server.createPostValidator( - '--frontier\r\n' + - 'content-type: text/html\r\n' + - '\r\n' + - 'Oh hi.' + - '\r\n--frontier\r\n\r\n' + - 'Oh hi.' + - '\r\n--frontier--' - ) - , method: "PUT" - , multipart: - [ {'content-type': 'text/html', 'body': 'Oh hi.'} - , {'body': 'Oh hi.'} - ] - } - } - -s.listen(s.port, function () { - - var counter = 0 - - for (i in tests) { - (function () { - var test = tests[i] - s.on('/'+i, test.resp) - test.uri = s.url + '/' + i - test.strictSSL = true - test.ca = ca - test.headers = { host: 'testing.request.mikealrogers.com' } - request(test, function (err, resp, body) { - if (err) throw err - if (test.expectBody) { - assert.deepEqual(test.expectBody, body) - } - counter = counter - 1; - if (counter === 0) { - console.log(Object.keys(tests).length+" tests passed.") - s.close() - } - }) - counter++ - })() - } -}) diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-https.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-https.js deleted file mode 100644 index df7330b39..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-https.js +++ /dev/null @@ -1,86 +0,0 @@ -var server = require('./server') - , assert = require('assert') - , request = require('../main.js') - -var s = server.createSSLServer(); - -var tests = - { testGet : - { resp : server.createGetResponse("TESTING!") - , expectBody: "TESTING!" - } - , testGetChunkBreak : - { resp : server.createChunkResponse( - [ new Buffer([239]) - , new Buffer([163]) - , new Buffer([191]) - , new Buffer([206]) - , new Buffer([169]) - , new Buffer([226]) - , new Buffer([152]) - , new Buffer([131]) - ]) - , expectBody: "Ω☃" - } - , testGetJSON : - { resp : server.createGetResponse('{"test":true}', 'application/json') - , json : true - , expectBody: {"test":true} - } - , testPutString : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : "PUTTINGDATA" - } - , testPutBuffer : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : new Buffer("PUTTINGDATA") - } - , testPutJSON : - { resp : server.createPostValidator(JSON.stringify({foo: 'bar'})) - , method: "PUT" - , json: {foo: 'bar'} - } - , testPutMultipart : - { resp: server.createPostValidator( - '--frontier\r\n' + - 'content-type: text/html\r\n' + - '\r\n' + - 'Oh hi.' + - '\r\n--frontier\r\n\r\n' + - 'Oh hi.' + - '\r\n--frontier--' - ) - , method: "PUT" - , multipart: - [ {'content-type': 'text/html', 'body': 'Oh hi.'} - , {'body': 'Oh hi.'} - ] - } - } - -s.listen(s.port, function () { - - var counter = 0 - - for (i in tests) { - (function () { - var test = tests[i] - s.on('/'+i, test.resp) - test.uri = s.url + '/' + i - request(test, function (err, resp, body) { - if (err) throw err - if (test.expectBody) { - assert.deepEqual(test.expectBody, body) - } - counter = counter - 1; - if (counter === 0) { - console.log(Object.keys(tests).length+" tests passed.") - s.close() - } - }) - counter++ - })() - } -}) diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-params.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-params.js deleted file mode 100644 index 8354f6d8d..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-params.js +++ /dev/null @@ -1,92 +0,0 @@ -var server = require('./server') - , assert = require('assert') - , request = require('../main.js') - ; - -var s = server.createServer(); - -var tests = - { testGet : - { resp : server.createGetResponse("TESTING!") - , expectBody: "TESTING!" - } - , testGetChunkBreak : - { resp : server.createChunkResponse( - [ new Buffer([239]) - , new Buffer([163]) - , new Buffer([191]) - , new Buffer([206]) - , new Buffer([169]) - , new Buffer([226]) - , new Buffer([152]) - , new Buffer([131]) - ]) - , expectBody: "Ω☃" - } - , testGetBuffer : - { resp : server.createGetResponse(new Buffer("TESTING!")) - , encoding: null - , expectBody: new Buffer("TESTING!") - } - , testGetJSON : - { resp : server.createGetResponse('{"test":true}', 'application/json') - , json : true - , expectBody: {"test":true} - } - , testPutString : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : "PUTTINGDATA" - } - , testPutBuffer : - { resp : server.createPostValidator("PUTTINGDATA") - , method : "PUT" - , body : new Buffer("PUTTINGDATA") - } - , testPutJSON : - { resp : server.createPostValidator(JSON.stringify({foo: 'bar'})) - , method: "PUT" - , json: {foo: 'bar'} - } - , testPutMultipart : - { resp: server.createPostValidator( - '--frontier\r\n' + - 'content-type: text/html\r\n' + - '\r\n' + - 'Oh hi.' + - '\r\n--frontier\r\n\r\n' + - 'Oh hi.' + - '\r\n--frontier--' - ) - , method: "PUT" - , multipart: - [ {'content-type': 'text/html', 'body': 'Oh hi.'} - , {'body': 'Oh hi.'} - ] - } - } - -s.listen(s.port, function () { - - var counter = 0 - - for (i in tests) { - (function () { - var test = tests[i] - s.on('/'+i, test.resp) - //test.uri = s.url + '/' + i - request(s.url + '/' + i, test, function (err, resp, body) { - if (err) throw err - if (test.expectBody) { - assert.deepEqual(test.expectBody, body) - } - counter = counter - 1; - if (counter === 0) { - console.log(Object.keys(tests).length+" tests passed.") - s.close() - } - }) - counter++ - })() - } -}) diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-pipes.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-pipes.js deleted file mode 100644 index 186987445..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-pipes.js +++ /dev/null @@ -1,202 +0,0 @@ -var server = require('./server') - , events = require('events') - , stream = require('stream') - , assert = require('assert') - , fs = require('fs') - , request = require('../main.js') - , path = require('path') - , util = require('util') - ; - -var s = server.createServer(3453); - -function ValidationStream(str) { - this.str = str - this.buf = '' - this.on('data', function (data) { - this.buf += data - }) - this.on('end', function () { - assert.equal(this.str, this.buf) - }) - this.writable = true -} -util.inherits(ValidationStream, stream.Stream) -ValidationStream.prototype.write = function (chunk) { - this.emit('data', chunk) -} -ValidationStream.prototype.end = function (chunk) { - if (chunk) emit('data', chunk) - this.emit('end') -} - -s.listen(s.port, function () { - counter = 0; - - var check = function () { - counter = counter - 1 - if (counter === 0) { - console.log('All tests passed.') - setTimeout(function () { - process.exit(); - }, 500) - } - } - - // Test pipeing to a request object - s.once('/push', server.createPostValidator("mydata")); - - var mydata = new stream.Stream(); - mydata.readable = true - - counter++ - var r1 = request.put({url:'http://localhost:3453/push'}, function () { - check(); - }) - mydata.pipe(r1) - - mydata.emit('data', 'mydata'); - mydata.emit('end'); - - - // Test pipeing from a request object. - s.once('/pull', server.createGetResponse("mypulldata")); - - var mypulldata = new stream.Stream(); - mypulldata.writable = true - - counter++ - request({url:'http://localhost:3453/pull'}).pipe(mypulldata) - - var d = ''; - - mypulldata.write = function (chunk) { - d += chunk; - } - mypulldata.end = function () { - assert.equal(d, 'mypulldata'); - check(); - }; - - - s.on('/cat', function (req, resp) { - if (req.method === "GET") { - resp.writeHead(200, {'content-type':'text/plain-test', 'content-length':4}); - resp.end('asdf') - } else if (req.method === "PUT") { - assert.equal(req.headers['content-type'], 'text/plain-test'); - assert.equal(req.headers['content-length'], 4) - var validate = ''; - - req.on('data', function (chunk) {validate += chunk}) - req.on('end', function () { - resp.writeHead(201); - resp.end(); - assert.equal(validate, 'asdf'); - check(); - }) - } - }) - s.on('/pushjs', function (req, resp) { - if (req.method === "PUT") { - assert.equal(req.headers['content-type'], 'text/javascript'); - check(); - } - }) - s.on('/catresp', function (req, resp) { - request.get('http://localhost:3453/cat').pipe(resp) - }) - s.on('/doodle', function (req, resp) { - if (req.headers['x-oneline-proxy']) { - resp.setHeader('x-oneline-proxy', 'yup') - } - resp.writeHead('200', {'content-type':'image/png'}) - fs.createReadStream(path.join(__dirname, 'googledoodle.png')).pipe(resp) - }) - s.on('/onelineproxy', function (req, resp) { - var x = request('http://localhost:3453/doodle') - req.pipe(x) - x.pipe(resp) - }) - - counter++ - fs.createReadStream(__filename).pipe(request.put('http://localhost:3453/pushjs')) - - counter++ - request.get('http://localhost:3453/cat').pipe(request.put('http://localhost:3453/cat')) - - counter++ - request.get('http://localhost:3453/catresp', function (e, resp, body) { - assert.equal(resp.headers['content-type'], 'text/plain-test'); - assert.equal(resp.headers['content-length'], 4) - check(); - }) - - var doodleWrite = fs.createWriteStream(path.join(__dirname, 'test.png')) - - counter++ - request.get('http://localhost:3453/doodle').pipe(doodleWrite) - - doodleWrite.on('close', function () { - assert.deepEqual(fs.readFileSync(path.join(__dirname, 'googledoodle.png')), fs.readFileSync(path.join(__dirname, 'test.png'))) - check() - }) - - process.on('exit', function () { - fs.unlinkSync(path.join(__dirname, 'test.png')) - }) - - counter++ - request.get({uri:'http://localhost:3453/onelineproxy', headers:{'x-oneline-proxy':'nope'}}, function (err, resp, body) { - assert.equal(resp.headers['x-oneline-proxy'], 'yup') - check() - }) - - s.on('/afterresponse', function (req, resp) { - resp.write('d') - resp.end() - }) - - counter++ - var afterresp = request.post('http://localhost:3453/afterresponse').on('response', function () { - var v = new ValidationStream('d') - afterresp.pipe(v) - v.on('end', check) - }) - - s.on('/forward1', function (req, resp) { - resp.writeHead(302, {location:'/forward2'}) - resp.end() - }) - s.on('/forward2', function (req, resp) { - resp.writeHead('200', {'content-type':'image/png'}) - resp.write('d') - resp.end() - }) - - counter++ - var validateForward = new ValidationStream('d') - validateForward.on('end', check) - request.get('http://localhost:3453/forward1').pipe(validateForward) - - // Test pipe options - s.once('/opts', server.createGetResponse('opts response')); - - var optsStream = new stream.Stream(); - optsStream.writable = true - - var optsData = ''; - optsStream.write = function (buf) { - optsData += buf; - if (optsData === 'opts response') { - setTimeout(check, 10); - } - } - - optsStream.end = function () { - assert.fail('end called') - }; - - counter++ - request({url:'http://localhost:3453/opts'}).pipe(optsStream, { end : false }) -}) diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-tunnel.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-tunnel.js deleted file mode 100644 index 58131b9bb..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tests/test-tunnel.js +++ /dev/null @@ -1,61 +0,0 @@ -// test that we can tunnel a https request over an http proxy -// keeping all the CA and whatnot intact. -// -// Note: this requires that squid is installed. -// If the proxy fails to start, we'll just log a warning and assume success. - -var server = require('./server') - , assert = require('assert') - , request = require('../main.js') - , fs = require('fs') - , path = require('path') - , caFile = path.resolve(__dirname, 'ssl/npm-ca.crt') - , ca = fs.readFileSync(caFile) - , child_process = require('child_process') - , sqConf = path.resolve(__dirname, 'squid.conf') - , sqArgs = ['-f', sqConf, '-N', '-d', '5'] - , proxy = 'http://localhost:3128' - , hadError = null - -var squid = child_process.spawn('squid', sqArgs); -var ready = false - -squid.stderr.on('data', function (c) { - console.error('SQUIDERR ' + c.toString().trim().split('\n') - .join('\nSQUIDERR ')) - ready = c.toString().match(/ready to serve requests/i) -}) - -squid.stdout.on('data', function (c) { - console.error('SQUIDOUT ' + c.toString().trim().split('\n') - .join('\nSQUIDOUT ')) -}) - -squid.on('exit', function (c) { - console.error('exit '+c) - if (c && !ready) { - console.error('squid must be installed to run this test.') - c = null - hadError = null - process.exit(0) - return - } - - if (c) { - hadError = hadError || new Error('Squid exited with '+c) - } - if (hadError) throw hadError -}) - -setTimeout(function F () { - if (!ready) return setTimeout(F, 100) - request({ uri: 'https://registry.npmjs.org/request/' - , proxy: 'http://localhost:3128' - , ca: ca - , json: true }, function (er, body) { - hadError = er - console.log(er || typeof body) - if (!er) console.log("ok") - squid.kill('SIGKILL') - }) -}, 100) diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tunnel.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tunnel.js deleted file mode 100644 index 453786c5e..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/request/tunnel.js +++ /dev/null @@ -1,229 +0,0 @@ -'use strict'; - -var net = require('net'); -var tls = require('tls'); -var http = require('http'); -var https = require('https'); -var events = require('events'); -var assert = require('assert'); -var util = require('util'); - - -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; - - -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; -} - -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - return agent; -} - -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; -} - -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - return agent; -} - - -function TunnelingAgent(options) { - var self = this; - self.options = options || {}; - self.proxyOptions = self.options.proxy || {}; - self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; - self.requests = []; - self.sockets = []; - - self.on('free', function onFree(socket, host, port) { - for (var i = 0, len = self.requests.length; i < len; ++i) { - var pending = self.requests[i]; - if (pending.host === host && pending.port === port) { - // Detect the request to connect same origin server, - // reuse the connection. - self.requests.splice(i, 1); - pending.request.onSocket(socket); - return; - } - } - socket.destroy(); - self.removeSocket(socket); - }); -} -util.inherits(TunnelingAgent, events.EventEmitter); - -TunnelingAgent.prototype.addRequest = function addRequest(req, host, port) { - var self = this; - - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push({host: host, port: port, request: req}); - return; - } - - // If we are under maxSockets create a new one. - self.createSocket({host: host, port: port, request: req}, function(socket) { - socket.on('free', onFree); - socket.on('close', onCloseOrRemove); - socket.on('agentRemove', onCloseOrRemove); - req.onSocket(socket); - - function onFree() { - self.emit('free', socket, host, port); - } - - function onCloseOrRemove(err) { - self.removeSocket(); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); - } - }); -}; - -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); - - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false - }); - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {}; - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - new Buffer(connectOptions.proxyAuth).toString('base64'); - } - - debug('making CONNECT request'); - var connectReq = self.request(connectOptions); - connectReq.useChunkedEncodingByDefault = false; // for v0.6 - connectReq.once('response', onResponse); // for v0.6 - connectReq.once('upgrade', onUpgrade); // for v0.6 - connectReq.once('connect', onConnect); // for v0.7 or later - connectReq.once('error', onError); - connectReq.end(); - - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; - } - - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); - } - - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); - - if (res.statusCode === 200) { - assert.equal(head.length, 0); - debug('tunneling connection has established'); - self.sockets[self.sockets.indexOf(placeholder)] = socket; - cb(socket); - } else { - debug('tunneling socket could not be established, statusCode=%d', - res.statusCode); - var error = new Error('tunneling socket could not be established, ' + - 'sutatusCode=' + res.statusCode); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - } - } - - function onError(cause) { - connectReq.removeAllListeners(); - - debug('tunneling socket could not be established, cause=%s\n', - cause.message, cause.stack); - var error = new Error('tunneling socket could not be established, ' + - 'cause=' + cause.message); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - } -}; - -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) { - return; - } - this.sockets.splice(pos, 1); - - var pending = this.requests.shift(); - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(pending, function(socket) { - pending.request.onSocket(socket); - }); - } -}; - -function createSecureSocket(options, cb) { - var self = this; - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, mergeOptions({}, self.options, { - socket: socket - })); - cb(secureSocket); - }); -} - - -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i]; - if (typeof overrides === 'object') { - var keys = Object.keys(overrides); - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j]; - if (overrides[k] !== undefined) { - target[k] = overrides[k]; - } - } - } - } - return target; -} - - -var debug; -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments); - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0]; - } else { - args.unshift('TUNNEL:'); - } - console.error.apply(console, args); - } -} else { - debug = function() {}; -} -exports.debug = debug; // for test diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/.npmignore b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/.npmignore deleted file mode 100644 index e3bc27506..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -node_modules/ -node_modules/* -npm-debug.log \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/CHANGELOG.md b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/CHANGELOG.md deleted file mode 100644 index 1effdd28a..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/CHANGELOG.md +++ /dev/null @@ -1,15 +0,0 @@ -#VERSION HISTORY - -##2.0 -* [Breaking] Refactored this to work in node.js. Backwards compatibility to existing browser API coming in future 2.x releases. (indexzero) - -## 1.2 -* Added TimeSpan.FromDates Constructor to take two dates - and create a TimeSpan from the difference. (mstum) - -## 1.1 -* Changed naming to follow JavaScript standards (mstum) -* Added Documentation (mstum) - -## 1.0 -* Initial Revision (mstum) diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/LICENSE b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/LICENSE deleted file mode 100644 index 071d8fb7b..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Michael Stum, Charlie Robbins - -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/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/README.md b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/README.md deleted file mode 100644 index 2bb99048a..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/README.md +++ /dev/null @@ -1,199 +0,0 @@ -# timespan - -A simple implementation of TimeSpans in Javascript. - -## Installation in node.js - -### Installing npm (node package manager) -``` bash - $ curl http://npmjs.org/install.sh | sh -``` - -### Installing timespan -``` bash - [sudo] npm install timespan -``` - -## Usage -You have two options when creating a new TimeSpan object: either explicitly instantiate it using the TimeSpan constructor function or use a helper method to create from a specific length of time. - -### Using the new constructor - -``` js - var timespan = require('timespan'); - var ts = new timespan.TimeSpan(); -``` - -The constructor takes 5 parameters, all which are optional and which can be used to initialize the TimeSpan to a given value. These parameters are: `milliseconds`, `seconds`, `minutes`, `hours`, `days`. - -``` js - // - // Initializes the TimeSpan to 4 Minutes, 16 Seconds and 0 Milliseconds. - // - var ts = new TimeSpan(0,16,4) - - // - // Initializes the TimeSpan to 3 hours, 4 minutes, 10 seconds and 0 msecs. - // - var ts = new TimeSpan(0,10,64,2); -``` - -### Using Construction Helper Method(s) -You can initialize a new TimeSpan by calling one of these Functions: - -``` js - timespan.FromSeconds(/* seconds */); - timespan.FromMinutes(/* minutes */); - timespan.FromHours(/* hours */); - timespan.FromDays(/* hours */); - - // - // This behaves differently, see below - // - timespan.FromDates(start, end); -``` - -The first four helper methods take a single numeric parameter and create a new TimeSpan instance. e.g. `timespan.FromSeconds(45)` is equivalent to `new TimeSpan(0,45)`. If the parameter is invalid/not a number, it will just be treated as 0 no error will be thrown. - -`timespan.FromDates()` is different as it takes two dates. The TimeSpan will be the difference between these dates. - -If the second date is earlier than the first date, the TimeSpan will have a negative value. You can pass in "true" as the third parameter to force the TimeSpan to be positive always. - -``` js - var date1 = new Date(2010, 3, 1, 10, 10, 5, 0); - var date2 = new Date(2010, 3, 1, 10, 10, 10, 0); - var ts = TimeSpan.FromDates(date2, date1); - var ts2 = TimeSpan.FromDates(date2, date1, true); - - // - // -5, because we put the later date first - // - console.log(ts.totalSeconds()); - - // - // 5, because we passed true as third parameter - // - console.log(ts2.totalSeconds()); -``` - - -### Adding / Subtracting TimeSpans -There are several functions to add or subtract time: - -``` js - ts.addMilliseconds() - ts.addSeconds() - ts.addMinutes() - ts.addHours() - ts.addDays() - ts.subtractMilliseconds() - ts.subtractSeconds() - ts.subtractMinutes() - ts.subtractHours() - ts.subtractDays() -``` - -All these functions take a single numeric parameter. If the parameter is invalid, not a number, or missing it will be ignored and no Error is thrown. - -``` js - var ts = new TimeSpan(); - ts.addSeconds(30); - ts.addMinutes(2); - ts.subtractSeconds(60); - - // - // ts will now be a timespan of 1 minute and 30 seconds - // -``` - -The parameter can be negative to negate the operation `ts.addSeconds(-30)` is equivalent to `ts.subtractSeconds(30)`. - -### Interacting with Other TimeSpan instances -These are the functions that interact with another TimeSpan: - -``` js - ts.add() - ts.subtract() - ts.equals() -``` - -add and subtract add/subtract the other TimeSpan to the current one: - -``` js - var ts = TimeSpan.FromSeconds(30); - var ts2 = TimeSpan.FromMinutes(2); - ts.add(ts2); - - // - // ts is now a TimeSpan of 2 Minutes, 30 Seconds - // ts2 is unchanged - // -``` - -equals checks if two TimeSpans have the same time: - -``` js - var ts = TimeSpan.FromSeconds(30); - var ts2 = TimeSpan.FromSeconds(30); - var eq = ts.equals(ts2); // true - ts2.addSeconds(1); - var eq2 = ts.equals(ts2); // false -``` - -### Retrieving the Value of a TimeSpan -There are two sets of functions to retreive the function of the TimeSpan: those that deal with the full value in various measurements and another that gets the individual components. - -#### Retrieve the full value - -``` js - ts.totalMilliseconds() - ts.totalSeconds() - ts.totalMinutes() - ts.totalHours() - ts.totalDays() -``` - -These functions convert the value to the given format and return it. The result can be a floating point number. These functions take a single parameter roundDown which can be set to true to round the value down to an Integer. - -``` js - var ts = TimeSpan.fromSeconds(90); - console.log(ts.totalMilliseconds()); // 90000 - console.log(ts.totalSeconds()); // 90 - console.log(ts.totalMinutes()); // 1.5 - console.log(ts.totalMinutes(true)); // 1 -``` - -#### Retrieve a component of the TimeSpan - -``` js - ts.milliseconds - ts.seconds - ts.minutes - ts.hours - ts.days -``` - -These functions return a component of the TimeSpan that could be used to represent a clock. - -``` js - var ts = TimeSpan.FromSeconds(90); - console.log(ts.seconds()); // 30 - console.log(ts.minutes()); // 1 -``` - -Basically these value never "overflow" - seconds will only return 0 to 59, hours only 0 to 23 etc. Days could grow infinitely. All of these functions automatically round down the result: - -``` js - var ts = TimeSpan.FromDays(2); - ts.addHours(12); - console.log(ts.days()); // 2 - console.log(ts.hours()); // 12 -``` - -## Remark about Backwards Compatibility -Version 0.2.x was designed to work with [node.js][0] and backwards compatibility to the browser-based usage was not considered a high priority. This will be fixed in future versions, but for now if you need to use this in the browser, you can find the 0.1.x code under `/browser`. - -#### Author: [Michael Stum](http://www.stum.de) -#### Contributors: [Charlie Robbins](http://github.com/indexzero) - -[0]: http://nodejs.org \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.js deleted file mode 100644 index bc8149d8d..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.js +++ /dev/null @@ -1,226 +0,0 @@ -/*! -* JavaScript TimeSpan Library -* -* Copyright (c) 2010 Michael Stum, http://www.Stum.de/ -* -* 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. -*/ - -/*global window: false */ -"use strict"; -(function () { - // Constructor function, all parameters are optional - var TimeSpan = window.TimeSpan = function (milliseconds, seconds, minutes, hours, days) { - var version = "1.2", - // Millisecond-constants - msecPerSecond = 1000, - msecPerMinute = 60000, - msecPerHour = 3600000, - msecPerDay = 86400000, - // Internally we store the TimeSpan as Milliseconds - msecs = 0, - - // Helper functions - isNumeric = function (input) { - return !isNaN(parseFloat(input)) && isFinite(input); - }; - - // Constructor Logic - if (isNumeric(days)) { - msecs += (days * msecPerDay); - } - if (isNumeric(hours)) { - msecs += (hours * msecPerHour); - } - if (isNumeric(minutes)) { - msecs += (minutes * msecPerMinute); - } - if (isNumeric(seconds)) { - msecs += (seconds * msecPerSecond); - } - if (isNumeric(milliseconds)) { - msecs += milliseconds; - } - - // Addition Functions - this.addMilliseconds = function (milliseconds) { - if (!isNumeric(milliseconds)) { - return; - } - msecs += milliseconds; - }; - this.addSeconds = function (seconds) { - if (!isNumeric(seconds)) { - return; - } - msecs += (seconds * msecPerSecond); - }; - this.addMinutes = function (minutes) { - if (!isNumeric(minutes)) { - return; - } - msecs += (minutes * msecPerMinute); - }; - this.addHours = function (hours) { - if (!isNumeric(hours)) { - return; - } - msecs += (hours * msecPerHour); - }; - this.addDays = function (days) { - if (!isNumeric(days)) { - return; - } - msecs += (days * msecPerDay); - }; - - // Subtraction Functions - this.subtractMilliseconds = function (milliseconds) { - if (!isNumeric(milliseconds)) { - return; - } - msecs -= milliseconds; - }; - this.subtractSeconds = function (seconds) { - if (!isNumeric(seconds)) { - return; - } - msecs -= (seconds * msecPerSecond); - }; - this.subtractMinutes = function (minutes) { - if (!isNumeric(minutes)) { - return; - } - msecs -= (minutes * msecPerMinute); - }; - this.subtractHours = function (hours) { - if (!isNumeric(hours)) { - return; - } - msecs -= (hours * msecPerHour); - }; - this.subtractDays = function (days) { - if (!isNumeric(days)) { - return; - } - msecs -= (days * msecPerDay); - }; - - // Functions to interact with other TimeSpans - this.isTimeSpan = true; - this.add = function (otherTimeSpan) { - if (!otherTimeSpan.isTimeSpan) { - return; - } - msecs += otherTimeSpan.totalMilliseconds(); - }; - this.subtract = function (otherTimeSpan) { - if (!otherTimeSpan.isTimeSpan) { - return; - } - msecs -= otherTimeSpan.totalMilliseconds(); - }; - this.equals = function (otherTimeSpan) { - if (!otherTimeSpan.isTimeSpan) { - return; - } - return msecs === otherTimeSpan.totalMilliseconds(); - }; - - // Getters - this.totalMilliseconds = function (roundDown) { - var result = msecs; - if (roundDown === true) { - result = Math.floor(result); - } - return result; - }; - this.totalSeconds = function (roundDown) { - var result = msecs / msecPerSecond; - if (roundDown === true) { - result = Math.floor(result); - } - return result; - }; - this.totalMinutes = function (roundDown) { - var result = msecs / msecPerMinute; - if (roundDown === true) { - result = Math.floor(result); - } - return result; - }; - this.totalHours = function (roundDown) { - var result = msecs / msecPerHour; - if (roundDown === true) { - result = Math.floor(result); - } - return result; - }; - this.totalDays = function (roundDown) { - var result = msecs / msecPerDay; - if (roundDown === true) { - result = Math.floor(result); - } - return result; - }; - // Return a Fraction of the TimeSpan - this.milliseconds = function () { - return msecs % 1000; - }; - this.seconds = function () { - return Math.floor(msecs / msecPerSecond) % 60; - }; - this.minutes = function () { - return Math.floor(msecs / msecPerMinute) % 60; - }; - this.hours = function () { - return Math.floor(msecs / msecPerHour) % 24; - }; - this.days = function () { - return Math.floor(msecs / msecPerDay); - }; - - // Misc. Functions - this.getVersion = function () { - return version; - }; - }; - - // "Static Constructors" - TimeSpan.FromSeconds = function (seconds) { - return new TimeSpan(0, seconds, 0, 0, 0); - }; - TimeSpan.FromMinutes = function (minutes) { - return new TimeSpan(0, 0, minutes, 0, 0); - }; - TimeSpan.FromHours = function (hours) { - return new TimeSpan(0, 0, 0, hours, 0); - }; - TimeSpan.FromDays = function (days) { - return new TimeSpan(0, 0, 0, 0, days); - }; - TimeSpan.FromDates = function (firstDate, secondDate, forcePositive) { - var differenceMsecs = secondDate.valueOf() - firstDate.valueOf(); - if(forcePositive === true) { - differenceMsecs = Math.abs(differenceMsecs); - } - return new TimeSpan(differenceMsecs, 0, 0, 0, 0); - }; -}()); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.min.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.min.js deleted file mode 100644 index 0326cbbc7..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/browser/TimeSpan-1.2.min.js +++ /dev/null @@ -1 +0,0 @@ -"use strict";(function(){var a=window.TimeSpan=function(g,i,h,j,k){var l="1.2",d=1e3,c=6e4,e=3.6e6,f=8.64e7,a=0,b=function(a){return !isNaN(parseFloat(a))&&isFinite(a)};if(b(k))a+=k*f;if(b(j))a+=j*e;if(b(h))a+=h*c;if(b(i))a+=i*d;if(b(g))a+=g;this.addMilliseconds=function(c){if(!b(c))return;a+=c};this.addSeconds=function(c){if(!b(c))return;a+=c*d};this.addMinutes=function(d){if(!b(d))return;a+=d*c};this.addHours=function(c){if(!b(c))return;a+=c*e};this.addDays=function(c){if(!b(c))return;a+=c*f};this.subtractMilliseconds=function(c){if(!b(c))return;a-=c};this.subtractSeconds=function(c){if(!b(c))return;a-=c*d};this.subtractMinutes=function(d){if(!b(d))return;a-=d*c};this.subtractHours=function(c){if(!b(c))return;a-=c*e};this.subtractDays=function(c){if(!b(c))return;a-=c*f};this.isTimeSpan=true;this.add=function(b){if(!b.isTimeSpan)return;a+=b.totalMilliseconds()};this.subtract=function(b){if(!b.isTimeSpan)return;a-=b.totalMilliseconds()};this.equals=function(b){if(!b.isTimeSpan)return;return a===b.totalMilliseconds()};this.totalMilliseconds=function(c){var b=a;if(c===true)b=Math.floor(b);return b};this.totalSeconds=function(c){var b=a/d;if(c===true)b=Math.floor(b);return b};this.totalMinutes=function(d){var b=a/c;if(d===true)b=Math.floor(b);return b};this.totalHours=function(c){var b=a/e;if(c===true)b=Math.floor(b);return b};this.totalDays=function(c){var b=a/f;if(c===true)b=Math.floor(b);return b};this.milliseconds=function(){return a%1e3};this.seconds=function(){return Math.floor(a/d)%60};this.minutes=function(){return Math.floor(a/c)%60};this.hours=function(){return Math.floor(a/e)%24};this.days=function(){return Math.floor(a/f)};this.getVersion=function(){return l}};a.FromSeconds=function(b){return new a(0,b,0,0,0)};a.FromMinutes=function(b){return new a(0,0,b,0,0)};a.FromHours=function(b){return new a(0,0,0,b,0)};a.FromDays=function(b){return new a(0,0,0,0,b)};a.FromDates=function(e,d,c){var b=d.valueOf()-e.valueOf();if(c===true)b=Math.abs(b);return new a(b,0,0,0,0)}})() \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/docco.css b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/docco.css deleted file mode 100644 index bd5413433..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/docco.css +++ /dev/null @@ -1,194 +0,0 @@ -/*--------------------- Layout and Typography ----------------------------*/ -body { - font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; - font-size: 15px; - line-height: 22px; - color: #252519; - margin: 0; padding: 0; -} -a { - color: #261a3b; -} - a:visited { - color: #261a3b; - } -p { - margin: 0 0 15px 0; -} -h4, h5, h6 { - color: #333; - margin: 6px 0 6px 0; - font-size: 13px; -} - h2, h3 { - margin-bottom: 0; - color: #000; - } - h1 { - margin-top: 40px; - margin-bottom: 15px; - color: #000; - } -#container { - position: relative; -} -#background { - position: fixed; - top: 0; left: 525px; right: 0; bottom: 0; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - z-index: -1; -} -#jump_to, #jump_page { - background: white; - -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; - -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; - font: 10px Arial; - text-transform: uppercase; - cursor: pointer; - text-align: right; -} -#jump_to, #jump_wrapper { - position: fixed; - right: 0; top: 0; - padding: 5px 10px; -} - #jump_wrapper { - padding: 0; - display: none; - } - #jump_to:hover #jump_wrapper { - display: block; - } - #jump_page { - padding: 5px 0 3px; - margin: 0 0 25px 25px; - } - #jump_page .source { - display: block; - padding: 5px 10px; - text-decoration: none; - border-top: 1px solid #eee; - } - #jump_page .source:hover { - background: #f5f5ff; - } - #jump_page .source:first-child { - } -table td { - border: 0; - outline: 0; -} - td.docs, th.docs { - max-width: 450px; - min-width: 450px; - min-height: 5px; - padding: 10px 25px 1px 50px; - overflow-x: hidden; - vertical-align: top; - text-align: left; - } - .docs pre { - margin: 15px 0 15px; - padding-left: 15px; - } - .docs p tt, .docs p code { - background: #f8f8ff; - border: 1px solid #dedede; - font-size: 12px; - padding: 0 0.2em; - } - .pilwrap { - position: relative; - } - .pilcrow { - font: 12px Arial; - text-decoration: none; - color: #454545; - position: absolute; - top: 3px; left: -20px; - padding: 1px 2px; - opacity: 0; - -webkit-transition: opacity 0.2s linear; - } - td.docs:hover .pilcrow { - opacity: 1; - } - td.code, th.code { - padding: 14px 15px 16px 25px; - width: 100%; - vertical-align: top; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - } - pre, tt, code { - font-size: 12px; line-height: 18px; - font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; - margin: 0; padding: 0; - } - - -/*---------------------- Syntax Highlighting -----------------------------*/ -td.linenos { background-color: #f0f0f0; padding-right: 10px; } -span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } -body .hll { background-color: #ffffcc } -body .c { color: #408080; font-style: italic } /* Comment */ -body .err { border: 1px solid #FF0000 } /* Error */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ -body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { color: #0000FF } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/time-span.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/time-span.html deleted file mode 100644 index 9eb2cc933..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/docs/time-span.html +++ /dev/null @@ -1,692 +0,0 @@ - time-span.js

        time-span.js

        /*
        -* JavaScript TimeSpan Library
        -*
        -* Copyright (c) 2010 Michael Stum, Charlie Robbins
        -* 
        -* 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.
        -*/

        Time constants

        var msecPerSecond = 1000,
        -    msecPerMinute = 60000,
        -    msecPerHour = 3600000,
        -    msecPerDay = 86400000;

        Timespan Parsers

        var timeSpanWithDays = /^(\d+):(\d+):(\d+):(\d+)(\.\d+)?/,
        -    timeSpanNoDays = /^(\d+):(\d+):(\d+)(\.\d+)?/;

        function TimeSpan (milliseconds, seconds, minutes, hours, days)

        - -

        @milliseconds {Number} Number of milliseconds for this instance.

        - -

        @seconds {Number} Number of seconds for this instance.

        - -

        @minutes {Number} Number of minutes for this instance.

        - -

        @hours {Number} Number of hours for this instance.

        - -

        @days {Number} Number of days for this instance.

        - -

        Constructor function for the TimeSpan object which represents a length -of positive or negative milliseconds componentized into milliseconds, -seconds, hours, and days.

        var TimeSpan = exports.TimeSpan = function (milliseconds, seconds, minutes, hours, days) {
        -  this.msecs = 0;
        -  
        -  if (isNumeric(days)) {
        -    this.msecs += (days * msecPerDay);
        -  }
        -  
        -  if (isNumeric(hours)) {
        -    this.msecs += (hours * msecPerHour);
        -  }
        -  
        -  if (isNumeric(minutes)) {
        -    this.msecs += (minutes * msecPerMinute);
        -  }
        -  
        -  if (isNumeric(seconds)) {
        -    this.msecs += (seconds * msecPerSecond);
        -  }
        -  
        -  if (isNumeric(milliseconds)) {
        -    this.msecs += milliseconds;
        -  }
        -};

        Factory methods

        - -

        Helper methods for creating new TimeSpan objects -from various criteria: milliseconds, seconds, minutes, -hours, days, strings and other TimeSpan instances.

        function fromMilliseconds (milliseconds)

        - -

        @milliseconds {Number} Amount of milliseconds for the new TimeSpan instance.

        - -

        Creates a new TimeSpan instance with the specified milliseconds.

        exports.fromMilliseconds = function (milliseconds) {
        -  if (!isNumeric(milliseconds)) {
        -    return;
        -  }
        -  
        -  return new TimeSpan(milliseconds, 0, 0, 0, 0);
        -}

        function fromSeconds (seconds)

        - -

        @milliseconds {Number} Amount of seconds for the new TimeSpan instance.

        - -

        Creates a new TimeSpan instance with the specified seconds.

        exports.fromSeconds = function (seconds) {
        -  if (!isNumeric(seconds)) {
        -    return;
        -  }
        -  
        -  return new TimeSpan(0, seconds, 0, 0, 0);
        -};

        function fromMinutes (milliseconds)

        - -

        @milliseconds {Number} Amount of minutes for the new TimeSpan instance.

        - -

        Creates a new TimeSpan instance with the specified minutes.

        exports.fromMinutes = function (minutes) {
        -  if (!isNumeric(minutes)) {
        -    return;
        -  }
        -  
        -  return new TimeSpan(0, 0, minutes, 0, 0);
        -};

        function fromHours (hours)

        - -

        @milliseconds {Number} Amount of hours for the new TimeSpan instance.

        - -

        Creates a new TimeSpan instance with the specified hours.

        exports.fromHours = function (hours) {
        -  if (!isNumeric(hours)) {
        -    return;
        -  }
        -  
        -  return new TimeSpan(0, 0, 0, hours, 0);
        -};

        function fromDays (days)

        - -

        @milliseconds {Number} Amount of days for the new TimeSpan instance.

        - -

        Creates a new TimeSpan instance with the specified days.

        exports.fromDays = function (days) {
        -  if (!isNumeric(days)) {
        -    return;
        -  }
        -  
        -  return new TimeSpan(0, 0, 0, 0, days);
        -};

        function parse (str)

        - -

        @str {string} Timespan string to parse.

        - -

        Creates a new TimeSpan instance from the specified -string, str.

        exports.parse = function (str) {
        -  var match, milliseconds;
        -  
        -  function parseMilliseconds (value) {
        -    return value ? parseFloat('0' + value) * 1000 : 0;
        -  }
        -  

        If we match against a full TimeSpan:

          if ((match = str.match(timeSpanWithDays))) {
        -    return new TimeSpan(parseMilliseconds(match[5]), match[4], match[3], match[2], match[1]);
        -  }
        -  

        If we match against a partial TimeSpan:

          if ((match = str.match(timeSpanNoDays))) {
        -    return new TimeSpan(parseMilliseconds(match[4]), match[3], match[2], match[1], 0);
        -  }
        -  
        -  return null;
        -};
        -
        -var months  = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

        List of default singular time modifiers and associated -computation algoritm. Assumes in order, smallest to greatest -performing carry forward additiona / subtraction for each -Date-Time component.

        var parsers = {
        -  'milliseconds': {
        -    exp: /(\d+)milli[second]?[s]?/i,
        -    get: function (date) { return date.getMilliseconds(date) },
        -    set: function (val, date) { date.setMilliseconds(val) },
        -    compute: function (delta, date, computed) {
        -      var round = delta > 0 ? Math.floor : Math.ceil;
        -      if (delta) {
        -        computed.seconds += round.call(null, delta / 1000);
        -        computed.milliseconds += delta % 1000;
        -      }
        -      
        -      if (Math.abs(computed.milliseconds) >= 1000) {
        -        computed.seconds += round.call(null, computed.milliseconds / 1000)
        -        computed.milliseconds = computed.milliseconds % 1000;
        -      }
        -
        -      return computed;
        -    }
        -  },
        -  'seconds': {
        -    exp: /(\d+)second[s]?/i,
        -    get: function (date) { return date.getSeconds(date) },
        -    set: function (val, date) { date.setSeconds(val) },
        -    compute: function (delta, date, computed) {
        -      var round = delta > 0 ? Math.floor : Math.ceil;
        -      if (delta) {
        -        computed.minutes += round.call(null, delta / 60);
        -        computed.seconds += delta % 60;
        -      }
        -      
        -      if (Math.abs(computed.seconds) >= 60) {
        -        computed.minutes += round.call(null, computed.seconds / 60);
        -        computed.seconds = computed.seconds % 60; 
        -      }
        -      
        -      return computed;
        -    }
        -  },
        -  'minutes': {
        -    exp: /(\d+)minute[s]?/i,
        -    get: function (date) { return date.getMinutes(date) },
        -    set: function (val, date) { date.setMinutes(val) },
        -    compute: function (delta, date, computed) {
        -      var round = delta > 0 ? Math.floor : Math.ceil;
        -      if (delta) { 
        -        computed.hours += round.call(null, delta / 60);
        -        computed.minutes += delta % 60;
        -      }
        -      
        -      if (Math.abs(computed.minutes) >= 60) {
        -        computed.hours += round.call(null, computed.minutes / 60);
        -        computed.minutes = computed.minutes % 60; 
        -      }
        -      
        -      return computed;
        -    }
        -  },
        -  'hours': {
        -    exp: /(\d+)hour[s]?/i,
        -    get: function (date) { return date.getHours(date) },
        -    set: function (val, date) { date.setHours(val) },
        -    compute: function (delta, date, computed) {
        -      var round = delta > 0 ? Math.floor : Math.ceil;
        -      if (delta) { 
        -        computed.days += round.call(null, delta / 24);
        -        computed.hours += delta % 24;
        -      }
        -      
        -      if (Math.abs(computed.hours) >= 24) {
        -        computed.days += round.call(null, computed.hours / 24);
        -        computed.hours = computed.hours % 24;
        -      }
        -      
        -      return computed;
        -    }
        -  },
        -  'days': {
        -    exp: /(\d+)day[s]?/i,
        -    get: function (date) { return date.getDate(date) },
        -    set: function (val, date) { date.setDate(val) },
        -    compute: function (delta, date, computed) {
        -      var sign     = delta >= 0 ? 1 : -1,
        -          opsign   = delta >= 0 ? -1 : 1,
        -          clean    = 0,
        -          original = delta,
        -          month    = computed.months,
        -          days     = months[month];
        -      
        -      if (delta) {          
        -        while (Math.abs(delta) >= days) {
        -          month += sign * 1;
        -          computed.months += sign * 1;
        -          delta += opsign * days;
        -        
        -          if (month < 0) { month = 11 }
        -          else if (month > 11) { month = 0 }
        -        
        -          days = months[month];
        -        }
        -      
        -        computed.days += (sign * delta);
        -      }
        -      
        -      if (computed.days < 0) {
        -        clean = -1;
        -      }
        -      else if (computed.days > months[computed.months]) {
        -        clean = 1;
        -      }
        -      
        -      if (clean !== 0) {
        -        computed.months += clean;
        -        if (computed.months < 0) { computed.months = 11 }
        -        else if (computed.months > 11) { computed.months = 0 }
        -        computed.days = months[computed.months] + computed.days;
        -      }
        -            
        -      return computed;
        -    }
        -  },
        -  'months': {
        -    exp: /(\d+)month[s]?/i,
        -    get: function (date) { return date.getMonth(date) },
        -    set: function (val, date) { date.setMonth(val) },
        -    compute: function (delta, date, computed) {
        -      var round = delta > 0 ? Math.floor : Math.ceil;
        -      if (delta) { 
        -        computed.years += round.call(null, delta / 12);
        -        computed.months += delta % 12;
        -      }
        -      
        -      if (computed.months > 11) {
        -        computed.years += Math.floor((computed.months + 1) / 12);
        -        computed.months = ((computed.months + 1) % 12) - 1;
        -      }
        -      
        -      return computed;
        -    }
        -  },
        -  'years': {
        -    exp: /(\d+)year[s]?/i,
        -    get: function (date) { return date.getFullYear(date) },
        -    set: function (val, date) { date.setFullYear(val) },
        -    compute: function (delta, date, computed) {
        -      if (delta) { 
        -        computed.years += delta;
        -      }
        -      
        -      return computed;
        -    }
        -  }
        -};

        Compute the list of parser names for -later use.

        var parserNames = Object.keys(parsers);

        function parseDate (str)

        - -

        @str {string} String to parse into a date

        - -

        Parses the specified liberal Date-Time string according to -ISO8601 and:

        - -
          -
        1. 2010-04-03T12:34:15Z+12MINUTES
        2. -
        3. NOW-4HOURS
        4. -
        - -

        Valid modifiers for the more liberal Date-Time string(s):

        - -
        YEAR, YEARS
        -MONTH, MONTHS
        -DAY, DAYS
        -HOUR, HOURS
        -MINUTE, MINUTES
        -SECOND, SECONDS
        -MILLI, MILLIS, MILLISECOND, MILLISECONDS
        -
        exports.parseDate = function (str) {
        -  var simple = Date.parse(str),
        -      iso = '^([^Z]+)',
        -      zulu = 'Z([\\+|\\-])?',
        -      diff = {},
        -      base,
        -      sign,
        -      complex,
        -      inspect,
        -      dateTime,
        -      modifiers;
        -
        -  if (/now/i.test(str)) {
        -    iso = '^(NOW)';
        -    zulu = zulu.replace(/Z/, 'NOW');
        -  }

        If Date string supplied actually conforms -to UTC Time (ISO8601), return a new Date.

          if (!isNaN(simple)) {
        -    return new Date(simple);
        -  }
        -  

        Create the RegExp for the end component -of the target str to parse.

          parserNames.forEach(function (group) {
        -    zulu += '(\\d+[a-zA-Z]+)?';
        -  });
        -  

        Parse the ISO8601 component, and the end -component from the target str.

          dateTime = str.match(new RegExp(iso, 'i'));
        -  modifiers = str.match(new RegExp(zulu, 'i'));
        -  

        If there was no match on either part then -it must be a bad value.

          if (!dateTime || !modifiers) {
        -    return null;
        -  }
        -    

        Create a new Date object from the ISO8601 -component of the target str.

          base = /now/i.test(dateTime[1]) ? Date.now() : Date.parse(dateTime[1]);
        -  complex = new Date(base);
        -  sign = modifiers[1] === '+' ? 1 : -1;
        -  

        Parse the individual component spans (months, years, etc) -from the modifier strings that we parsed from the end -of the target str.

          modifiers.slice(2).filter(Boolean).forEach(function (modifier) {
        -    parserNames.forEach(function (name) {
        -      var match;
        -      if (!(match = modifier.match(parsers[name].exp))) {
        -        return;
        -      }
        -      
        -      diff[name] = sign * parseInt(match[1], 10);
        -    })
        -  });
        -  

        Compute the total diff by iteratively computing -the partial components from smallest to largest.

          var computed = {
        -    milliseconds: complex.getMilliseconds(),
        -    seconds: complex.getSeconds(),
        -    minutes: complex.getMinutes(),
        -    hours: complex.getHours(),
        -    days: complex.getDate(),
        -    months: complex.getMonth(),
        -    years: complex.getFullYear()
        -  };
        -  
        -  parserNames.forEach(function (name) {    
        -    computed = parsers[name].compute(diff[name], complex, computed);
        -  });
        -  
        -  return new Date(
        -    Date.UTC(
        -      computed.years,
        -      computed.months,
        -      computed.days,
        -      computed.hours,
        -      computed.minutes,
        -      computed.seconds,
        -      computed.milliseconds
        -    )
        -  );
        -};

        function fromDates (start, end, abs)

        - -

        @start {Date} Start date of the TimeSpan instance to return

        - -

        @end {Date} End date of the TimeSpan instance to return

        - -

        @abs {boolean} Value indicating to return an absolute value

        - -

        Returns a new TimeSpan instance representing the difference between -the start and end Dates.

        exports.fromDates = function (start, end, abs) {
        -  if (!start instanceof Date) {
        -    start = exports.parseDate(start);
        -  }
        -  
        -  if (!end instanceof Date) {
        -    end = exports.parseDate(end);
        -  }
        -  
        -  var differenceMsecs = end.valueOf() - start.valueOf();
        -  if (abs) {
        -    differenceMsecs = Math.abs(differenceMsecs);
        -  }
        -
        -  return new TimeSpan(differenceMsecs, 0, 0, 0, 0);
        -};

        Module Helpers

        - -

        Module-level helpers for various utilities such as: -instanceOf, parsability, and cloning.

        function test (str)

        - -

        @str {string} String value to test if it is a TimeSpan

        - -

        Returns a value indicating if the specified string, str, -is a parsable TimeSpan value.

        exports.test = function (str) {
        -  return timeSpanWithDays.test(str) || timeSpanNoDays.test(str);
        -};

        function instanceOf (timeSpan)

        - -

        @timeSpan {Object} Object to check TimeSpan quality.

        - -

        Returns a value indicating if the specified timeSpan is -in fact a TimeSpan instance.

        exports.instanceOf = function (timeSpan) {
        -  return timeSpan instanceof TimeSpan;
        -};

        function clone (timeSpan)

        - -

        @timeSpan {TimeSpan} TimeSpan object to clone.

        - -

        Returns a new TimeSpan instance with the same value -as the timeSpan object supplied.

        exports.clone = function (timeSpan) {
        -  if (!(timeSpan instanceof TimeSpan)) {
        -    return;
        -  }
        -  
        -  return exports.fromMilliseconds(timeSpan.totalMilliseconds());
        -};

        Addition

        - -

        Methods for adding TimeSpan instances, -milliseconds, seconds, hours, and days to other -TimeSpan instances.

        function add (timeSpan)

        - -

        @timeSpan {TimeSpan} TimeSpan to add to this instance

        - -

        Adds the specified timeSpan to this instance.

        TimeSpan.prototype.add = function (timeSpan) {
        -  if (!(timeSpan instanceof TimeSpan)) {
        -    return;
        -  }
        -  
        -  this.msecs += timeSpan.totalMilliseconds();
        -};

        function addMilliseconds (milliseconds)

        - -

        @milliseconds {Number} Number of milliseconds to add.

        - -

        Adds the specified milliseconds to this instance.

        TimeSpan.prototype.addMilliseconds = function (milliseconds) {
        -  if (!isNumeric(milliseconds)) {
        -    return;
        -  }
        -  
        -  this.msecs += milliseconds;
        -};

        function addSeconds (seconds)

        - -

        @seconds {Number} Number of seconds to add.

        - -

        Adds the specified seconds to this instance.

        TimeSpan.prototype.addSeconds = function (seconds) {
        -  if (!isNumeric(seconds)) {
        -    return;
        -  }
        -  
        -  this.msecs += (seconds * msecPerSecond);
        -};

        function addMinutes (minutes)

        - -

        @minutes {Number} Number of minutes to add.

        - -

        Adds the specified minutes to this instance.

        TimeSpan.prototype.addMinutes = function (minutes) {
        -  if (!isNumeric(minutes)) {
        -    return;
        -  }
        -  
        -  this.msecs += (minutes * msecPerMinute);
        -};

        function addHours (hours)

        - -

        @hours {Number} Number of hours to add.

        - -

        Adds the specified hours to this instance.

        TimeSpan.prototype.addHours = function (hours) {
        -  if (!isNumeric(hours)) {
        -    return;
        -  }
        -  
        -  this.msecs += (hours * msecPerHour);
        -};

        function addDays (days)

        - -

        @days {Number} Number of days to add.

        - -

        Adds the specified days to this instance.

        TimeSpan.prototype.addDays = function (days) {
        -  if (!isNumeric(days)) {
        -    return;
        -  }
        -  
        -  this.msecs += (days * msecPerDay);
        -};

        Subtraction

        - -

        Methods for subtracting TimeSpan instances, -milliseconds, seconds, hours, and days from other -TimeSpan instances.

        function subtract (timeSpan)

        - -

        @timeSpan {TimeSpan} TimeSpan to subtract from this instance.

        - -

        Subtracts the specified timeSpan from this instance.

        TimeSpan.prototype.subtract = function (timeSpan) {
        -  if (!(timeSpan instanceof TimeSpan)) {
        -    return;
        -  }
        -  
        -  this.msecs -= timeSpan.totalMilliseconds();
        -};

        function subtractMilliseconds (milliseconds)

        - -

        @milliseconds {Number} Number of milliseconds to subtract.

        - -

        Subtracts the specified milliseconds from this instance.

        TimeSpan.prototype.subtractMilliseconds = function (milliseconds) {
        -  if (!isNumeric(milliseconds)) {
        -    return;
        -  }
        -  
        -  this.msecs -= milliseconds;
        -};

        function subtractSeconds (seconds)

        - -

        @seconds {Number} Number of seconds to subtract.

        - -

        Subtracts the specified seconds from this instance.

        TimeSpan.prototype.subtractSeconds = function (seconds) {
        -  if (!isNumeric(seconds)) {
        -    return;
        -  }
        -  
        -  this.msecs -= (seconds * msecPerSecond);
        -};

        function subtractMinutes (minutes)

        - -

        @minutes {Number} Number of minutes to subtract.

        - -

        Subtracts the specified minutes from this instance.

        TimeSpan.prototype.subtractMinutes = function (minutes) {
        -  if (!isNumeric(minutes)) {
        -    return;
        -  }
        -  
        -  this.msecs -= (minutes * msecPerMinute);
        -};

        function subtractHours (hours)

        - -

        @hours {Number} Number of hours to subtract.

        - -

        Subtracts the specified hours from this instance.

        TimeSpan.prototype.subtractHours = function (hours) {
        -  if (!isNumeric(hours)) {
        -    return;
        -  }
        -  
        -  this.msecs -= (hours * msecPerHour);
        -};

        function subtractDays (days)

        - -

        @days {Number} Number of days to subtract.

        - -

        Subtracts the specified days from this instance.

        TimeSpan.prototype.subtractDays = function (days) {
        -  if (!isNumeric(days)) {
        -    return;
        -  }
        -  
        -  this.msecs -= (days * msecPerDay);
        -};

        Getters

        - -

        Methods for retrieving components of a TimeSpan -instance: milliseconds, seconds, minutes, hours, and days.

        function totalMilliseconds (roundDown)

        - -

        @roundDown {boolean} Value indicating if the value should be rounded down.

        - -

        Returns the total number of milliseconds for this instance, rounding down -to the nearest integer if roundDown is set.

        TimeSpan.prototype.totalMilliseconds = function (roundDown) {
        -  var result = this.msecs;
        -  if (roundDown === true) {
        -    result = Math.floor(result);
        -  }
        -  
        -  return result;
        -};

        function totalSeconds (roundDown)

        - -

        @roundDown {boolean} Value indicating if the value should be rounded down.

        - -

        Returns the total number of seconds for this instance, rounding down -to the nearest integer if roundDown is set.

        TimeSpan.prototype.totalSeconds = function (roundDown) {
        -  var result = this.msecs / msecPerSecond;
        -  if (roundDown === true) {
        -    result = Math.floor(result);
        -  }
        -  
        -  return result;
        -};

        function totalMinutes (roundDown)

        - -

        @roundDown {boolean} Value indicating if the value should be rounded down.

        - -

        Returns the total number of minutes for this instance, rounding down -to the nearest integer if roundDown is set.

        TimeSpan.prototype.totalMinutes = function (roundDown) {
        -  var result = this.msecs / msecPerMinute;
        -  if (roundDown === true) {
        -    result = Math.floor(result);
        -  }
        -  
        -  return result;
        -};

        function totalHours (roundDown)

        - -

        @roundDown {boolean} Value indicating if the value should be rounded down.

        - -

        Returns the total number of hours for this instance, rounding down -to the nearest integer if roundDown is set.

        TimeSpan.prototype.totalHours = function (roundDown) {
        -  var result = this.msecs / msecPerHour;
        -  if (roundDown === true) {
        -    result = Math.floor(result);
        -  }
        -  
        -  return result;
        -};

        function totalDays (roundDown)

        - -

        @roundDown {boolean} Value indicating if the value should be rounded down.

        - -

        Returns the total number of days for this instance, rounding down -to the nearest integer if roundDown is set.

        TimeSpan.prototype.totalDays = function (roundDown) {
        -  var result = this.msecs / msecPerDay;
        -  if (roundDown === true) {
        -    result = Math.floor(result);
        -  }
        -  
        -  return result;
        -};

        @milliseconds

        - -

        Returns the length of this TimeSpan instance in milliseconds.

        TimeSpan.prototype.__defineGetter__('milliseconds', function () {
        -  return this.msecs % 1000;
        -});

        @seconds

        - -

        Returns the length of this TimeSpan instance in seconds.

        TimeSpan.prototype.__defineGetter__('seconds', function () {
        -  return Math.floor(this.msecs / msecPerSecond) % 60;
        -});

        @minutes

        - -

        Returns the length of this TimeSpan instance in minutes.

        TimeSpan.prototype.__defineGetter__('minutes', function () {
        -  return Math.floor(this.msecs / msecPerMinute) % 60;
        -});

        @hours

        - -

        Returns the length of this TimeSpan instance in hours.

        TimeSpan.prototype.__defineGetter__('hours', function () {
        -  return Math.floor(this.msecs / msecPerHour) % 24;
        -});

        @days

        - -

        Returns the length of this TimeSpan instance in days.

        TimeSpan.prototype.__defineGetter__('days', function () {
        -  return Math.floor(this.msecs / msecPerDay);
        -});

        Instance Helpers

        - -

        Various help methods for performing utilities -such as equality and serialization

        function equals (timeSpan)

        - -

        @timeSpan {TimeSpan} TimeSpan instance to assert equal

        - -

        Returns a value indicating if the specified timeSpan is equal -in milliseconds to this instance.

        TimeSpan.prototype.equals = function (timeSpan) {
        -  if (!(timeSpan instanceof TimeSpan)) {
        -    return;
        -  }
        -  
        -  return this.msecs === timeSpan.totalMilliseconds();
        -};

        function toString ()

        - -

        Returns a string representation of this TimeSpan -instance according to current format.

        TimeSpan.prototype.toString = function () {
        -  if (!this.format) {
        -    return this._format();
        -  };
        -  
        -  return this.format(this);
        -};

        @private function _format ()

        - -

        Returns the default string representation of this instance.

        TimeSpan.prototype._format = function () {
        -  return [
        -    this.days,
        -    this.hours,
        -    this.minutes,
        -    this.seconds + '.' + this.milliseconds
        -  ].join(':')
        -};

        @private function isNumeric (input)

        - -

        @input {Number} Value to check numeric quality of.

        - -

        Returns a value indicating the numeric quality of the -specified input.

        function isNumeric (input) {
        -  return input && !isNaN(parseFloat(input)) && isFinite(input);
        -};
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/lib/time-span.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/lib/time-span.js deleted file mode 100644 index 23a9cc860..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/lib/time-span.js +++ /dev/null @@ -1,827 +0,0 @@ -/* -* JavaScript TimeSpan Library -* -* Copyright (c) 2010 Michael Stum, Charlie Robbins -* -* 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. -*/ - -// -// ### Time constants -// -var msecPerSecond = 1000, - msecPerMinute = 60000, - msecPerHour = 3600000, - msecPerDay = 86400000; - -// -// ### Timespan Parsers -// -var timeSpanWithDays = /^(\d+):(\d+):(\d+):(\d+)(\.\d+)?/, - timeSpanNoDays = /^(\d+):(\d+):(\d+)(\.\d+)?/; - -// -// ### function TimeSpan (milliseconds, seconds, minutes, hours, days) -// #### @milliseconds {Number} Number of milliseconds for this instance. -// #### @seconds {Number} Number of seconds for this instance. -// #### @minutes {Number} Number of minutes for this instance. -// #### @hours {Number} Number of hours for this instance. -// #### @days {Number} Number of days for this instance. -// Constructor function for the `TimeSpan` object which represents a length -// of positive or negative milliseconds componentized into milliseconds, -// seconds, hours, and days. -// -var TimeSpan = exports.TimeSpan = function (milliseconds, seconds, minutes, hours, days) { - this.msecs = 0; - - if (isNumeric(days)) { - this.msecs += (days * msecPerDay); - } - - if (isNumeric(hours)) { - this.msecs += (hours * msecPerHour); - } - - if (isNumeric(minutes)) { - this.msecs += (minutes * msecPerMinute); - } - - if (isNumeric(seconds)) { - this.msecs += (seconds * msecPerSecond); - } - - if (isNumeric(milliseconds)) { - this.msecs += milliseconds; - } -}; - -// -// ## Factory methods -// Helper methods for creating new TimeSpan objects -// from various criteria: milliseconds, seconds, minutes, -// hours, days, strings and other `TimeSpan` instances. -// - -// -// ### function fromMilliseconds (milliseconds) -// #### @milliseconds {Number} Amount of milliseconds for the new TimeSpan instance. -// Creates a new `TimeSpan` instance with the specified `milliseconds`. -// -exports.fromMilliseconds = function (milliseconds) { - if (!isNumeric(milliseconds)) { return } - return new TimeSpan(milliseconds, 0, 0, 0, 0); -} - -// -// ### function fromSeconds (seconds) -// #### @milliseconds {Number} Amount of seconds for the new TimeSpan instance. -// Creates a new `TimeSpan` instance with the specified `seconds`. -// -exports.fromSeconds = function (seconds) { - if (!isNumeric(seconds)) { return } - return new TimeSpan(0, seconds, 0, 0, 0); -}; - -// -// ### function fromMinutes (milliseconds) -// #### @milliseconds {Number} Amount of minutes for the new TimeSpan instance. -// Creates a new `TimeSpan` instance with the specified `minutes`. -// -exports.fromMinutes = function (minutes) { - if (!isNumeric(minutes)) { return } - return new TimeSpan(0, 0, minutes, 0, 0); -}; - -// -// ### function fromHours (hours) -// #### @milliseconds {Number} Amount of hours for the new TimeSpan instance. -// Creates a new `TimeSpan` instance with the specified `hours`. -// -exports.fromHours = function (hours) { - if (!isNumeric(hours)) { return } - return new TimeSpan(0, 0, 0, hours, 0); -}; - -// -// ### function fromDays (days) -// #### @milliseconds {Number} Amount of days for the new TimeSpan instance. -// Creates a new `TimeSpan` instance with the specified `days`. -// -exports.fromDays = function (days) { - if (!isNumeric(days)) { return } - return new TimeSpan(0, 0, 0, 0, days); -}; - -// -// ### function parse (str) -// #### @str {string} Timespan string to parse. -// Creates a new `TimeSpan` instance from the specified -// string, `str`. -// -exports.parse = function (str) { - var match, milliseconds; - - function parseMilliseconds (value) { - return value ? parseFloat('0' + value) * 1000 : 0; - } - - // If we match against a full TimeSpan: - // [days]:[hours]:[minutes]:[seconds].[milliseconds]? - if ((match = str.match(timeSpanWithDays))) { - return new TimeSpan(parseMilliseconds(match[5]), match[4], match[3], match[2], match[1]); - } - - // If we match against a partial TimeSpan: - // [hours]:[minutes]:[seconds].[milliseconds]? - if ((match = str.match(timeSpanNoDays))) { - return new TimeSpan(parseMilliseconds(match[4]), match[3], match[2], match[1], 0); - } - - return null; -}; - -// -// List of default singular time modifiers and associated -// computation algoritm. Assumes in order, smallest to greatest -// performing carry forward additiona / subtraction for each -// Date-Time component. -// -var parsers = { - 'milliseconds': { - exp: /(\d+)milli(?:second)?[s]?/i, - compute: function (delta, computed) { - return _compute(delta, computed, { - current: 'milliseconds', - next: 'seconds', - max: 1000 - }); - } - }, - 'seconds': { - exp: /(\d+)second[s]?/i, - compute: function (delta, computed) { - return _compute(delta, computed, { - current: 'seconds', - next: 'minutes', - max: 60 - }); - } - }, - 'minutes': { - exp: /(\d+)minute[s]?/i, - compute: function (delta, computed) { - return _compute(delta, computed, { - current: 'minutes', - next: 'hours', - max: 60 - }); - } - }, - 'hours': { - exp: /(\d+)hour[s]?/i, - compute: function (delta, computed) { - return _compute(delta, computed, { - current: 'hours', - next: 'days', - max: 24 - }); - } - }, - 'days': { - exp: /(\d+)day[s]?/i, - compute: function (delta, computed) { - var days = monthDays(computed.months, computed.years), - sign = delta >= 0 ? 1 : -1, - opsign = delta >= 0 ? -1 : 1, - clean = 0; - - function update (months) { - if (months < 0) { - computed.years -= 1; - return 11; - } - else if (months > 11) { - computed.years += 1; - return 0 - } - - return months; - } - - if (delta) { - while (Math.abs(delta) >= days) { - computed.months += sign * 1; - computed.months = update(computed.months); - delta += opsign * days; - days = monthDays(computed.months, computed.years); - } - - computed.days += (opsign * delta); - } - - if (computed.days < 0) { clean = -1 } - else if (computed.days > months[computed.months]) { clean = 1 } - - if (clean === -1 || clean === 1) { - computed.months += clean; - computed.months = update(computed.months); - computed.days = months[computed.months] + computed.days; - } - - return computed; - } - }, - 'months': { - exp: /(\d+)month[s]?/i, - compute: function (delta, computed) { - var round = delta > 0 ? Math.floor : Math.ceil; - if (delta) { - computed.years += round.call(null, delta / 12); - computed.months += delta % 12; - } - - if (computed.months > 11) { - computed.years += Math.floor((computed.months + 1) / 12); - computed.months = ((computed.months + 1) % 12) - 1; - } - - return computed; - } - }, - 'years': { - exp: /(\d+)year[s]?/i, - compute: function (delta, computed) { - if (delta) { computed.years += delta; } - return computed; - } - } -}; - -// -// Compute the list of parser names for -// later use. -// -var parserNames = Object.keys(parsers); - -// -// ### function parseDate (str) -// #### @str {string} String to parse into a date -// Parses the specified liberal Date-Time string according to -// ISO8601 **and**: -// -// 1. `2010-04-03T12:34:15Z+12MINUTES` -// 2. `NOW-4HOURS` -// -// Valid modifiers for the more liberal Date-Time string(s): -// -// YEAR, YEARS -// MONTH, MONTHS -// DAY, DAYS -// HOUR, HOURS -// MINUTE, MINUTES -// SECOND, SECONDS -// MILLI, MILLIS, MILLISECOND, MILLISECONDS -// -exports.parseDate = function (str) { - var dateTime = Date.parse(str), - iso = '^([^Z]+)', - zulu = 'Z([\\+|\\-])?', - diff = {}, - computed, - modifiers, - sign; - - // - // If Date string supplied actually conforms - // to UTC Time (ISO8601), return a new Date. - // - if (!isNaN(dateTime)) { - return new Date(dateTime); - } - - // - // Create the `RegExp` for the end component - // of the target `str` to parse. - // - parserNames.forEach(function (group) { - zulu += '(\\d+[a-zA-Z]+)?'; - }); - - if (/^NOW/i.test(str)) { - // - // If the target `str` is a liberal `NOW-*`, - // then set the base `dateTime` appropriately. - // - dateTime = Date.now(); - zulu = zulu.replace(/Z/, 'NOW'); - } - else { - // - // Parse the `ISO8601` component, and the end - // component from the target `str`. - // - dateTime = str.match(new RegExp(iso, 'i')); - dateTime = Date.parse(dateTime[1]); - } - - // - // If there was no match on either part then - // it must be a bad value. - // - if (!dateTime || !(modifiers = str.match(new RegExp(zulu, 'i')))) { - return null; - } - - // - // Create a new `Date` object from the `ISO8601` - // component of the target `str`. - // - dateTime = new Date(dateTime); - sign = modifiers[1] === '+' ? 1 : -1; - - // - // Create an Object-literal for consistently accessing - // the various components of the computed Date. - // - var computed = { - milliseconds: dateTime.getMilliseconds(), - seconds: dateTime.getSeconds(), - minutes: dateTime.getMinutes(), - hours: dateTime.getHours(), - days: dateTime.getDate(), - months: dateTime.getMonth(), - years: dateTime.getFullYear() - }; - - // - // Parse the individual component spans (months, years, etc) - // from the modifier strings that we parsed from the end - // of the target `str`. - // - modifiers.slice(2).filter(Boolean).forEach(function (modifier) { - parserNames.forEach(function (name) { - var match; - if (!(match = modifier.match(parsers[name].exp))) { - return; - } - - diff[name] = sign * parseInt(match[1], 10); - }) - }); - - // - // Compute the total `diff` by iteratively computing - // the partial components from smallest to largest. - // - parserNames.forEach(function (name) { - computed = parsers[name].compute(diff[name], computed); - }); - - return new Date( - Date.UTC( - computed.years, - computed.months, - computed.days, - computed.hours, - computed.minutes, - computed.seconds, - computed.milliseconds - ) - ); -}; - -// -// ### function fromDates (start, end, abs) -// #### @start {Date} Start date of the `TimeSpan` instance to return -// #### @end {Date} End date of the `TimeSpan` instance to return -// #### @abs {boolean} Value indicating to return an absolute value -// Returns a new `TimeSpan` instance representing the difference between -// the `start` and `end` Dates. -// -exports.fromDates = function (start, end, abs) { - if (typeof start === 'string') { - start = exports.parseDate(start); - } - - if (typeof end === 'string') { - end = exports.parseDate(end); - } - - if (!(start instanceof Date && end instanceof Date)) { - return null; - } - - var differenceMsecs = end.valueOf() - start.valueOf(); - if (abs) { - differenceMsecs = Math.abs(differenceMsecs); - } - - return new TimeSpan(differenceMsecs, 0, 0, 0, 0); -}; - -// -// ## Module Helpers -// Module-level helpers for various utilities such as: -// instanceOf, parsability, and cloning. -// - -// -// ### function test (str) -// #### @str {string} String value to test if it is a TimeSpan -// Returns a value indicating if the specified string, `str`, -// is a parsable `TimeSpan` value. -// -exports.test = function (str) { - return timeSpanWithDays.test(str) || timeSpanNoDays.test(str); -}; - -// -// ### function instanceOf (timeSpan) -// #### @timeSpan {Object} Object to check TimeSpan quality. -// Returns a value indicating if the specified `timeSpan` is -// in fact a `TimeSpan` instance. -// -exports.instanceOf = function (timeSpan) { - return timeSpan instanceof TimeSpan; -}; - -// -// ### function clone (timeSpan) -// #### @timeSpan {TimeSpan} TimeSpan object to clone. -// Returns a new `TimeSpan` instance with the same value -// as the `timeSpan` object supplied. -// -exports.clone = function (timeSpan) { - if (!(timeSpan instanceof TimeSpan)) { return } - return exports.fromMilliseconds(timeSpan.totalMilliseconds()); -}; - -// -// ## Addition -// Methods for adding `TimeSpan` instances, -// milliseconds, seconds, hours, and days to other -// `TimeSpan` instances. -// - -// -// ### function add (timeSpan) -// #### @timeSpan {TimeSpan} TimeSpan to add to this instance -// Adds the specified `timeSpan` to this instance. -// -TimeSpan.prototype.add = function (timeSpan) { - if (!(timeSpan instanceof TimeSpan)) { return } - this.msecs += timeSpan.totalMilliseconds(); -}; - -// -// ### function addMilliseconds (milliseconds) -// #### @milliseconds {Number} Number of milliseconds to add. -// Adds the specified `milliseconds` to this instance. -// -TimeSpan.prototype.addMilliseconds = function (milliseconds) { - if (!isNumeric(milliseconds)) { return } - this.msecs += milliseconds; -}; - -// -// ### function addSeconds (seconds) -// #### @seconds {Number} Number of seconds to add. -// Adds the specified `seconds` to this instance. -// -TimeSpan.prototype.addSeconds = function (seconds) { - if (!isNumeric(seconds)) { return } - - this.msecs += (seconds * msecPerSecond); -}; - -// -// ### function addMinutes (minutes) -// #### @minutes {Number} Number of minutes to add. -// Adds the specified `minutes` to this instance. -// -TimeSpan.prototype.addMinutes = function (minutes) { - if (!isNumeric(minutes)) { return } - this.msecs += (minutes * msecPerMinute); -}; - -// -// ### function addHours (hours) -// #### @hours {Number} Number of hours to add. -// Adds the specified `hours` to this instance. -// -TimeSpan.prototype.addHours = function (hours) { - if (!isNumeric(hours)) { return } - this.msecs += (hours * msecPerHour); -}; - -// -// ### function addDays (days) -// #### @days {Number} Number of days to add. -// Adds the specified `days` to this instance. -// -TimeSpan.prototype.addDays = function (days) { - if (!isNumeric(days)) { return } - this.msecs += (days * msecPerDay); -}; - -// -// ## Subtraction -// Methods for subtracting `TimeSpan` instances, -// milliseconds, seconds, hours, and days from other -// `TimeSpan` instances. -// - -// -// ### function subtract (timeSpan) -// #### @timeSpan {TimeSpan} TimeSpan to subtract from this instance. -// Subtracts the specified `timeSpan` from this instance. -// -TimeSpan.prototype.subtract = function (timeSpan) { - if (!(timeSpan instanceof TimeSpan)) { return } - this.msecs -= timeSpan.totalMilliseconds(); -}; - -// -// ### function subtractMilliseconds (milliseconds) -// #### @milliseconds {Number} Number of milliseconds to subtract. -// Subtracts the specified `milliseconds` from this instance. -// -TimeSpan.prototype.subtractMilliseconds = function (milliseconds) { - if (!isNumeric(milliseconds)) { return } - this.msecs -= milliseconds; -}; - -// -// ### function subtractSeconds (seconds) -// #### @seconds {Number} Number of seconds to subtract. -// Subtracts the specified `seconds` from this instance. -// -TimeSpan.prototype.subtractSeconds = function (seconds) { - if (!isNumeric(seconds)) { return } - this.msecs -= (seconds * msecPerSecond); -}; - -// -// ### function subtractMinutes (minutes) -// #### @minutes {Number} Number of minutes to subtract. -// Subtracts the specified `minutes` from this instance. -// -TimeSpan.prototype.subtractMinutes = function (minutes) { - if (!isNumeric(minutes)) { return } - this.msecs -= (minutes * msecPerMinute); -}; - -// -// ### function subtractHours (hours) -// #### @hours {Number} Number of hours to subtract. -// Subtracts the specified `hours` from this instance. -// -TimeSpan.prototype.subtractHours = function (hours) { - if (!isNumeric(hours)) { return } - this.msecs -= (hours * msecPerHour); -}; - -// -// ### function subtractDays (days) -// #### @days {Number} Number of days to subtract. -// Subtracts the specified `days` from this instance. -// -TimeSpan.prototype.subtractDays = function (days) { - if (!isNumeric(days)) { return } - this.msecs -= (days * msecPerDay); -}; - -// -// ## Getters -// Methods for retrieving components of a `TimeSpan` -// instance: milliseconds, seconds, minutes, hours, and days. -// - -// -// ### function totalMilliseconds (roundDown) -// #### @roundDown {boolean} Value indicating if the value should be rounded down. -// Returns the total number of milliseconds for this instance, rounding down -// to the nearest integer if `roundDown` is set. -// -TimeSpan.prototype.totalMilliseconds = function (roundDown) { - var result = this.msecs; - if (roundDown === true) { - result = Math.floor(result); - } - - return result; -}; - -// -// ### function totalSeconds (roundDown) -// #### @roundDown {boolean} Value indicating if the value should be rounded down. -// Returns the total number of seconds for this instance, rounding down -// to the nearest integer if `roundDown` is set. -// -TimeSpan.prototype.totalSeconds = function (roundDown) { - var result = this.msecs / msecPerSecond; - if (roundDown === true) { - result = Math.floor(result); - } - - return result; -}; - -// -// ### function totalMinutes (roundDown) -// #### @roundDown {boolean} Value indicating if the value should be rounded down. -// Returns the total number of minutes for this instance, rounding down -// to the nearest integer if `roundDown` is set. -// -TimeSpan.prototype.totalMinutes = function (roundDown) { - var result = this.msecs / msecPerMinute; - if (roundDown === true) { - result = Math.floor(result); - } - - return result; -}; - -// -// ### function totalHours (roundDown) -// #### @roundDown {boolean} Value indicating if the value should be rounded down. -// Returns the total number of hours for this instance, rounding down -// to the nearest integer if `roundDown` is set. -// -TimeSpan.prototype.totalHours = function (roundDown) { - var result = this.msecs / msecPerHour; - if (roundDown === true) { - result = Math.floor(result); - } - - return result; -}; - -// -// ### function totalDays (roundDown) -// #### @roundDown {boolean} Value indicating if the value should be rounded down. -// Returns the total number of days for this instance, rounding down -// to the nearest integer if `roundDown` is set. -// -TimeSpan.prototype.totalDays = function (roundDown) { - var result = this.msecs / msecPerDay; - if (roundDown === true) { - result = Math.floor(result); - } - - return result; -}; - -// -// ### @milliseconds -// Returns the length of this `TimeSpan` instance in milliseconds. -// -TimeSpan.prototype.__defineGetter__('milliseconds', function () { - return this.msecs % 1000; -}); - -// -// ### @seconds -// Returns the length of this `TimeSpan` instance in seconds. -// -TimeSpan.prototype.__defineGetter__('seconds', function () { - return Math.floor(this.msecs / msecPerSecond) % 60; -}); - -// -// ### @minutes -// Returns the length of this `TimeSpan` instance in minutes. -// -TimeSpan.prototype.__defineGetter__('minutes', function () { - return Math.floor(this.msecs / msecPerMinute) % 60; -}); - -// -// ### @hours -// Returns the length of this `TimeSpan` instance in hours. -// -TimeSpan.prototype.__defineGetter__('hours', function () { - return Math.floor(this.msecs / msecPerHour) % 24; -}); - -// -// ### @days -// Returns the length of this `TimeSpan` instance in days. -// -TimeSpan.prototype.__defineGetter__('days', function () { - return Math.floor(this.msecs / msecPerDay); -}); - -// -// ## Instance Helpers -// Various help methods for performing utilities -// such as equality and serialization -// - -// -// ### function equals (timeSpan) -// #### @timeSpan {TimeSpan} TimeSpan instance to assert equal -// Returns a value indicating if the specified `timeSpan` is equal -// in milliseconds to this instance. -// -TimeSpan.prototype.equals = function (timeSpan) { - if (!(timeSpan instanceof TimeSpan)) { return } - return this.msecs === timeSpan.totalMilliseconds(); -}; - -// -// ### function toString () -// Returns a string representation of this `TimeSpan` -// instance according to current `format`. -// -TimeSpan.prototype.toString = function () { - if (!this.format) { return this._format() } - return this.format(this); -}; - -// -// ### @private function _format () -// Returns the default string representation of this instance. -// -TimeSpan.prototype._format = function () { - return [ - this.days, - this.hours, - this.minutes, - this.seconds + '.' + this.milliseconds - ].join(':') -}; - -// -// ### @private function isNumeric (input) -// #### @input {Number} Value to check numeric quality of. -// Returns a value indicating the numeric quality of the -// specified `input`. -// -function isNumeric (input) { - return input && !isNaN(parseFloat(input)) && isFinite(input); -}; - -// -// ### @private function _compute (delta, date, computed, options) -// #### @delta {Number} Channge in this component of the date -// #### @computed {Object} Currently computed date. -// #### @options {Object} Options for the computation -// Performs carry forward addition or subtraction for the -// `options.current` component of the `computed` date, carrying -// it forward to `options.next` depending on the maximum value, -// `options.max`. -// -function _compute (delta, computed, options) { - var current = options.current, - next = options.next, - max = options.max, - round = delta > 0 ? Math.floor : Math.ceil; - - if (delta) { - computed[next] += round.call(null, delta / max); - computed[current] += delta % max; - } - - if (Math.abs(computed[current]) >= max) { - computed[next] += round.call(null, computed[current] / max) - computed[current] = computed[current] % max; - } - - return computed; -} - - -// -// ### @private monthDays (month, year) -// #### @month {Number} Month to get days for. -// #### @year {Number} Year of the month to get days for. -// Returns the number of days in the specified `month` observing -// leap years. -// -var months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -function monthDays (month, year) { - if (((year % 100 !== 0 && year % 4 === 0) - || year % 400 === 0) && month === 1) { - return 29; - } - - return months[month]; -} \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/package.json b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/package.json deleted file mode 100644 index 0dddb8ca2..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "timespan", - "description": "A JavaScript TimeSpan library for node.js (and soon the browser)", - "version": "2.2.0", - "author": { - "name": "Michael Stum", - "email": "blog@stum.de" - }, - "contributors": [ - { - "name": "Charlie Robbins", - "email": "charlie.robbins@gmail.com" - } - ], - "repository": { - "type": "git", - "url": "http://github.com/indexzero/timespan.git" - }, - "keywords": [ - "time", - "dates", - "utilities", - "timespan" - ], - "devDependencies": { - "vows": ">= 0.5.2" - }, - "main": "./lib/time-span.js", - "scripts": { - "test": "vows test/*-test.js --spec" - }, - "engines": { - "node": ">= 0.2.0" - }, - "readme": "# timespan\n\nA simple implementation of TimeSpans in Javascript.\n\n## Installation in node.js\n\n### Installing npm (node package manager)\n``` bash\n $ curl http://npmjs.org/install.sh | sh\n```\n\n### Installing timespan\n``` bash\n [sudo] npm install timespan\n```\n\n## Usage \nYou have two options when creating a new TimeSpan object: either explicitly instantiate it using the TimeSpan constructor function or use a helper method to create from a specific length of time.\n\n### Using the new constructor\n\n``` js\n var timespan = require('timespan');\n var ts = new timespan.TimeSpan();\n```\n\nThe constructor takes 5 parameters, all which are optional and which can be used to initialize the TimeSpan to a given value. These parameters are: `milliseconds`, `seconds`, `minutes`, `hours`, `days`.\n\n``` js\n //\n // Initializes the TimeSpan to 4 Minutes, 16 Seconds and 0 Milliseconds.\n //\n var ts = new TimeSpan(0,16,4)\n\n //\n // Initializes the TimeSpan to 3 hours, 4 minutes, 10 seconds and 0 msecs.\n //\n var ts = new TimeSpan(0,10,64,2);\n```\n\n### Using Construction Helper Method(s) \nYou can initialize a new TimeSpan by calling one of these Functions:\n\n``` js\n timespan.FromSeconds(/* seconds */);\n timespan.FromMinutes(/* minutes */);\n timespan.FromHours(/* hours */);\n timespan.FromDays(/* hours */);\n \n //\n // This behaves differently, see below\n //\n timespan.FromDates(start, end);\n```\n\nThe first four helper methods take a single numeric parameter and create a new TimeSpan instance. e.g. `timespan.FromSeconds(45)` is equivalent to `new TimeSpan(0,45)`. If the parameter is invalid/not a number, it will just be treated as 0 no error will be thrown.\n\n`timespan.FromDates()` is different as it takes two dates. The TimeSpan will be the difference between these dates.\n\nIf the second date is earlier than the first date, the TimeSpan will have a negative value. You can pass in \"true\" as the third parameter to force the TimeSpan to be positive always.\n\n``` js\n var date1 = new Date(2010, 3, 1, 10, 10, 5, 0);\n var date2 = new Date(2010, 3, 1, 10, 10, 10, 0);\n var ts = TimeSpan.FromDates(date2, date1);\n var ts2 = TimeSpan.FromDates(date2, date1, true);\n \n //\n // -5, because we put the later date first\n //\n console.log(ts.totalSeconds()); \n \n //\n // 5, because we passed true as third parameter\n //\n console.log(ts2.totalSeconds()); \n```\n\n\n### Adding / Subtracting TimeSpans\nThere are several functions to add or subtract time:\n\n``` js\n ts.addMilliseconds()\n ts.addSeconds()\n ts.addMinutes()\n ts.addHours()\n ts.addDays()\n ts.subtractMilliseconds()\n ts.subtractSeconds()\n ts.subtractMinutes()\n ts.subtractHours()\n ts.subtractDays()\n```\n\nAll these functions take a single numeric parameter. If the parameter is invalid, not a number, or missing it will be ignored and no Error is thrown.\n\n``` js\n var ts = new TimeSpan();\n ts.addSeconds(30);\n ts.addMinutes(2);\n ts.subtractSeconds(60);\n \n //\n // ts will now be a timespan of 1 minute and 30 seconds\n //\n```\n\nThe parameter can be negative to negate the operation `ts.addSeconds(-30)` is equivalent to `ts.subtractSeconds(30)`.\n\n### Interacting with Other TimeSpan instances\nThese are the functions that interact with another TimeSpan:\n\n``` js\n ts.add()\n ts.subtract()\n ts.equals()\n```\n\nadd and subtract add/subtract the other TimeSpan to the current one:\n\n``` js\n var ts = TimeSpan.FromSeconds(30);\n var ts2 = TimeSpan.FromMinutes(2);\n ts.add(ts2);\n \n //\n // ts is now a TimeSpan of 2 Minutes, 30 Seconds\n // ts2 is unchanged\n //\n```\n\nequals checks if two TimeSpans have the same time:\n\n``` js\n var ts = TimeSpan.FromSeconds(30);\n var ts2 = TimeSpan.FromSeconds(30);\n var eq = ts.equals(ts2); // true\n ts2.addSeconds(1);\n var eq2 = ts.equals(ts2); // false\n```\n\n### Retrieving the Value of a TimeSpan\nThere are two sets of functions to retreive the function of the TimeSpan: those that deal with the full value in various measurements and another that gets the individual components.\n\n#### Retrieve the full value\n\n``` js\n ts.totalMilliseconds()\n ts.totalSeconds()\n ts.totalMinutes()\n ts.totalHours()\n ts.totalDays()\n```\n\nThese functions convert the value to the given format and return it. The result can be a floating point number. These functions take a single parameter roundDown which can be set to true to round the value down to an Integer.\n\n``` js\n var ts = TimeSpan.fromSeconds(90);\n console.log(ts.totalMilliseconds()); // 90000\n console.log(ts.totalSeconds()); // 90\n console.log(ts.totalMinutes()); // 1.5\n console.log(ts.totalMinutes(true)); // 1\n```\n\n#### Retrieve a component of the TimeSpan\n\n``` js\n ts.milliseconds\n ts.seconds\n ts.minutes\n ts.hours\n ts.days\n```\n\nThese functions return a component of the TimeSpan that could be used to represent a clock. \n\n``` js\n var ts = TimeSpan.FromSeconds(90);\n console.log(ts.seconds()); // 30\n console.log(ts.minutes()); // 1\n```\n\nBasically these value never \"overflow\" - seconds will only return 0 to 59, hours only 0 to 23 etc. Days could grow infinitely. All of these functions automatically round down the result:\n\n``` js\n var ts = TimeSpan.FromDays(2);\n ts.addHours(12);\n console.log(ts.days()); // 2\n console.log(ts.hours()); // 12\n```\n\n## Remark about Backwards Compatibility\nVersion 0.2.x was designed to work with [node.js][0] and backwards compatibility to the browser-based usage was not considered a high priority. This will be fixed in future versions, but for now if you need to use this in the browser, you can find the 0.1.x code under `/browser`.\n\n#### Author: [Michael Stum](http://www.stum.de)\n#### Contributors: [Charlie Robbins](http://github.com/indexzero)\n\n[0]: http://nodejs.org ", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/indexzero/timespan/issues" - }, - "_id": "timespan@2.2.0", - "_from": "timespan@2.x.x" -} diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/test/date-parser-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/test/date-parser-test.js deleted file mode 100644 index 6f08973ad..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/test/date-parser-test.js +++ /dev/null @@ -1,72 +0,0 @@ -/* - * time-span-test.js: Tests for the TimeSpan module. - * - * (C) Charlie Robbins - * MIT LICENSE - * - */ - -var vows = require('vows'), - assert = require('assert'), - timeSpan = require('../lib/time-span'); - -vows.describe('time-span/date-time').addBatch({ - "When using the TimeSpan module": { - "the parseDate() method": { - "when passed a TimeSpan string using ISO8601 with explicit time modifiers": { - "which do not carry over": { - "should return the correct value": function () { - var target = new Date(Date.parse('2010-04-03T10:04:15Z')), - parsed = timeSpan.parseDate('2010-04-03T12:34:15Z-2HOURS30MINUTES'); - - assert.equal(target.toString(), parsed.toString()); - } - }, - "which carry under": { - "should return the correct value": function () { - var target = new Date(Date.parse('2010-03-29T12:34:15Z')), - parsed = timeSpan.parseDate('2010-04-01T12:34:15Z-72HOURS'); - - assert.equal(target.toString(), parsed.toString()); - } - }, - "which carry under a leap year": { - "should return the correct value": function () { - var target = new Date(Date.parse('2007-03-31T12:00:00Z')), - parsed = timeSpan.parseDate('2010-03-31T12:00:00Z-1096DAYS'); - - assert.equal(target.toString(), parsed.toString()); - } - }, - "which carry over": { - "should return the correct value": function () { - var target = new Date(Date.parse('2013-04-03T12:34:15Z')), - parsed = timeSpan.parseDate('2010-04-03T12:34:15Z+2YEARS365DAYS'); - - assert.equal(target.toString(), parsed.toString()); - } - } - }, - "when passed a TimeSpan string using NOW with explicit time modifiers": { - "which do not carry over": { - "should return the correct value": function () { - var now = new Date(Date.now()), - parsed = timeSpan.parseDate('NOW-2HOURS'); - - now.setHours(now.getHours() - 2 - (now.getTimezoneOffset() / 60)); - assert.equal(now.getHours(), parsed.getHours()); - } - }, - "which carry under": { - "should return the correct value": function () { - var now = new Date(Date.now()), - parsed = timeSpan.parseDate('NOW-72HOURS'); - - now.setHours(now.getHours() - 72 - (now.getTimezoneOffset() / 60)); - assert.equal(now.getHours(), parsed.getHours()); - } - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/test/helpers.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/test/helpers.js deleted file mode 100644 index 4a1b84aa8..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/test/helpers.js +++ /dev/null @@ -1,36 +0,0 @@ -/* - * helpers.js: Tests helpers for the TimeSpan module. - * - * (C) Charlie Robbins - * MIT LICENSE - * - */ - -var assert = require('assert'), - timeSpan = require('../lib/time-span') - -function capitalize(str) { - return str.charAt(0).toUpperCase() + str.slice(1); -} - -var helpers = exports, - components = ['milliseconds', 'seconds', 'minutes', 'hours', 'days']; - -// -// Tests all of the factory methods for the `TimeSpan` object: -// `fromMilliseconds`, `fromSeconds`, etc. -// -exports.testFactories = function (num) { - var context = {}; - - components.forEach(function (component) { - var method = 'from' + capitalize(component); - - context['the ' + method + '() method'] = function () { - var value = timeSpan[method](num); - assert.equal(value[component], num); - } - }); - - return context; -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/test/time-span-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/test/time-span-test.js deleted file mode 100644 index 66a7be518..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/node_modules/timespan/test/time-span-test.js +++ /dev/null @@ -1,68 +0,0 @@ -/* - * time-span-test.js: Tests for the TimeSpan module. - * - * (C) Charlie Robbins - * MIT LICENSE - * - */ - -var vows = require('vows'), - assert = require('assert'), - timeSpan = require('../lib/time-span'), - helpers = require('./helpers'); - -vows.describe('time-span').addBatch({ - "When using the TimeSpan module": { - "the parse() method": { - "when passed a TimeSpan string with no days": { - "should return a valid TimeSpan object": function () { - var ts = timeSpan.parse("04:03:02.10"); - assert.equal(ts.hours, 4); - assert.equal(ts.minutes, 3); - assert.equal(ts.seconds, 2); - assert.equal(ts.milliseconds, 100); - } - }, - "when passed a TimeSpan string with days": { - "should return a valid TimeSpan object": function () { - var ts = timeSpan.parse("01:04:03:02.10"); - assert.equal(ts.days, 1); - assert.equal(ts.hours, 4); - assert.equal(ts.minutes, 3); - assert.equal(ts.seconds, 2); - assert.equal(ts.milliseconds, 100); - } - } - }, - "the test() method": { - "when passed a TimeSpan string with no days": { - "should return true": function () { - assert.isTrue(timeSpan.test("04:03:02.10")); - } - }, - "when passed a TimeSpan string with days": { - "should return true": function () { - assert.isTrue(timeSpan.test("01:04:03:02.10")); - } - }, - "when passed an invalid TimeSpan string": { - "should return false": function () { - assert.isFalse(timeSpan.test('xx:00:invalid')); - } - } - }, - "the fromDates() method": { - "with two Date values": function () { - var diff = 1000 * 60 * 60 * 12, - end = new Date(), - start = new Date(end.getTime() - diff); - - assert.equal(12, timeSpan.fromDates(start, end).hours); - }, - "with two string values": function () { - assert.equal(2, timeSpan.fromDates('NOW-4DAYS', 'NOW-2DAYS').days); - } - }, - "the factory methods": helpers.testFactories(10) - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/package.json b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/package.json deleted file mode 100644 index 661c834a8..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/package.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "name": "loggly", - "description": "A client implementation for Loggly cloud Logging-as-a-Service API", - "version": "0.3.11", - "author": { - "name": "Charlie Robbins", - "email": "charlie.robbins@gmail.com" - }, - "contributors": [ - { - "name": "Marak Squires", - "email": "marak.squires@gmail.com" - }, - { - "name": "hij1nx", - "email": "hij1nx@me.com" - }, - { - "name": "Kord Campbell", - "email": "kordless@loggly.com" - }, - { - "name": "Erik Hedenstrom", - "email": "erik@hedenstroem.com" - } - ], - "repository": { - "type": "git", - "url": "http://github.com/nodejitsu/node-loggly.git" - }, - "keywords": [ - "cloud computing", - "api", - "logging", - "loggly" - ], - "dependencies": { - "request": "2.9.x", - "timespan": "2.x.x" - }, - "devDependencies": { - "vows": "0.6.x" - }, - "main": "./lib/loggly", - "scripts": { - "test": "vows test/*-test.js --spec" - }, - "engines": { - "node": ">= 0.4.0" - }, - "readme": "# node-loggly\n\nA client implementation for Loggly in node.js\n\n## Installation\n\n### Installing npm (node package manager)\n``` bash\n $ curl http://npmjs.org/install.sh | sh\n```\n\n### Installing node-loggly\n``` bash\n $ [sudo] npm install loggly\n```\n\n## Usage\n\nThe node-loggly library is compliant with the [Loggly API][0]. Using node-loggly is easy for a variety of scenarios: logging, working with devices and inputs, searching, and facet searching.\n\n### Getting Started\nBefore we can do anything with Loggly, we have to create a client with valid credentials. We will authenticate for you automatically: \n\n``` js\n var loggly = require('loggly');\n var config = {\n subdomain: \"your-subdomain\",\n auth: {\n username: \"your-username\",\n password: \"your-password\"\n }\n };\n var client = loggly.createClient(config);\n```\n\n### Logging\nThere are two ways to send log information to Loggly via node-loggly. The first is to simply call client.log with an appropriate input token:\n\n``` js\n client.log('your-really-long-input-token', '127.0.0.1 - Theres no place like home', function (err, result) {\n // Do something once you've logged\n });\n```\n\nNote that the callback in the above example is optional, if you prefer the 'fire and forget' method of logging:\n\n``` js\n client.log('your-really-long-input-token', '127.0.0.1 - Theres no place like home');\n```\n\nThe second way to send log information to Loggly is to do so once you've retrieved an input directly from Loggly:\n\n``` js\n client.getInput('your-input-name', function (err, input) {\n input.log('127.0.0.1 - Theres no place like home');\n });\n```\n\nAgain the callback in the above example is optional and you can pass it if you'd like to.\n\n### Logging Shallow JSON Object Literals as a String\nIn addition to logging pure strings it is also possible to pass shallow JSON object literals (i.e. no nested objects) to client.log(..) or input.log(..) methods, which will get converted into the [Loggly recommended string representation][1]. So\n\n``` js\n var source = {\n foo: 1,\n bar: 2,\n buzz: 3\n };\n \n input.log(source);\n```\n\nwill be logged as: \n\n```\n foo=1,bar=2,buzz=3\n```\n\n### Logging Objects to JSON Enabled Loggly Inputs\nIt is also possible to log complex objects using the new JSON capabilities of Loggly. To enable JSON functionality in the client simply add 'json: true' to the configuration:\n\n``` js\n var config = {\n subdomain: \"your-subdomain\",\n auth: {\n username: \"your-username\",\n password: \"your-password\"\n },\n json: true\n };\n```\n\nWhen the json flag is enabled, objects will be converted to JSON using JSON.stringify before being transmitted to Loggly. So\n\n``` js\n var source = {\n foo: 1,\n bar: 2,\n buzz: {\n sheep: 'jumped',\n times: 10\n }\n };\n\n input.log(source);\n```\n\nwill be logged as:\n\n``` json\n { \"foo\": 1, \"bar\": 2, \"buzz\": {\"sheep\": \"jumped\", \"times\": 10 }}\n```\n\n### Searching\n[Searching][3] with node-loggly is easy. All you have to do is use the search() method defined on each Loggly client:\n\n``` js\n var util = require('util');\n \n client.search('404', function (err, results) {\n // Inspect the result set\n util.inspect(results.data);\n });\n```\n\nThe search() exposes a chainable interface that allows you to set additional search parameters such as: ip, input name, rows, start, end, etc. \n\n``` js\n var util = require('util');\n \n client.search('404')\n .meta({ ip: '127.0.0.1', inputname: test })\n .context({ rows: 10 })\n .run(function (err, results) {\n // Inspect the result set\n util.inspect(results.data);\n });\n```\n\nThe context of the search (set using the `.context()` method) represents additional parameters in the Loggly API besides the search query itself. See the [Search API documentation][9] for a list of all options.\n\nMetadata set using the `.meta()` method is data that is set in the query parameter of your Loggly search, but `:` delimited. For more information about search queries in Loggly, check out the [Search Language Guide][4] on the [Loggly Wiki][5].\n\n### Facet Searching\nLoggly also exposes searches that can return counts of events over a time range. These are called [facets][6]. The valid facets are 'ip', 'date', and 'input'. Performing a facet search is very similar to a normal search: \n\n``` js\n var util = require('util');\n \n client.facet('ip', '404')\n .context({ buckets: 10 })\n .run(function (err, results) {\n // Inspect the result set\n util.inspect(results.data);\n });\n```\n\nThe chaining and options for the facet method(s) are the same as the search method above. \n\n### Working with Devices and Inputs\nLoggly exposes several entities that are available through node-loggly: inputs and devices. For more information about these terms, checkout the [Loggly Jargon][7] on the wiki. There are several methods available in node-loggly to work with these entities: \n\n``` js\n //\n // Returns all inputs associated with your account\n //\n client.getInputs(function (err, inputs) { /* ... */ });\n \n //\n // Returns an input with the specified name\n //\n client.getInput('input-name', function (err, input) { /* ... */ });\n \n //\n // Returns all devices associated with your account\n //\n client.getDevices(function (err, devices) { /* ... */ });\n```\n\n## Run Tests\nAll of the node-loggly tests are written in [vows][8], and cover all of the use cases described above. You will need to add your Loggly username, password, subdomain, and a two test inputs to test/data/test-config.json before running tests. When configuring the test inputs on Loggly, the first test input should be named 'test' using the HTTP service. The second input should be name 'test_json' using the HTTP service with the JSON logging option enabled:\n\n``` js\n {\n \"subdomain\": \"your-subdomain\",\n \"auth\": {\n \"username\": \"your-username\",\n \"password\": \"your-password\"\n },\n \"inputs\": {\n \"test\": {\n //\n // Token and ID of your plain-text input.\n //\n \"token\": \"your-really-long-token-you-got-when-you-created-an-http-input\",\n \"id\": 000\n },\n \"test_json\": {\n //\n // Token and ID of your JSON input.\n //\n \"token\": \"your-really-long-token-you-got-when-you-created-an-http-input\",\n \"id\": 001\n },\n }\n }\n```\n\nOnce you have valid Loggly credentials you can run tests with [vows][8]:\n\n``` bash\n $ npm test\n```\n\n#### Author: [Charlie Robbins](http://www.github.com/indexzero)\n#### Contributors: [Marak Squires](http://github.com/marak), [hij1nx](http://github.com/hij1nx), [Kord Campbell](http://loggly.com), [Erik Hedenström](http://github.com/ehedenst),\n\n[0]: http://wiki.loggly.com/apidocumentation\n[1]: http://wiki.loggly.com/loggingfromcode\n[3]: http://wiki.loggly.com/retrieve_events#search_uri\n[4]: http://wiki.loggly.com/searchguide\n[5]: http://wiki.loggly.com/\n[6]: http://wiki.loggly.com/retrieve_events#facet_uris\n[7]: http://wiki.loggly.com/loggingjargon\n[8]: http://vowsjs.org\n[9]: http://wiki.loggly.com/retrieve_events#optional\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/nodejitsu/node-loggly/issues" - }, - "_id": "loggly@0.3.11", - "_from": "loggly@0.3.x >=0.3.7" -} diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/common-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/common-test.js deleted file mode 100644 index 51c6b4abf..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/common-test.js +++ /dev/null @@ -1,32 +0,0 @@ -/* - * common-test.js: Tests for Loggly `common` utility module - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - common = require('../lib/loggly/common'); - -vows.describe('node-loggly/common').addBatch({ - "When using the common module": { - "the clone() method": { - topic: function () { - this.obj = { - name: 'common', - deep: { - first: 'first', - second: 'second' - } - }; - return common.clone(this.obj); - }, - "should return a deep clone of the object": function (clone) { - assert.isFalse(this.obj.deep === clone.deep); - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/device-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/device-test.js deleted file mode 100644 index 81241805a..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/device-test.js +++ /dev/null @@ -1,41 +0,0 @@ -/* - * device-test.js: Tests for Loggly device requests - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - helpers = require('./helpers'); - -var options = {}, - config = helpers.loadConfig(), - loggly = require('../lib/loggly').createClient(config); - -vows.describe('node-loggly/devices').addBatch({ - "When using the node-loggly client": { - "the getDevices() method": { - topic: function () { - loggly.getDevices(this.callback); - }, - "should return a list of valid devices": function (err, devices) { - assert.isNull(err); - devices.forEach(function (device) { - helpers.assertDevice(device); - }); - } - }, - "the addDeviceToInput() method": { - topic: function () { - loggly.addDeviceToInput(config.inputs.test.id, '127.0.0.1', this.callback); - }, - "should respond with 200 status code": function (err, res) { - assert.isNull(err); - assert.equal(res.statusCode, 200); - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/helpers.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/helpers.js deleted file mode 100644 index b8ed45c0e..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/helpers.js +++ /dev/null @@ -1,79 +0,0 @@ -/* - * helpers.js: Test helpers for node-loggly - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var fs = require('fs'), - util = require('util'), - path = require('path'), - vows = require('vows'), - assert = require('assert'), - loggly = require('../lib/loggly'); - -var helpers = exports; - -helpers.validConfig = function (config) { - return config - && config.subdomain !== 'test-subdomain' - && config.auth - && config.auth.username !== 'test-username' - && config.auth.password !== 'test-password' - && config.inputs - && config.inputs.test - && config.inputs.test_json; -}; - -helpers.loadConfig = function () { - try { - var configFile = path.join(__dirname, 'data', 'test-config.json'), - stats = fs.statSync(configFile) - config = JSON.parse(fs.readFileSync(configFile).toString()); - - if (!helpers.validConfig(config)) { - util.puts('Config file test-config.json must be updated with valid data before running tests'); - process.exit(0); - } - - helpers.config = config || {} - return config || {}; - } - catch (ex) { - util.puts('Error parsing test-config.json'); - ex.stack.split('\n').forEach(function (line) { - console.log(line); - }); - - process.exit(0); - } -}; - -helpers.assertInput = function (input) { - assert.instanceOf(input, loggly.Input); - assert.isNotNull(input.id); - assert.isNotNull(input.name); - assert.isNotNull(input.service); - assert.isNotNull(input.create); - assert.isNotNull(input.discover); - assert.isNotNull(input.discoverTime); - assert.isNotNull(input.description); -}; - -helpers.assertDevice = function (device) { - assert.instanceOf(device, loggly.Device); - assert.isNotNull(device.id); - assert.isNotNull(device.input); - assert.isNotNull(device.ipAddress); - assert.isNotNull(device.launched); - assert.isNotNull(device.resourceUri); -}; - -helpers.assertSearch = function (err, results) { - assert.isNull(err); - assert.isObject(results); - assert.isTrue(typeof results.data !== 'undefined'); - assert.isTrue(typeof results.numFound !== 'undefined'); - assert.isTrue(typeof results.context !== 'undefined'); -}; diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/input-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/input-test.js deleted file mode 100644 index 06cd76348..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/input-test.js +++ /dev/null @@ -1,197 +0,0 @@ -/* - * input-test.js: Tests for Loggly input requests - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - helpers = require('./helpers'); - -var options = {}, - testContext = {}, - config = helpers.loadConfig(), - loggly = require('../lib/loggly').createClient(config), - logglyJSON = require('../lib/loggly').createClient(config); - -logglyJSON.config.json = true; - -vows.describe('node-loggly/inputs').addBatch({ - "When using the node-loggly client": { - "the getInputs() method": { - topic: function () { - loggly.getInputs(this.callback); - }, - "should return a list of valid inputs": function (err, inputs) { - assert.isNull(err); - inputs.forEach(function (input) { - helpers.assertInput(input); - }); - } - }, - "the getInput method": { - "when called with a plaintext input": { - topic: function () { - loggly.getInput('test', this.callback); - }, - "should return a valid input": function (err, input) { - assert.isNull(err); - helpers.assertInput(input); - }, - "of the format 'text'": function (err, input) { - assert.isNull(err); - assert.equal(input.format, 'text'); - }, - "that matches the first input in the test configuration": function (err, input) { - assert.equal(config.inputs.test.token,input.input_token); - assert.equal(config.inputs.test.id,input.id); - testContext.input = input; - } - }, - "when called with a json input": { - topic: function () { - logglyJSON.getInput('test_json', this.callback); - }, - "should return a valid input": function (err, input) { - assert.isNull(err); - helpers.assertInput(input); - }, - "of the format 'json'": function (err, input) { - assert.isNull(err); - assert.equal(input.format, 'json'); - }, - "that matches the second input in the test configuration": function (err, input) { - assert.equal(config.inputs.test_json.token,input.input_token); - assert.equal(config.inputs.test_json.id,input.id); - testContext.inputJSON = input; - } - } - } - } -}).addBatch({ - "When using the node-loggly client": { - "the log() method": { - "to a 'text' input": { - "when passed a callback": { - topic: function () { - loggly.log( - config.inputs.test.token, - 'this is a test logging message from /test/input-test.js', - this.callback); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - }, - "when not passed a callback": { - topic: function () { - var emitter = loggly.log(config.inputs.test.token, 'this is a test logging message from /test/input-test.js'); - emitter.on('log', this.callback.bind(null, null)); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - } - }, - "to a 'json' input": { - "when passed a callback": { - topic: function () { - logglyJSON.log( - config.inputs.test_json.token, - { - timestamp: new Date().getTime(), - message: 'this is a test logging message from /test/input-test.js' - }, - this.callback); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - }, - "when not passed a callback": { - topic: function () { - var emitter = logglyJSON.log( - config.inputs.test_json.token, - { - timestamp: new Date().getTime(), - message: 'this is a test logging message from /test/input-test.js' - } - ); - emitter.on('log', this.callback.bind(null, null)); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - } - } - } - } -}).addBatch({ - "When using an instance of an input": { - "the log() method of the 'text' instance": { - "when passed a callback": { - topic: function () { - testContext.input.log('this is a test logging message from /test/input-test.js', this.callback); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - }, - "when not passed a callback": { - topic: function () { - var emitter = testContext.input.log('this is a test logging message from /test/input-test.js'); - emitter.on('log', this.callback.bind(null, null)); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - } - }, - "the log() method of the 'json' instance": { - "when passed a callback": { - topic: function () { - testContext.inputJSON.log( - { - timestamp: new Date().getTime(), - message: 'this is a test logging message from /test/input-test.js' - }, - this.callback); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - }, - "when not passed a callback": { - topic: function () { - var emitter = testContext.inputJSON.log({ - timestamp: new Date().getTime(), - message: 'this is a test logging message from /test/input-test.js' - }); - emitter.on('log', this.callback.bind(null, null)); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/log-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/log-test.js deleted file mode 100644 index 876db6381..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/log-test.js +++ /dev/null @@ -1,84 +0,0 @@ -/* - * log-test.js: Tests for vanilla logging with no authentication. - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - helpers = require('./helpers'); - -var config = helpers.loadConfig(), - loggly = require('../lib/loggly').createClient({ subdomain: config.subdomain }), - logglyJSON = require('../lib/loggly').createClient({ subdomain: config.subdomain, json: true }); - -vows.describe('node-loggly/inputs (no auth)').addBatch({ - "When using the node-loggly client without authentication": { - "the log() method": { - "to a 'text' input": { - "when passed a callback": { - topic: function () { - loggly.log( - config.inputs.test.token, - 'this is a test logging message from /test/input-test.js', - this.callback); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - }, - "when not passed a callback": { - topic: function () { - var emitter = loggly.log(config.inputs.test.token, 'this is a test logging message from /test/input-test.js'); - emitter.on('log', this.callback.bind(null, null)); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - } - }, - "to a 'json' input": { - "when passed a callback": { - topic: function () { - logglyJSON.log( - config.inputs.test_json.token, - { - timestamp: new Date().getTime(), - message: 'this is a test logging message from /test/input-test.js' - }, - this.callback); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - }, - "when not passed a callback": { - topic: function () { - var emitter = logglyJSON.log( - config.inputs.test_json.token, - { - timestamp: new Date().getTime(), - message: 'this is a test logging message from /test/input-test.js' - } - ); - emitter.on('log', this.callback.bind(null, null)); - }, - "should log messages to loggly": function (err, result) { - assert.isNull(err); - assert.isObject(result); - assert.equal(result.response, 'ok'); - } - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/search-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/search-test.js deleted file mode 100644 index dac9da70c..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/loggly/test/search-test.js +++ /dev/null @@ -1,84 +0,0 @@ -/* - * input-test.js: Tests for Loggly input requests - * - * (C) 2010 Nodejitsu Inc. - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - helpers = require('./helpers'); - -var options = {}, - testContext = {}, - config = helpers.loadConfig(), - loggly = require('../lib/loggly').createClient(config); - -vows.describe('node-loggly/search').addBatch({ - "When using the node-loggly client": { - "the search() method": { - "when searching without chaining": { - topic: function () { - loggly.search('logging message', this.callback); - }, - "should return a set of valid search results": function (err, results) { - helpers.assertSearch(err, results); - } - }, - "when searching with chaining": { - topic: function () { - loggly.search('logging message') - .meta({ inputname: 'test' }) - .run(this.callback); - }, - "should return a set of valid search results": function (err, results) { - helpers.assertSearch(err, results); - } - } - }, - "the facet() method": { - "when searching by ip": { - topic: function () { - loggly.facet('ip', 'test', this.callback); - }, - "should return a set of valid search results": function (err, results) { - helpers.assertSearch(err, results); - } - }, - "when using chained searches": { - topic: function () { - loggly.facet('ip', 'test') - .context({ from: 'NOW-1MONTH' }) - .run(this.callback); - }, - "should return a set of valid search results": function (err, results) { - helpers.assertSearch(err, results); - } - } - }, - "the _checkRange() method": { - "with invalid options set": { - "should correct them": function () { - var search = loggly.search('logging message') - .context({ from: 'NOW', until: '1DAY' }) - ._checkRange(); - - assert.equal(search._context.from, 'NOW-24HOURS'); - assert.equal(search._context.until, 'NOW'); - } - }, - "with valid options set": { - "should not modify them": function () { - var search = loggly.search('logging message') - .context({ from: 'NOW-2MONTHS', until: 'NOW' }) - ._checkRange(); - - assert.equal(search._context.from, 'NOW-2MONTHS'); - assert.equal(search._context.until, 'NOW'); - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/.npmignore b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/.npmignore deleted file mode 100644 index 9303c347e..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -node_modules/ -npm-debug.log \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/README.md b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/README.md deleted file mode 100644 index 07ba942ca..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/README.md +++ /dev/null @@ -1,85 +0,0 @@ -# node-pkginfo - -An easy way to expose properties on a module from a package.json - -## Installation - -### Installing npm (node package manager) -``` - curl http://npmjs.org/install.sh | sh -``` - -### Installing pkginfo -``` - [sudo] npm install pkginfo -``` - -## Motivation -How often when writing node.js modules have you written the following line(s) of code? - -* Hard code your version string into your code - -``` js - exports.version = '0.1.0'; -``` - -* Programmatically expose the version from the package.json - -``` js - exports.version = JSON.parse(fs.readFileSync('/path/to/package.json', 'utf8')).version; -``` - -In other words, how often have you wanted to expose basic information from your package.json onto your module programmatically? **WELL NOW YOU CAN!** - -## Usage - -Using `pkginfo` is idiot-proof, just require and invoke it. - -``` js - var pkginfo = require('pkginfo')(module); - - console.dir(module.exports); -``` - -By invoking the `pkginfo` module all of the properties in your `package.json` file will be automatically exposed on the callee module (i.e. the parent module of `pkginfo`). - -Here's a sample of the output: - -``` - { name: 'simple-app', - description: 'A test fixture for pkginfo', - version: '0.1.0', - author: 'Charlie Robbins ', - keywords: [ 'test', 'fixture' ], - main: './index.js', - scripts: { test: 'vows test/*-test.js --spec' }, - engines: { node: '>= 0.4.0' } } -``` - -### Expose specific properties -If you don't want to expose **all** properties on from your `package.json` on your module then simple pass those properties to the `pkginfo` function: - -``` js - var pkginfo = require('pkginfo')(module, 'version', 'author'); - - console.dir(module.exports); -``` - -``` - { version: '0.1.0', - author: 'Charlie Robbins ' } -``` - -If you're looking for further usage see the [examples][0] included in this repository. - -## Run Tests -Tests are written in [vows][1] and give complete coverage of all APIs. - -``` - vows test/*-test.js --spec -``` - -[0]: https://github.com/indexzero/node-pkginfo/tree/master/examples -[1]: http://vowsjs.org - -#### Author: [Charlie Robbins](http://nodejitsu.com) \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/docs/docco.css b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/docs/docco.css deleted file mode 100644 index bd5413433..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/docs/docco.css +++ /dev/null @@ -1,194 +0,0 @@ -/*--------------------- Layout and Typography ----------------------------*/ -body { - font-family: 'Palatino Linotype', 'Book Antiqua', Palatino, FreeSerif, serif; - font-size: 15px; - line-height: 22px; - color: #252519; - margin: 0; padding: 0; -} -a { - color: #261a3b; -} - a:visited { - color: #261a3b; - } -p { - margin: 0 0 15px 0; -} -h4, h5, h6 { - color: #333; - margin: 6px 0 6px 0; - font-size: 13px; -} - h2, h3 { - margin-bottom: 0; - color: #000; - } - h1 { - margin-top: 40px; - margin-bottom: 15px; - color: #000; - } -#container { - position: relative; -} -#background { - position: fixed; - top: 0; left: 525px; right: 0; bottom: 0; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - z-index: -1; -} -#jump_to, #jump_page { - background: white; - -webkit-box-shadow: 0 0 25px #777; -moz-box-shadow: 0 0 25px #777; - -webkit-border-bottom-left-radius: 5px; -moz-border-radius-bottomleft: 5px; - font: 10px Arial; - text-transform: uppercase; - cursor: pointer; - text-align: right; -} -#jump_to, #jump_wrapper { - position: fixed; - right: 0; top: 0; - padding: 5px 10px; -} - #jump_wrapper { - padding: 0; - display: none; - } - #jump_to:hover #jump_wrapper { - display: block; - } - #jump_page { - padding: 5px 0 3px; - margin: 0 0 25px 25px; - } - #jump_page .source { - display: block; - padding: 5px 10px; - text-decoration: none; - border-top: 1px solid #eee; - } - #jump_page .source:hover { - background: #f5f5ff; - } - #jump_page .source:first-child { - } -table td { - border: 0; - outline: 0; -} - td.docs, th.docs { - max-width: 450px; - min-width: 450px; - min-height: 5px; - padding: 10px 25px 1px 50px; - overflow-x: hidden; - vertical-align: top; - text-align: left; - } - .docs pre { - margin: 15px 0 15px; - padding-left: 15px; - } - .docs p tt, .docs p code { - background: #f8f8ff; - border: 1px solid #dedede; - font-size: 12px; - padding: 0 0.2em; - } - .pilwrap { - position: relative; - } - .pilcrow { - font: 12px Arial; - text-decoration: none; - color: #454545; - position: absolute; - top: 3px; left: -20px; - padding: 1px 2px; - opacity: 0; - -webkit-transition: opacity 0.2s linear; - } - td.docs:hover .pilcrow { - opacity: 1; - } - td.code, th.code { - padding: 14px 15px 16px 25px; - width: 100%; - vertical-align: top; - background: #f5f5ff; - border-left: 1px solid #e5e5ee; - } - pre, tt, code { - font-size: 12px; line-height: 18px; - font-family: Menlo, Monaco, Consolas, "Lucida Console", monospace; - margin: 0; padding: 0; - } - - -/*---------------------- Syntax Highlighting -----------------------------*/ -td.linenos { background-color: #f0f0f0; padding-right: 10px; } -span.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; } -body .hll { background-color: #ffffcc } -body .c { color: #408080; font-style: italic } /* Comment */ -body .err { border: 1px solid #FF0000 } /* Error */ -body .k { color: #954121 } /* Keyword */ -body .o { color: #666666 } /* Operator */ -body .cm { color: #408080; font-style: italic } /* Comment.Multiline */ -body .cp { color: #BC7A00 } /* Comment.Preproc */ -body .c1 { color: #408080; font-style: italic } /* Comment.Single */ -body .cs { color: #408080; font-style: italic } /* Comment.Special */ -body .gd { color: #A00000 } /* Generic.Deleted */ -body .ge { font-style: italic } /* Generic.Emph */ -body .gr { color: #FF0000 } /* Generic.Error */ -body .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -body .gi { color: #00A000 } /* Generic.Inserted */ -body .go { color: #808080 } /* Generic.Output */ -body .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ -body .gs { font-weight: bold } /* Generic.Strong */ -body .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -body .gt { color: #0040D0 } /* Generic.Traceback */ -body .kc { color: #954121 } /* Keyword.Constant */ -body .kd { color: #954121; font-weight: bold } /* Keyword.Declaration */ -body .kn { color: #954121; font-weight: bold } /* Keyword.Namespace */ -body .kp { color: #954121 } /* Keyword.Pseudo */ -body .kr { color: #954121; font-weight: bold } /* Keyword.Reserved */ -body .kt { color: #B00040 } /* Keyword.Type */ -body .m { color: #666666 } /* Literal.Number */ -body .s { color: #219161 } /* Literal.String */ -body .na { color: #7D9029 } /* Name.Attribute */ -body .nb { color: #954121 } /* Name.Builtin */ -body .nc { color: #0000FF; font-weight: bold } /* Name.Class */ -body .no { color: #880000 } /* Name.Constant */ -body .nd { color: #AA22FF } /* Name.Decorator */ -body .ni { color: #999999; font-weight: bold } /* Name.Entity */ -body .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ -body .nf { color: #0000FF } /* Name.Function */ -body .nl { color: #A0A000 } /* Name.Label */ -body .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ -body .nt { color: #954121; font-weight: bold } /* Name.Tag */ -body .nv { color: #19469D } /* Name.Variable */ -body .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ -body .w { color: #bbbbbb } /* Text.Whitespace */ -body .mf { color: #666666 } /* Literal.Number.Float */ -body .mh { color: #666666 } /* Literal.Number.Hex */ -body .mi { color: #666666 } /* Literal.Number.Integer */ -body .mo { color: #666666 } /* Literal.Number.Oct */ -body .sb { color: #219161 } /* Literal.String.Backtick */ -body .sc { color: #219161 } /* Literal.String.Char */ -body .sd { color: #219161; font-style: italic } /* Literal.String.Doc */ -body .s2 { color: #219161 } /* Literal.String.Double */ -body .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ -body .sh { color: #219161 } /* Literal.String.Heredoc */ -body .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ -body .sx { color: #954121 } /* Literal.String.Other */ -body .sr { color: #BB6688 } /* Literal.String.Regex */ -body .s1 { color: #219161 } /* Literal.String.Single */ -body .ss { color: #19469D } /* Literal.String.Symbol */ -body .bp { color: #954121 } /* Name.Builtin.Pseudo */ -body .vc { color: #19469D } /* Name.Variable.Class */ -body .vg { color: #19469D } /* Name.Variable.Global */ -body .vi { color: #19469D } /* Name.Variable.Instance */ -body .il { color: #666666 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/docs/pkginfo.html b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/docs/pkginfo.html deleted file mode 100644 index bf615fa91..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/docs/pkginfo.html +++ /dev/null @@ -1,101 +0,0 @@ - pkginfo.js

        pkginfo.js

        /*
        - * pkginfo.js: Top-level include for the pkginfo module
        - *
        - * (C) 2011, Charlie Robbins
        - *
        - */
        - 
        -var fs = require('fs'),
        -    path = require('path');

        function pkginfo ([options, 'property', 'property' ..])

        - -

        @pmodule {Module} Parent module to read from.

        - -

        @options {Object|Array|string} Optional Options used when exposing properties.

        - -

        @arguments {string...} Optional Specified properties to expose.

        - -

        Exposes properties from the package.json file for the parent module on -it's exports. Valid usage:

        - -

        require('pkginfo')()

        - -

        require('pkginfo')('version', 'author');

        - -

        require('pkginfo')(['version', 'author']);

        - -

        require('pkginfo')({ include: ['version', 'author'] });

        var pkginfo = module.exports = function (pmodule, options) {
        -  var args = [].slice.call(arguments, 2).filter(function (arg) {
        -    return typeof arg === 'string';
        -  });
        -  

        Parse variable arguments

          if (Array.isArray(options)) {

        If the options passed in is an Array assume that -it is the Array of properties to expose from the -on the package.json file on the parent module.

            options = { include: options };
        -  }
        -  else if (typeof options === 'string') {

        Otherwise if the first argument is a string, then -assume that it is the first property to expose from -the package.json file on the parent module.

            options = { include: [options] };
        -  }
        -  

        Setup default options

          options = options || { include: [] };
        -  
        -  if (args.length > 0) {

        If additional string arguments have been passed in -then add them to the properties to expose on the -parent module.

            options.include = options.include.concat(args);
        -  }
        -  
        -  var pkg = pkginfo.read(pmodule, options.dir).package;
        -  Object.keys(pkg).forEach(function (key) {
        -    if (options.include.length > 0 && !~options.include.indexOf(key)) {
        -      return;
        -    }
        -    
        -    if (!pmodule.exports[key]) {
        -      pmodule.exports[key] = pkg[key];
        -    }
        -  });
        -  
        -  return pkginfo;
        -};

        function find (dir)

        - -

        @pmodule {Module} Parent module to read from.

        - -

        @dir {string} Optional Directory to start search from.

        - -

        Searches up the directory tree from dir until it finds a directory -which contains a package.json file.

        pkginfo.find = function (pmodule, dir) {
        -  dir = dir || pmodule.filename;
        -  dir = path.dirname(dir); 
        -  
        -  var files = fs.readdirSync(dir);
        -  
        -  if (~files.indexOf('package.json')) {
        -    return path.join(dir, 'package.json');
        -  }
        -  
        -  if (dir === '/') {
        -    throw new Error('Could not find package.json up from: ' + dir);
        -  }
        -  
        -  return pkginfo.find(dir);
        -};

        function read (pmodule, dir)

        - -

        @pmodule {Module} Parent module to read from.

        - -

        @dir {string} Optional Directory to start search from.

        - -

        Searches up the directory tree from dir until it finds a directory -which contains a package.json file and returns the package information.

        pkginfo.read = function (pmodule, dir) { 
        -  dir = pkginfo.find(pmodule, dir);
        -  
        -  var data = fs.readFileSync(dir).toString();
        -      
        -  return {
        -    dir: dir, 
        -    package: JSON.parse(data)
        -  };
        -};

        Call pkginfo on this module and expose version.

        pkginfo(module, {
        -  dir: __dirname,
        -  include: ['version'],
        -  target: pkginfo
        -});
        -
        -
        \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/all-properties.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/all-properties.js deleted file mode 100644 index fd1d831aa..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/all-properties.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * all-properties.js: Sample of including all properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/array-argument.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/array-argument.js deleted file mode 100644 index b1b684874..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/array-argument.js +++ /dev/null @@ -1,20 +0,0 @@ -/* - * array-argument.js: Sample of including specific properties from a package.json file - * using Array argument syntax. - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, ['version', 'author']); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/multiple-properties.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/multiple-properties.js deleted file mode 100644 index b4b5fd617..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/multiple-properties.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * multiple-properties.js: Sample of including multiple properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, 'version', 'author'); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/object-argument.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/object-argument.js deleted file mode 100644 index 28420c854..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/object-argument.js +++ /dev/null @@ -1,22 +0,0 @@ -/* - * object-argument.js: Sample of including specific properties from a package.json file - * using Object argument syntax. - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, { - include: ['version', 'author'] - }); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/package.json b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/package.json deleted file mode 100644 index 1f2f01c19..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "name": "simple-app", - "description": "A test fixture for pkginfo", - "version": "0.1.0", - "author": "Charlie Robbins ", - "keywords": ["test", "fixture"], - "main": "./index.js", - "scripts": { "test": "vows test/*-test.js --spec" }, - "engines": { "node": ">= 0.4.0" } -} diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/single-property.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/single-property.js deleted file mode 100644 index 4f445614b..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/examples/single-property.js +++ /dev/null @@ -1,19 +0,0 @@ -/* - * single-property.js: Sample of including a single specific properties from a package.json file - * - * (C) 2011, Charlie Robbins - * - */ - -var util = require('util'), - pkginfo = require('../lib/pkginfo')(module, 'version'); - -exports.someFunction = function () { - console.log('some of your custom logic here'); -}; - -console.log('Inspecting module:'); -console.dir(module.exports); - -console.log('\nAll exports exposed:'); -console.error(Object.keys(module.exports)); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/lib/pkginfo.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/lib/pkginfo.js deleted file mode 100644 index a4a622720..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/lib/pkginfo.js +++ /dev/null @@ -1,132 +0,0 @@ -/* - * pkginfo.js: Top-level include for the pkginfo module - * - * (C) 2011, Charlie Robbins - * - */ - -var fs = require('fs'), - path = require('path'); - -// -// ### function pkginfo ([options, 'property', 'property' ..]) -// #### @pmodule {Module} Parent module to read from. -// #### @options {Object|Array|string} **Optional** Options used when exposing properties. -// #### @arguments {string...} **Optional** Specified properties to expose. -// Exposes properties from the package.json file for the parent module on -// it's exports. Valid usage: -// -// `require('pkginfo')()` -// -// `require('pkginfo')('version', 'author');` -// -// `require('pkginfo')(['version', 'author']);` -// -// `require('pkginfo')({ include: ['version', 'author'] });` -// -var pkginfo = module.exports = function (pmodule, options) { - var args = [].slice.call(arguments, 2).filter(function (arg) { - return typeof arg === 'string'; - }); - - // - // **Parse variable arguments** - // - if (Array.isArray(options)) { - // - // If the options passed in is an Array assume that - // it is the Array of properties to expose from the - // on the package.json file on the parent module. - // - options = { include: options }; - } - else if (typeof options === 'string') { - // - // Otherwise if the first argument is a string, then - // assume that it is the first property to expose from - // the package.json file on the parent module. - // - options = { include: [options] }; - } - - // - // **Setup default options** - // - options = options || { include: [] }; - - if (args.length > 0) { - // - // If additional string arguments have been passed in - // then add them to the properties to expose on the - // parent module. - // - options.include = options.include.concat(args); - } - - var pkg = pkginfo.read(pmodule, options.dir).package; - Object.keys(pkg).forEach(function (key) { - if (options.include.length > 0 && !~options.include.indexOf(key)) { - return; - } - - if (!pmodule.exports[key]) { - pmodule.exports[key] = pkg[key]; - } - }); - - return pkginfo; -}; - -// -// ### function find (dir) -// #### @pmodule {Module} Parent module to read from. -// #### @dir {string} **Optional** Directory to start search from. -// Searches up the directory tree from `dir` until it finds a directory -// which contains a `package.json` file. -// -pkginfo.find = function (pmodule, dir) { - dir = dir || pmodule.filename; - dir = path.dirname(dir); - - var files = fs.readdirSync(dir); - - if (~files.indexOf('package.json')) { - return path.join(dir, 'package.json'); - } - - if (dir === '/') { - throw new Error('Could not find package.json up from: ' + dir); - } - else if (!dir || dir === '.') { - throw new Error('Cannot find package.json from unspecified directory'); - } - - return pkginfo.find(pmodule, dir); -}; - -// -// ### function read (pmodule, dir) -// #### @pmodule {Module} Parent module to read from. -// #### @dir {string} **Optional** Directory to start search from. -// Searches up the directory tree from `dir` until it finds a directory -// which contains a `package.json` file and returns the package information. -// -pkginfo.read = function (pmodule, dir) { - dir = pkginfo.find(pmodule, dir); - - var data = fs.readFileSync(dir).toString(); - - return { - dir: dir, - package: JSON.parse(data) - }; -}; - -// -// Call `pkginfo` on this module and expose version. -// -pkginfo(module, { - dir: __dirname, - include: ['version'], - target: pkginfo -}); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/package.json b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/package.json deleted file mode 100644 index b56a0bcec..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "pkginfo", - "version": "0.2.3", - "description": "An easy way to expose properties on a module from a package.json", - "author": { - "name": "Charlie Robbins", - "email": "charlie.robbins@gmail.com" - }, - "repository": { - "type": "git", - "url": "http://github.com/indexzero/node-pkginfo.git" - }, - "keywords": [ - "info", - "tools", - "package.json" - ], - "devDependencies": { - "vows": "0.6.x" - }, - "main": "./lib/pkginfo", - "scripts": { - "test": "vows test/*-test.js --spec" - }, - "engines": { - "node": ">= 0.4.0" - }, - "readme": "# node-pkginfo\n\nAn easy way to expose properties on a module from a package.json\n\n## Installation\n\n### Installing npm (node package manager)\n```\n curl http://npmjs.org/install.sh | sh\n```\n\n### Installing pkginfo\n```\n [sudo] npm install pkginfo\n```\n\n## Motivation\nHow often when writing node.js modules have you written the following line(s) of code? \n\n* Hard code your version string into your code\n\n``` js\n exports.version = '0.1.0';\n```\n\n* Programmatically expose the version from the package.json\n\n``` js\n exports.version = JSON.parse(fs.readFileSync('/path/to/package.json', 'utf8')).version;\n```\n\nIn other words, how often have you wanted to expose basic information from your package.json onto your module programmatically? **WELL NOW YOU CAN!**\n\n## Usage\n\nUsing `pkginfo` is idiot-proof, just require and invoke it. \n\n``` js\n var pkginfo = require('pkginfo')(module);\n \n console.dir(module.exports);\n```\n\nBy invoking the `pkginfo` module all of the properties in your `package.json` file will be automatically exposed on the callee module (i.e. the parent module of `pkginfo`). \n\nHere's a sample of the output:\n\n```\n { name: 'simple-app',\n description: 'A test fixture for pkginfo',\n version: '0.1.0',\n author: 'Charlie Robbins ',\n keywords: [ 'test', 'fixture' ],\n main: './index.js',\n scripts: { test: 'vows test/*-test.js --spec' },\n engines: { node: '>= 0.4.0' } }\n```\n\n### Expose specific properties\nIf you don't want to expose **all** properties on from your `package.json` on your module then simple pass those properties to the `pkginfo` function:\n\n``` js\n var pkginfo = require('pkginfo')(module, 'version', 'author');\n \n console.dir(module.exports);\n```\n\n```\n { version: '0.1.0',\n author: 'Charlie Robbins ' }\n```\n\nIf you're looking for further usage see the [examples][0] included in this repository. \n\n## Run Tests\nTests are written in [vows][1] and give complete coverage of all APIs.\n\n```\n vows test/*-test.js --spec\n```\n\n[0]: https://github.com/indexzero/node-pkginfo/tree/master/examples\n[1]: http://vowsjs.org\n\n#### Author: [Charlie Robbins](http://nodejitsu.com)", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/indexzero/node-pkginfo/issues" - }, - "_id": "pkginfo@0.2.3", - "_from": "pkginfo@0.2.x" -} diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/test/pkginfo-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/test/pkginfo-test.js deleted file mode 100644 index 3156c0012..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/pkginfo/test/pkginfo-test.js +++ /dev/null @@ -1,69 +0,0 @@ -/* - * pkginfo-test.js: Tests for the pkginfo module. - * - * (C) 2011, Charlie Robbins - * - */ - -var assert = require('assert'), - exec = require('child_process').exec, - fs = require('fs'), - path = require('path'), - vows = require('vows'), - pkginfo = require('../lib/pkginfo'); - -function assertProperties (source, target) { - assert.lengthOf(source, target.length + 1); - target.forEach(function (prop) { - assert.isTrue(!!~source.indexOf(prop)); - }); -} - -function testExposes (options) { - return { - topic: function () { - exec('node ' + path.join(__dirname, '..', 'examples', options.script), this.callback); - }, - "should expose that property correctly": function (err, stdout, stderr) { - assert.isNull(err); - - var exposed = stderr.match(/'(\w+)'/ig).map(function (p) { - return p.substring(1, p.length - 1); - }); - - return !options.assert - ? assertProperties(exposed, options.properties) - : options.assert(exposed); - } - } -} - -vows.describe('pkginfo').addBatch({ - "When using the pkginfo module": { - "and passed a single `string` argument": testExposes({ - script: 'single-property.js', - properties: ['version'] - }), - "and passed multiple `string` arguments": testExposes({ - script: 'multiple-properties.js', - properties: ['version', 'author'] - }), - "and passed an `object` argument": testExposes({ - script: 'object-argument.js', - properties: ['version', 'author'] - }), - "and passed an `array` argument": testExposes({ - script: 'array-argument.js', - properties: ['version', 'author'] - }), - "and passed no arguments": testExposes({ - script: 'all-properties.js', - assert: function (exposed) { - var pkg = fs.readFileSync(path.join(__dirname, '..', 'examples', 'package.json')).toString(), - keys = Object.keys(JSON.parse(pkg)); - - assertProperties(exposed, keys); - } - }) - } -}).export(module); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/.npmignore b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/.npmignore deleted file mode 100644 index 3f31ac20e..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -*.un~ -/node_modules diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/License b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/License deleted file mode 100644 index 11ec094ea..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/License +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011 Felix Geisendörfer (felix@debuggable.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/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/Makefile b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/Makefile deleted file mode 100644 index a7ce31d3f..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -SHELL := /bin/bash - -test: - @./test/run.js - -release: - git push - git push --tags - npm publish . - -.PHONY: test diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/Readme.md b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/Readme.md deleted file mode 100644 index fcd1b97c5..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/Readme.md +++ /dev/null @@ -1,98 +0,0 @@ -# stack-trace - -Get v8 stack traces as an array of CallSite objects. - -## Install - -``` bash -npm install stack-trace -``` - -## Usage - -The stack-trace module makes it easy for you to capture the current stack: - -``` javascript -var stackTrace = require('stack-trace'); -var trace = stackTrace.get(); - -require('assert').strictEqual(trace[0].getFileName(), __filename); -``` - -However, sometimes you have already popped the stack you are interested in, -and all you have left is an `Error` object. This module can help: - -``` javascript -var stackTrace = require('stack-trace'); -var err = new Error('something went wrong'); -var trace = stackTrace.parse(err); - -require('assert').strictEqual(trace[0].getFileName(), __filename); -``` - -Please note that parsing the `Error#stack` property is not perfect, only -certain properties can be retrieved with it as noted in the API docs below. - -## Long stack traces - -stack-trace works great with [long-stack-traces][], when parsing an `err.stack` -that has crossed the event loop boundary, a `CallSite` object returning -`'----------------------------------------'` for `getFileName()` is created. -All other methods of the event loop boundary call site return `null`. - -[long-stack-traces]: https://github.com/tlrobinson/long-stack-traces - -## API - -### stackTrace.get([belowFn]) - -Returns an array of `CallSite` objects, where element `0` is the current call -site. - -When passing a function on the current stack as the `belowFn` parameter, the -returned array will only include `CallSite` objects below this function. - -### stackTrace.parse(err) - -Parses the `err.stack` property of an `Error` object into an array compatible -with those returned by `stackTrace.get()`. However, only the following methods -are implemented on the returned `CallSite` objects. - -* getTypeName -* getFunctionName -* getMethodName -* getFileName -* getLineNumber -* getColumnNumber -* isNative - -Note: Except `getFunctionName()`, all of the above methods return exactly the -same values as you would get from `stackTrace.get()`. `getFunctionName()` -is sometimes a little different, but still useful. - -### CallSite - -The official v8 CallSite object API can be found [here][v8stackapi]. A quick -excerpt: - -> A CallSite object defines the following methods: -> -> * **getThis**: returns the value of this -> * **getTypeName**: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object's [[Class]] internal property. -> * **getFunction**: returns the current function -> * **getFunctionName**: returns the name of the current function, typically its name property. If a name property is not available an attempt will be made to try to infer a name from the function's context. -> * **getMethodName**: returns the name of the property of this or one of its prototypes that holds the current function -> * **getFileName**: if this function was defined in a script returns the name of the script -> * **getLineNumber**: if this function was defined in a script returns the current line number -> * **getColumnNumber**: if this function was defined in a script returns the current column number -> * **getEvalOrigin**: if this function was created using a call to eval returns a CallSite object representing the location where eval was called -> * **isToplevel**: is this a toplevel invocation, that is, is this the global object? -> * **isEval**: does this call take place in code defined by a call to eval? -> * **isNative**: is this call in native V8 code? -> * **isConstructor**: is this a constructor call? - -[v8stackapi]: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - -## License - -stack-trace is licensed under the MIT license. diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/lib/stack-trace.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/lib/stack-trace.js deleted file mode 100644 index 085ff40b2..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/lib/stack-trace.js +++ /dev/null @@ -1,111 +0,0 @@ -exports.get = function(belowFn) { - var oldLimit = Error.stackTraceLimit; - Error.stackTraceLimit = Infinity; - - var dummyObject = {}; - Error.captureStackTrace(dummyObject, belowFn || exports.get); - - var v8Handler = Error.prepareStackTrace; - Error.prepareStackTrace = function(dummyObject, v8StackTrace) { - return v8StackTrace; - }; - - var v8StackTrace = dummyObject.stack; - Error.prepareStackTrace = v8Handler; - Error.stackTraceLimit = oldLimit; - - return v8StackTrace; -}; - -exports.parse = function(err) { - if (!err.stack) { - return []; - } - - var self = this; - var lines = err.stack.split('\n').slice(1); - - return lines - .map(function(line) { - if (line.match(/^\s*[-]{4,}$/)) { - return self._createParsedCallSite({ - fileName: line, - lineNumber: null, - functionName: null, - typeName: null, - methodName: null, - columnNumber: null, - 'native': null, - }); - } - - var lineMatch = line.match(/at (?:([^\s]+)\s+)?\(?(?:(.+?):(\d+):(\d+)|([^)]+))\)?/); - if (!lineMatch) { - return; - } - - var object = null; - var method = null; - var functionName = null; - var typeName = null; - var methodName = null; - var isNative = (lineMatch[5] === 'native'); - - if (lineMatch[1]) { - var methodMatch = lineMatch[1].match(/([^\.]+)(?:\.(.+))?/); - object = methodMatch[1]; - method = methodMatch[2]; - functionName = lineMatch[1]; - typeName = 'Object'; - } - - if (method) { - typeName = object; - methodName = method; - } - - if (method === '') { - methodName = null; - functionName = ''; - } - - var properties = { - fileName: lineMatch[2] || null, - lineNumber: parseInt(lineMatch[3], 10) || null, - functionName: functionName, - typeName: typeName, - methodName: methodName, - columnNumber: parseInt(lineMatch[4], 10) || null, - 'native': isNative, - }; - - return self._createParsedCallSite(properties); - }) - .filter(function(callSite) { - return !!callSite; - }); -}; - -exports._createParsedCallSite = function(properties) { - var methods = {}; - for (var property in properties) { - var prefix = 'get'; - if (property === 'native') { - prefix = 'is'; - } - var method = prefix + property.substr(0, 1).toUpperCase() + property.substr(1); - - (function(property) { - methods[method] = function() { - return properties[property]; - } - })(property); - } - - var callSite = Object.create(methods); - for (var property in properties) { - callSite[property] = properties[property]; - } - - return callSite; -}; diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/package.json b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/package.json deleted file mode 100644 index 202d64790..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "author": { - "name": "Felix Geisendörfer", - "email": "felix@debuggable.com", - "url": "http://debuggable.com/" - }, - "name": "stack-trace", - "description": "Get v8 stack traces as an array of CallSite objects.", - "version": "0.0.6", - "homepage": "https://github.com/felixge/node-stack-trace", - "repository": { - "type": "git", - "url": "git://github.com/felixge/node-stack-trace.git" - }, - "main": "./lib/stack-trace", - "engines": { - "node": "*" - }, - "dependencies": {}, - "devDependencies": { - "far": "0.0.3", - "long-stack-traces": "0.1.2" - }, - "readme": "# stack-trace\n\nGet v8 stack traces as an array of CallSite objects.\n\n## Install\n\n``` bash\nnpm install stack-trace\n```\n\n## Usage\n\nThe stack-trace module makes it easy for you to capture the current stack:\n\n``` javascript\nvar stackTrace = require('stack-trace');\nvar trace = stackTrace.get();\n\nrequire('assert').strictEqual(trace[0].getFileName(), __filename);\n```\n\nHowever, sometimes you have already popped the stack you are interested in,\nand all you have left is an `Error` object. This module can help:\n\n``` javascript\nvar stackTrace = require('stack-trace');\nvar err = new Error('something went wrong');\nvar trace = stackTrace.parse(err);\n\nrequire('assert').strictEqual(trace[0].getFileName(), __filename);\n```\n\nPlease note that parsing the `Error#stack` property is not perfect, only\ncertain properties can be retrieved with it as noted in the API docs below.\n\n## Long stack traces\n\nstack-trace works great with [long-stack-traces][], when parsing an `err.stack`\nthat has crossed the event loop boundary, a `CallSite` object returning\n`'----------------------------------------'` for `getFileName()` is created.\nAll other methods of the event loop boundary call site return `null`.\n\n[long-stack-traces]: https://github.com/tlrobinson/long-stack-traces\n\n## API\n\n### stackTrace.get([belowFn])\n\nReturns an array of `CallSite` objects, where element `0` is the current call\nsite.\n\nWhen passing a function on the current stack as the `belowFn` parameter, the\nreturned array will only include `CallSite` objects below this function.\n\n### stackTrace.parse(err)\n\nParses the `err.stack` property of an `Error` object into an array compatible\nwith those returned by `stackTrace.get()`. However, only the following methods\nare implemented on the returned `CallSite` objects.\n\n* getTypeName\n* getFunctionName\n* getMethodName\n* getFileName\n* getLineNumber\n* getColumnNumber\n* isNative\n\nNote: Except `getFunctionName()`, all of the above methods return exactly the\nsame values as you would get from `stackTrace.get()`. `getFunctionName()`\nis sometimes a little different, but still useful.\n\n### CallSite\n\nThe official v8 CallSite object API can be found [here][v8stackapi]. A quick\nexcerpt:\n\n> A CallSite object defines the following methods:\n>\n> * **getThis**: returns the value of this\n> * **getTypeName**: returns the type of this as a string. This is the name of the function stored in the constructor field of this, if available, otherwise the object's [[Class]] internal property.\n> * **getFunction**: returns the current function\n> * **getFunctionName**: returns the name of the current function, typically its name property. If a name property is not available an attempt will be made to try to infer a name from the function's context.\n> * **getMethodName**: returns the name of the property of this or one of its prototypes that holds the current function\n> * **getFileName**: if this function was defined in a script returns the name of the script\n> * **getLineNumber**: if this function was defined in a script returns the current line number\n> * **getColumnNumber**: if this function was defined in a script returns the current column number\n> * **getEvalOrigin**: if this function was created using a call to eval returns a CallSite object representing the location where eval was called\n> * **isToplevel**: is this a toplevel invocation, that is, is this the global object?\n> * **isEval**: does this call take place in code defined by a call to eval?\n> * **isNative**: is this call in native V8 code?\n> * **isConstructor**: is this a constructor call?\n\n[v8stackapi]: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi\n\n## License\n\nstack-trace is licensed under the MIT license.\n", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/felixge/node-stack-trace/issues" - }, - "_id": "stack-trace@0.0.6", - "_from": "stack-trace@0.0.x" -} diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/test/common.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/test/common.js deleted file mode 100644 index 2985c2f1e..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/test/common.js +++ /dev/null @@ -1,10 +0,0 @@ -var common = exports; - -var path = require('path'); -var root = path.dirname(__dirname); - -common.dir = { - lib: root + '/lib', -}; - -common.assert = require('assert'); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/test/integration/test-get.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/test/integration/test-get.js deleted file mode 100644 index 53b2e612b..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/test/integration/test-get.js +++ /dev/null @@ -1,49 +0,0 @@ -var common = require('../common'); -var assert = common.assert; -var stackTrace = require(common.dir.lib + '/stack-trace'); - -(function testBasic() { - var trace = stackTrace.get(); - - assert.strictEqual(trace[0].getFunction(), testBasic); - assert.strictEqual(trace[0].getFunctionName(), 'testBasic'); - assert.strictEqual(trace[0].getFileName(), __filename); -})(); - -(function testWrapper() { - (function testBelowFn() { - var trace = stackTrace.get(testBelowFn); - assert.strictEqual(trace[0].getFunction(), testWrapper); - assert.strictEqual(trace[0].getFunctionName(), 'testWrapper'); - })(); -})(); - - -(function deep1() { - (function deep2() { - (function deep3() { - (function deep4() { - (function deep5() { - (function deep6() { - (function deep7() { - (function deep8() { - (function deep9() { - (function deep10() { - (function deep10() { - var trace = stackTrace.get(); - var hasFirstCallSite = trace.some(function(callSite) { - return callSite.getFunctionName() === 'deep1'; - }); - - assert.ok(hasFirstCallSite); - })(); - })(); - })(); - })(); - })(); - })(); - })(); - })(); - })(); - })(); -})(); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/test/integration/test-long-stack-trace.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/test/integration/test-long-stack-trace.js deleted file mode 100644 index 6106c4a2b..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/test/integration/test-long-stack-trace.js +++ /dev/null @@ -1,14 +0,0 @@ -var common = require('../common'); - -require('long-stack-traces'); -var assert = common.assert; -var stackTrace = require(common.dir.lib + '/stack-trace'); - -function badFn() { - var err = new Error('oh no'); - var trace = stackTrace.parse(err); - - assert.ok(trace[2].getFileName().match(/-----/)); -}; - -setTimeout(badFn, 10); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/test/integration/test-parse.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/test/integration/test-parse.js deleted file mode 100644 index 4171a688f..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/node_modules/stack-trace/test/integration/test-parse.js +++ /dev/null @@ -1,135 +0,0 @@ -var common = require('../common'); -var assert = common.assert; -var stackTrace = require(common.dir.lib + '/stack-trace'); - -(function testBasic() { - var err = new Error('something went wrong'); - var trace = stackTrace.parse(err); - - assert.strictEqual(trace[0].getFileName(), __filename); - assert.strictEqual(trace[0].getFunctionName(), 'testBasic'); -})(); - -(function testWrapper() { - (function testBelowFn() { - var err = new Error('something went wrong'); - var trace = stackTrace.parse(err); - assert.strictEqual(trace[0].getFunctionName(), 'testBelowFn'); - assert.strictEqual(trace[1].getFunctionName(), 'testWrapper'); - })(); -})(); - -(function testNoStack() { - var err = {stack: undefined}; - var trace = stackTrace.parse(err); - - assert.deepEqual(trace, []); -})(); - - -(function testCorruptStack() { - var err = {}; - err.stack = -'AssertionError: true == false\n' + -' fuck' + -' at Test.run (/Users/felix/code/node-fast-or-slow/lib/test.js:45:10)\n' + -'oh no' + -' at TestCase.run (/Users/felix/code/node-fast-or-slow/lib/test_case.js:61:8)\n'; - - var trace = stackTrace.parse(err); - assert.equal(trace.length, 2); -})(); - -(function testCompareRealWithParsedStackTrace() { - var realTrace = stackTrace.get(); var err = new Error('something went wrong'); - var parsedTrace = stackTrace.parse(err); - - realTrace.forEach(function(real, i) { - var parsed = parsedTrace[i]; - - function compare(method, exceptions) { - var realValue = real[method](); - var parsedValue = parsed[method](); - - if (exceptions && exceptions[i]) { - realValue = exceptions[i]; - } - - var realJson = JSON.stringify(realValue); - var parsedJson = JSON.stringify(parsedValue); - - var message = - method + ': ' + realJson + ' != ' + parsedJson + ' (#' + i + ')'; - - assert.strictEqual(realValue, parsedValue, message); - } - - compare('getFileName'); - compare('getFunctionName', { - 3: 'Object..js', - 5: 'Function._load', - 6: 'Array.0', - 7: 'EventEmitter._tickCallback', - }); - compare('getTypeName'); - compare('getMethodName'); - compare('getLineNumber'); - compare('getColumnNumber', { - 0: 47 - }); - compare('isNative'); - }); -})(); - -(function testStackWithNativeCall() { - var err = {}; - err.stack = -'AssertionError: true == false\n' + -' at Test.fn (/Users/felix/code/node-fast-or-slow/test/fast/example/test-example.js:6:10)\n' + -' at Test.run (/Users/felix/code/node-fast-or-slow/lib/test.js:45:10)\n' + -' at TestCase.runNext (/Users/felix/code/node-fast-or-slow/lib/test_case.js:73:8)\n' + -' at TestCase.run (/Users/felix/code/node-fast-or-slow/lib/test_case.js:61:8)\n' + -' at Array.0 (native)\n' + -' at EventEmitter._tickCallback (node.js:126:26)'; - - var trace = stackTrace.parse(err); - var nativeCallSite = trace[4]; - - assert.strictEqual(nativeCallSite.getFileName(), null); - assert.strictEqual(nativeCallSite.getFunctionName(), 'Array.0'); - assert.strictEqual(nativeCallSite.getTypeName(), 'Array'); - assert.strictEqual(nativeCallSite.getMethodName(), '0'); - assert.strictEqual(nativeCallSite.getLineNumber(), null); - assert.strictEqual(nativeCallSite.getColumnNumber(), null); - assert.strictEqual(nativeCallSite.isNative(), true); -})(); - -(function testStackWithFileOnly() { - var err = {}; - err.stack = -'AssertionError: true == false\n' + -' at /Users/felix/code/node-fast-or-slow/lib/test_case.js:80:10'; - - var trace = stackTrace.parse(err); - var callSite = trace[0]; - - assert.strictEqual(callSite.getFileName(), '/Users/felix/code/node-fast-or-slow/lib/test_case.js'); - assert.strictEqual(callSite.getFunctionName(), null); - assert.strictEqual(callSite.getTypeName(), null); - assert.strictEqual(callSite.getMethodName(), null); - assert.strictEqual(callSite.getLineNumber(), 80); - assert.strictEqual(callSite.getColumnNumber(), 10); - assert.strictEqual(callSite.isNative(), false); -})(); - -(function testStackWithMultilineMessage() { - var err = {}; - err.stack = -'AssertionError: true == false\nAnd some more shit\n' + -' at /Users/felix/code/node-fast-or-slow/lib/test_case.js:80:10'; - - var trace = stackTrace.parse(err); - var callSite = trace[0]; - - assert.strictEqual(callSite.getFileName(), '/Users/felix/code/node-fast-or-slow/lib/test_case.js'); -})(); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/package.json b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/package.json deleted file mode 100644 index 9080f0ef8..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "winston", - "description": "A multi-transport async logging library for Node.js", - "version": "0.5.11", - "author": { - "name": "Charlie Robbins", - "email": "charlie.robbins@gmail.com" - }, - "contributors": [ - { - "name": "Matthew Bergman", - "email": "mzbphoto@gmail.com" - }, - { - "name": "Marak Squires", - "email": "marak@nodejitsu.com" - } - ], - "repository": { - "type": "git", - "url": "https://github.com/flatiron/winston.git" - }, - "keywords": [ - "logging", - "sysadmin", - "tools" - ], - "dependencies": { - "async": "0.1.x", - "colors": "0.x.x", - "eyes": "0.1.x", - "loggly": "0.3.x >=0.3.7", - "pkginfo": "0.2.x", - "stack-trace": "0.0.x" - }, - "devDependencies": { - "vows": "0.6.x" - }, - "main": "./lib/winston", - "scripts": { - "test": "vows --spec --isolate" - }, - "engines": { - "node": ">= 0.4.0" - }, - "readme": "# winston [![Build Status](https://secure.travis-ci.org/flatiron/winston.png)](http://travis-ci.org/flatiron/winston)\n\nA multi-transport async logging library for node.js. "CHILL WINSTON! ... I put it in the logs."\n\n## Installation\n\n### Installing npm (node package manager)\n```\n curl http://npmjs.org/install.sh | sh\n```\n\n### Installing winston\n```\n [sudo] npm install winston\n```\n\n## Motivation\nWinston is designed to be a simple and universal logging library with support for multiple transports. A transport is essentially a storage device for your logs. Each instance of a winston logger can have multiple transports configured at different levels. For example, one may want error logs to be stored in a persistent remote location (like a database), but all logs output to the console or a local file. \n\nThere also seemed to be a lot of logging libraries out there that coupled their implementation of logging (i.e. how the logs are stored / indexed) to the API that they exposed to the programmer. This library aims to decouple those parts of the process to make it more flexible and extensible.\n\n## Usage\nThere are two different ways to use winston: directly via the default logger, or by instantiating your own Logger. The former is merely intended to be a convenient shared logger to use throughout your application if you so choose. \n\n### Using the Default Logger\nThe default logger is accessible through the winston module directly. Any method that you could call on an instance of a logger is available on the default logger:\n\n``` js\n var winston = require('winston');\n \n winston.log('info', 'Hello distributed log files!');\n winston.info('Hello again distributed logs');\n```\n\nBy default, only the Console transport is set on the default logger. You can add or remove transports via the add() and remove() methods:\n\n``` js\n winston.add(winston.transports.File, { filename: 'somefile.log' });\n winston.remove(winston.transports.Console);\n```\n\nFor more documenation about working with each individual transport supported by Winston see the \"Working with Transports\" section below. \n\n### Instantiating your own Logger\nIf you would prefer to manage the object lifetime of loggers you are free to instantiate them yourself:\n\n``` js\n var logger = new (winston.Logger)({\n transports: [\n new (winston.transports.Console)(),\n new (winston.transports.File)({ filename: 'somefile.log' })\n ]\n });\n```\n\nYou can work with this logger in the same way that you work with the default logger: \n\n``` js\n //\n // Logging\n //\n logger.log('info', 'Hello distributed log files!');\n logger.info('Hello again distributed logs');\n \n //\n // Adding / Removing Transports\n // (Yes It's chainable)\n //\n logger.add(winston.transports.File)\n .remove(winston.transports.Console);\n```\n\n### Handling Uncaught Exceptions with winston\n\nWith `winston`, it is possible to catch and log `uncaughtException` events from your process. There are two distinct ways of enabling this functionality either through the default winston logger or your own logger instance.\n\nIf you want to use this feature with the default logger simply call `.handleExceptions()` with a transport instance.\n\n``` js\n //\n // You can add a separate exception logger by passing it to `.handleExceptions`\n //\n winston.handleExceptions(new winston.transports.File({ filename: 'path/to/exceptions.log' }))\n \n //\n // Alternatively you can set `.handleExceptions` to true when adding transports to winston\n //\n winston.add(winston.transports.File, { \n filename: 'path/to/all-logs.log', \n handleExceptions: true \n });\n```\n\n## to exit or not to exit\n\nby default, winston will exit after logging an uncaughtException. if this is not the behavior you want,\nset `exitOnError = false`\n\n``` js\n var logger = new (winston.Logger)({ exitOnError: false });\n\n //\n // or, like this:\n //\n logger.exitOnError = false;\n```\n\nWhen working with custom logger instances, you can pass in separate transports to the `exceptionHandlers` property or set `.handleExceptions` on any transport.\n\n``` js\n var logger = new (winston.Logger)({\n transports: [\n new winston.transports.File({ filename: 'path/to/all-logs.log' })\n ]\n exceptionHandlers: [\n new winston.transports.File({ filename: 'path/to/exceptions.log' })\n ]\n });\n```\n\nThe `exitOnError` option can also be a function to prevent exit on only certain types of errors:\n\n``` js\n function ignoreEpipe(err) {\n return err.code !== 'EPIPE';\n }\n\n var logger = new (winston.Logger)({ exitOnError: ignoreEpipe });\n\n //\n // or, like this:\n //\n logger.exitOnError = ignoreEpipe;\n```\n\n### Using Logging Levels\nSetting the level for your logging message can be accomplished in one of two ways. You can pass a string representing the logging level to the log() method or use the level specified methods defined on every winston Logger. \n\n``` js\n //\n // Any logger instance\n //\n logger.log('info', \"127.0.0.1 - there's no place like home\");\n logger.info(\"127.0.0.1 - there's no place like home\");\n \n //\n // Default logger\n //\n winston.log('info', \"127.0.0.1 - there's no place like home\");\n winston.info(\"127.0.0.1 - there's no place like home\");\n```\n\nAs of 0.2.0, winston supports customizable logging levels, defaulting to [npm][0] style logging levels. Changing logging levels is easy:\n\n``` js\n //\n // Change levels on the default winston logger\n //\n winston.setLevels(winston.config.syslog.levels);\n \n //\n // Change levels on an instance of a logger\n //\n logger.setLevels(winston.config.syslog.levels);\n```\n\nCalling `.setLevels` on a logger will remove all of the previous helper methods for the old levels and define helper methods for the new levels. Thus, you should be careful about the logging statements you use when changing levels. For example, if you ran this code after changing to the syslog levels:\n\n``` js\n //\n // Logger does not have 'silly' defined since that level is not in the syslog levels \n //\n logger.silly('some silly message');\n```\n\n### Using Custom Logging Levels\nIn addition to the predefined `npm` and `syslog` levels available in Winston, you can also choose to define your own:\n\n``` js\n var myCustomLevels = {\n levels: {\n foo: 0,\n bar: 1,\n baz: 2,\n foobar: 3\n },\n colors: {\n foo: 'blue',\n bar: 'green',\n baz: 'yellow',\n foobar: 'red'\n }\n };\n \n var customLevelLogger = new (winston.Logger)({ levels: myCustomLevels.levels }); \n customLevelLogger.foobar('some foobar level-ed message');\n```\n\nAlthough there is slight repetition in this data structure, it enables simple encapsulation if you not to have colors. If you do wish to have colors, in addition to passing the levels to the Logger itself, you must make winston aware of them:\n\n``` js\n //\n // Make winston aware of these colors\n //\n winston.addColors(myCustomLevels.colors);\n```\n\nThis enables transports with the 'colorize' option set to appropriately color the output of custom levels.\n\n### Events and Callbacks in Winston\nEach instance of winston.Logger is also an instance of an [EventEmitter][1]. A log event will be raised each time a transport successfully logs a message:\n\n``` js\n logger.on('logging', function (transport, level, msg, meta) {\n // [msg] and [meta] have now been logged at [level] to [transport]\n });\n \n logger.info('CHILL WINSTON!', { seriously: true });\n```\n\nIt is also worth mentioning that the logger also emits an 'error' event which you should handle or suppress if you don't want unhandled exceptions:\n\n``` js\n //\n // Handle errors\n //\n logger.on('error', function (err) { /* Do Something */ });\n \n //\n // Or just suppress them.\n //\n logger.emitErrs = false;\n```\n\nEvery logging method described in the previous section also takes an optional callback which will be called only when all of the transports have logged the specified message.\n\n``` js\n logger.info('CHILL WINSTON!', { seriously: true }, function (err, level, msg, meta) {\n // [msg] and [meta] have now been logged at [level] to **every** transport.\n });\n```\n\n### Working with multiple Loggers in winston\n\nOften in larger, more complex applications it is necessary to have multiple logger instances with different settings. Each logger is responsible for a different feature area (or category). This is exposed in `winston` in two ways: through `winston.loggers` and instances of `winston.Container`. In fact, `winston.loggers` is just a predefined instance of `winston.Container`:\n\n``` js\n var winston = require('winston');\n \n //\n // Configure the logger for `category1`\n //\n winston.loggers.add('category1', {\n console: {\n level: 'silly',\n colorize: 'true'\n },\n file: {\n filename: '/path/to/some/file'\n }\n });\n \n //\n // Configure the logger for `category2`\n //\n winston.loggers.add('category2', {\n couchdb: {\n host: '127.0.0.1',\n port: 5984\n }\n });\n```\n\nNow that your loggers are setup you can require winston _in any file in your application_ and access these pre-configured loggers:\n\n``` js\n var winston = require('winston');\n \n //\n // Grab your preconfigured logger\n //\n var category1 = winston.loggers.get('category1');\n \n category1.info('logging from your IoC container-based logger');\n```\n\nIf you prefer to manage the `Container` yourself you can simply instantiate one:\n\n``` js\n var winston = require('winston'),\n container = new winston.Container();\n \n container.add('category1', {\n console: {\n level: 'silly',\n colorize: 'true'\n },\n file: {\n filename: '/path/to/some/file'\n }\n });\n```\n\n### Sharing transports between Loggers in winston\n\n``` js\n var winston = require('winston');\n\n //\n // Setup transports to be shared across all loggers\n // in three ways:\n //\n // 1. By setting it on the default Container\n // 2. By passing `transports` into the constructor function of winston.Container\n // 3. By passing `transports` into the `.get()` or `.add()` methods \n //\n\n //\n // 1. By setting it on the default Container\n //\n winston.loggers.options.transports = [\n // Setup your shared transports here\n ];\n\n //\n // 2. By passing `transports` into the constructor function of winston.Container\n //\n var container = new winston.Container({\n transports: [\n // Setup your shared transports here\n ]\n });\n\n //\n // 3. By passing `transports` into the `.get()` or `.add()` methods \n // \n winston.loggers.add('some-category', {\n transports: [\n // Setup your shared transports here\n ]\n });\n\n container.add('some-category', {\n transports: [\n // Setup your shared transports here\n ]\n });\n```\n\n### Logging with Metadata\nIn addition to logging string messages, winston will also optionally log additional JSON metadata objects. Adding metadata is simple:\n\n``` js\n winston.log('info', 'Test Log Message', { anything: 'This is metadata' });\n```\n\nThe way these objects is stored varies from transport to transport (to best support the storage mechanisms offered). Here's a quick summary of how each transports handles metadata:\n\n1. __Console:__ Logged via util.inspect(meta)\n2. __File:__ Logged via util.inspect(meta)\n3. __Loggly:__ Logged in suggested [Loggly format][2]\n\n### Profiling with Winston\nIn addition to logging messages and metadata, winston also has a simple profiling mechanism implemented for any logger:\n\n``` js\n //\n // Start profile of 'test'\n // Remark: Consider using Date.now() with async operations \n //\n winston.profile('test');\n \n setTimeout(function () {\n //\n // Stop profile of 'test'. Logging will now take place:\n // \"17 Jan 21:00:00 - info: test duration=1000ms\"\n //\n winston.profile('test');\n }, 1000);\n``` \n\nAll profile messages are set to the 'info' by default and both message and metadata are optional There are no plans in the Roadmap to make this configurable, but I'm open to suggestions / issues.\n\n### Using winston in a CLI tool\nA common use-case for logging is output to a CLI tool. Winston has a special helper method which will pretty print output from your CLI tool. Here's an example from the [require-analyzer][15] written by [Nodejitsu][5]:\n\n```\n info: require-analyzer starting in /Users/Charlie/Nodejitsu/require-analyzer\n info: Found existing dependencies\n data: {\n data: colors: '0.x.x',\n data: eyes: '0.1.x',\n data: findit: '0.0.x',\n data: npm: '1.0.x',\n data: optimist: '0.2.x',\n data: semver: '1.0.x',\n data: winston: '0.2.x'\n data: }\n info: Analyzing dependencies...\n info: Done analyzing raw dependencies\n info: Retrieved packages from npm\n warn: No additional dependencies found\n```\n\nConfiguring output for this style is easy, just use the `.cli()` method on `winston` or an instance of `winston.Logger`:\n\n``` js\n var winston = require('winston');\n \n //\n // Configure CLI output on the default logger\n //\n winston.cli();\n \n //\n // Configure CLI on an instance of winston.Logger\n //\n var logger = new winston.Logger({\n transports: [\n new (winston.transports.Console)()\n ]\n });\n \n logger.cli();\n```\n\n### Extending another object with Logging functionality\nOften in a given code base with lots of Loggers it is useful to add logging methods a different object so that these methods can be called with less syntax. Winston exposes this functionality via the 'extend' method:\n\n``` js\n var myObject = {};\n \n logger.extend(myObject);\n \n //\n // You can now call logger methods on 'myObject'\n //\n myObject.info('127.0.0.1 - there's no place like home');\n```\n\n## Working with Transports\nRight now there are four transports supported by winston core. If you have a transport you would like to add either open an issue or fork and submit a pull request. Commits are welcome, but I'll give you extra street cred if you __add tests too :D__\n \n1. __Console:__ Output to the terminal\n2. __Files:__ Append to a file\n3. __Loggly:__ Log to Logging-as-a-Service platform Loggly\n\n### Console Transport\n``` js\n winston.add(winston.transports.Console, options)\n```\n\nThe Console transport takes two simple options:\n\n* __level:__ Level of messages that this transport should log (default 'debug').\n* __silent:__ Boolean flag indicating whether to suppress output (default false).\n* __colorize:__ Boolean flag indicating if we should colorize output (default false).\n* __timestamp:__ Boolean flag indicating if we should prepend output with timestamps (default false). If function is specified, its return value will be used instead of timestamps.\n\n*Metadata:* Logged via util.inspect(meta);\n\n### File Transport\n``` js\n winston.add(winston.transports.File, options)\n```\n\nThe File transport should really be the 'Stream' transport since it will accept any [WritableStream][14]. It is named such because it will also accept filenames via the 'filename' option:\n\n* __level:__ Level of messages that this transport should log.\n* __silent:__ Boolean flag indicating whether to suppress output.\n* __colorize:__ Boolean flag indicating if we should colorize output.\n* __timestamp:__ Boolean flag indicating if we should prepend output with timestamps (default false). If function is specified, its return value will be used instead of timestamps.\n* __filename:__ The filename of the logfile to write output to.\n* __maxsize:__ Max size in bytes of the logfile, if the size is exceeded then a new file is created.\n* __maxFiles:__ Limit the number of files created when the size of the logfile is exceeded.\n* __stream:__ The WriteableStream to write output to.\n* __json:__ If true, messages will be logged as JSON (default true).\n\n*Metadata:* Logged via util.inspect(meta);\n\n### Loggly Transport\n``` js\n winston.add(winston.transports.Loggly, options);\n```\n\nThe Loggly transport is based on [Nodejitsu's][5] [node-loggly][6] implementation of the [Loggly][7] API. If you haven't heard of Loggly before, you should probably read their [value proposition][8]. The Loggly transport takes the following options. Either 'inputToken' or 'inputName' is required:\n\n* __level:__ Level of messages that this transport should log. \n* __subdomain:__ The subdomain of your Loggly account. *[required]*\n* __auth__: The authentication information for your Loggly account. *[required with inputName]*\n* __inputName:__ The name of the input this instance should log to.\n* __inputToken:__ The input token of the input this instance should log to.\n* __json:__ If true, messages will be sent to Loggly as JSON.\n\n*Metadata:* Logged in suggested [Loggly format][2]\n\n### Riak Transport\nAs of `0.3.0` the Riak transport has been broken out into a new module: [winston-riak][17]. Using it is just as easy:\n\n``` js\n var Riak = require('winston-riak').Riak;\n winston.add(Riak, options);\n```\n\nIn addition to the options accepted by the [riak-js][3] [client][4], the Riak transport also accepts the following options. It is worth noting that the riak-js debug option is set to *false* by default:\n\n* __level:__ Level of messages that this transport should log.\n* __bucket:__ The name of the Riak bucket you wish your logs to be in or a function to generate bucket names dynamically.\n\n``` js\n // Use a single bucket for all your logs\n var singleBucketTransport = new (Riak)({ bucket: 'some-logs-go-here' });\n \n // Generate a dynamic bucket based on the date and level\n var dynamicBucketTransport = new (Riak)({\n bucket: function (level, msg, meta, now) {\n var d = new Date(now);\n return level + [d.getDate(), d.getMonth(), d.getFullYear()].join('-');\n }\n });\n```\n\n*Metadata:* Logged as JSON literal in Riak\n\n### MongoDB Transport\nAs of `0.3.0` the MongoDB transport has been broken out into a new module: [winston-mongodb][16]. Using it is just as easy:\n\n``` js\n var MongoDB = require('winston-mongodb').MongoDB;\n winston.add(MongoDB, options);\n```\n\nThe MongoDB transport takes the following options. 'db' is required:\n\n* __level:__ Level of messages that this transport should log. \n* __silent:__ Boolean flag indicating whether to suppress output.\n* __db:__ The name of the database you want to log to. *[required]*\n* __collection__: The name of the collection you want to store log messages in, defaults to 'log'.\n* __safe:__ Boolean indicating if you want eventual consistency on your log messages, if set to true it requires an extra round trip to the server to ensure the write was committed, defaults to true.\n* __host:__ The host running MongoDB, defaults to localhost.\n* __port:__ The port on the host that MongoDB is running on, defaults to MongoDB's default port.\n\n*Metadata:* Logged as a native JSON object.\n\n### SimpleDB Transport\n\nThe [winston-simpledb][18] transport is just as easy:\n\n``` js\n var SimpleDB = require('winston-simpledb').SimpleDB;\n winston.add(SimpleDB, options);\n```\n\nThe SimpleDB transport takes the following options. All items marked with an asterisk are required:\n\n* __awsAccessKey__:* your AWS Access Key\n* __secretAccessKey__:* your AWS Secret Access Key\n* __awsAccountId__:* your AWS Account Id\n* __domainName__:* a string or function that returns the domain name to log to\n* __region__:* the region your domain resides in\n* __itemName__: a string ('uuid', 'epoch', 'timestamp') or function that returns the item name to log\n\n*Metadata:* Logged as a native JSON object to the 'meta' attribute of the item.\n\n### Mail Transport\n\nThe [winston-mail][19] is an email transport:\n\n``` js\n var Mail = require('winston-mail').Mail;\n winston.add(Mail, options);\n```\n\nThe Mail transport uses [node-mail][20] behind the scenes. Options are the following, `to` and `host` are required:\n\n* __to:__ The address(es) you want to send to. *[required]*\n* __from:__ The address you want to send from. (default: `winston@[server-host-name]`)\n* __host:__ SMTP server hostname\n* __port:__ SMTP port (default: 587 or 25)\n* __secure:__ Use secure\n* __username__ User for server auth\n* __password__ Password for server auth\n* __level:__ Level of messages that this transport should log. \n* __silent:__ Boolean flag indicating whether to suppress output.\n\n*Metadata:* Stringified as JSON in email.\n\n### Amazon SNS (Simple Notification System) Transport\n\nThe [winston-sns][21] transport uses amazon SNS to send emails, texts, or a bunch of other notifications.\n\n``` js\n require('winston-sns').SNS;\n winston.add(winston.transports.SNS, options);\n```\n\nOptions:\n\n* __aws_key:__ Your Amazon Web Services Key. *[required]*\n* __aws_secret:__ Your Amazon Web Services Secret. *[required]*\n* __subscriber:__ Subscriber number - found in your SNS AWS Console, after clicking on a topic. Same as AWS Account ID. *[required]*\n* __topic_arn:__ Also found in SNS AWS Console - listed under a topic as Topic ARN. *[required]*\n* __region:__ AWS Region to use. Can be one of: `us-east-1`,`us-west-1`,`eu-west-1`,`ap-southeast-1`,`ap-northeast-1`,`us-gov-west-1`,`sa-east-1`. (default: `us-east-1`)\n* __subject:__ Subject for notifications. (default: \"Winston Error Report\")\n* __message:__ Message of notifications. Uses placeholders for level (%l), error message (%e), and metadata (%m). (default: \"Level '%l' Error:\\n%e\\n\\nMetadata:\\n%m\")\n* __level:__ lowest level this transport will log. (default: `info`)\n\n### Graylog2 Transport\n\n[winston-graylog2][22] is a Graylog2 transport:\n\n``` js\n var Graylog2 = require('winston-graylog2').Graylog2;\n winston.add(Graylog2, options);\n```\n\nThe Graylog2 transport connects to a Graylog2 server over UDP using the following options:\n\n* __level:__ Level of messages this transport should log. (default: info)\n* __silent:__ Boolean flag indicating whether to suppress output. (default: false)\n\n* __graylogHost:__ IP address or hostname of the graylog2 server. (default: localhost)\n* __graylogPort:__ Port to send messages to on the graylog2 server. (default: 12201)\n* __graylogHostname:__ The hostname associated with graylog2 messages. (default: require('os').hostname())\n* __graylogFacility:__ The graylog2 facility to send log messages.. (default: nodejs)\n\n*Metadata:* Stringified as JSON in the full message GELF field.\n\n### Adding Custom Transports\nAdding a custom transport (say for one of the datastore on the Roadmap) is actually pretty easy. All you need to do is accept a couple of options, set a name, implement a log() method, and add it to the set of transports exposed by winston.\n\n``` js\n var util = require('util'),\n winston = require('winston');\n \n var CustomLogger = winston.transports.CustomerLogger = function (options) {\n //\n // Name this logger\n //\n this.name = 'customLogger';\n \n //\n // Set the level from your options\n //\n this.level = options.level || 'info';\n \n //\n // Configure your storage backing as you see fit\n //\n };\n \n //\n // Inherit from `winston.Transport` so you can take advantage\n // of the base functionality and `.handleExceptions()`.\n //\n util.inherits(CustomLogger, winston.Transport);\n \n CustomLogger.prototype.log = function (level, msg, meta, callback) {\n //\n // Store this message and metadata, maybe use some custom logic\n // then callback indicating success.\n //\n callback(null, true); \n };\n```\n\n## What's Next?\nWinston is stable and under active development. It is supported by and used at [Nodejitsu][5]. \n\n### Inspirations\n1. [npm][0]\n2. [log.js][9]\n3. [socket.io][10]\n4. [node-rlog][11]\n5. [BigBrother][12]\n6. [Loggly][7]\n\n### Road Map\n1. Improve support for adding custom Transports not defined in Winston core.\n2. Create API for reading from logs across all transports. \n3. Add more transports: Redis\n\n## Run Tests\nAll of the winston tests are written in [vows][13], and cover all of the use cases described above. You will need to add valid credentials for the various transports included to test/fixtures/test-config.json before running tests:\n\n``` js\n {\n \"transports\": {\n \"loggly\": {\n \"subdomain\": \"your-subdomain\",\n \"inputToken\": \"really-long-token-you-got-from-loggly\",\n \"auth\": {\n \"username\": \"your-username\",\n \"password\": \"your-password\"\n }\n }\n }\n }\n```\n\nOnce you have valid configuration and credentials you can run tests with [vows][13]:\n\n```\n vows --spec --isolate\n```\n\n#### Author: [Charlie Robbins](http://twitter.com/indexzero)\n#### Contributors: [Matthew Bergman](http://github.com/fotoverite), [Marak Squires](http://github.com/marak)\n\n[0]: https://github.com/isaacs/npm/blob/master/lib/utils/log.js\n[1]: http://nodejs.org/docs/v0.3.5/api/events.html#events.EventEmitter\n[2]: http://wiki.loggly.com/loggingfromcode\n[3]: http://riakjs.org\n[4]: https://github.com/frank06/riak-js/blob/master/src/http_client.coffee#L10\n[5]: http://nodejitsu.com\n[6]: http://github.com/nodejitsu/node-loggly\n[7]: http://loggly.com\n[8]: http://www.loggly.com/product/\n[9]: https://github.com/visionmedia/log.js\n[10]: http://socket.io\n[11]: https://github.com/jbrisbin/node-rlog\n[12]: https://github.com/feisty/BigBrother\n[13]: http://vowsjs.org\n[14]: http://nodejs.org/docs/v0.3.5/api/streams.html#writable_Stream\n[15]: http://github.com/nodejitsu/require-analyzer\n[16]: http://github.com/indexzero/winston-mongodb\n[17]: http://github.com/indexzero/winston-riak\n[18]: http://github.com/appsattic/winston-simpledb\n[19]: http://github.com/wavded/winston-mail\n[20]: https://github.com/weaver/node-mail\n[21]: https://github.com/jesseditson/winston-sns\n[22]: https://github.com/flite/winston-graylog2\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/flatiron/winston/issues" - }, - "_id": "winston@0.5.11", - "_from": "winston@0.5.x" -} diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/cli-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/cli-test.js deleted file mode 100644 index 365fba3f3..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/cli-test.js +++ /dev/null @@ -1,40 +0,0 @@ -/* - * cli-test.js: Tests for the cli levels available in winston. - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winston/logger/cli').addBatch({ - "When an instance of winston.Logger": { - topic: function () { - return new winston.Logger({ - transports: [ - new winston.transports.Console() - ] - }) - }, - "the cli() method": { - "should set the appropriate values on the logger": function (logger) { - logger.cli(); - assert.isTrue(logger.padLevels); - assert.isTrue(logger.transports.console.colorize); - assert.isFalse(logger.transports.console.timestamp); - Object.keys(winston.config.cli.levels).forEach(function (level) { - assert.isNumber(logger.levels[level]); - }); - - Object.keys(winston.config.cli.colors).forEach(function (color) { - assert.isString(winston.config.allColors[color]); - }); - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/container-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/container-test.js deleted file mode 100644 index 2fcc26a38..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/container-test.js +++ /dev/null @@ -1,99 +0,0 @@ -/* - * container-test.js: Tests for the Container object - * - * (C) 2011 Charlie Robbins - * MIT LICENSE - * - */ - -var assert = require('assert'), - fs = require('fs'), - http = require('http'), - path = require('path'), - vows = require('vows'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winston/container').addBatch({ - "An instance of winston.Container": { - topic: new winston.Container(), - "the add() method": { - topic: function (container) { - return container.add('default-test'); - }, - "should correctly instantiate a Logger": function (logger) { - assert.instanceOf(logger, winston.Logger); - }, - "the get() method": { - topic: function (logger, container) { - this.callback.apply(this, arguments); - }, - "should respond with the logger previously created": function (existing, container) { - var logger = container.get('default-test'); - assert.isTrue(existing === logger); - } - }, - "the has() method": { - topic: function (logger, container) { - this.callback.apply(this, arguments); - }, - "should indicate `default-test` logger exists": function (existing, container) { - assert.isTrue(container.has('default-test')); - }, - "should indicate `not-has` logger doesnt exists": function (existing, container) { - assert.isFalse(container.has('not-has')); - } - }, - "the close() method": { - topic: function (logger, container) { - this.callback.apply(this, arguments); - }, - "should remove the specified logger": function (logger, container) { - container.close('default-test'); - assert.isTrue(!container.loggers['default-test']); - } - } - } - }, - "An instance of winston.Container with explicit transports": { - topic: function () { - this.port = 9412; - this.transports = [ - new winston.transports.Webhook({ - port: this.port - }) - ]; - - this.container = new winston.Container({ - transports: this.transports - }); - - return null; - }, - "the get() method": { - topic: function (container) { - var server = http.createServer(function (req, res) { - res.end(); - }); - - server.listen(this.port, this.callback.bind(this, null)); - }, - "should add the logger correctly": function () { - this.someLogger = this.container.get('some-logger'); - assert.isObject(this.someLogger.transports); - assert.instanceOf(this.someLogger.transports['webhook'], winston.transports.Webhook); - assert.strictEqual(this.someLogger.transports['webhook'], this.transports[0]); - }, - "a second call to get()": { - "should respond with the same transport object": function () { - this.someOtherLogger = this.container.get('some-other-logger'); - - assert.isObject(this.someOtherLogger.transports); - assert.instanceOf(this.someOtherLogger.transports['webhook'], winston.transports.Webhook); - assert.strictEqual(this.someOtherLogger.transports['webhook'], this.transports[0]); - assert.strictEqual(this.someOtherLogger.transports['webhook'], this.someLogger.transports['webhook']); - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/custom-timestamp-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/custom-timestamp-test.js deleted file mode 100644 index c9753e2db..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/custom-timestamp-test.js +++ /dev/null @@ -1,62 +0,0 @@ -/* - * custom-timestamp-test.js: Test function as timestamp option for transport `{ timestamp: function () {} }` - * - * (C) 2011 Charlie Robbins, Tom Shinnick - * MIT LICENSE - * - */ - -var assert = require('assert'), - events = require('events'), - fs = require('fs'), - path = require('path'), - vows = require('vows'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -function assertTimestamp (basename, options) { - var filename = path.join(__dirname, 'fixtures', 'logs', basename + '.log'); - - try { fs.unlinkSync(filename) } - catch (ex) { } - - return { - topic: function () { - options.filename = filename; - var transport = new (winston.transports.File)(options); - - // We must wait until transport file has emitted the 'flush' - // event to be sure the file has been created and written - transport.once('flush', this.callback.bind(this, null, filename)); - transport.log('info', 'When a fake tree falls in the forest...', null, function () {}); - }, - "should log with the appropriate timestamp": function (_, filename) { - var data = fs.readFileSync(filename, 'utf8'); - assert.isNotNull(data.match(options.pattern)); - } - } -} - -vows.describe('winston/transport/timestamp').addBatch({ - "When timestamp option is used": { - "with file transport": { - "with value set to false": assertTimestamp('noTimestamp', { - pattern: /^info\:/, - json: false, - timestamp: false - }), - "with value set to true ": assertTimestamp('defaultTimestamp', { - pattern: /^\d\d? \w{3}/, - json: false, - timestamp: true - }), - "and function value": assertTimestamp('customTimestamp', { - pattern: /^\d{8}\./, - json: false, - timestamp: function () { - return '20110803.171657'; - } - }) - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/exception-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/exception-test.js deleted file mode 100644 index 6bc8aec83..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/exception-test.js +++ /dev/null @@ -1,46 +0,0 @@ -/* - * exception-test.js: Tests for exception data gathering in winston. - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winston/exception').addBatch({ - "When using the winston exception module": { - "the getProcessInfo() method": { - topic: winston.exception.getProcessInfo(), - "should respond with the appropriate data": function (info) { - helpers.assertProcessInfo(info); - } - }, - "the getOsInfo() method": { - topic: winston.exception.getOsInfo(), - "should respond with the appropriate data": function (info) { - helpers.assertOsInfo(info); - } - }, - "the getTrace() method": { - topic: winston.exception.getTrace(new Error()), - "should have the appropriate info": function (trace) { - helpers.assertTrace(trace); - } - }, - "the getAllInfo() method": { - topic: winston.exception.getAllInfo(new Error()), - "should have the appropriate info": function (info) { - assert.isObject(info); - assert.isArray(info.stack); - helpers.assertProcessInfo(info.process); - helpers.assertOsInfo(info.os); - helpers.assertTrace(info.trace); - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/keys/agent2-cert.pem b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/keys/agent2-cert.pem deleted file mode 100644 index 8e4354db4..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/keys/agent2-cert.pem +++ /dev/null @@ -1,13 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIB7DCCAZYCCQC7gs0MDNn6MTANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJV -UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO -BgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MjEgMB4GCSqGSIb3DQEJARYR -cnlAdGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEy -WjB9MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYD -VQQKEwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MjEg -MB4GCSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwXDANBgkqhkiG9w0BAQEF -AANLADBIAkEAyXb8FrRdKbhrKLgLSsn61i1C7w7fVVVd7OQsmV/7p9WB2lWFiDlC -WKGU9SiIz/A6wNZDUAuc2E+VwtpCT561AQIDAQABMA0GCSqGSIb3DQEBBQUAA0EA -C8HzpuNhFLCI3A5KkBS5zHAQax6TFUOhbpBCR0aTDbJ6F1liDTK1lmU/BjvPoj+9 -1LHwrmh29rK8kBPEjmymCQ== ------END CERTIFICATE----- diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/keys/agent2-key.pem b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/keys/agent2-key.pem deleted file mode 100644 index 522903c63..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/keys/agent2-key.pem +++ /dev/null @@ -1,9 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIBOgIBAAJBAMl2/Ba0XSm4ayi4C0rJ+tYtQu8O31VVXezkLJlf+6fVgdpVhYg5 -QlihlPUoiM/wOsDWQ1ALnNhPlcLaQk+etQECAwEAAQJBAMT6Bf34+UHKY1ObpsbH -9u2jsVblFq1rWvs8GPMY6oertzvwm3DpuSUp7PTgOB1nLTLYtCERbQ4ovtN8tn3p -OHUCIQDzIEGsoCr5vlxXvy2zJwu+fxYuhTZWMVuo1397L0VyhwIhANQh+yzqUgaf -WRtSB4T2W7ADtJI35ET61jKBty3CqJY3AiAIwju7dVW3A5WeD6Qc1SZGKZvp9yCb -AFI2BfVwwaY11wIgXF3PeGcvACMyMWsuSv7aPXHfliswAbkWuzcwA4TW01ECIGWa -cgsDvVFxmfM5NPSuT/UDTa6R5BFISB5ea0N0AR3I ------END RSA PRIVATE KEY----- diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/scripts/default-exceptions.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/scripts/default-exceptions.js deleted file mode 100644 index ab26aa5e1..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/scripts/default-exceptions.js +++ /dev/null @@ -1,21 +0,0 @@ -/* - * default-exceptions.js: A test fixture for logging exceptions with the default winston logger. - * - * (C) 2011 Charlie Robbins - * MIT LICENCE - * - */ - -var path = require('path'), - winston = require('../../../lib/winston'); - -winston.handleExceptions([ - new (winston.transports.File)({ - filename: path.join(__dirname, '..', 'logs', 'default-exception.log'), - handleExceptions: true - }) -]); - -setTimeout(function () { - throw new Error('OH NOES! It failed!'); -}, 1000); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/scripts/exit-on-error.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/scripts/exit-on-error.js deleted file mode 100644 index fa3dd6566..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/scripts/exit-on-error.js +++ /dev/null @@ -1,25 +0,0 @@ -/* - * default-exceptions.js: A test fixture for logging exceptions with the default winston logger. - * - * (C) 2011 Charlie Robbins - * MIT LICENCE - * - */ - -var path = require('path'), - winston = require('../../../lib/winston'); - -winston.exitOnError = function (err) { - return err.message !== 'Ignore this error'; -}; - -winston.handleExceptions([ - new (winston.transports.File)({ - filename: path.join(__dirname, '..', 'logs', 'exit-on-error.log'), - handleExceptions: true - }) -]); - -setTimeout(function () { - throw new Error('Ignore this error'); -}, 1000); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/scripts/log-exceptions.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/scripts/log-exceptions.js deleted file mode 100644 index 43ce7ebcf..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/scripts/log-exceptions.js +++ /dev/null @@ -1,25 +0,0 @@ -/* - * log-exceptions.js: A test fixture for logging exceptions in winston. - * - * (C) 2011 Charlie Robbins - * MIT LICENCE - * - */ - -var path = require('path'), - winston = require('../../../lib/winston'); - -var logger = new (winston.Logger)({ - transports: [ - new (winston.transports.File)({ - filename: path.join(__dirname, '..', 'logs', 'exception.log'), - handleExceptions: true - }) - ] -}); - -logger.handleExceptions(); - -setTimeout(function () { - throw new Error('OH NOES! It failed!'); -}, 1000); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/scripts/unhandle-exceptions.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/scripts/unhandle-exceptions.js deleted file mode 100644 index 5d722a74a..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/fixtures/scripts/unhandle-exceptions.js +++ /dev/null @@ -1,26 +0,0 @@ -/* - * unhandle-exceptions.js: A test fixture for using `.unhandleExceptions()` winston. - * - * (C) 2011 Charlie Robbins - * MIT LICENCE - * - */ - -var path = require('path'), - winston = require('../../../lib/winston'); - -var logger = new (winston.Logger)({ - transports: [ - new (winston.transports.File)({ - filename: path.join(__dirname, '..', 'logs', 'unhandle-exception.log'), - handleExceptions: true - }) - ] -}); - -logger.handleExceptions(); -logger.unhandleExceptions(); - -setTimeout(function () { - throw new Error('OH NOES! It failed!'); -}, 1000); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/helpers.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/helpers.js deleted file mode 100644 index f961f8543..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/helpers.js +++ /dev/null @@ -1,179 +0,0 @@ -/* - * helpers.js: Test helpers for winston - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var assert = require('assert'), - fs = require('fs'), - path = require('path'), - spawn = require('child_process').spawn, - util = require('util'), - loggly = require('loggly'), - vows = require('vows'), - winston = require('../lib/winston'); - -var helpers = exports; - -helpers.loadConfig = function (dir) { - try { - if (helpers.config) return helpers.config; - var configFile = path.join(dir || __dirname, 'fixtures', 'test-config.json'), - stats = fs.statSync(configFile), - config = JSON.parse(fs.readFileSync(configFile).toString()); - - helpers.config = config; - return config; - } - catch (ex) { - console.error('test/fixtures/test-config.json must be created with valid data before running tests'); - return false; - } -}; - -helpers.size = function (obj) { - var size = 0, key; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - size++; - } - } - - return size; -}; - -helpers.tryUnlink = function (file) { - try { fs.unlinkSync(file) } - catch (ex) { } -}; - -helpers.assertProcessInfo = function (info) { - assert.isNumber(info.pid); - assert.isNumber(info.uid); - assert.isNumber(info.gid); - assert.isString(info.cwd); - assert.isString(info.execPath); - assert.isString(info.version); - assert.isArray(info.argv); - assert.isObject(info.memoryUsage); -}; - -helpers.assertOsInfo = function (info) { - assert.isArray(info.loadavg); - assert.isNumber(info.uptime); -}; - -helpers.assertTrace = function (trace) { - trace.forEach(function (site) { - assert.isTrue(!site.column || typeof site.column === 'number'); - assert.isTrue(!site.line || typeof site.line === 'number'); - assert.isTrue(!site.file || typeof site.file === 'string'); - assert.isTrue(!site.method || typeof site.method === 'string'); - assert.isTrue(!site.function || typeof site.function === 'string'); - assert.isTrue(typeof site.native === 'boolean'); - }); -}; - -helpers.assertLogger = function (logger, level) { - assert.instanceOf(logger, winston.Logger); - assert.isFunction(logger.log); - assert.isFunction(logger.add); - assert.isFunction(logger.remove); - assert.equal(logger.level, level || "info"); - Object.keys(logger.levels).forEach(function (method) { - assert.isFunction(logger[method]); - }); -}; - -helpers.assertConsole = function (transport) { - assert.instanceOf(transport, winston.transports.Console); - assert.isFunction(transport.log); -}; - -helpers.assertFile = function (transport) { - assert.instanceOf(transport, winston.transports.File); - assert.isFunction(transport.log); -} - -helpers.assertLoggly = function (transport) { - assert.instanceOf(transport, winston.transports.Loggly); - assert.isFunction(transport.log); -}; - -helpers.assertWebhook = function (transport) { - assert.instanceOf(transport, winston.transports.Webhook); - assert.isFunction(transport.log); -}; - -helpers.assertCouchdb = function (transport) { - assert.instanceOf(transport, winston.transports.Couchdb); - assert.isFunction(transport.log); -}; - -helpers.assertHandleExceptions = function (options) { - return { - topic: function () { - var that = this, - child = spawn('node', [options.script]); - - helpers.tryUnlink(options.logfile); - child.on('exit', function () { - fs.readFile(options.logfile, that.callback); - }); - }, - "should save the error information to the specified file": function (err, data) { - assert.isTrue(!err); - data = JSON.parse(data); - - assert.isObject(data); - helpers.assertProcessInfo(data.process); - helpers.assertOsInfo(data.os); - helpers.assertTrace(data.trace); - } - } -} - -helpers.testNpmLevels = function (transport, assertMsg, assertFn) { - return helpers.testLevels(winston.config.npm.levels, transport, assertMsg, assertFn); -}; - -helpers.testSyslogLevels = function (transport, assertMsg, assertFn) { - return helpers.testLevels(winston.config.syslog.levels, transport, assertMsg, assertFn); -}; - -helpers.testLevels = function (levels, transport, assertMsg, assertFn) { - var tests = {}; - - Object.keys(levels).forEach(function (level) { - var test = { - topic: function () { - transport.log(level, 'test message', {}, this.callback.bind(this, null)); - } - }; - - test[assertMsg] = assertFn; - tests['with the ' + level + ' level'] = test; - }); - - var metadatatest = { - topic: function () { - transport.log('info', 'test message', { metadata: true }, this.callback.bind(this, null)); - } - }; - - metadatatest[assertMsg] = assertFn; - tests['when passed metadata'] = metadatatest; - - var primmetadatatest = { - topic: function () { - transport.log('info', 'test message', 'metadata', this.callback.bind(this, null)); - } - }; - - primmetadatatest[assertMsg] = assertFn; - tests['when passed primitive metadata'] = primmetadatatest; - - return tests; -}; diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/log-exception-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/log-exception-test.js deleted file mode 100644 index b077a0ab8..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/log-exception-test.js +++ /dev/null @@ -1,58 +0,0 @@ -/* - * exception-test.js: Tests for exception data gathering in winston. - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var assert = require('assert'), - path = require('path'), - spawn = require('child_process').spawn, - vows = require('vows'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winston/logger/exceptions').addBatch({ - "When using winston": { - "the handleException() method": { - "with a custom winston.Logger instance": helpers.assertHandleExceptions({ - script: path.join(__dirname, 'fixtures', 'scripts', 'log-exceptions.js'), - logfile: path.join(__dirname, 'fixtures', 'logs', 'exception.log') - }), - "with the default winston logger": helpers.assertHandleExceptions({ - script: path.join(__dirname, 'fixtures', 'scripts', 'default-exceptions.js'), - logfile: path.join(__dirname, 'fixtures', 'logs', 'default-exception.log') - }), - "when a custom exitOnError function is set": { - topic: function () { - var that = this, - scriptDir = path.join(__dirname, 'fixtures', 'scripts'); - - that.child = spawn('node', [path.join(scriptDir, 'exit-on-error.js')]); - setTimeout(this.callback.bind(this), 1500); - }, - "should not exit the process": function () { - assert.isFalse(this.child.killed); - this.child.kill(); - } - } - }, - "the unhandleException() method": { - topic: function () { - var that = this, - child = spawn('node', [path.join(__dirname, 'fixtures', 'scripts', 'unhandle-exceptions.js')]), - exception = path.join(__dirname, 'fixtures', 'logs', 'unhandle-exception.log'); - - helpers.tryUnlink(exception); - child.on('exit', function () { - path.exists(exception, that.callback.bind(this, null)); - }); - }, - "should not write to the specified error file": function (err, exists) { - assert.isTrue(!err); - assert.isFalse(exists); - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/log-rewriter-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/log-rewriter-test.js deleted file mode 100644 index 4753fcce9..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/log-rewriter-test.js +++ /dev/null @@ -1,98 +0,0 @@ -/* - * log-rewriter-test.js: Tests for rewriting metadata in winston. - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var assert = require('assert'), - vows = require('vows'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winston/logger/rewriter').addBatch({ - "An instance of winston.Logger": { - topic: new (winston.Logger)({transports: [ - new (winston.transports.Console)({ level: 'info' }) - ]}), - "the addRewriter() method": { - topic: function(logger) { - logger.addRewriter(function(level, msg, meta) { - meta.level = level; - meta.msg = msg; - meta.foo = 'bar'; - return meta; - }); - return logger; - }, - "should add the rewriter": function(logger) { - assert.equal(helpers.size(logger.rewriters), 1); - }, - "the log() method": { - topic: function(logger) { - logger.once('logging', this.callback); - logger.log('info', 'test message', {"a": "b"}); - }, - "should run the rewriter": function(transport, level, msg, meta) { - assert.equal(meta.a, 'b'); - assert.equal(meta.level, 'info'); - assert.equal(meta.msg, 'test message'); - assert.equal(meta.foo, 'bar'); - } - } - } - } -}).addBatch({ - "An instance of winston.Logger with explicit rewriter": { - topic: new (winston.Logger)({transports: [ - new (winston.transports.Console)({ level: 'info'}) - ], rewriters: [ - function(level, msg, meta) { - meta.level = level; - meta.msg = msg; - meta.foo = 'bar'; - return meta; - } - ]}), - "should add the rewriter": function(logger) { - assert.equal(helpers.size(logger.rewriters), 1); - }, - "the log() method": { - topic: function(logger) { - logger.once('logging', this.callback); - logger.log('info', 'test message', {"a": "b"}); - }, - "should run the rewriter": function(transport, level, msg, meta) { - assert.equal(meta.a, 'b'); - assert.equal(meta.level, 'info'); - assert.equal(meta.msg, 'test message'); - assert.equal(meta.foo, 'bar'); - } - } - } -}).addBatch({ - "An instance of winston.Logger with rewriters": { - topic: new (winston.Logger)({transports: [ - new (winston.transports.Console)({ level: 'info' }) - ], rewriters: [ - function(level, msg, meta) { - meta.numbers.push(1); - return meta; - }, - function(level, msg, meta) { - meta.numbers.push(2); - return meta; - } - ]}), - "the log() method": { - topic: function(logger) { - logger.once('logging', this.callback); - logger.log('info', 'test message', {"numbers": [0]}); - }, - "should run the rewriters in correct order": function(transport, level, msg, meta) { - assert.deepEqual(meta.numbers, [0, 1, 2]); - } - } - } -}).export(module); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/logger-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/logger-test.js deleted file mode 100644 index 01058250d..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/logger-test.js +++ /dev/null @@ -1,199 +0,0 @@ -/* - * logger-test.js: Tests for instances of the winston Logger - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winton/logger').addBatch({ - "An instance of winston.Logger": { - topic: new (winston.Logger)({ transports: [new (winston.transports.Console)({ level: 'info' })] }), - "should have the correct methods / properties defined": function (logger) { - helpers.assertLogger(logger); - }, - "the add() with an unsupported transport": { - "should throw an error": function () { - assert.throws(function () { logger.add('unsupported') }, Error); - } - } - } -}).addBatch({ - "An instance of winston.Logger with no transports": { - topic: new (winston.Logger)({ emitErrs: true }), - "the log() method should throw an error": function (logger) { - assert.throws(function () { logger.log('anything') }, Error); - }, - "the extend() method called on an empty object": { - topic: function (logger) { - var empty = {}; - logger.extend(empty); - return empty; - }, - "should define the appropriate methods": function (extended) { - ['log', 'profile', 'startTimer'].concat(Object.keys(winston.config.npm.levels)).forEach(function (method) { - assert.isFunction(extended[method]); - }); - } - }, - "the add() method with a supported transport": { - topic: function (logger) { - return logger.add(winston.transports.Console); - }, - "should add the console Transport onto transports": function (logger) { - assert.equal(helpers.size(logger.transports), 1); - helpers.assertConsole(logger.transports.console); - }, - "should throw an error when the same Transport is added": function (logger) { - assert.throws(function () { logger.add(winston.transports.Console) }, Error); - }, - "the log() method": { - topic: function (logger) { - logger.once('logging', this.callback); - logger.log('info', 'test message'); - }, - "should emit the 'log' event with the appropriate transport": function (transport, ign) { - helpers.assertConsole(transport); - } - }, - "the profile() method": { - "when passed a callback": { - topic: function (logger) { - var that = this; - logger.profile('test1'); - setTimeout(function () { - logger.profile('test1', function (err, level, msg, meta) { - that.callback(err, level, msg, meta, logger); - }); - }, 1000); - }, - "should respond with the appropriate profile message": function (err, level, msg, meta, logger) { - assert.isNull(err); - assert.equal(level, 'info'); - assert.match(meta.duration, /(\d+)ms/); - assert.isTrue(typeof logger.profilers['test'] === 'undefined'); - } - }, - "when not passed a callback": { - topic: function (logger) { - var that = this; - logger.profile('test2'); - logger.once('logging', that.callback.bind(null, null)); - setTimeout(function () { - logger.profile('test2'); - }, 1000); - }, - "should respond with the appropriate profile message": function (err, transport, level, msg, meta) { - assert.isNull(err); - assert.equal(level, 'info'); - assert.match(meta.duration, /(\d+)ms/); - } - } - }, - "the startTimer() method": { - "when passed a callback": { - topic: function (logger) { - var that = this; - var timer = logger.startTimer() - setTimeout(function () { - timer.done('test', function (err, level, msg, meta) { - that.callback(err, level, msg, meta, logger); - }); - }, 1000); - }, - "should respond with the appropriate message": function (err, level, msg, meta, logger) { - assert.isNull(err); - assert.equal(level, 'info'); - assert.match(meta.duration, /(\d+)ms/); - } - }, - "when not passed a callback": { - topic: function (logger) { - var that = this; - var timer = logger.startTimer() - logger.once('logging', that.callback.bind(null, null)); - setTimeout(function () { - timer.done(); - }, 1000); - }, - "should respond with the appropriate message": function (err, transport, level, msg, meta) { - assert.isNull(err); - assert.equal(level, 'info'); - assert.match(meta.duration, /(\d+)ms/); - - var duration = parseInt(meta.duration); - assert.isNumber(duration); - assert.isTrue(duration > 900 && duration < 1100); - } - } - }, - "and adding an additional transport": { - topic: function (logger) { - return logger.add(winston.transports.File, { - filename: path.join(__dirname, 'fixtures', 'logs', 'testfile2.log') - }); - }, - "should be able to add multiple transports": function (logger) { - assert.equal(helpers.size(logger.transports), 2); - helpers.assertConsole(logger.transports.console); - helpers.assertFile(logger.transports.file); - } - } - } - } -}).addBatch({ - "The winston logger": { - topic: new (winston.Logger)({ - transports: [ - new (winston.transports.Console)(), - new (winston.transports.File)({ filename: path.join(__dirname, 'fixtures', 'logs', 'filelog.log' )}) - ] - }), - "should return have two transports": function (logger) { - assert.equal(helpers.size(logger.transports), 2); - }, - "the remove() with an unadded transport": { - "should throw an Error": function (logger) { - assert.throws(function () { logger.remove(winston.transports.Loggly) }, Error); - } - }, - "the remove() method with an added transport": { - topic: function (logger) { - return logger.remove(winston.transports.Console); - }, - "should remove the Console transport from transports": function (logger) { - assert.equal(helpers.size(logger.transports), 1); - helpers.assertFile(logger.transports.file); - }, - "and removing an additional transport": { - topic: function (logger) { - return logger.remove(winston.transports.File); - }, - "should remove File transport from transports": function (logger) { - assert.equal(helpers.size(logger.transports), 0); - } - } - } - } -}).addBatch({ - "The winston logger": { - topic: new (winston.Logger)({ - transports: [ - new (winston.transports.Console)(), - new (winston.transports.File)({ filename: path.join(__dirname, 'fixtures', 'logs', 'filelog.log' )}) - ] - }), - "the clear() method": { - "should remove all transports": function (logger) { - logger.clear(); - assert.equal(helpers.size(logger.transports), 0); - } - } - } -}).export(module); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/console-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/console-test.js deleted file mode 100644 index 07f5a6ea6..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/console-test.js +++ /dev/null @@ -1,39 +0,0 @@ -/* - * console-test.js: Tests for instances of the Console transport - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var npmTransport = new (winston.transports.Console)(), - syslogTransport = new (winston.transports.Console)({ levels: winston.config.syslog.levels }); - -vows.describe('winston/transports/console').addBatch({ - "An instance of the Console Transport": { - "with npm levels": { - "should have the proper methods defined": function () { - helpers.assertConsole(npmTransport); - }, - "the log() method": helpers.testNpmLevels(npmTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - }, - "with syslog levels": { - "should have the proper methods defined": function () { - helpers.assertConsole(syslogTransport); - }, - "the log() method": helpers.testSyslogLevels(syslogTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/couchdb-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/couchdb-test.js deleted file mode 100644 index d0057e89c..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/couchdb-test.js +++ /dev/null @@ -1,47 +0,0 @@ -/* - * couchdb-test.js: Tests for instances of the Couchdb transport - * - * (C) 2011 Max Ogden - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - fs = require('fs'), - http = require('http'), - assert = require('assert'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var couchdbTransport = new (winston.transports.Couchdb)({ - "host": "localhost", - "port": 4567, - "db": "logs" -}); - -var server = http.createServer(function (req, res) { - res.end(); -}); - -server.listen(4567); - -vows.describe('winston/transports/couchdb').addBatch({ - "An instance of the Couchdb Transport": { - "when passed valid options": { - "should have the proper methods defined": function () { - helpers.assertCouchdb(couchdbTransport); - }, - "the log() method": helpers.testNpmLevels(couchdbTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - } - } -}).addBatch({ - "When the tests are over": { - "the server should cleanup": function () { - server.close(); - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/file-maxfiles-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/file-maxfiles-test.js deleted file mode 100644 index a9fa89e8c..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/file-maxfiles-test.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - * file-maxfiles-test.js: Tests for instances of the File transport setting the max file size, - * and setting a number for max files created. - * maxSize * maxFiles = total storage used by winston. - * - * (C) 2011 Daniel Aristizabal - * MIT LICENSE - * - */ - -var assert = require('assert'), - exec = require('child_process').exec, - fs = require('fs'), - path = require('path'), - vows = require('vows'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var maxfilesTransport = new winston.transports.File({ - timestamp: false, - json: false, - filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxfiles.log'), - maxsize: 4096, - maxFiles: 3 -}); - -vows.describe('winston/transports/file/maxfiles').addBatch({ - "An instance of the File Transport": { - "when passed a valid filename": { - topic: maxfilesTransport, - "should be a valid transporter": function (transportTest) { - helpers.assertFile(transportTest); - }, - "should set the maxFiles option correctly": function (transportTest) { - assert.isNumber(transportTest.maxFiles); - } - }, - "when delete old test files": { - topic: function () { - exec('rm -rf ' + path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxfiles*'), this.callback); - }, - "and when passed more files than the maxFiles": { - topic: function () { - var that = this, - created = 0; - - function data(ch) { - return new Array(1018).join(String.fromCharCode(65 + ch)); - }; - - function logKbytes(kbytes, txt) { - // - // With no timestamp and at the info level, - // winston adds exactly 7 characters: - // [info](4)[ :](2)[\n](1) - // - for (var i = 0; i < kbytes; i++) { - maxfilesTransport.log('info', data(txt), null, function () { }); - } - } - - maxfilesTransport.on('logged', function () { - if (++created === 6) { - return that.callback(); - } - - logKbytes(4, created); - }); - - logKbytes(4, created); - }, - "should be only 3 files called 5.log, 4.log and 3.log": function () { - for (var num = 0; num < 6; num++) { - var file = !num ? 'testmaxfiles.log' : 'testmaxfiles' + num + '.log', - fullpath = path.join(__dirname, '..', 'fixtures', 'logs', file); - - // There should be no files with that name - if (num >= 0 && num < 3) { - return assert.throws(function () { - fs.statSync(file); - }, Error); - } - - // The other files should be exist - assert.doesNotThrow(function () { - fs.statSync(file); - }, Error); - } - }, - "should have the correct content": function () { - ['D', 'E', 'F'].forEach(function (name, inx) { - var counter = inx + 3, - logsDir = path.join(__dirname, '..', 'fixtures', 'logs'), - content = fs.readFileSync(path.join(logsDir, 'testmaxfiles' + counter + '.log'), 'utf-8'); - // The content minus the 7 characters added by winston - assert.lengthOf(content.match(new RegExp(name, 'g')), 4068); - }); - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/file-maxsize-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/file-maxsize-test.js deleted file mode 100644 index 7d20e0893..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/file-maxsize-test.js +++ /dev/null @@ -1,82 +0,0 @@ -/* - * file-test.js: Tests for instances of the File transport - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var assert = require('assert'), - exec = require('child_process').exec, - fs = require('fs'), - path = require('path'), - vows = require('vows'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var maxsizeTransport = new winston.transports.File({ - timestamp: false, - json: false, - filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxsize.log'), - maxsize: 4096 -}); - -vows.describe('winston/transports/file/maxsize').addBatch({ - "An instance of the File Transport": { - "when passed a valid filename": { - "the log() method": { - topic: function () { - exec('rm -rf ' + path.join(__dirname, '..', 'fixtures', 'logs', 'testmaxsize*'), this.callback); - }, - "when passed more than the maxsize": { - topic: function () { - var that = this, - data = new Array(1018).join('-'); - - // - // Setup a list of files which we will later stat. - // - that.files = []; - - function logKbytes (kbytes) { - // - // With no timestamp and at the info level, - // winston adds exactly 7 characters: - // [info](4)[ :](2)[\n](1) - // - for (var i = 0; i < kbytes; i++) { - maxsizeTransport.log('info', data, null, function () { }); - } - } - - maxsizeTransport.on('open', function (file) { - var match = file.match(/(\d+)\.log$/), - count = match ? match[1] : 0; - - that.files.push(file); - - if (that.files.length === 5) { - return that.callback(); - } - - logKbytes(4); - }); - - logKbytes(4); - }, - "should create multiple files correctly": function () { - this.files.forEach(function (file) { - try { - var stats = fs.statSync(file); - assert.equal(stats.size, 4096); - } - catch (ex) { - assert.isNull(ex); - } - }); - } - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/file-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/file-test.js deleted file mode 100644 index c28779441..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/file-test.js +++ /dev/null @@ -1,50 +0,0 @@ -/* - * file-test.js: Tests for instances of the File transport - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - fs = require('fs'), - assert = require('assert'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var stream = fs.createWriteStream(path.join(__dirname, '..', 'fixtures', 'logs', 'testfile.log')), - fileTransport = new (winston.transports.File)({ filename: path.join(__dirname, '..', 'fixtures', 'logs', 'testfilename.log') }), - streamTransport = new (winston.transports.File)({ stream: stream }); - -vows.describe('winston/transports/file').addBatch({ - "An instance of the File Transport": { - "when passed a valid filename": { - "should have the proper methods defined": function () { - helpers.assertFile(fileTransport); - }, - "the log() method": helpers.testNpmLevels(fileTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - }, - "when passed a valid file stream": { - "should have the proper methods defined": function () { - helpers.assertFile(streamTransport); - }, - "the log() method": helpers.testNpmLevels(streamTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - } - } -}).addBatch({ - "These tests have a non-deterministic end": { - topic: function () { - setTimeout(this.callback, 200); - }, - "and this should be fixed before releasing": function () { - assert.isTrue(true); - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/loggly-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/loggly-test.js deleted file mode 100644 index 8271b9004..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/loggly-test.js +++ /dev/null @@ -1,61 +0,0 @@ -/* - * loggly-test.js: Tests for instances of the Loggly transport - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - assert = require('assert'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var config = helpers.loadConfig(); - -if (!config) { - return; -} - -var tokenTransport = new (winston.transports.Loggly)({ - subdomain: config.transports.loggly.subdomain, - inputToken: config.transports.loggly.inputToken - }), - nameTransport = new (winston.transports.Loggly)({ - subdomain: config.transports.loggly.subdomain, - inputName: config.transports.loggly.inputName, - auth: config.transports.loggly.auth - }); - -vows.describe('winston/transports/loggly').addBatch({ - "An instance of the Loggly Transport": { - "when passed an input token": { - "should have the proper methods defined": function () { - helpers.assertLoggly(tokenTransport); - }, - "the log() method": helpers.testNpmLevels(tokenTransport, "should log messages to loggly", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }), - "the log() method with no metadata": { - topic: function () { - tokenTransport.log('info', 'test-message', null, this.callback.bind(null, null)); - }, - "should respond immediately": function () { - assert.isTrue(true); - } - } - }, - "when passed an input name": { - "should have the proper methods defined": function () { - helpers.assertLoggly(nameTransport); - }, - "the log() method": helpers.testNpmLevels(nameTransport, "should log messages to loggly", function (ign, err, result) { - assert.isNull(err); - assert.isTrue(result === true || result.response === 'ok'); - }) - } - } -}).export(module); - diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/webhook-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/webhook-test.js deleted file mode 100644 index e106374dc..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/transports/webhook-test.js +++ /dev/null @@ -1,119 +0,0 @@ -/* - * webhook-test.js: Tests for instances of the Webhook transport - * - * (C) 2011 Marak Squires - * MIT LICENSE - * - */ - -var path = require('path'), - vows = require('vows'), - fs = require('fs'), - http = require('http'), - https = require('https'), - assert = require('assert'), - winston = require('../../lib/winston'), - helpers = require('../helpers'); - -var webhookTransport = new (winston.transports.Webhook)({ - "host": "localhost", - "port": 8080, - "path": "/winston-test" -}); - -var httpsWebhookTransport = new (winston.transports.Webhook)({ - "host": "localhost", - "port": 8081, - "path": "/winston-test", - "ssl": true -}); - -var authWebhookTransport = new (winston.transports.Webhook)({ - "host": "localhost", - "port": 8080, - "path": "/winston-auth-test", - "auth": { - "username": "winston", - "password": "churchill" - } -}); - -var requestsAuthenticated = true; - -var server = http.createServer(function (req, res) { - if (req.url == '/winston-auth-test') { - // - // Test if request has been correctly authenticated - // - // Strip 'Basic' from Authorization header - var signature = req.headers['authorization'].substr(6); - requestsAuthenticated = requestsAuthenticated && - new Buffer(signature, 'base64').toString('utf8') == 'winston:churchill'; - } - res.end(); -}); - -server.listen(8080); - - -var httpsServer = https.createServer({ - cert: fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'keys', 'agent2-cert.pem')), - key: fs.readFileSync(path.join(__dirname, '..', 'fixtures', 'keys', 'agent2-key.pem')) -}, function (req, res) { - res.end(); -}); - -httpsServer.listen(8081); - -vows.describe('winston/transports/webhook').addBatch({ - "An instance of the Webhook Transport": { - "when passed valid options": { - "should have the proper methods defined": function () { - helpers.assertWebhook(webhookTransport); - }, - "the log() method": helpers.testNpmLevels(webhookTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - } - }, - "An https instance of the Webhook Transport": { - "when passed valid options": { - "should have the proper methods defined": function () { - helpers.assertWebhook(httpsWebhookTransport); - }, - "the log() method": helpers.testNpmLevels(httpsWebhookTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - } - }, - "An http Basic Auth instance of the Webhook Transport": { - "when passed valid options": { - "should have the proper methods defined": function () { - helpers.assertWebhook(authWebhookTransport); - }, - "the log() method": helpers.testNpmLevels(authWebhookTransport, "should respond with true", function (ign, err, logged) { - assert.isNull(err); - assert.isTrue(logged); - }) - } - } -}).addBatch({ - "When the tests are over": { - topic: function () { - // - // Delay destruction of the server since the - // WebHook transport responds before the request - // has actually be completed. - // - setTimeout(this.callback, 1000); - }, - "the server should cleanup": function () { - server.close(); - }, - "requests have been correctly authenticated": function () { - assert.ok(requestsAuthenticated); - } - } -}).export(module); diff --git a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/winston-test.js b/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/winston-test.js deleted file mode 100644 index e790cb9b3..000000000 --- a/node/node_modules/grunt/node_modules/prompt/node_modules/winston/test/winston-test.js +++ /dev/null @@ -1,100 +0,0 @@ -/* - * logger-test.js: Tests for instances of the winston Logger - * - * (C) 2010 Charlie Robbins - * MIT LICENSE - * - */ - -var fs = require('fs'), - path = require('path'), - vows = require('vows'), - http = require('http'), - assert = require('assert'), - winston = require('../lib/winston'), - helpers = require('./helpers'); - -vows.describe('winston').addBatch({ - "The winston module": { - topic: function () { - winston.default.transports.console.level = 'silly'; - return null; - }, - "should have the correct methods defined": function () { - assert.isObject(winston.transports); - assert.isFunction(winston.Transport); - assert.isTrue(!winston.transports.Transport); - assert.isFunction(winston.transports.Console); - assert.isFunction(winston.transports.File); - assert.isFunction(winston.transports.Loggly); - assert.isFunction(winston.transports.Webhook); - assert.isObject(winston.default.transports.console); - assert.isFalse(winston.emitErrs); - assert.isObject(winston.config); - ['Logger', 'add', 'remove', 'extend'] - .concat(Object.keys(winston.config.npm.levels)) - .forEach(function (key) { - assert.isFunction(winston[key]); - }); - }, - "it should": { - topic: function () { - fs.readFile(path.join(__dirname, '..', 'package.json'), this.callback); - }, - "have the correct version set": function (err, data) { - assert.isNull(err); - data = JSON.parse(data.toString()); - assert.equal(winston.version, data.version); - } - }, - "the log() method": helpers.testNpmLevels(winston, "should respond without an error", function (err) { - assert.isNull(err); - }), - "the extend() method called on an empty object": { - topic: function (logger) { - var empty = {}; - winston.extend(empty); - return empty; - }, - "should define the appropriate methods": function (extended) { - ['log', 'profile', 'startTimer'].concat(Object.keys(winston.config.npm.levels)).forEach(function (method) { - assert.isFunction(extended[method]); - }); - } - } - } -}).addBatch({ - "The winston module": { - "the setLevels() method": { - topic: function () { - winston.setLevels(winston.config.syslog.levels); - return null; - }, - "should have the proper methods defined": function () { - assert.isObject(winston.transports); - assert.isFunction(winston.transports.Console); - assert.isFunction(winston.transports.Loggly); - assert.isFunction(winston.transports.Webhook); - assert.isObject(winston.default.transports.console); - assert.isFalse(winston.emitErrs); - assert.isObject(winston.config); - - var newLevels = Object.keys(winston.config.syslog.levels); - ['Logger', 'add', 'remove', 'extend'] - .concat(newLevels) - .forEach(function (key) { - assert.isFunction(winston[key]); - }); - - - Object.keys(winston.config.npm.levels) - .filter(function (key) { - return newLevels.indexOf(key) === -1; - }) - .forEach(function (key) { - assert.isTrue(typeof winston[key] === 'undefined'); - }); - } - } - } -}).export(module); diff --git a/node/node_modules/grunt/node_modules/prompt/package.json b/node/node_modules/grunt/node_modules/prompt/package.json deleted file mode 100644 index a1c96bd4d..000000000 --- a/node/node_modules/grunt/node_modules/prompt/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "prompt", - "description": "A beautiful command-line prompt for node.js", - "version": "0.1.12", - "author": { - "name": "Nodejitsu Inc.", - "email": "info@nodejitsu.com" - }, - "contributors": [ - { - "name": "Charlie Robbins", - "email": "charlie@nodejitsu.com" - }, - { - "name": "Joshua Holbrook", - "email": "josh.holbrook@gmail.com" - }, - { - "name": "Bradley Meck", - "email": "bradley.meck@gmail.com" - }, - { - "name": "Maciej Malecki", - "email": "maciej@nodejitsu.com" - } - ], - "repository": { - "type": "git", - "url": "http://github.com/flatiron/prompt.git" - }, - "dependencies": { - "async": "0.1.x", - "colors": "0.x.x", - "pkginfo": "0.x.x", - "winston": "0.5.x" - }, - "devDependencies": { - "vows": "0.6.x" - }, - "main": "./lib/prompt", - "scripts": { - "test": "vows test/prompt-test.js --spec", - "test-all": "vows --spec" - }, - "engines": { - "node": ">= 0.4.0" - }, - "readme": "# prompt [![Build Status](https://secure.travis-ci.org/flatiron/prompt.png)](http://travis-ci.org/flatiron/prompt)\n\nA beautiful command-line prompt for node.js\n\n## Features\n\n* prompts the user for input\n* supports validation and defaults\n* hides passwords\n\n## Installation\n\n### Installing npm (node package manager)\n```\ncurl http://npmjs.org/install.sh | sh\n```\n\n### Installing prompt\n```\n[sudo] npm install prompt\n```\n\n## Usage\nUsing prompt is relatively straight forward. There are two core methods you should be aware of: `prompt.get()` and `prompt.addProperties()`. There methods take strings representing property names in addition to objects for complex property validation (and more). There are a number of [examples][0] that you should examine for detailed usage.\n\n### Getting Basic Prompt Information\nGetting started with `prompt` is easy. Lets take a look at `examples/simple-prompt.js`:\n\n``` js\nvar prompt = require('prompt');\n\n//\n// Start the prompt\n//\nprompt.start();\n\n//\n// Get two properties from the user: username and email\n//\nprompt.get(['username', 'email'], function (err, result) {\n //\n // Log the results.\n //\n console.log('Command-line input received:');\n console.log(' username: ' + result.username);\n console.log(' email: ' + result.email);\n})\n```\n\nThis will result in the following command-line output:\n\n```\n$ node examples/simple-prompt.js \nprompt: username: some-user\nprompt: email: some-user@some-place.org\nCommand-line input received:\n username: some-user\n email: some-user@some-place.org\n```\n\n### Prompting with Validation, Default Values, and More (Complex Properties)\nIn addition to prompting the user with simple string prompts, there is a robust API for getting and validating complex information from a command-line prompt. Here's a quick sample:\n\n``` js\nvar properties = [\n {\n name: 'name', \n validator: /^[a-zA-Z\\s\\-]+$/,\n warning: 'Name must be only letters, spaces, or dashes',\n empty: false\n },\n {\n name: 'password',\n hidden: true\n }\n];\n\n//\n// Start the prompt\n//\nprompt.start();\n\n//\n// Get two properties from the user: email, password\n//\nprompt.get(properties, function (err, result) {\n //\n // Log the results.\n //\n console.log('Command-line input received:');\n console.log(' name: ' + result.name);\n console.log(' password: ' + result.password);\n});\n```\n\nPretty easy right? The output from the above script is: \n\n```\n$ node examples/property-prompt.js\nprompt: name: nodejitsu000\nerror: Invalid input for name\nerror: Name must be only letters, spaces, or dashes\nprompt: name: Nodejitsu Inc\nprompt: password: \nCommand-line input received:\n name: Nodejitsu Inc\n password: some-password \n```\n\n## Valid Property Settings\n`prompt` uses a simple property system for performing a couple of basic validation operations against input received from the command-line. The motivations here were speed and simplicity of implementation to integration of pseudo-standards like JSON-Schema were not feasible. \n\nLets examine the anatomy of a prompt property:\n\n``` js\n{\n message: 'Enter your password', // Prompt displayed to the user. If not supplied name will be used.\n name: 'password' // Key in the JSON object returned from `.get()`.\n validator: /^\\w+$/ // Regular expression that input must be valid against.\n warning: 'Password must be letters' // Warning message to display if validation fails.\n hidden: true // If true, characters entered will not be output to console.\n default: 'lamepassword' // Default value to use if no value is entered.\n empty: false // If false, value entered must be non-empty.\n}\n```\n### skipping prompts\n\nSometimes power users may wish to skip promts and specify all data as command line options. \nif a value is set as a property of `prompt.override` prompt will use that instead of \nprompting the user.\n\n``` js\n//prompt-everride.js\n\nvar prompt = require('prompt'),\n optimist = require('optimist')\n\n//\n// set the overrides\n//\nprompt.override = optimist.argv\n\n//\n// Start the prompt\n//\nprompt.start();\n\n//\n// Get two properties from the user: username and email\n//\nprompt.get(['username', 'email'], function (err, result) {\n //\n // Log the results.\n //\n console.log('Command-line input received:');\n console.log(' username: ' + result.username);\n console.log(' email: ' + result.email);\n})\n\n//: node prompt-everride.js --username USER --email EMAIL\n\n```\n\n\n### Adding Properties to an Object \nA common use-case for prompting users for data from the command-line is to extend or create a configuration object that is passed onto the entry-point method for your CLI tool. `prompt` exposes a convenience method for doing just this: \n\n``` js\nvar obj = {\n password: 'lamepassword',\n mindset: 'NY'\n}\n\n//\n// Log the initial object.\n//\nconsole.log('Initial object to be extended:');\nconsole.dir(obj);\n\n//\n// Add two properties to the empty object: username and email\n//\nprompt.addProperties(obj, ['username', 'email'], function (err) {\n //\n // Log the results.\n //\n console.log('Updated object received:');\n console.dir(obj);\n});\n```\n\n## Customizing your prompt\nAside from changing `property.message`, you can also change `prompt.message`\nand `prompt.delimiter` to change the appearance of your prompt.\n\nThe basic structure of a prompt is this:\n\n``` js\nprompt.message + prompt.delimiter + property.message + prompt.delimiter;\n```\n\nThe default `prompt.message` is \"prompt,\" the default `prompt.delimiter` is\n\": \", and the default `property.message` is `property.name`.\nChanging these allows you to customize the appearance of your prompts! In\naddition, prompt supports ANSI color codes via the\n[colors module](https://github.com/Marak/colors.js) for custom colors. For a\nvery colorful example:\n\n``` js\nvar prompt = require(\"prompt\");\n//\n// The colors module adds color properties to String.prototype\n//\nrequire(\"colors\");\n\n//\n// Setting these properties customizes the prompt.\n//\nprompt.message = \"Question!\".rainbow;\nprompt.delimiter = \"><\".green;\n\nprompt.start();\n\nprompt.get([{ name: \"name\",\n message: \"What is your name?\".magenta }], function (err, result) {\n console.log(\"You said your name is: \".cyan + result.name.cyan);\n});\n```\n\n## Running tests\n```\nvows test/*-test.js --spec\n```\n\n#### Author: [Charlie Robbins][1]\n\n[0]: https://github.com/flatiron/prompt/tree/master/examples\n[1]: http://nodejitsu.com\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/flatiron/prompt/issues" - }, - "_id": "prompt@0.1.12", - "_from": "prompt@~0.1.12" -} diff --git a/node/node_modules/grunt/node_modules/prompt/test/helpers.js b/node/node_modules/grunt/node_modules/prompt/test/helpers.js deleted file mode 100644 index ff9f23317..000000000 --- a/node/node_modules/grunt/node_modules/prompt/test/helpers.js +++ /dev/null @@ -1,102 +0,0 @@ -/* - * helpers.js: Test helpers for the prompt tests. - * - * (C) 2010, Nodejitsu Inc. - * - */ - -var events = require('events'), - stream = require('stream'), - util = require('util'), - prompt = require('../lib/prompt'); - -var helpers = exports; - -var MockReadWriteStream = helpers.MockReadWriteStream = function () { - // - // No need to do anything here, it's just a mock. - // -}; - -util.inherits(MockReadWriteStream, events.EventEmitter); - -['resume', 'pause', 'setEncoding', 'flush'].forEach(function (method) { - MockReadWriteStream.prototype[method] = function () { /* Mock */ }; -}); - -MockReadWriteStream.prototype.write = function (msg) { - this.emit('data', msg); -}; - -// -// Create some mock streams for asserting against -// in our prompt tests. -// -helpers.stdin = new MockReadWriteStream(); -helpers.stdout = new MockReadWriteStream(); -helpers.stderr = new MockReadWriteStream(); - -// -// Monkey punch `util.error` to silence console output -// and redirect to helpers.stderr for testing. -// -util.error = function () { - helpers.stderr.write.apply(helpers.stderr, arguments); -} - -helpers.properties = { - riffwabbles: { - name: 'riffwabbles', - validator: /^[\w|\-]+$/, - warning: 'riffwabbles can only be letters, numbers, and dashes', - default: 'foobizzles' - }, - username: { - name: 'username', - validator: /^[\w|\-]+$/, - warning: 'Username can only be letters, numbers, and dashes' - }, - notblank: { - name: 'notblank', - empty: false - }, - password: { - name: 'password', - hidden: true, - empty: false - }, - badValidator: { - name: 'bad-validator', - validator: ['cant', 'use', 'array'] - }, - animal: { - name: 'animal', - description: 'Enter an animal', - default: 'dog', - validator: /dog|cat/ - }, - sound: { - name: 'sound', - description: 'What sound does this animal make?', - validator: function (value) { - var animal = prompt.history(0).value; - - return animal === 'dog' && value === 'woof' - || animal === 'cat' && value === 'meow'; - } - }, - fnvalidator: { - name: 'fnvalidator', - validator: function (line) { - return line.slice(0,2) == 'fn'; - }, - warning: 'fnvalidator must start with "fn"' - }, - cbvalidator: { - name: 'cbvalidator', - validator: function (line, next) { - next(line.slice(0,2) == 'cb'); - }, - warning: 'cbvalidator must start with "cb"' - } -}; diff --git a/node/node_modules/grunt/node_modules/prompt/test/interactive-prompt-test.js b/node/node_modules/grunt/node_modules/prompt/test/interactive-prompt-test.js deleted file mode 100644 index 75ccc0c8d..000000000 --- a/node/node_modules/grunt/node_modules/prompt/test/interactive-prompt-test.js +++ /dev/null @@ -1,39 +0,0 @@ -/* - * prompt-test.js: Tests for prompt. - * - * (C) 2010, Nodejitsu Inc. - * - */ - -var assert = require('assert'), - vows = require('vows'), - prompt = require('../lib/prompt'), - winston = require('winston').cli(), - helpers = require('./helpers'); - -vows.describe('prompt/interactive').addBatch({ - "When using prompt": { - topic: function () { - // - // Reset the prompt for interactive testing - // - prompt.started = false; - prompt.start(); - winston.info('These prompt tests are interactive'); - winston.info('Not following instructions will result in test failure'); - return null; - }, - "the getInput() method": { - "when passed a complex property with `hidden: true`": { - topic: function () { - winston.info('When prompted, enter: 12345 [backspace] [backspace] [enter]'); - prompt.getInput(helpers.properties.password, this.callback); - }, - "should respond with `123`": function (err, result) { - assert.isNull(err); - assert.equal(result, '123'); - } - } - } - } -}).export(module); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/prompt/test/prompt-test.js b/node/node_modules/grunt/node_modules/prompt/test/prompt-test.js deleted file mode 100644 index 096f6ba42..000000000 --- a/node/node_modules/grunt/node_modules/prompt/test/prompt-test.js +++ /dev/null @@ -1,390 +0,0 @@ -/* - * prompt-test.js: Tests for prompt. - * - * (C) 2010, Nodejitsu Inc. - * - */ - -var assert = require('assert'), - vows = require('vows'), - prompt = require('../lib/prompt'), - helpers = require('./helpers'); - -vows.describe('prompt').addBatch({ - "When using prompt": { - topic: function () { - // - // Reset the prompt for mock testing - // - prompt.started = false; - prompt.start({ - stdin: helpers.stdin, - stdout: helpers.stdout - }); - - return null; - }, - "the readLine() method": { - topic: function () { - prompt.readLine(this.callback); - helpers.stdin.write('testing\n'); - }, - "should respond with data from the stdin stream": function (err, input) { - assert.isNull(err); - assert.equal(input, 'testing'); - } - }, - "the readLineHidden() method": { - "when given backspaces": { - topic: function () { - prompt.readLineHidden(this.callback); - helpers.stdin.write('no-\x08backspace.\x7f'); - helpers.stdin.write('\n'); - }, - "should remove the proper characters": function (err,input) { - assert.isNull(err); - assert.equal(input, 'nobackspace'); - } - }, - topic: function () { - prompt.readLineHidden(this.callback); - helpers.stdin.write('testing'); - helpers.stdin.write('\r\n'); - }, - "should respond with data from the stdin stream": function (err, input) { - assert.isNull(err); - assert.equal(input, 'testing'); - } - }, - "the getInput() method": { - "with a simple string prompt": { - topic: function () { - var that = this; - helpers.stdout.once('data', function (msg) { - that.msg = msg; - }) - - prompt.getInput('test input', this.callback); - helpers.stdin.write('test value\n'); - }, - "should prompt to stdout and respond with data": function (err, input) { - assert.isNull(err); - assert.equal(input, 'test value'); - assert.isTrue(this.msg.indexOf('test input') !== -1); - } - }, - "with any field that is not supposed to be empty": { - "and we don't provide any input": { - topic: function () { - var that = this; - helpers.stdout.once('data', function (msg) { - that.msg = msg; - }); - - helpers.stderr.once('data', function (msg) { - that.errmsg = msg; - }); - - prompt.getInput(helpers.properties.notblank, function () {}); - prompt.once('invalid', this.callback.bind(null, null)) - helpers.stdin.write('\n'); - }, - - "should prompt with an error": function (ign, prop, input) { - assert.isObject(prop); - assert.equal(input, ''); - assert.isTrue(this.errmsg.indexOf('Invalid input') !== -1); - assert.isTrue(this.msg.indexOf('notblank') !== -1); - } - } - }, - "with a hidden field that is not supposed to be empty": { - "and we provide valid input": { - topic: function () { - var that = this; - helpers.stdout.once('data', function (msg) { - that.msg = msg; - }); - - prompt.getInput('password', this.callback); - helpers.stdin.write('trustno1\n'); - }, - - "should prompt to stdout and respond with data": function (err, input) { - assert.isNull(err); - assert.equal(input, 'trustno1'); - assert.isTrue(this.msg.indexOf('password') !== -1); - } - }, - "and we don't provide an input": { - topic: function () { - var that = this; - helpers.stdout.once('data', function (msg) { - that.msg = msg; - }); - - helpers.stderr.once('data', function (msg) { - that.errmsg = msg; - }); - - prompt.getInput(helpers.properties.password, function () {}); - prompt.once('invalid', this.callback.bind(null, null)) - helpers.stdin.write('\n'); - }, - "should prompt with an error": function (ign, prop, input) { - assert.isObject(prop); - assert.equal(input, ''); - assert.isTrue(this.errmsg.indexOf('Invalid input') !== -1); - assert.isTrue(this.msg.indexOf('password') !== -1); - } - } - }, - "with a complex property prompt": { - "and a valid input": { - topic: function () { - var that = this; - helpers.stdout.once('data', function (msg) { - that.msg = msg; - }); - - prompt.getInput(helpers.properties.username, this.callback); - helpers.stdin.write('some-user\n'); - }, - "should prompt to stdout and respond with data": function (err, input) { - assert.isNull(err); - assert.equal(input, 'some-user'); - assert.isTrue(this.msg.indexOf('username') !== -1); - } - }, - "and an invalid input": { - topic: function () { - var that = this; - helpers.stdout.once('data', function (msg) { - that.msg = msg; - }); - - helpers.stderr.once('data', function (msg) { - that.errmsg = msg; - }) - - prompt.getInput(helpers.properties.username, this.callback); - - prompt.once('invalid', function () { - prompt.once('prompt', function () { - process.nextTick(function () { - helpers.stdin.write('some-user\n'); - }) - }) - }); - - helpers.stdin.write('some -user\n'); - }, - "should prompt with an error before completing the operation": function (err, input) { - assert.isNull(err); - assert.equal(input, 'some-user'); - assert.isTrue(this.errmsg.indexOf('Invalid input') !== -1); - assert.isTrue(this.msg.indexOf('username') !== -1); - } - }, - "with an invalid validator (array)": { - topic: function () { - prompt.getInput(helpers.properties.badValidator, this.callback); - }, - "should respond with an error": function (err, ign) { - assert.isTrue(!!err); - } - } - } - }, - "the get() method": { - "with a simple string prompt": { - "that is not a property in prompt.properties": { - topic: function () { - var that = this; - helpers.stdout.once('data', function (msg) { - that.msg = msg; - }) - - prompt.get('test input', this.callback); - helpers.stdin.write('test value\n'); - }, - "should prompt to stdout and respond with the value": function (err, result) { - assert.isNull(err); - assert.include(result, 'test input'); - assert.equal(result['test input'], 'test value'); - assert.isTrue(this.msg.indexOf('test input') !== -1); - } - }, - "that is a property name in prompt.properties": { - "with a default value": { - topic: function () { - var that = this; - - helpers.stdout.once('data', function (msg) { - that.msg = msg; - }); - - prompt.properties['riffwabbles'] = helpers.properties['riffwabbles']; - prompt.get('riffwabbles', this.callback); - helpers.stdin.write('\n'); - }, - "should prompt to stdout and respond with the default value": function (err, result) { - assert.isNull(err); - assert.isTrue(this.msg.indexOf('riffwabbles') !== -1); - assert.isTrue(this.msg.indexOf('(foobizzles)') !== -1); - assert.include(result, 'riffwabbles'); - assert.equal(result['riffwabbles'], helpers.properties['riffwabbles'].default); - } - }, - "with a sync function validator": { - topic: function () { - var that = this; - - helpers.stdout.once('data', function (msg) { - that.msg = msg; - }); - - prompt.get(helpers.properties.fnvalidator, this.callback); - helpers.stdin.write('fn123\n'); - }, - "should accept a value that is checked": function (err, result) { - assert.isNull(err); - assert.equal(result['fnvalidator'],'fn123'); - } - }, - "with a callback validator": { - topic: function () { - var that = this; - - helpers.stdout.once('data', function (msg) { - that.msg = msg; - }); - - prompt.get(helpers.properties.cbvalidator, this.callback); - helpers.stdin.write('cb123\n'); - }, - "should not accept a value that is correct": function (err, result) { - assert.isNull(err); - assert.equal(result['cbvalidator'],'cb123'); - } - } - } - }, - "skip prompt with prompt.overide": { - topic: function () { - prompt.override = { coconihet: 'whatever' } - prompt.get('coconihet', this.callback); - }, - "skips prompt and uses overide": function (err, results) { - assert.equal(results.coconihet, 'whatever') - } - } - }, - "the addProperties() method": { - topic: function () { - prompt.addProperties({}, ['foo', 'bar'], this.callback); - helpers.stdin.write('foo\n'); - helpers.stdin.write('bar\n'); - }, - "should add the properties to the object": function (err, obj) { - assert.isNull(err); - assert.isObject(obj); - assert.equal(obj.foo, 'foo'); - assert.equal(obj.bar, 'bar'); - } - } - } -}).addBatch({ - "When using prompt": { - "the history() method": { - "when used inside of a complex property": { - "with correct value(s)": { - topic: function () { - prompt.get([helpers.properties.animal, helpers.properties.sound], this.callback); - helpers.stdin.write('dog\n'); - helpers.stdin.write('woof\n'); - }, - "should respond with the values entered": function (err, result) { - assert.isTrue(!err); - assert.equal(result.animal, 'dog'); - assert.equal(result.sound, 'woof'); - } - }, - "with an incorrect value": { - topic: function () { - prompt.get([helpers.properties.animal, helpers.properties.sound], function () {}); - prompt.once('invalid', this.callback.bind(null, null)); - helpers.stdin.write('dog\n'); - helpers.stdin.write('meow\n'); - }, - "should prompt for the error": function (ign, property, line) { - assert.equal(property.name, 'sound'); - assert.equal(line, 'meow'); - } - } - } - } - } -}).addBatch({ - "when using prompt": { - topic: function () { - // - // Reset the prompt for mock testing - // - prompt.started = false; - prompt.start({ - stdin: helpers.stdin, - stdout: helpers.stdout - }); - - return null; - }, - "the get() method": { - topic: function () { - prompt.override = { xyz: 468, abc: 123 } - prompt.get(['xyz', 'abc'], this.callback); - }, - "should respond with overrides": function (err, results) { - assert.isNull(err); - assert.deepEqual(results, { xyz: 468, abc: 123 }); - } - } - } -}).addBatch({ - "when using prompt": { - topic: function () { - // - // Reset the prompt for mock testing - // - prompt.started = false; - prompt.start({ - stdin: helpers.stdin, - stdout: helpers.stdout - }); - - return null; - }, - "with fancy properties": { - "the get() method": { - topic: function () { - prompt.override = { UVW: 5423, DEF: 64235 } - prompt.get([{ - name:'UVW', - message: 'a custom message', - default: 6 - },{ - name:'DEF', - message: 'a custom message', - default: 6 - }], this.callback); - }, - "should respond with overrides": function (err, results) { - assert.isNull(err); - assert.deepEqual(results, { UVW: 5423, DEF: 64235 }); - } - } - } - } -}).export(module); - - diff --git a/node/node_modules/grunt/node_modules/rimraf/AUTHORS b/node/node_modules/grunt/node_modules/rimraf/AUTHORS new file mode 100644 index 000000000..247b75437 --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/AUTHORS @@ -0,0 +1,6 @@ +# Authors sorted by whether or not they're me. +Isaac Z. Schlueter (http://blog.izs.me) +Wayne Larsen (http://github.com/wvl) +ritch +Marcel Laverdet +Yosef Dinerstein diff --git a/node/node_modules/grunt/node_modules/rimraf/LICENSE b/node/node_modules/grunt/node_modules/rimraf/LICENSE new file mode 100644 index 000000000..05a401094 --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/LICENSE @@ -0,0 +1,23 @@ +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/node_modules/grunt/node_modules/rimraf/README.md b/node/node_modules/grunt/node_modules/rimraf/README.md new file mode 100644 index 000000000..96ce9b2a0 --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/README.md @@ -0,0 +1,21 @@ +A `rm -rf` for node. + +Install with `npm install rimraf`, or just drop rimraf.js somewhere. + +## API + +`rimraf(f, callback)` + +The callback will be called with an error if there is one. Certain +errors are handled for you: + +* `EBUSY` - rimraf will back off a maximum of opts.maxBusyTries times + before giving up. +* `EMFILE` - If too many file descriptors get opened, rimraf will + patiently wait until more become available. + + +## rimraf.sync + +It can remove stuff synchronously, too. But that's not so good. Use +the async API. It's better. diff --git a/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/.npmignore b/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/.npmignore new file mode 100644 index 000000000..c2658d7d1 --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/.npmignore @@ -0,0 +1 @@ +node_modules/ diff --git a/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/LICENSE b/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/LICENSE new file mode 100644 index 000000000..05a401094 --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/LICENSE @@ -0,0 +1,23 @@ +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/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/README.md b/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/README.md new file mode 100644 index 000000000..7d2e681e3 --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/README.md @@ -0,0 +1,5 @@ +Just like node's `fs` module, but it does an incremental back-off when +EMFILE is encountered. + +Useful in asynchronous situations where one needs to try to open lots +and lots of files. diff --git a/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/graceful-fs.js b/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/graceful-fs.js new file mode 100644 index 000000000..be9951eac --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/graceful-fs.js @@ -0,0 +1,312 @@ +// this keeps a queue of opened file descriptors, and will make +// fs operations wait until some have closed before trying to open more. + +var fs = require("fs") + +// there is such a thing as TOO graceful. +if (fs.open === gracefulOpen) return + +var queue = [] + , constants = require("constants") + +exports = module.exports = fs +fs._curOpen = 0 + +fs.MIN_MAX_OPEN = 64 +fs.MAX_OPEN = 1024 + +var originalOpen = fs.open + , originalOpenSync = fs.openSync + , originalClose = fs.close + , originalCloseSync = fs.closeSync + + +// prevent EMFILE errors +function OpenReq (path, flags, mode, cb) { + this.path = path + this.flags = flags + this.mode = mode + this.cb = cb +} + +function noop () {} + +fs.open = gracefulOpen + +function gracefulOpen (path, flags, mode, cb) { + if (typeof mode === "function") cb = mode, mode = null + if (typeof cb !== "function") cb = noop + + if (fs._curOpen >= fs.MAX_OPEN) { + queue.push(new OpenReq(path, flags, mode, cb)) + setTimeout(flush) + return + } + open(path, flags, mode, function (er, fd) { + if (er && er.code === "EMFILE" && fs._curOpen > fs.MIN_MAX_OPEN) { + // that was too many. reduce max, get back in queue. + // this should only happen once in a great while, and only + // if the ulimit -n is set lower than 1024. + fs.MAX_OPEN = fs._curOpen - 1 + return fs.open(path, flags, mode, cb) + } + cb(er, fd) + }) +} + +function open (path, flags, mode, cb) { + cb = cb || noop + fs._curOpen ++ + originalOpen.call(fs, path, flags, mode, function (er, fd) { + if (er) onclose() + cb(er, fd) + }) +} + +fs.openSync = function (path, flags, mode) { + var ret + ret = originalOpenSync.call(fs, path, flags, mode) + fs._curOpen ++ + return ret +} + +function onclose () { + fs._curOpen -- + flush() +} + +function flush () { + while (fs._curOpen < fs.MAX_OPEN) { + var req = queue.shift() + if (!req) return + open(req.path, req.flags || "r", req.mode || 0777, req.cb) + } +} + +fs.close = function (fd, cb) { + cb = cb || noop + originalClose.call(fs, fd, function (er) { + onclose() + cb(er) + }) +} + +fs.closeSync = function (fd) { + onclose() + return originalCloseSync.call(fs, fd) +} + + +// (re-)implement some things that are known busted or missing. + +var constants = require("constants") + +// 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/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/package.json b/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/package.json new file mode 100644 index 000000000..f5922a0fd --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/package.json @@ -0,0 +1,36 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + "name": "graceful-fs", + "description": "fs monkey-patching to avoid EMFILE and other problems", + "version": "1.1.14", + "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", + "EMFILE", + "error", + "handling", + "monkeypatch" + ], + "license": "BSD", + "readme": "Just like node's `fs` module, but it does an incremental back-off when\nEMFILE is encountered.\n\nUseful in asynchronous situations where one needs to try to open lots\nand lots of files.\n", + "readmeFilename": "README.md", + "_id": "graceful-fs@1.1.14", + "_from": "graceful-fs@~1.1" +} diff --git a/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/test/open.js b/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/test/open.js new file mode 100644 index 000000000..d05f880c8 --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/test/open.js @@ -0,0 +1,41 @@ +var test = require('tap').test +var fs = require('../graceful-fs.js') + +test('open an existing file works', function (t) { + var start = fs._curOpen + var fd = fs.openSync(__filename, 'r') + t.equal(fs._curOpen, start + 1) + fs.closeSync(fd) + t.equal(fs._curOpen, start) + fs.open(__filename, 'r', function (er, fd) { + if (er) throw er + t.equal(fs._curOpen, start + 1) + fs.close(fd, function (er) { + if (er) throw er + t.equal(fs._curOpen, start) + t.end() + }) + }) +}) + +test('open a non-existing file throws', function (t) { + var start = fs._curOpen + 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') + t.equal(fs._curOpen, start) + + 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.equal(fs._curOpen, start) + t.end() + }) +}) diff --git a/node/node_modules/grunt/node_modules/rimraf/package.json b/node/node_modules/grunt/node_modules/rimraf/package.json new file mode 100644 index 000000000..05d87fa6c --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/package.json @@ -0,0 +1,55 @@ +{ + "name": "rimraf", + "version": "2.0.3", + "main": "rimraf.js", + "description": "A deep deletion module for node (like `rm -rf`)", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": { + "type": "MIT", + "url": "https://github.com/isaacs/rimraf/raw/master/LICENSE" + }, + "optionalDependencies": { + "graceful-fs": "~1.1" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/rimraf.git" + }, + "scripts": { + "test": "cd test && bash run.sh" + }, + "contributors": [ + { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + { + "name": "Wayne Larsen", + "email": "wayne@larsen.st", + "url": "http://github.com/wvl" + }, + { + "name": "ritch", + "email": "skawful@gmail.com" + }, + { + "name": "Marcel Laverdet" + }, + { + "name": "Yosef Dinerstein", + "email": "yosefd@microsoft.com" + } + ], + "readme": "A `rm -rf` for node.\n\nInstall with `npm install rimraf`, or just drop rimraf.js somewhere.\n\n## API\n\n`rimraf(f, callback)`\n\nThe callback will be called with an error if there is one. Certain\nerrors are handled for you:\n\n* `EBUSY` - rimraf will back off a maximum of opts.maxBusyTries times\n before giving up.\n* `EMFILE` - If too many file descriptors get opened, rimraf will\n patiently wait until more become available.\n\n\n## rimraf.sync\n\nIt can remove stuff synchronously, too. But that's not so good. Use\nthe async API. It's better.\n", + "readmeFilename": "README.md", + "_id": "rimraf@2.0.3", + "dependencies": { + "graceful-fs": "~1.1" + }, + "_from": "rimraf@~2.0.2" +} diff --git a/node/node_modules/grunt/node_modules/rimraf/rimraf.js b/node/node_modules/grunt/node_modules/rimraf/rimraf.js new file mode 100644 index 000000000..95b2de8b9 --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/rimraf.js @@ -0,0 +1,161 @@ +module.exports = rimraf +rimraf.sync = rimrafSync + +var path = require("path") + , fs + +try { + // optional dependency + fs = require("graceful-fs") +} catch (er) { + fs = require("fs") +} + +var lstat = "lstat" +if (process.platform === "win32") { + // not reliable on windows prior to 0.7.9 + var v = process.version.replace(/^v/, '').split(/\.|-/).map(Number) + if (v[0] === 0 && (v[1] < 7 || v[1] == 7 && v[2] < 9)) { + lstat = "stat" + } +} +if (!fs[lstat]) lstat = "stat" +var lstatSync = lstat + "Sync" + +// for EMFILE handling +var timeout = 0 +exports.EMFILE_MAX = 1000 +exports.BUSYTRIES_MAX = 3 + +function rimraf (p, cb) { + + if (!cb) throw new Error("No callback passed to rimraf()") + + var busyTries = 0 + + rimraf_(p, function CB (er) { + if (er) { + if (er.code === "EBUSY" && busyTries < exports.BUSYTRIES_MAX) { + busyTries ++ + var time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(function () { + rimraf_(p, CB) + }, time) + } + + // this one won't happen if graceful-fs is used. + if (er.code === "EMFILE" && timeout < exports.EMFILE_MAX) { + return setTimeout(function () { + rimraf_(p, CB) + }, timeout ++) + } + + // already gone + if (er.code === "ENOENT") er = null + } + + timeout = 0 + cb(er) + }) +} + +function rimraf_ (p, cb) { + fs[lstat](p, function (er, s) { + if (er) { + // already gone + if (er.code === "ENOENT") return cb() + // some other kind of error, permissions, etc. + return cb(er) + } + + return rm_(p, s, false, cb) + }) +} + + +var myGid = function myGid () { + var g = process.getgid && process.getgid() + myGid = function myGid () { return g } + return g +} + +var myUid = function myUid () { + var u = process.getuid && process.getuid() + myUid = function myUid () { return u } + return u +} + + +function writable (s) { + var mode = s.mode || 0777 + , uid = myUid() + , gid = myGid() + return (mode & 0002) + || (gid === s.gid && (mode & 0020)) + || (uid === s.uid && (mode & 0200)) +} + +function rm_ (p, s, didWritableCheck, cb) { + if (!didWritableCheck && !writable(s)) { + // make file writable + // user/group/world, doesn't matter at this point + // since it's about to get nuked. + return fs.chmod(p, s.mode | 0222, function (er) { + if (er) return cb(er) + rm_(p, s, true, cb) + }) + } + + if (!s.isDirectory()) { + return fs.unlink(p, cb) + } + + // directory + fs.readdir(p, function (er, files) { + if (er) return cb(er) + asyncForEach(files.map(function (f) { + return path.join(p, f) + }), function (file, cb) { + rimraf(file, cb) + }, function (er) { + if (er) return cb(er) + fs.rmdir(p, cb) + }) + }) +} + +function asyncForEach (list, fn, cb) { + if (!list.length) cb() + var c = list.length + , errState = null + list.forEach(function (item, i, list) { + fn(item, function (er) { + if (errState) return + if (er) return cb(errState = er) + if (-- c === 0) return cb() + }) + }) +} + +// this looks simpler, but it will fail with big directory trees, +// or on slow stupid awful cygwin filesystems +function rimrafSync (p) { + try { + var s = fs[lstatSync](p) + } catch (er) { + if (er.code === "ENOENT") return + throw er + } + + if (!writable(s)) { + fs.chmodSync(p, s.mode | 0222) + } + + if (!s.isDirectory()) return fs.unlinkSync(p) + + fs.readdirSync(p).forEach(function (f) { + rimrafSync(path.join(p, f)) + }) + fs.rmdirSync(p) +} diff --git a/node/node_modules/grunt/node_modules/rimraf/test/run.sh b/node/node_modules/grunt/node_modules/rimraf/test/run.sh new file mode 100644 index 000000000..598f0163b --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/test/run.sh @@ -0,0 +1,10 @@ +#!/bin/bash +set -e +for i in test-*.js; do + echo -n $i ... + bash setup.sh + node $i + ! [ -d target ] + echo "pass" +done +rm -rf target diff --git a/node/node_modules/grunt/node_modules/rimraf/test/setup.sh b/node/node_modules/grunt/node_modules/rimraf/test/setup.sh new file mode 100644 index 000000000..2602e6316 --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/test/setup.sh @@ -0,0 +1,47 @@ +#!/bin/bash + +set -e + +files=10 +folders=2 +depth=4 +target="$PWD/target" + +rm -rf target + +fill () { + local depth=$1 + local files=$2 + local folders=$3 + local target=$4 + + if ! [ -d $target ]; then + mkdir -p $target + fi + + local f + + f=$files + while [ $f -gt 0 ]; do + touch "$target/f-$depth-$f" + let f-- + done + + let depth-- + + if [ $depth -le 0 ]; then + return 0 + fi + + f=$folders + while [ $f -gt 0 ]; do + mkdir "$target/folder-$depth-$f" + fill $depth $files $folders "$target/d-$depth-$f" + let f-- + done +} + +fill $depth $files $folders $target + +# sanity assert +[ -d $target ] diff --git a/node/node_modules/grunt/node_modules/rimraf/test/test-async.js b/node/node_modules/grunt/node_modules/rimraf/test/test-async.js new file mode 100644 index 000000000..9c2e0b7be --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/test/test-async.js @@ -0,0 +1,5 @@ +var rimraf = require("../rimraf") + , path = require("path") +rimraf(path.join(__dirname, "target"), function (er) { + if (er) throw er +}) diff --git a/node/node_modules/grunt/node_modules/rimraf/test/test-fiber.js b/node/node_modules/grunt/node_modules/rimraf/test/test-fiber.js new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/node_modules/rimraf/test/test-sync.js b/node/node_modules/grunt/node_modules/rimraf/test/test-sync.js new file mode 100644 index 000000000..eb71f1047 --- /dev/null +++ b/node/node_modules/grunt/node_modules/rimraf/test/test-sync.js @@ -0,0 +1,3 @@ +var rimraf = require("../rimraf") + , path = require("path") +rimraf.sync(path.join(__dirname, "target")) diff --git a/node/node_modules/grunt/node_modules/semver/README.md b/node/node_modules/grunt/node_modules/semver/README.md deleted file mode 100644 index 6fa37a3d8..000000000 --- a/node/node_modules/grunt/node_modules/semver/README.md +++ /dev/null @@ -1,119 +0,0 @@ -semver(1) -- The semantic versioner for npm -=========================================== - -## Usage - - $ npm install semver - - semver.valid('1.2.3') // true - semver.valid('a.b.c') // false - semver.clean(' =v1.2.3 ') // '1.2.3' - semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true - semver.gt('1.2.3', '9.8.7') // false - semver.lt('1.2.3', '9.8.7') // true - -As a command-line utility: - - $ semver -h - - Usage: semver -v [-r ] - Test if version(s) satisfy the supplied range(s), - and sort them. - - Multiple versions or ranges may be supplied. - - Program exits successfully if any valid version satisfies - all supplied ranges, and prints all satisfying versions. - - If no versions are valid, or ranges are not satisfied, - then exits failure. - - Versions are printed in ascending order, so supplying - multiple versions to the utility will just sort them. - -## Versions - -A version is the following things, in this order: - -* a number (Major) -* a period -* a number (minor) -* a period -* a number (patch) -* OPTIONAL: a hyphen, followed by a number (build) -* OPTIONAL: a collection of pretty much any non-whitespace characters - (tag) - -A leading `"="` or `"v"` character is stripped off and ignored. - -## Comparisons - -The ordering of versions is done using the following algorithm, given -two versions and asked to find the greater of the two: - -* If the majors are numerically different, then take the one - with a bigger major number. `2.3.4 > 1.3.4` -* If the minors are numerically different, then take the one - with the bigger minor number. `2.3.4 > 2.2.4` -* If the patches are numerically different, then take the one with the - bigger patch number. `2.3.4 > 2.3.3` -* If only one of them has a build number, then take the one with the - build number. `2.3.4-0 > 2.3.4` -* If they both have build numbers, and the build numbers are numerically - different, then take the one with the bigger build number. - `2.3.4-10 > 2.3.4-9` -* If only one of them has a tag, then take the one without the tag. - `2.3.4 > 2.3.4-beta` -* If they both have tags, then take the one with the lexicographically - larger tag. `2.3.4-beta > 2.3.4-alpha` -* At this point, they're equal. - -## Ranges - -The following range styles are supported: - -* `>1.2.3` Greater than a specific version. -* `<1.2.3` Less than -* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4` -* `~1.2.3` := `>=1.2.3 <1.3.0` -* `~1.2` := `>=1.2.0 <2.0.0` -* `~1` := `>=1.0.0 <2.0.0` -* `1.2.x` := `>=1.2.0 <1.3.0` -* `1.x` := `>=1.0.0 <2.0.0` - -Ranges can be joined with either a space (which implies "and") or a -`||` (which implies "or"). - -## Functions - -* valid(v): Return the parsed version, or null if it's not valid. -* inc(v, release): Return the version incremented by the release type - (major, minor, patch, or build), or null if it's not valid. - -### Comparison - -* gt(v1, v2): `v1 > v2` -* gte(v1, v2): `v1 >= v2` -* lt(v1, v2): `v1 < v2` -* lte(v1, v2): `v1 <= v2` -* eq(v1, v2): `v1 == v2` This is true if they're logically equivalent, - even if they're not the exact same string. You already know how to - compare strings. -* neq(v1, v2): `v1 != v2` The opposite of eq. -* cmp(v1, comparator, v2): Pass in a comparison string, and it'll call - the corresponding function above. `"==="` and `"!=="` do simple - string comparison, but are included for completeness. Throws if an - invalid comparison string is provided. -* compare(v1, v2): Return 0 if v1 == v2, or 1 if v1 is greater, or -1 if - v2 is greater. Sorts in ascending order if passed to Array.sort(). -* rcompare(v1, v2): The reverse of compare. Sorts an array of versions - in descending order when passed to Array.sort(). - - -### Ranges - -* validRange(range): Return the valid range or null if it's not valid -* satisfies(version, range): Return true if the version satisfies the - range. -* maxSatisfying(versions, range): Return the highest version in the list - that satisfies the range, or null if none of them do. diff --git a/node/node_modules/grunt/node_modules/semver/bin/semver b/node/node_modules/grunt/node_modules/semver/bin/semver deleted file mode 100755 index 3e6afb40d..000000000 --- a/node/node_modules/grunt/node_modules/semver/bin/semver +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env node -// Standalone semver comparison program. -// Exits successfully and prints matching version(s) if -// any supplied version is valid and passes all tests. - -var argv = process.argv.slice(2) - , versions = [] - , range = [] - , gt = [] - , lt = [] - , eq = [] - , semver = require("../semver") - -main() - -function main () { - if (!argv.length) return help() - while (argv.length) { - var a - switch (a = argv.shift()) { - case "-v": case "--version": - versions.push(argv.shift()) - break - case "-r": case "--range": - range.push(argv.shift()) - break - case "-h": case "--help": case "-?": - return help() - default: - versions.push(a) - break - } - } - - versions = versions.filter(semver.valid) - for (var i = 0, l = range.length; i < l ; i ++) { - versions = versions.filter(function (v) { - return semver.satisfies(v, range[i]) - }) - if (!versions.length) return fail() - } - return success(versions) -} - -function fail () { process.exit(1) } - -function success () { - versions.sort(semver.compare) - .map(semver.clean) - .forEach(function (v,i,_) { console.log(v) }) -} - -function help () { - console.log(["Usage: semver -v [-r ]" - ,"Test if version(s) satisfy the supplied range(s)," - ,"and sort them." - ,"" - ,"Multiple versions or ranges may be supplied." - ,"" - ,"Program exits successfully if any valid version satisfies" - ,"all supplied ranges, and prints all satisfying versions." - ,"" - ,"If no versions are valid, or ranges are not satisfied," - ,"then exits failure." - ,"" - ,"Versions are printed in ascending order, so supplying" - ,"multiple versions to the utility will just sort them." - ].join("\n")) -} - - diff --git a/node/node_modules/grunt/node_modules/semver/package.json b/node/node_modules/grunt/node_modules/semver/package.json deleted file mode 100644 index 21af829bd..000000000 --- a/node/node_modules/grunt/node_modules/semver/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "semver", - "version": "1.0.14", - "description": "The semantic version parser used by npm.", - "main": "semver.js", - "scripts": { - "test": "tap test.js" - }, - "devDependencies": { - "tap": "0.x >=0.0.4" - }, - "license": { - "type": "MIT", - "url": "https://github.com/isaacs/semver/raw/master/LICENSE" - }, - "repository": { - "type": "git", - "url": "git://github.com/isaacs/node-semver.git" - }, - "bin": { - "semver": "./bin/semver" - }, - "readme": "semver(1) -- The semantic versioner for npm\n===========================================\n\n## Usage\n\n $ npm install semver\n\n semver.valid('1.2.3') // true\n semver.valid('a.b.c') // false\n semver.clean(' =v1.2.3 ') // '1.2.3'\n semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true\n semver.gt('1.2.3', '9.8.7') // false\n semver.lt('1.2.3', '9.8.7') // true\n\nAs a command-line utility:\n\n $ semver -h\n\n Usage: semver -v [-r ]\n Test if version(s) satisfy the supplied range(s),\n and sort them.\n\n Multiple versions or ranges may be supplied.\n\n Program exits successfully if any valid version satisfies\n all supplied ranges, and prints all satisfying versions.\n\n If no versions are valid, or ranges are not satisfied,\n then exits failure.\n\n Versions are printed in ascending order, so supplying\n multiple versions to the utility will just sort them.\n\n## Versions\n\nA version is the following things, in this order:\n\n* a number (Major)\n* a period\n* a number (minor)\n* a period\n* a number (patch)\n* OPTIONAL: a hyphen, followed by a number (build)\n* OPTIONAL: a collection of pretty much any non-whitespace characters\n (tag)\n\nA leading `\"=\"` or `\"v\"` character is stripped off and ignored.\n\n## Comparisons\n\nThe ordering of versions is done using the following algorithm, given\ntwo versions and asked to find the greater of the two:\n\n* If the majors are numerically different, then take the one\n with a bigger major number. `2.3.4 > 1.3.4`\n* If the minors are numerically different, then take the one\n with the bigger minor number. `2.3.4 > 2.2.4`\n* If the patches are numerically different, then take the one with the\n bigger patch number. `2.3.4 > 2.3.3`\n* If only one of them has a build number, then take the one with the\n build number. `2.3.4-0 > 2.3.4`\n* If they both have build numbers, and the build numbers are numerically\n different, then take the one with the bigger build number.\n `2.3.4-10 > 2.3.4-9`\n* If only one of them has a tag, then take the one without the tag.\n `2.3.4 > 2.3.4-beta`\n* If they both have tags, then take the one with the lexicographically\n larger tag. `2.3.4-beta > 2.3.4-alpha`\n* At this point, they're equal.\n\n## Ranges\n\nThe following range styles are supported:\n\n* `>1.2.3` Greater than a specific version.\n* `<1.2.3` Less than\n* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`\n* `~1.2.3` := `>=1.2.3 <1.3.0`\n* `~1.2` := `>=1.2.0 <2.0.0`\n* `~1` := `>=1.0.0 <2.0.0`\n* `1.2.x` := `>=1.2.0 <1.3.0`\n* `1.x` := `>=1.0.0 <2.0.0`\n\nRanges can be joined with either a space (which implies \"and\") or a\n`||` (which implies \"or\").\n\n## Functions\n\n* valid(v): Return the parsed version, or null if it's not valid.\n* inc(v, release): Return the version incremented by the release type\n (major, minor, patch, or build), or null if it's not valid.\n\n### Comparison\n\n* gt(v1, v2): `v1 > v2`\n* gte(v1, v2): `v1 >= v2`\n* lt(v1, v2): `v1 < v2`\n* lte(v1, v2): `v1 <= v2`\n* eq(v1, v2): `v1 == v2` This is true if they're logically equivalent,\n even if they're not the exact same string. You already know how to\n compare strings.\n* neq(v1, v2): `v1 != v2` The opposite of eq.\n* cmp(v1, comparator, v2): Pass in a comparison string, and it'll call\n the corresponding function above. `\"===\"` and `\"!==\"` do simple\n string comparison, but are included for completeness. Throws if an\n invalid comparison string is provided.\n* compare(v1, v2): Return 0 if v1 == v2, or 1 if v1 is greater, or -1 if\n v2 is greater. Sorts in ascending order if passed to Array.sort().\n* rcompare(v1, v2): The reverse of compare. Sorts an array of versions\n in descending order when passed to Array.sort().\n\n\n### Ranges\n\n* validRange(range): Return the valid range or null if it's not valid\n* satisfies(version, range): Return true if the version satisfies the\n range.\n* maxSatisfying(versions, range): Return the highest version in the list\n that satisfies the range, or null if none of them do.\n", - "readmeFilename": "README.md", - "bugs": { - "url": "https://github.com/isaacs/node-semver/issues" - }, - "_id": "semver@1.0.14", - "_from": "semver@~1.0.13" -} diff --git a/node/node_modules/grunt/node_modules/semver/semver.js b/node/node_modules/grunt/node_modules/semver/semver.js deleted file mode 100644 index 8090e0c0d..000000000 --- a/node/node_modules/grunt/node_modules/semver/semver.js +++ /dev/null @@ -1,305 +0,0 @@ -;(function (exports) { // nothing in here is node-specific. - -// See http://semver.org/ -// This implementation is a *hair* less strict in that it allows -// v1.2.3 things, and also tags that don't begin with a char. - -var semver = "\\s*[v=]*\\s*([0-9]+)" // major - + "\\.([0-9]+)" // minor - + "\\.([0-9]+)" // patch - + "(-[0-9]+-?)?" // build - + "([a-zA-Z-][a-zA-Z0-9-\.:]*)?" // tag - , exprComparator = "^((<|>)?=?)\s*("+semver+")$|^$" - , xRangePlain = "[v=]*([0-9]+|x|X|\\*)" - + "(?:\\.([0-9]+|x|X|\\*)" - + "(?:\\.([0-9]+|x|X|\\*)" - + "([a-zA-Z-][a-zA-Z0-9-\.:]*)?)?)?" - , xRange = "((?:<|>)=?)?\\s*" + xRangePlain - , exprSpermy = "(?:~>?)"+xRange - , expressions = exports.expressions = - { parse : new RegExp("^\\s*"+semver+"\\s*$") - , parsePackage : new RegExp("^\\s*([^\/]+)[-@](" +semver+")\\s*$") - , parseRange : new RegExp( - "^\\s*(" + semver + ")\\s+-\\s+(" + semver + ")\\s*$") - , validComparator : new RegExp("^"+exprComparator+"$") - , parseXRange : new RegExp("^"+xRange+"$") - , parseSpermy : new RegExp("^"+exprSpermy+"$") - } - - -Object.getOwnPropertyNames(expressions).forEach(function (i) { - exports[i] = function (str) { - return ("" + (str || "")).match(expressions[i]) - } -}) - -exports.rangeReplace = ">=$1 <=$7" -exports.clean = clean -exports.compare = compare -exports.rcompare = rcompare -exports.satisfies = satisfies -exports.gt = gt -exports.gte = gte -exports.lt = lt -exports.lte = lte -exports.eq = eq -exports.neq = neq -exports.cmp = cmp -exports.inc = inc - -exports.valid = valid -exports.validPackage = validPackage -exports.validRange = validRange -exports.maxSatisfying = maxSatisfying - -exports.replaceStars = replaceStars -exports.toComparators = toComparators - -function stringify (version) { - var v = version - return [v[1]||'', v[2]||'', v[3]||''].join(".") + (v[4]||'') + (v[5]||'') -} - -function clean (version) { - version = exports.parse(version) - if (!version) return version - return stringify(version) -} - -function valid (version) { - if (typeof version !== "string") return null - return exports.parse(version) && version.trim().replace(/^[v=]+/, '') -} - -function validPackage (version) { - if (typeof version !== "string") return null - return version.match(expressions.parsePackage) && version.trim() -} - -// range can be one of: -// "1.0.3 - 2.0.0" range, inclusive, like ">=1.0.3 <=2.0.0" -// ">1.0.2" like 1.0.3 - 9999.9999.9999 -// ">=1.0.2" like 1.0.2 - 9999.9999.9999 -// "<2.0.0" like 0.0.0 - 1.9999.9999 -// ">1.0.2 <2.0.0" like 1.0.3 - 1.9999.9999 -var starExpression = /(<|>)?=?\s*\*/g - , starReplace = "" - , compTrimExpression = new RegExp("((<|>)?=?)\\s*(" - +semver+"|"+xRangePlain+")", "g") - , compTrimReplace = "$1$3" - -function toComparators (range) { - var ret = (range || "").trim() - .replace(expressions.parseRange, exports.rangeReplace) - .replace(compTrimExpression, compTrimReplace) - .split(/\s+/) - .join(" ") - .split("||") - .map(function (orchunk) { - return orchunk - .split(" ") - .map(replaceXRanges) - .map(replaceSpermies) - .map(replaceStars) - .join(" ").trim() - }) - .map(function (orchunk) { - return orchunk - .trim() - .split(/\s+/) - .filter(function (c) { return c.match(expressions.validComparator) }) - }) - .filter(function (c) { return c.length }) - return ret -} - -function replaceStars (stars) { - return stars.trim().replace(starExpression, starReplace) -} - -// "2.x","2.x.x" --> ">=2.0.0- <2.1.0-" -// "2.3.x" --> ">=2.3.0- <2.4.0-" -function replaceXRanges (ranges) { - return ranges.split(/\s+/) - .map(replaceXRange) - .join(" ") -} - -function replaceXRange (version) { - return version.trim().replace(expressions.parseXRange, - function (v, gtlt, M, m, p, t) { - var anyX = !M || M.toLowerCase() === "x" || M === "*" - || !m || m.toLowerCase() === "x" || m === "*" - || !p || p.toLowerCase() === "x" || p === "*" - , ret = v - - if (gtlt && anyX) { - // just replace x'es with zeroes - ;(!M || M === "*" || M.toLowerCase() === "x") && (M = 0) - ;(!m || m === "*" || m.toLowerCase() === "x") && (m = 0) - ;(!p || p === "*" || p.toLowerCase() === "x") && (p = 0) - ret = gtlt + M+"."+m+"."+p+"-" - } else if (!M || M === "*" || M.toLowerCase() === "x") { - ret = "*" // allow any - } else if (!m || m === "*" || m.toLowerCase() === "x") { - // append "-" onto the version, otherwise - // "1.x.x" matches "2.0.0beta", since the tag - // *lowers* the version value - ret = ">="+M+".0.0- <"+(+M+1)+".0.0-" - } else if (!p || p === "*" || p.toLowerCase() === "x") { - ret = ">="+M+"."+m+".0- <"+M+"."+(+m+1)+".0-" - } - //console.error("parseXRange", [].slice.call(arguments), ret) - return ret - }) -} - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceSpermies (version) { - return version.trim().replace(expressions.parseSpermy, - function (v, gtlt, M, m, p, t) { - if (gtlt) throw new Error( - "Using '"+gtlt+"' with ~ makes no sense. Don't do it.") - - if (!M || M.toLowerCase() === "x") { - return "" - } - // ~1 == >=1.0.0- <2.0.0- - if (!m || m.toLowerCase() === "x") { - return ">="+M+".0.0- <"+(+M+1)+".0.0-" - } - // ~1.2 == >=1.2.0- <1.3.0- - if (!p || p.toLowerCase() === "x") { - return ">="+M+"."+m+".0- <"+M+"."+(+m+1)+".0-" - } - // ~1.2.3 == >=1.2.3- <1.3.0- - t = t || "-" - return ">="+M+"."+m+"."+p+t+" <"+M+"."+(+m+1)+".0-" - }) -} - -function validRange (range) { - range = replaceStars(range) - var c = toComparators(range) - return (c.length === 0) - ? null - : c.map(function (c) { return c.join(" ") }).join("||") -} - -// returns the highest satisfying version in the list, or undefined -function maxSatisfying (versions, range) { - return versions - .filter(function (v) { return satisfies(v, range) }) - .sort(compare) - .pop() -} -function satisfies (version, range) { - version = valid(version) - if (!version) return false - range = toComparators(range) - for (var i = 0, l = range.length ; i < l ; i ++) { - var ok = false - for (var j = 0, ll = range[i].length ; j < ll ; j ++) { - var r = range[i][j] - , gtlt = r.charAt(0) === ">" ? gt - : r.charAt(0) === "<" ? lt - : false - , eq = r.charAt(!!gtlt) === "=" - , sub = (!!eq) + (!!gtlt) - if (!gtlt) eq = true - r = r.substr(sub) - r = (r === "") ? r : valid(r) - ok = (r === "") || (eq && r === version) || (gtlt && gtlt(version, r)) - if (!ok) break - } - if (ok) return true - } - return false -} - -// return v1 > v2 ? 1 : -1 -function compare (v1, v2) { - var g = gt(v1, v2) - return g === null ? 0 : g ? 1 : -1 -} - -function rcompare (v1, v2) { - return compare(v2, v1) -} - -function lt (v1, v2) { return gt(v2, v1) } -function gte (v1, v2) { return !lt(v1, v2) } -function lte (v1, v2) { return !gt(v1, v2) } -function eq (v1, v2) { return gt(v1, v2) === null } -function neq (v1, v2) { return gt(v1, v2) !== null } -function cmp (v1, c, v2) { - switch (c) { - case ">": return gt(v1, v2) - case "<": return lt(v1, v2) - case ">=": return gte(v1, v2) - case "<=": return lte(v1, v2) - case "==": return eq(v1, v2) - case "!=": return neq(v1, v2) - case "===": return v1 === v2 - case "!==": return v1 !== v2 - default: throw new Error("Y U NO USE VALID COMPARATOR!? "+c) - } -} - -// return v1 > v2 -function num (v) { - return v === undefined ? -1 : parseInt((v||"0").replace(/[^0-9]+/g, ''), 10) -} -function gt (v1, v2) { - v1 = exports.parse(v1) - v2 = exports.parse(v2) - if (!v1 || !v2) return false - - for (var i = 1; i < 5; i ++) { - v1[i] = num(v1[i]) - v2[i] = num(v2[i]) - if (v1[i] > v2[i]) return true - else if (v1[i] !== v2[i]) return false - } - // no tag is > than any tag, or use lexicographical order. - var tag1 = v1[5] || "" - , tag2 = v2[5] || "" - - // kludge: null means they were equal. falsey, and detectable. - // embarrassingly overclever, though, I know. - return tag1 === tag2 ? null - : !tag1 ? true - : !tag2 ? false - : tag1 > tag2 -} - -function inc (version, release) { - version = exports.parse(version) - if (!version) return null - - var parsedIndexLookup = - { 'major': 1 - , 'minor': 2 - , 'patch': 3 - , 'build': 4 } - var incIndex = parsedIndexLookup[release] - if (incIndex === undefined) return null - - var current = num(version[incIndex]) - version[incIndex] = current === -1 ? 1 : current + 1 - - for (var i = incIndex + 1; i < 5; i ++) { - if (num(version[i]) !== -1) version[i] = "0" - } - - if (version[4]) version[4] = "-" + version[4] - version[5] = "" - - return stringify(version) -} -})(typeof exports === "object" ? exports : semver = {}) diff --git a/node/node_modules/grunt/node_modules/semver/test.js b/node/node_modules/grunt/node_modules/semver/test.js deleted file mode 100644 index 65ff8a963..000000000 --- a/node/node_modules/grunt/node_modules/semver/test.js +++ /dev/null @@ -1,405 +0,0 @@ -var tap = require("tap") - , test = tap.test - , semver = require("./semver.js") - , eq = semver.eq - , gt = semver.gt - , lt = semver.lt - , neq = semver.neq - , cmp = semver.cmp - , gte = semver.gte - , lte = semver.lte - , satisfies = semver.satisfies - , validRange = semver.validRange - , inc = semver.inc - , replaceStars = semver.replaceStars - , toComparators = semver.toComparators - -tap.plan(8) - -test("\ncomparison tests", function (t) { -; [ ["0.0.0", "0.0.0foo"] - , ["0.0.1", "0.0.0"] - , ["1.0.0", "0.9.9"] - , ["0.10.0", "0.9.0"] - , ["0.99.0", "0.10.0"] - , ["2.0.0", "1.2.3"] - , ["v0.0.0", "0.0.0foo"] - , ["v0.0.1", "0.0.0"] - , ["v1.0.0", "0.9.9"] - , ["v0.10.0", "0.9.0"] - , ["v0.99.0", "0.10.0"] - , ["v2.0.0", "1.2.3"] - , ["0.0.0", "v0.0.0foo"] - , ["0.0.1", "v0.0.0"] - , ["1.0.0", "v0.9.9"] - , ["0.10.0", "v0.9.0"] - , ["0.99.0", "v0.10.0"] - , ["2.0.0", "v1.2.3"] - , ["1.2.3", "1.2.3-asdf"] - , ["1.2.3-4", "1.2.3"] - , ["1.2.3-4-foo", "1.2.3"] - , ["1.2.3-5", "1.2.3-5-foo"] - , ["1.2.3-5", "1.2.3-4"] - , ["1.2.3-5-foo", "1.2.3-5-Foo"] - ].forEach(function (v) { - var v0 = v[0] - , v1 = v[1] - t.ok(gt(v0, v1), "gt('"+v0+"', '"+v1+"')") - t.ok(lt(v1, v0), "lt('"+v1+"', '"+v0+"')") - t.ok(!gt(v1, v0), "!gt('"+v1+"', '"+v0+"')") - t.ok(!lt(v0, v1), "!lt('"+v0+"', '"+v1+"')") - t.ok(eq(v0, v0), "eq('"+v0+"', '"+v0+"')") - t.ok(eq(v1, v1), "eq('"+v1+"', '"+v1+"')") - t.ok(neq(v0, v1), "neq('"+v0+"', '"+v1+"')") - t.ok(cmp(v1, "==", v1), "cmp('"+v1+"' == '"+v1+"')") - t.ok(cmp(v0, ">=", v1), "cmp('"+v0+"' >= '"+v1+"')") - t.ok(cmp(v1, "<=", v0), "cmp('"+v1+"' <= '"+v0+"')") - t.ok(cmp(v0, "!=", v1), "cmp('"+v0+"' != '"+v1+"')") - }) - t.end() -}) - -test("\nequality tests", function (t) { -; [ ["1.2.3", "v1.2.3"] - , ["1.2.3", "=1.2.3"] - , ["1.2.3", "v 1.2.3"] - , ["1.2.3", "= 1.2.3"] - , ["1.2.3", " v1.2.3"] - , ["1.2.3", " =1.2.3"] - , ["1.2.3", " v 1.2.3"] - , ["1.2.3", " = 1.2.3"] - , ["1.2.3-0", "v1.2.3-0"] - , ["1.2.3-0", "=1.2.3-0"] - , ["1.2.3-0", "v 1.2.3-0"] - , ["1.2.3-0", "= 1.2.3-0"] - , ["1.2.3-0", " v1.2.3-0"] - , ["1.2.3-0", " =1.2.3-0"] - , ["1.2.3-0", " v 1.2.3-0"] - , ["1.2.3-0", " = 1.2.3-0"] - , ["1.2.3-01", "v1.2.3-1"] - , ["1.2.3-01", "=1.2.3-1"] - , ["1.2.3-01", "v 1.2.3-1"] - , ["1.2.3-01", "= 1.2.3-1"] - , ["1.2.3-01", " v1.2.3-1"] - , ["1.2.3-01", " =1.2.3-1"] - , ["1.2.3-01", " v 1.2.3-1"] - , ["1.2.3-01", " = 1.2.3-1"] - , ["1.2.3beta", "v1.2.3beta"] - , ["1.2.3beta", "=1.2.3beta"] - , ["1.2.3beta", "v 1.2.3beta"] - , ["1.2.3beta", "= 1.2.3beta"] - , ["1.2.3beta", " v1.2.3beta"] - , ["1.2.3beta", " =1.2.3beta"] - , ["1.2.3beta", " v 1.2.3beta"] - , ["1.2.3beta", " = 1.2.3beta"] - ].forEach(function (v) { - var v0 = v[0] - , v1 = v[1] - t.ok(eq(v0, v1), "eq('"+v0+"', '"+v1+"')") - t.ok(!neq(v0, v1), "!neq('"+v0+"', '"+v1+"')") - t.ok(cmp(v0, "==", v1), "cmp("+v0+"=="+v1+")") - t.ok(!cmp(v0, "!=", v1), "!cmp("+v0+"!="+v1+")") - t.ok(!cmp(v0, "===", v1), "!cmp("+v0+"==="+v1+")") - t.ok(cmp(v0, "!==", v1), "cmp("+v0+"!=="+v1+")") - t.ok(!gt(v0, v1), "!gt('"+v0+"', '"+v1+"')") - t.ok(gte(v0, v1), "gte('"+v0+"', '"+v1+"')") - t.ok(!lt(v0, v1), "!lt('"+v0+"', '"+v1+"')") - t.ok(lte(v0, v1), "lte('"+v0+"', '"+v1+"')") - }) - t.end() -}) - - -test("\nrange tests", function (t) { -; [ ["1.0.0 - 2.0.0", "1.2.3"] - , ["1.0.0", "1.0.0"] - , [">=*", "0.2.4"] - , ["", "1.0.0"] - , ["*", "1.2.3"] - , ["*", "v1.2.3-foo"] - , [">=1.0.0", "1.0.0"] - , [">=1.0.0", "1.0.1"] - , [">=1.0.0", "1.1.0"] - , [">1.0.0", "1.0.1"] - , [">1.0.0", "1.1.0"] - , ["<=2.0.0", "2.0.0"] - , ["<=2.0.0", "1.9999.9999"] - , ["<=2.0.0", "0.2.9"] - , ["<2.0.0", "1.9999.9999"] - , ["<2.0.0", "0.2.9"] - , [">= 1.0.0", "1.0.0"] - , [">= 1.0.0", "1.0.1"] - , [">= 1.0.0", "1.1.0"] - , ["> 1.0.0", "1.0.1"] - , ["> 1.0.0", "1.1.0"] - , ["<= 2.0.0", "2.0.0"] - , ["<= 2.0.0", "1.9999.9999"] - , ["<= 2.0.0", "0.2.9"] - , ["< 2.0.0", "1.9999.9999"] - , ["<\t2.0.0", "0.2.9"] - , [">=0.1.97", "v0.1.97"] - , [">=0.1.97", "0.1.97"] - , ["0.1.20 || 1.2.4", "1.2.4"] - , [">=0.2.3 || <0.0.1", "0.0.0"] - , [">=0.2.3 || <0.0.1", "0.2.3"] - , [">=0.2.3 || <0.0.1", "0.2.4"] - , ["||", "1.3.4"] - , ["2.x.x", "2.1.3"] - , ["1.2.x", "1.2.3"] - , ["1.2.x || 2.x", "2.1.3"] - , ["1.2.x || 2.x", "1.2.3"] - , ["x", "1.2.3"] - , ["2.*.*", "2.1.3"] - , ["1.2.*", "1.2.3"] - , ["1.2.* || 2.*", "2.1.3"] - , ["1.2.* || 2.*", "1.2.3"] - , ["*", "1.2.3"] - , ["2", "2.1.2"] - , ["2.3", "2.3.1"] - , ["~2.4", "2.4.0"] // >=2.4.0 <2.5.0 - , ["~2.4", "2.4.5"] - , ["~>3.2.1", "3.2.2"] // >=3.2.1 <3.3.0 - , ["~1", "1.2.3"] // >=1.0.0 <2.0.0 - , ["~>1", "1.2.3"] - , ["~> 1", "1.2.3"] - , ["~1.0", "1.0.2"] // >=1.0.0 <1.1.0 - , ["~ 1.0", "1.0.2"] - , [">=1", "1.0.0"] - , [">= 1", "1.0.0"] - , ["<1.2", "1.1.1"] - , ["< 1.2", "1.1.1"] - , ["1", "1.0.0beta"] - , ["~v0.5.4-pre", "0.5.5"] - , ["~v0.5.4-pre", "0.5.4"] - , ["=0.7.x", "0.7.2"] - , [">=0.7.x", "0.7.2"] - , ["=0.7.x", "0.7.0-asdf"] - , [">=0.7.x", "0.7.0-asdf"] - , ["<=0.7.x", "0.6.2"] - ].forEach(function (v) { - t.ok(satisfies(v[1], v[0]), v[0]+" satisfied by "+v[1]) - }) - t.end() -}) - -test("\nnegative range tests", function (t) { -; [ ["1.0.0 - 2.0.0", "2.2.3"] - , ["1.0.0", "1.0.1"] - , [">=1.0.0", "0.0.0"] - , [">=1.0.0", "0.0.1"] - , [">=1.0.0", "0.1.0"] - , [">1.0.0", "0.0.1"] - , [">1.0.0", "0.1.0"] - , ["<=2.0.0", "3.0.0"] - , ["<=2.0.0", "2.9999.9999"] - , ["<=2.0.0", "2.2.9"] - , ["<2.0.0", "2.9999.9999"] - , ["<2.0.0", "2.2.9"] - , [">=0.1.97", "v0.1.93"] - , [">=0.1.97", "0.1.93"] - , ["0.1.20 || 1.2.4", "1.2.3"] - , [">=0.2.3 || <0.0.1", "0.0.3"] - , [">=0.2.3 || <0.0.1", "0.2.2"] - , ["2.x.x", "1.1.3"] - , ["2.x.x", "3.1.3"] - , ["1.2.x", "1.3.3"] - , ["1.2.x || 2.x", "3.1.3"] - , ["1.2.x || 2.x", "1.1.3"] - , ["2.*.*", "1.1.3"] - , ["2.*.*", "3.1.3"] - , ["1.2.*", "1.3.3"] - , ["1.2.* || 2.*", "3.1.3"] - , ["1.2.* || 2.*", "1.1.3"] - , ["2", "1.1.2"] - , ["2.3", "2.4.1"] - , ["~2.4", "2.5.0"] // >=2.4.0 <2.5.0 - , ["~2.4", "2.3.9"] - , ["~>3.2.1", "3.3.2"] // >=3.2.1 <3.3.0 - , ["~>3.2.1", "3.2.0"] // >=3.2.1 <3.3.0 - , ["~1", "0.2.3"] // >=1.0.0 <2.0.0 - , ["~>1", "2.2.3"] - , ["~1.0", "1.1.0"] // >=1.0.0 <1.1.0 - , ["<1", "1.0.0"] - , [">=1.2", "1.1.1"] - , ["1", "2.0.0beta"] - , ["~v0.5.4-beta", "0.5.4-alpha"] - , ["<1", "1.0.0beta"] - , ["< 1", "1.0.0beta"] - , ["=0.7.x", "0.8.2"] - , [">=0.7.x", "0.6.2"] - , ["<=0.7.x", "0.7.2"] - ].forEach(function (v) { - t.ok(!satisfies(v[1], v[0]), v[0]+" not satisfied by "+v[1]) - }) - t.end() -}) - -test("\nincrement versions test", function (t) { -; [ [ "1.2.3", "major", "2.0.0" ] - , [ "1.2.3", "minor", "1.3.0" ] - , [ "1.2.3", "patch", "1.2.4" ] - , [ "1.2.3", "build", "1.2.3-1" ] - , [ "1.2.3-4", "build", "1.2.3-5" ] - , [ "1.2.3tag", "major", "2.0.0" ] - , [ "1.2.3-tag", "major", "2.0.0" ] - , [ "1.2.3tag", "build", "1.2.3-1" ] - , [ "1.2.3-tag", "build", "1.2.3-1" ] - , [ "1.2.3-4-tag", "build", "1.2.3-5" ] - , [ "1.2.3-4tag", "build", "1.2.3-5" ] - , [ "1.2.3", "fake", null ] - , [ "fake", "major", null ] - ].forEach(function (v) { - t.equal(inc(v[0], v[1]), v[2], "inc("+v[0]+", "+v[1]+") === "+v[2]) - }) - - t.end() -}) - -test("\nreplace stars test", function (t) { -; [ [ "", "" ] - , [ "*", "" ] - , [ "> *", "" ] - , [ "<*", "" ] - , [ " >= *", "" ] - , [ "* || 1.2.3", " || 1.2.3" ] - ].forEach(function (v) { - t.equal(replaceStars(v[0]), v[1], "replaceStars("+v[0]+") === "+v[1]) - }) - - t.end() -}) - -test("\nvalid range test", function (t) { -; [ ["1.0.0 - 2.0.0", ">=1.0.0 <=2.0.0"] - , ["1.0.0", "1.0.0"] - , [">=*", ""] - , ["", ""] - , ["*", ""] - , ["*", ""] - , [">=1.0.0", ">=1.0.0"] - , [">1.0.0", ">1.0.0"] - , ["<=2.0.0", "<=2.0.0"] - , ["1", ">=1.0.0- <2.0.0-"] - , ["<=2.0.0", "<=2.0.0"] - , ["<=2.0.0", "<=2.0.0"] - , ["<2.0.0", "<2.0.0"] - , ["<2.0.0", "<2.0.0"] - , [">= 1.0.0", ">=1.0.0"] - , [">= 1.0.0", ">=1.0.0"] - , [">= 1.0.0", ">=1.0.0"] - , ["> 1.0.0", ">1.0.0"] - , ["> 1.0.0", ">1.0.0"] - , ["<= 2.0.0", "<=2.0.0"] - , ["<= 2.0.0", "<=2.0.0"] - , ["<= 2.0.0", "<=2.0.0"] - , ["< 2.0.0", "<2.0.0"] - , ["< 2.0.0", "<2.0.0"] - , [">=0.1.97", ">=0.1.97"] - , [">=0.1.97", ">=0.1.97"] - , ["0.1.20 || 1.2.4", "0.1.20||1.2.4"] - , [">=0.2.3 || <0.0.1", ">=0.2.3||<0.0.1"] - , [">=0.2.3 || <0.0.1", ">=0.2.3||<0.0.1"] - , [">=0.2.3 || <0.0.1", ">=0.2.3||<0.0.1"] - , ["||", "||"] - , ["2.x.x", ">=2.0.0- <3.0.0-"] - , ["1.2.x", ">=1.2.0- <1.3.0-"] - , ["1.2.x || 2.x", ">=1.2.0- <1.3.0-||>=2.0.0- <3.0.0-"] - , ["1.2.x || 2.x", ">=1.2.0- <1.3.0-||>=2.0.0- <3.0.0-"] - , ["x", ""] - , ["2.*.*", null] - , ["1.2.*", null] - , ["1.2.* || 2.*", null] - , ["1.2.* || 2.*", null] - , ["*", ""] - , ["2", ">=2.0.0- <3.0.0-"] - , ["2.3", ">=2.3.0- <2.4.0-"] - , ["~2.4", ">=2.4.0- <2.5.0-"] - , ["~2.4", ">=2.4.0- <2.5.0-"] - , ["~>3.2.1", ">=3.2.1- <3.3.0-"] - , ["~1", ">=1.0.0- <2.0.0-"] - , ["~>1", ">=1.0.0- <2.0.0-"] - , ["~> 1", ">=1.0.0- <2.0.0-"] - , ["~1.0", ">=1.0.0- <1.1.0-"] - , ["~ 1.0", ">=1.0.0- <1.1.0-"] - , ["<1", "<1.0.0-"] - , ["< 1", "<1.0.0-"] - , [">=1", ">=1.0.0-"] - , [">= 1", ">=1.0.0-"] - , ["<1.2", "<1.2.0-"] - , ["< 1.2", "<1.2.0-"] - , ["1", ">=1.0.0- <2.0.0-"] - ].forEach(function (v) { - t.equal(validRange(v[0]), v[1], "validRange("+v[0]+") === "+v[1]) - }) - - t.end() -}) - -test("\ncomparators test", function (t) { -; [ ["1.0.0 - 2.0.0", [[">=1.0.0", "<=2.0.0"]] ] - , ["1.0.0", [["1.0.0"]] ] - , [">=*", [[">=0.0.0-"]] ] - , ["", [[""]]] - , ["*", [[""]] ] - , ["*", [[""]] ] - , [">=1.0.0", [[">=1.0.0"]] ] - , [">=1.0.0", [[">=1.0.0"]] ] - , [">=1.0.0", [[">=1.0.0"]] ] - , [">1.0.0", [[">1.0.0"]] ] - , [">1.0.0", [[">1.0.0"]] ] - , ["<=2.0.0", [["<=2.0.0"]] ] - , ["1", [[">=1.0.0-", "<2.0.0-"]] ] - , ["<=2.0.0", [["<=2.0.0"]] ] - , ["<=2.0.0", [["<=2.0.0"]] ] - , ["<2.0.0", [["<2.0.0"]] ] - , ["<2.0.0", [["<2.0.0"]] ] - , [">= 1.0.0", [[">=1.0.0"]] ] - , [">= 1.0.0", [[">=1.0.0"]] ] - , [">= 1.0.0", [[">=1.0.0"]] ] - , ["> 1.0.0", [[">1.0.0"]] ] - , ["> 1.0.0", [[">1.0.0"]] ] - , ["<= 2.0.0", [["<=2.0.0"]] ] - , ["<= 2.0.0", [["<=2.0.0"]] ] - , ["<= 2.0.0", [["<=2.0.0"]] ] - , ["< 2.0.0", [["<2.0.0"]] ] - , ["<\t2.0.0", [["<2.0.0"]] ] - , [">=0.1.97", [[">=0.1.97"]] ] - , [">=0.1.97", [[">=0.1.97"]] ] - , ["0.1.20 || 1.2.4", [["0.1.20"], ["1.2.4"]] ] - , [">=0.2.3 || <0.0.1", [[">=0.2.3"], ["<0.0.1"]] ] - , [">=0.2.3 || <0.0.1", [[">=0.2.3"], ["<0.0.1"]] ] - , [">=0.2.3 || <0.0.1", [[">=0.2.3"], ["<0.0.1"]] ] - , ["||", [[""], [""]] ] - , ["2.x.x", [[">=2.0.0-", "<3.0.0-"]] ] - , ["1.2.x", [[">=1.2.0-", "<1.3.0-"]] ] - , ["1.2.x || 2.x", [[">=1.2.0-", "<1.3.0-"], [">=2.0.0-", "<3.0.0-"]] ] - , ["1.2.x || 2.x", [[">=1.2.0-", "<1.3.0-"], [">=2.0.0-", "<3.0.0-"]] ] - , ["x", [[""]] ] - , ["2.*.*", [[">=2.0.0-", "<3.0.0-"]] ] - , ["1.2.*", [[">=1.2.0-", "<1.3.0-"]] ] - , ["1.2.* || 2.*", [[">=1.2.0-", "<1.3.0-"], [">=2.0.0-", "<3.0.0-"]] ] - , ["1.2.* || 2.*", [[">=1.2.0-", "<1.3.0-"], [">=2.0.0-", "<3.0.0-"]] ] - , ["*", [[""]] ] - , ["2", [[">=2.0.0-", "<3.0.0-"]] ] - , ["2.3", [[">=2.3.0-", "<2.4.0-"]] ] - , ["~2.4", [[">=2.4.0-", "<2.5.0-"]] ] - , ["~2.4", [[">=2.4.0-", "<2.5.0-"]] ] - , ["~>3.2.1", [[">=3.2.1-", "<3.3.0-"]] ] - , ["~1", [[">=1.0.0-", "<2.0.0-"]] ] - , ["~>1", [[">=1.0.0-", "<2.0.0-"]] ] - , ["~> 1", [[">=1.0.0-", "<2.0.0-"]] ] - , ["~1.0", [[">=1.0.0-", "<1.1.0-"]] ] - , ["~ 1.0", [[">=1.0.0-", "<1.1.0-"]] ] - , ["<1", [["<1.0.0-"]] ] - , ["< 1", [["<1.0.0-"]] ] - , [">=1", [[">=1.0.0-"]] ] - , [">= 1", [[">=1.0.0-"]] ] - , ["<1.2", [["<1.2.0-"]] ] - , ["< 1.2", [["<1.2.0-"]] ] - , ["1", [[">=1.0.0-", "<2.0.0-"]] ] - ].forEach(function (v) { - t.equivalent(toComparators(v[0]), v[1], "toComparators("+v[0]+") === "+JSON.stringify(v[1])) - }) - - t.end() -}) diff --git a/node/node_modules/grunt/node_modules/temporary/.npmignore b/node/node_modules/grunt/node_modules/temporary/.npmignore deleted file mode 100644 index 3b3a32f78..000000000 --- a/node/node_modules/grunt/node_modules/temporary/.npmignore +++ /dev/null @@ -1,22 +0,0 @@ -tmp -node_modules -*._ -*.tmp -.monitor -*.diff -*.err -*.orig -*.log -*.rej -*.swo -*.swp -*.vi -*~ -.DS_Store -Thumbs.db -.cache -.project -.settings -.tmproj -*.esproj -nbproject diff --git a/node/node_modules/grunt/node_modules/temporary/History.md b/node/node_modules/grunt/node_modules/temporary/History.md deleted file mode 100644 index 2ad4405ce..000000000 --- a/node/node_modules/grunt/node_modules/temporary/History.md +++ /dev/null @@ -1,5 +0,0 @@ - -0.0.5 / 2012-11-12 -================== - - * Solved process.env issue in detector on certain version so linux. diff --git a/node/node_modules/grunt/node_modules/temporary/Makefile b/node/node_modules/grunt/node_modules/temporary/Makefile deleted file mode 100644 index 98957d674..000000000 --- a/node/node_modules/grunt/node_modules/temporary/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -TESTS = test/*.test.js - -test: - @NODE_ENV=test ./node_modules/.bin/mocha \ - --reporter spec \ - $(TESTS) - -clean: - rm -f examples/tmp/* - -.PHONY: test clean diff --git a/node/node_modules/grunt/node_modules/temporary/Readme.md b/node/node_modules/grunt/node_modules/temporary/Readme.md deleted file mode 100644 index 858510f35..000000000 --- a/node/node_modules/grunt/node_modules/temporary/Readme.md +++ /dev/null @@ -1,82 +0,0 @@ -[![Build Status](https://secure.travis-ci.org/vesln/temporary.png)](http://travis-ci.org/vesln/temporary) - -# temporary - The lord of tmp. - -## Intro - -Temporary provides an easy way to create temporary files and directories. -It will create a temporary file/directory with a unique name. - -## Features - -- Generates unique name. -- Auto-discovers tmp dir. - -## Installation - - $ npm install temporary - -## Usage - - var Tempfile = require('temporary/file'); - var Tempdir = require('temporary/dir'); - var file = new Tempfile; - var dir = new Tempdir; - - console.log(file.path); // path. - console.log(dir.path); // path. - - file.unlink(); - dir.rmdir(); - -## Methods - -### File - -- File.readFile -- File.readFileSync -- File.writeFile -- File.writeFileSync -- File.open -- File.openSync -- File.close -- File.closeSync -- File.unlink -- File.unlinkSync - -### Dir - -- Dir.rmdir -- Dir.rmdirSync - -## Tests - - $ make test - -## Contribution - -Bug fixes and features are welcomed. - -## License - -MIT License - -Copyright (C) 2012 Veselin Todorov - -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/node_modules/grunt/node_modules/temporary/examples/dir.js b/node/node_modules/grunt/node_modules/temporary/examples/dir.js deleted file mode 100644 index 5182b8334..000000000 --- a/node/node_modules/grunt/node_modules/temporary/examples/dir.js +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -var Tempdir = require('../lib/dir'); -var dir = new Tempdir('foo') // name - optional - -console.log(dir.path); // path. - -/** - * You can also use: - * - * dir.rmdir - * dir.rmdirSync - */ \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/temporary/examples/file.js b/node/node_modules/grunt/node_modules/temporary/examples/file.js deleted file mode 100644 index 6a3fe31e7..000000000 --- a/node/node_modules/grunt/node_modules/temporary/examples/file.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -var Tempfile = require('../lib/file'); -var file = new Tempfile('foo') // name - optional - -console.log(file.path); // file path. - -/** - * You can also use: - * - * file.readFile - * file.readFileSync - * file.writeFile - * file.writeFileSync - * file.open - * file.openSync - * file.close - * file.closeSync - * file.unlink - * file.unlinkSync - */ \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/temporary/index.js b/node/node_modules/grunt/node_modules/temporary/index.js deleted file mode 100644 index b1ec2b75f..000000000 --- a/node/node_modules/grunt/node_modules/temporary/index.js +++ /dev/null @@ -1,26 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var package = require('package')(module); - -/** - * Version. - */ -module.exports.version = package.version; - -/** - * Exporting the temp file - */ -module.exports.File = require('./file'); - -/** - * Exporting the temp directory. - */ -module.exports.Dir = require('./dir'); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/temporary/lib/base.js b/node/node_modules/grunt/node_modules/temporary/lib/base.js deleted file mode 100644 index a3e95c867..000000000 --- a/node/node_modules/grunt/node_modules/temporary/lib/base.js +++ /dev/null @@ -1,80 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var fs = require('fs'); -var path = require('path'); -var generator = require('./generator'); -var detector = require('./detector'); - -/** - * Base constructor. - * - * @param {String|null} name - */ -function Base(name) { - this.init(name); -}; - -/** - * Initializes the class. - * - * @param {String|null} name - */ -Base.prototype.init = function(name) { - var filename = generator.build(name); - this.create(filename); - this.path = filename; -}; - -/** - * Converts the arguments object to array and - * append `this.path` as first element. - * - * @returns {Array} - */ -Base.prototype.prepareArgs = function(args) { - args = Array.prototype.slice.call(args); - args.unshift(this.path); - return args; -}; - -/** - * Renames the dir/file. - * - * @param {String} name - * @param {Function} cb Callback. - */ -Base.prototype.rename = function(name, cb) { - var self = this; - var args = arguments; - var tmp = path.normalize(path.dirname(self.path) + '/' + name); - - fs.rename(this.path, tmp, function(err) { - self.path = tmp; - if (args.length === 2) cb(err); - }); -}; - -/** - * Renames the dir/file sync. - * - * @param {String} name - */ -Base.prototype.renameSync = function(name) { - var tmp = path.normalize(path.dirname(this.path) + '/' + name); - var result = fs.renameSync(this.path, tmp); - this.path = tmp; - return result; -}; - -/** - * Exporting the lib. - */ -module.exports = Base; diff --git a/node/node_modules/grunt/node_modules/temporary/lib/detector.js b/node/node_modules/grunt/node_modules/temporary/lib/detector.js deleted file mode 100644 index c09b46d2b..000000000 --- a/node/node_modules/grunt/node_modules/temporary/lib/detector.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Detection stolen from NPM (https://github.com/isaacs/npm/) - * - * Copyright 2009, 2010, 2011 Isaac Z. Schlueter (the "Author") - * MIT License (https://github.com/isaacs/npm/blob/master/LICENSE) - */ - -/** - * Detector namespace. - * - * @type {Object} - */ -var detector = module.exports; - -var normalize = function(path) { - var last = Array.prototype.pop.apply(path); - - if (process.platform !== "win32" && last !== '/') { - path += '/'; - } - - return path; -} - -/** - * Returns tmp dir. Thank you npm. - * - * @returns {String} tmp dir. - */ -detector.tmp = function() { - var temp = process.env.TMPDIR - || process.env.TMP - || process.env.TEMP - || (process.platform === "win32" ? "c:\\windows\\temp\\" : "/tmp/") - - return normalize(temp); -}; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/temporary/lib/dir.js b/node/node_modules/grunt/node_modules/temporary/lib/dir.js deleted file mode 100644 index 73acecc32..000000000 --- a/node/node_modules/grunt/node_modules/temporary/lib/dir.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var fs = require('fs'); -var path = require('path'); -var generator = require('./generator'); -var detector = require('./detector'); -var Base = require('./base'); - -/** - * Dir constructor. - * - * @param {String|null} name - */ -function Dir(name) { - this.init(name); -}; - -/** - * Dir extends from tmp. - */ -Dir.prototype.__proto__ = Base.prototype; - -/** - * Creates new file. - * - * @param {String} dirname - */ -Dir.prototype.create = function(dirname) { - return fs.mkdirSync(path.normalize(dirname), 0777); -}; - -/** - * Asynchronous dir. - */ -Dir.prototype.rmdir = function() { - fs.rmdir.apply(fs, this.prepareArgs(arguments)); -}; - -/** - * Synchronous rmdir. - */ -Dir.prototype.rmdirSync = function() { - return fs.rmdirSync.apply(fs, this.prepareArgs(arguments)); -}; - -/** - * Exporting the lib. - */ -module.exports = Dir; diff --git a/node/node_modules/grunt/node_modules/temporary/lib/file.js b/node/node_modules/grunt/node_modules/temporary/lib/file.js deleted file mode 100644 index 49de02693..000000000 --- a/node/node_modules/grunt/node_modules/temporary/lib/file.js +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var fs = require('fs'); -var path = require('path'); -var generator = require('./generator'); -var detector = require('./detector'); -var Base = require('./base'); - -/** - * File constructor. - * - * @param {String|null} name - */ -function File(name) { - this.init(name); -}; - -/** - * File extends from tmp. - */ -File.prototype.__proto__ = Base.prototype; - -/** - * Creates new file. - * - * @param {String} filename - */ -File.prototype.create = function(filename) { - return fs.writeFileSync(path.normalize(filename), ''); -}; - -/** - * Asynchronously reads the entire contents of a file. - */ -File.prototype.readFile = function() { - fs.readFile.apply(fs, this.prepareArgs(arguments)); -}; - -/** - * Synchronous read. - */ -File.prototype.readFileSync = function() { - return fs.readFileSync.apply(fs, this.prepareArgs(arguments)); -}; - -/** - * Asynchronously writes data to a file. - */ -File.prototype.writeFile = function() { - fs.writeFile.apply(fs, this.prepareArgs(arguments)); -}; - -/** - * Synchronous writes data to a file. - */ -File.prototype.writeFileSync = function() { - return fs.writeFileSync.apply(fs, this.prepareArgs(arguments)); -}; - -/** - * Asynchronous file open. - */ -File.prototype.open = function() { - fs.open.apply(fs, this.prepareArgs(arguments)); -}; - -/** - * Synchronous open. - */ -File.prototype.openSync = function() { - return fs.openSync.apply(fs, this.prepareArgs(arguments)); -}; - -/** - * Asynchronous close. - */ -File.prototype.close = function() { - fs.close.apply(fs, Array.prototype.slice.call(arguments)); -}; - -/** - * Synchronous close. - */ -File.prototype.closeSync = function() { - return fs.closeSync.apply(fs, Array.prototype.slice.call(arguments)); -}; - -/** - * Asynchronous unlink. - */ -File.prototype.unlink = function() { - fs.unlink.apply(fs, this.prepareArgs(arguments)); -}; - -/** - * Synchronous unlink. - */ -File.prototype.unlinkSync = function() { - return fs.unlinkSync.apply(fs, this.prepareArgs(arguments)); -}; - -/** - * Exporting the lib. - */ -module.exports = File; diff --git a/node/node_modules/grunt/node_modules/temporary/lib/generator.js b/node/node_modules/grunt/node_modules/temporary/lib/generator.js deleted file mode 100644 index a68f0baff..000000000 --- a/node/node_modules/grunt/node_modules/temporary/lib/generator.js +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var fs = require('fs'); -var path = require('path'); -var detector = require('./detector'); -var existsSync = fs.existsSync || path.existsSync; - -/** - * Generator namespace. - * - * @type {Object} - */ -var generator = module.exports; - -/** - * Generates random name. - * - * @returns {String} - */ -generator.name = function() { - var id = null; - var tmp = detector.tmp(); - do { - id = Date.now() + Math.random(); - } while(existsSync(tmp + '/' + id)); - - return id + ''; -}; - -/** - * Buld a full name. (tmp dir + name). - * - * @param {String} name - * @returns {String} - */ -generator.build = function(name) { - var filename = detector.tmp(); - if (name) filename += name + '.'; - return filename + this.name(); -}; diff --git a/node/node_modules/grunt/node_modules/temporary/node_modules/package/.npmignore b/node/node_modules/grunt/node_modules/temporary/node_modules/package/.npmignore deleted file mode 100644 index 3b3a32f78..000000000 --- a/node/node_modules/grunt/node_modules/temporary/node_modules/package/.npmignore +++ /dev/null @@ -1,22 +0,0 @@ -tmp -node_modules -*._ -*.tmp -.monitor -*.diff -*.err -*.orig -*.log -*.rej -*.swo -*.swp -*.vi -*~ -.DS_Store -Thumbs.db -.cache -.project -.settings -.tmproj -*.esproj -nbproject diff --git a/node/node_modules/grunt/node_modules/temporary/node_modules/package/.travis.yml b/node/node_modules/grunt/node_modules/temporary/node_modules/package/.travis.yml deleted file mode 100644 index b8e1f1720..000000000 --- a/node/node_modules/grunt/node_modules/temporary/node_modules/package/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: node_js -node_js: - - 0.6 \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/temporary/node_modules/package/Makefile b/node/node_modules/grunt/node_modules/temporary/node_modules/package/Makefile deleted file mode 100644 index 277485cbc..000000000 --- a/node/node_modules/grunt/node_modules/temporary/node_modules/package/Makefile +++ /dev/null @@ -1,12 +0,0 @@ -TESTS = $(shell find test -iname \*.test.js) - -test: - @NODE_ENV=test ./node_modules/.bin/mocha \ - --require should \ - --reporter spec \ - $(TESTS) - -clean: - rm -f examples/tmp/* - -.PHONY: test clean \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/temporary/node_modules/package/Readme.md b/node/node_modules/grunt/node_modules/temporary/node_modules/package/Readme.md deleted file mode 100644 index c53196586..000000000 --- a/node/node_modules/grunt/node_modules/temporary/node_modules/package/Readme.md +++ /dev/null @@ -1,54 +0,0 @@ -[![Build Status](https://secure.travis-ci.org/vesln/package.png)](http://travis-ci.org/vesln/package) - -# package - Easy package.json exports. - -## Intro - -This module provides an easy and simple way to export package.json data. - -## Installation - - $ npm install package - -## Usage - - var package = require('package')(module); // contains package.json data. - var yourAwesomeModule = {}; - yourAwesomeModule.version = package.version; - -## Tests - - $ make test - -## Contribution - -Bug fixes and features are welcomed. - -## Other similar modules - -- pkginfo (https://github.com/indexzero/node-pkginfo) by indexzero. -- JSON.parse + fs.readFile - -## License - -MIT License - -Copyright (C) 2012 Veselin Todorov - -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/node_modules/grunt/node_modules/temporary/node_modules/package/examples/custom_path.js b/node/node_modules/grunt/node_modules/temporary/node_modules/package/examples/custom_path.js deleted file mode 100644 index a03c0cc01..000000000 --- a/node/node_modules/grunt/node_modules/temporary/node_modules/package/examples/custom_path.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * package - Easy package.json exports. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ - -var package = require('../')(__dirname + '/..'); // parent dir. - -console.log(package); // This will contain the package.json data. \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/temporary/node_modules/package/examples/module.js b/node/node_modules/grunt/node_modules/temporary/node_modules/package/examples/module.js deleted file mode 100644 index c4790692d..000000000 --- a/node/node_modules/grunt/node_modules/temporary/node_modules/package/examples/module.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * package - Easy package.json exports. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ - -var package = require('../')(module); - -console.log(package); // This will contain the package.json data. \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/temporary/node_modules/package/lib/package.js b/node/node_modules/grunt/node_modules/temporary/node_modules/package/lib/package.js deleted file mode 100644 index 348db0ce4..000000000 --- a/node/node_modules/grunt/node_modules/temporary/node_modules/package/lib/package.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * package - Easy package.json exports. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var fs = require('fs'); -var path = require('path'); -var exists = fs.existsSync || path.existsSync; - -/** - * Package. - * - * @param {String|null} location - * @returns {Object} package.json data - */ -var package = function(location) { - if (location === Object(location)) { - location = package.discover(location); - } - return package.read(path.normalize(location + '/package.json')); -}; - -/** - * Reads and parses a package.json file. - * - * @param {String} file - * @returns {Object} package.json data - */ -package.read = function(file) { - var data = fs.readFileSync(file, 'utf8'); - return JSON.parse(data); -}; - -/** - * Makes an atempt to find package.json file. - * - * @returns {Object} package.json data - */ -package.discover = function(module) { - var location = path.dirname(module.filename); - var found = null; - - while (!found) { - if (exists(location + '/package.json')) { - found = location; - } else if (location !== '/') { - location = path.dirname(location); - } else { - throw new Error('package.json can not be located'); - } - } - - return found; -}; - -/** - * Exporting the lib. - */ -module.exports = package; diff --git a/node/node_modules/grunt/node_modules/temporary/node_modules/package/package.json b/node/node_modules/grunt/node_modules/temporary/node_modules/package/package.json deleted file mode 100644 index 10df33f6a..000000000 --- a/node/node_modules/grunt/node_modules/temporary/node_modules/package/package.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "package", - "version": "1.0.1", - "description": "Easy package.json exports.", - "keywords": [ - "package.json" - ], - "author": { - "name": "Veselin Todorov", - "email": "hi@vesln.com" - }, - "devDependencies": { - "mocha": "0.3.3", - "should": "0.3.2" - }, - "repository": { - "type": "git", - "url": "http://github.com/vesln/package.git" - }, - "homepage": "http://github.com/vesln/package", - "scripts": { - "test": "make test" - }, - "main": "./lib/package", - "engines": { - "node": ">= 0.6.0" - }, - "readme": "[![Build Status](https://secure.travis-ci.org/vesln/package.png)](http://travis-ci.org/vesln/package)\n\n# package - Easy package.json exports.\n\n## Intro\n\nThis module provides an easy and simple way to export package.json data.\n\n## Installation\n\n\t$ npm install package\n\n## Usage\n\n\tvar package = require('package')(module); // contains package.json data.\n\tvar yourAwesomeModule = {};\n\tyourAwesomeModule.version = package.version;\n\n## Tests\n\n\t$ make test\n\n## Contribution\n\nBug fixes and features are welcomed.\n\n## Other similar modules\n\n- pkginfo (https://github.com/indexzero/node-pkginfo) by indexzero.\n- JSON.parse + fs.readFile\n\n## License\n\nMIT License\n\nCopyright (C) 2012 Veselin Todorov\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/vesln/package/issues" - }, - "_id": "package@1.0.1", - "_from": "package@>= 1.0.0 < 1.2.0" -} diff --git a/node/node_modules/grunt/node_modules/temporary/node_modules/package/test/index.test.js b/node/node_modules/grunt/node_modules/temporary/node_modules/package/test/index.test.js deleted file mode 100644 index c43364bc4..000000000 --- a/node/node_modules/grunt/node_modules/temporary/node_modules/package/test/index.test.js +++ /dev/null @@ -1,42 +0,0 @@ -/** - * package - Easy package.json exports. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var package = require('../'); - -describe('package', function() { - describe('read', function() { - it('should read and parse .json file', function() { - var result = package.read(__dirname + '/support/package.json'); - result.should.eql({ - name: 'test-package-json-file', - version: '0.0.1', - private: true - }); - }); - }); - - it('should read and parse given .json file', function() { - var result = package(__dirname + '/support'); - result.should.eql({ - name: 'test-package-json-file', - version: '0.0.1', - private: true - }); - }); - - it('should autodiscover, read and parse package.json', function() { - var result = package(module); - result.should.eql({ - name: 'test-package-json-file', - version: '0.0.1', - private: true - }); - }); -}); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/temporary/node_modules/package/test/nested/two/nested.test.js b/node/node_modules/grunt/node_modules/temporary/node_modules/package/test/nested/two/nested.test.js deleted file mode 100644 index 99c012ed9..000000000 --- a/node/node_modules/grunt/node_modules/temporary/node_modules/package/test/nested/two/nested.test.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * package - Easy package.json exports. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var package = require('../../../'); - -describe('nested package json', function() { - it('should autodiscover, read and parse package.json', function() { - var result = package(module); - result.should.eql({ - name: 'test-package-json-file', - version: '0.0.1', - private: true - }); - }); -}); \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/temporary/node_modules/package/test/package.json b/node/node_modules/grunt/node_modules/temporary/node_modules/package/test/package.json deleted file mode 100644 index ed5e67177..000000000 --- a/node/node_modules/grunt/node_modules/temporary/node_modules/package/test/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "test-package-json-file" - , "version": "0.0.1" - , "private": true -} \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/temporary/node_modules/package/test/support/package.json b/node/node_modules/grunt/node_modules/temporary/node_modules/package/test/support/package.json deleted file mode 100644 index ed5e67177..000000000 --- a/node/node_modules/grunt/node_modules/temporary/node_modules/package/test/support/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "test-package-json-file" - , "version": "0.0.1" - , "private": true -} \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/temporary/package.json b/node/node_modules/grunt/node_modules/temporary/package.json deleted file mode 100644 index 6d7b4b1e5..000000000 --- a/node/node_modules/grunt/node_modules/temporary/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "temporary", - "version": "0.0.5", - "description": "The lord of tmp.", - "keywords": [ - "tmp", - "temp", - "tempfile", - "tempdirectory" - ], - "author": { - "name": "Veselin Todorov", - "email": "hi@vesln.com" - }, - "dependencies": { - "package": ">= 1.0.0 < 1.2.0" - }, - "devDependencies": { - "mocha": "1.2.x", - "chai": "*", - "sinon": "1.2.0" - }, - "repository": { - "type": "git", - "url": "http://github.com/vesln/temporary.git" - }, - "homepage": "http://github.com/vesln/temporary", - "scripts": { - "test": "make test" - }, - "main": "index", - "engines": { - "node": ">= 0.6.0" - }, - "readme": "[![Build Status](https://secure.travis-ci.org/vesln/temporary.png)](http://travis-ci.org/vesln/temporary)\n\n# temporary - The lord of tmp.\n\n## Intro\n\nTemporary provides an easy way to create temporary files and directories.\nIt will create a temporary file/directory with a unique name.\n\n## Features\n\n- Generates unique name.\n- Auto-discovers tmp dir.\n\n## Installation\n\n\t$ npm install temporary\n\n## Usage\n\n\tvar Tempfile = require('temporary/file');\n\tvar Tempdir = require('temporary/dir');\n\tvar file = new Tempfile;\n\tvar dir = new Tempdir;\n\t\n\tconsole.log(file.path); // path.\n\tconsole.log(dir.path); // path.\n\t\n\tfile.unlink();\n\tdir.rmdir();\n\n## Methods\n\n### File\n\n- File.readFile\n- File.readFileSync\n- File.writeFile\n- File.writeFileSync\n- File.open\n- File.openSync\n- File.close\n- File.closeSync\n- File.unlink\n- File.unlinkSync\n\n### Dir\n\n- Dir.rmdir\n- Dir.rmdirSync\n\n## Tests\n\n\t$ make test\n\n## Contribution\n\nBug fixes and features are welcomed.\n\n## License\n\nMIT License\n\nCopyright (C) 2012 Veselin Todorov\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.", - "readmeFilename": "Readme.md", - "bugs": { - "url": "https://github.com/vesln/temporary/issues" - }, - "_id": "temporary@0.0.5", - "_from": "temporary@~0.0.4" -} diff --git a/node/node_modules/grunt/node_modules/temporary/test/base.test.js b/node/node_modules/grunt/node_modules/temporary/test/base.test.js deleted file mode 100644 index 2fdea2872..000000000 --- a/node/node_modules/grunt/node_modules/temporary/test/base.test.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var path = require('path'); -var fs = require('fs'); -var existsSync = fs.existsSync || path.existsSync; - -var Base = require('../lib/base'); -var generator = require('../lib/generator'); -var should = require('chai').should(); - -Base.prototype.create = function() {}; - -describe('Base', function() { - describe('rename', function() { - it('should rename the directory', function(done) { - var tmp = new Base; - tmp.path = generator.build(); - fs.mkdirSync(path.normalize(tmp.path), 0777); - existsSync(tmp.path).should.be.ok; - tmp.rename('foo', function(err) { - existsSync(tmp.path).should.be.ok; - done(); - }); - }); - }); - - describe('renameSync', function() { - it('should rename the directory', function() { - var tmp = new Base('foo'); - tmp.path = generator.build(); - fs.mkdirSync(path.normalize(tmp.path), 0777); - var oldPath = tmp.path; - existsSync(tmp.path).should.be.ok; - tmp.renameSync('foo3'); - existsSync(tmp.path).should.be.ok; - path.should.not.eql(oldPath); - }); - }); - - describe('prepareArgs', function() { - it('should convert object to array and append path as first element', function() { - var tmp = new Base('foo'); - var args = { 0: 'foo' }; - args.length = 1; - tmp.path = generator.build(); - tmp.prepareArgs(args).should.eql([tmp.path, 'foo']); - }); - }); -}); diff --git a/node/node_modules/grunt/node_modules/temporary/test/detector.test.js b/node/node_modules/grunt/node_modules/temporary/test/detector.test.js deleted file mode 100644 index ed4836645..000000000 --- a/node/node_modules/grunt/node_modules/temporary/test/detector.test.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var detector = require('../lib/detector'); -var should = require('chai').should(); - -describe('detector', function() { - describe('tmp', function() { - it('should return the tmp dir of the system', function() { - var tmp = process.env.TMPDIR - || process.env.TMP - || process.env.TEMP - || (process.platform === "win32" ? "c:\\windows\\temp\\" : "/tmp/"); - detector.tmp().should.eql(tmp); - }); - }); -}); diff --git a/node/node_modules/grunt/node_modules/temporary/test/dir.test.js b/node/node_modules/grunt/node_modules/temporary/test/dir.test.js deleted file mode 100644 index 8875a88cb..000000000 --- a/node/node_modules/grunt/node_modules/temporary/test/dir.test.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var fs = require('fs'); -var path = require('path'); -var existsSync = fs.existsSync || path.existsSync; - -var Tempdir = require('../lib/dir'); -var sinon = require('sinon'); -var should = require('chai').should(); - -describe('Tempdir', function() { - it('should create file', function() { - var tmp = new Tempdir('foo'); - existsSync(tmp.path).should.be.ok; - }); - - describe('rmdir', function() { - it('should remove the directory', function() { - var tmp = new Tempdir('foo'); - sinon.spy(fs, 'rmdir'); - tmp.rmdir(); - fs.rmdir.getCall(0).args[0].should.eql(tmp.path); - fs.rmdir.restore(); - }); - }); - - describe('rmdirSync', function() { - it('should remove the directory', function() { - var tmp = new Tempdir('foo'); - sinon.spy(fs, 'rmdirSync'); - tmp.rmdirSync(); - fs.rmdirSync.getCall(0).args[0].should.eql(tmp.path); - fs.rmdirSync.restore(); - }); - }); -}); diff --git a/node/node_modules/grunt/node_modules/temporary/test/file.test.js b/node/node_modules/grunt/node_modules/temporary/test/file.test.js deleted file mode 100644 index 9927e31b1..000000000 --- a/node/node_modules/grunt/node_modules/temporary/test/file.test.js +++ /dev/null @@ -1,126 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var path = require('path'); -var fs = require('fs'); -var existsSync = fs.existsSync || path.existsSync; - -var Tempfile = require('../lib/file'); -var sinon = require('sinon'); -var should = require('chai').should(); - -describe('Tempfile', function() { - it('should create file', function() { - var tmp = new Tempfile('foo'); - existsSync(tmp.path).should.be.ok; - }); - - describe('readFile', function() { - it('should call fs.readfile', function() { - sinon.spy(fs, 'readFile'); - var tmp = new Tempfile; - tmp.readFile(); - fs.readFile.getCall(0).args[0].should.eql(tmp.path); - fs.readFile.restore(); - }); - }); - - describe('readFileSync', function() { - it('should call fs.readfileSync', function() { - sinon.spy(fs, 'readFileSync'); - var tmp = new Tempfile; - tmp.readFileSync(); - fs.readFileSync.getCall(0).args[0].should.eql(tmp.path); - fs.readFileSync.restore(); - }); - }); - - describe('writeFile', function() { - it('should call fs.readfile', function() { - sinon.spy(fs, 'writeFile'); - var tmp = new Tempfile; - tmp.writeFile(); - fs.writeFile.getCall(0).args[0].should.eql(tmp.path); - fs.writeFile.restore(); - }); - }); - - describe('writeFileSync', function() { - it('should call fs.writeFileSync', function() { - sinon.spy(fs, 'writeFileSync'); - var tmp = new Tempfile; - tmp.writeFileSync(); - fs.writeFileSync.getCall(0).args[0].should.eql(tmp.path); - fs.writeFileSync.restore(); - }); - }); - - describe('open', function() { - it('should call fs.open', function() { - sinon.spy(fs, 'open'); - var tmp = new Tempfile; - tmp.open('r'); - fs.open.getCall(0).args[0].should.eql(tmp.path); - fs.open.restore(); - }); - }); - - describe('openSync', function() { - it('should call fs.openSync', function() { - sinon.spy(fs, 'openSync'); - var tmp = new Tempfile; - tmp.openSync('r'); - fs.openSync.getCall(0).args[0].should.eql(tmp.path); - fs.openSync.restore(); - }); - }); - - describe('close', function() { - it('should call fs.close', function() { - sinon.spy(fs, 'close'); - var tmp = new Tempfile; - var fd = tmp.openSync('r'); - tmp.close(fd); - fs.close.getCall(0).args[0].should.eql(fd); - fs.close.restore(); - }); - }); - - describe('closeSync', function() { - it('should call fs.closeSync', function() { - sinon.spy(fs, 'closeSync'); - var tmp = new Tempfile; - var fd = tmp.openSync('r'); - tmp.closeSync(fd); - fs.closeSync.getCall(0).args[0].should.eql(fd); - fs.closeSync.restore(); - }); - }); - - describe('unlink', function() { - it('should call fs.unlink', function() { - sinon.spy(fs, 'unlink'); - var tmp = new Tempfile; - tmp.unlink(); - fs.unlink.getCall(0).args[0].should.eql(tmp.path); - fs.unlink.restore(); - }); - }); - - describe('unlinkSync', function() { - it('should call fs.readfileSync', function() { - sinon.spy(fs, 'unlinkSync'); - var tmp = new Tempfile; - tmp.unlinkSync(); - fs.unlinkSync.getCall(0).args[0].should.eql(tmp.path); - fs.unlinkSync.restore(); - }); - }); -}); diff --git a/node/node_modules/grunt/node_modules/temporary/test/generator.test.js b/node/node_modules/grunt/node_modules/temporary/test/generator.test.js deleted file mode 100644 index 2483a91aa..000000000 --- a/node/node_modules/grunt/node_modules/temporary/test/generator.test.js +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Temporary - The lord of tmp. - * - * Author: Veselin Todorov - * Licensed under the MIT License. - */ - -/** - * Dependencies. - */ -var generator = require('../lib/generator'); -var detector = require('../lib/detector'); -var should = require('chai').should(); - -describe('generator', function() { - describe('name', function() { - it('should unique generate name', function() { - generator.name().should.be.ok; - }); - }); - - describe('build', function() { - it('should build full names', function() { - var tmp = detector.tmp(); - generator.build().should.match(new RegExp("^" + tmp)); - generator.build('foo').should.match(new RegExp("^" + tmp + 'foo.')); - }); - }); -}); diff --git a/node/node_modules/grunt/node_modules/uglify-js/.npmignore b/node/node_modules/grunt/node_modules/uglify-js/.npmignore deleted file mode 100644 index 83c3dac18..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/.npmignore +++ /dev/null @@ -1,6 +0,0 @@ -.DS_Store -.tmp*~ -*.local.* -.pinf-* -node_modules/ -npm-debug.log diff --git a/node/node_modules/grunt/node_modules/uglify-js/README.html b/node/node_modules/grunt/node_modules/uglify-js/README.html deleted file mode 100644 index abefdf113..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/README.html +++ /dev/null @@ -1,1012 +0,0 @@ - - - - -UglifyJS – a JavaScript parser/compressor/beautifier - - - - - - - - - - - - - -
        - -
        - -
        -

        UglifyJS – a JavaScript parser/compressor/beautifier

        - - - - -
        -

        1 NEW: UglifyJS2

        -
        - - -

        -I started working on UglifyJS's successor, version 2. It's almost a full -rewrite (except for the parser which is heavily modified, everything else -starts from scratch). I've detailed my reasons in the README, see the -project page. -

        -

        -https://github.com/mishoo/UglifyJS2 -

        -

        -Version 1 will continue to be maintained for fixing show-stopper bugs, but -no new features should be expected. -

        -

        -Please help me focus on version 2 by making a donation! -

        -
        - -
        - -
        -

        2 UglifyJS — a JavaScript parser/compressor/beautifier

        -
        - - -

        -This package implements a general-purpose JavaScript -parser/compressor/beautifier toolkit. It is developed on NodeJS, but it -should work on any JavaScript platform supporting the CommonJS module system -(and if your platform of choice doesn't support CommonJS, you can easily -implement it, or discard the exports.* lines from UglifyJS sources). -

        -

        -The tokenizer/parser generates an abstract syntax tree from JS code. You -can then traverse the AST to learn more about the code, or do various -manipulations on it. This part is implemented in parse-js.js and it's a -port to JavaScript of the excellent parse-js Common Lisp library from Marijn Haverbeke. -

        -

        -( See cl-uglify-js if you're looking for the Common Lisp version of -UglifyJS. ) -

        -

        -The second part of this package, implemented in process.js, inspects and -manipulates the AST generated by the parser to provide the following: -

        -
          -
        • ability to re-generate JavaScript code from the AST. Optionally - indented—you can use this if you want to “beautify” a program that has - been compressed, so that you can inspect the source. But you can also run - our code generator to print out an AST without any whitespace, so you - achieve compression as well. - -
        • -
        • shorten variable names (usually to single characters). Our mangler will - analyze the code and generate proper variable names, depending on scope - and usage, and is smart enough to deal with globals defined elsewhere, or - with eval() calls or with{} statements. In short, if eval() or - with{} are used in some scope, then all variables in that scope and any - variables in the parent scopes will remain unmangled, and any references - to such variables remain unmangled as well. - -
        • -
        • various small optimizations that may lead to faster code but certainly - lead to smaller code. Where possible, we do the following: - -
            -
          • foo["bar"] ==> foo.bar - -
          • -
          • remove block brackets {} - -
          • -
          • join consecutive var declarations: - var a = 10; var b = 20; ==> var a=10,b=20; - -
          • -
          • resolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the - replacement if the result occupies less bytes; for example 1/3 would - translate to 0.333333333333, so in this case we don't replace it. - -
          • -
          • consecutive statements in blocks are merged into a sequence; in many - cases, this leaves blocks with a single statement, so then we can remove - the block brackets. - -
          • -
          • various optimizations for IF statements: - -
              -
            • if (foo) bar(); else baz(); ==> foo?bar():baz(); -
            • -
            • if (!foo) bar(); else baz(); ==> foo?baz():bar(); -
            • -
            • if (foo) bar(); ==> foo&&bar(); -
            • -
            • if (!foo) bar(); ==> foo||bar(); -
            • -
            • if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); -
            • -
            • if (foo) return bar(); else something(); ==> {if(foo)return bar();something()} - -
            • -
            - -
          • -
          • remove some unreachable code and warn about it (code that follows a - return, throw, break or continue statement, except - function/variable declarations). - -
          • -
          • act a limited version of a pre-processor (c.f. the pre-processor of - C/C++) to allow you to safely replace selected global symbols with - specified values. When combined with the optimisations above this can - make UglifyJS operate slightly more like a compilation process, in - that when certain symbols are replaced by constant values, entire code - blocks may be optimised away as unreachable. -
          • -
          - -
        • -
        - - - -
        - -
        -

        2.1 Unsafe transformations

        -
        - - -

        -The following transformations can in theory break code, although they're -probably safe in most practical cases. To enable them you need to pass the ---unsafe flag. -

        - -
        - -
        -

        2.1.1 Calls involving the global Array constructor

        -
        - - -

        -The following transformations occur: -

        - - - -
        new Array(1, 2, 3, 4)  => [1,2,3,4]
        -Array(a, b, c)         => [a,b,c]
        -new Array(5)           => Array(5)
        -new Array(a)           => Array(a)
        -
        - - -

        -These are all safe if the Array name isn't redefined. JavaScript does allow -one to globally redefine Array (and pretty much everything, in fact) but I -personally don't see why would anyone do that. -

        -

        -UglifyJS does handle the case where Array is redefined locally, or even -globally but with a function or var declaration. Therefore, in the -following cases UglifyJS doesn't touch calls or instantiations of Array: -

        - - - -
        // case 1.  globally declared variable
        -  var Array;
        -  new Array(1, 2, 3);
        -  Array(a, b);
        -
        -  // or (can be declared later)
        -  new Array(1, 2, 3);
        -  var Array;
        -
        -  // or (can be a function)
        -  new Array(1, 2, 3);
        -  function Array() { ... }
        -
        -// case 2.  declared in a function
        -  (function(){
        -    a = new Array(1, 2, 3);
        -    b = Array(5, 6);
        -    var Array;
        -  })();
        -
        -  // or
        -  (function(Array){
        -    return Array(5, 6, 7);
        -  })();
        -
        -  // or
        -  (function(){
        -    return new Array(1, 2, 3, 4);
        -    function Array() { ... }
        -  })();
        -
        -  // etc.
        -
        - - -
        - -
        - -
        -

        2.1.2 obj.toString() ==> obj+“”

        -
        - - -
        -
        - -
        - -
        -

        2.2 Install (NPM)

        -
        - - -

        -UglifyJS is now available through NPM — npm install uglify-js should do -the job. -

        -
        - -
        - -
        -

        2.3 Install latest code from GitHub

        -
        - - - - - -
        ## clone the repository
        -mkdir -p /where/you/wanna/put/it
        -cd /where/you/wanna/put/it
        -git clone git://github.com/mishoo/UglifyJS.git
        -
        -## make the module available to Node
        -mkdir -p ~/.node_libraries/
        -cd ~/.node_libraries/
        -ln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js
        -
        -## and if you want the CLI script too:
        -mkdir -p ~/bin
        -cd ~/bin
        -ln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs
        -  # (then add ~/bin to your $PATH if it's not there already)
        -
        - - -
        - -
        - -
        -

        2.4 Usage

        -
        - - -

        -There is a command-line tool that exposes the functionality of this library -for your shell-scripting needs: -

        - - - -
        uglifyjs [ options... ] [ filename ]
        -
        - - -

        -filename should be the last argument and should name the file from which -to read the JavaScript code. If you don't specify it, it will read code -from STDIN. -

        -

        -Supported options: -

        -
          -
        • -b or --beautify — output indented code; when passed, additional - options control the beautifier: - -
            -
          • -i N or --indent N — indentation level (number of spaces) - -
          • -
          • -q or --quote-keys — quote keys in literal objects (by default, - only keys that cannot be identifier names will be quotes). - -
          • -
          - -
        • -
        • -c or ----consolidate-primitive-values — consolidates null, Boolean, - and String values. Known as aliasing in the Closure Compiler. Worsens the - data compression ratio of gzip. - -
        • -
        • --ascii — pass this argument to encode non-ASCII characters as - \uXXXX sequences. By default UglifyJS won't bother to do it and will - output Unicode characters instead. (the output is always encoded in UTF8, - but if you pass this option you'll only get ASCII). - -
        • -
        • -nm or --no-mangle — don't mangle names. - -
        • -
        • -nmf or --no-mangle-functions – in case you want to mangle variable - names, but not touch function names. - -
        • -
        • -ns or --no-squeeze — don't call ast_squeeze() (which does various - optimizations that result in smaller, less readable code). - -
        • -
        • -mt or --mangle-toplevel — mangle names in the toplevel scope too - (by default we don't do this). - -
        • -
        • --no-seqs — when ast_squeeze() is called (thus, unless you pass - --no-squeeze) it will reduce consecutive statements in blocks into a - sequence. For example, "a = 10; b = 20; foo();" will be written as - "a=10,b=20,foo();". In various occasions, this allows us to discard the - block brackets (since the block becomes a single statement). This is ON - by default because it seems safe and saves a few hundred bytes on some - libs that I tested it on, but pass --no-seqs to disable it. - -
        • -
        • --no-dead-code — by default, UglifyJS will remove code that is - obviously unreachable (code that follows a return, throw, break or - continue statement and is not a function/variable declaration). Pass - this option to disable this optimization. - -
        • -
        • -nc or --no-copyright — by default, uglifyjs will keep the initial - comment tokens in the generated code (assumed to be copyright information - etc.). If you pass this it will discard it. - -
        • -
        • -o filename or --output filename — put the result in filename. If - this isn't given, the result goes to standard output (or see next one). - -
        • -
        • --overwrite — if the code is read from a file (not from STDIN) and you - pass --overwrite then the output will be written in the same file. - -
        • -
        • --ast — pass this if you want to get the Abstract Syntax Tree instead - of JavaScript as output. Useful for debugging or learning more about the - internals. - -
        • -
        • -v or --verbose — output some notes on STDERR (for now just how long - each operation takes). - -
        • -
        • -d SYMBOL[=VALUE] or --define SYMBOL[=VALUE] — will replace - all instances of the specified symbol where used as an identifier - (except where symbol has properly declared by a var declaration or - use as function parameter or similar) with the specified value. This - argument may be specified multiple times to define multiple - symbols - if no value is specified the symbol will be replaced with - the value true, or you can specify a numeric value (such as - 1024), a quoted string value (such as ="object"= or - ='https://github.com'), or the name of another symbol or keyword (such as =null or document). - This allows you, for example, to assign meaningful names to key - constant values but discard the symbolic names in the uglified - version for brevity/efficiency, or when used wth care, allows - UglifyJS to operate as a form of conditional compilation - whereby defining appropriate values may, by dint of the constant - folding and dead code removal features above, remove entire - superfluous code blocks (e.g. completely remove instrumentation or - trace code for production use). - Where string values are being defined, the handling of quotes are - likely to be subject to the specifics of your command shell - environment, so you may need to experiment with quoting styles - depending on your platform, or you may find the option - --define-from-module more suitable for use. - -
        • -
        • -define-from-module SOMEMODULE — will load the named module (as - per the NodeJS require() function) and iterate all the exported - properties of the module defining them as symbol names to be defined - (as if by the --define option) per the name of each property - (i.e. without the module name prefix) and given the value of the - property. This is a much easier way to handle and document groups of - symbols to be defined rather than a large number of --define - options. - -
        • -
        • --unsafe — enable other additional optimizations that are known to be - unsafe in some contrived situations, but could still be generally useful. - For now only these: - -
            -
          • foo.toString() ==> foo+"" -
          • -
          • new Array(x,…) ==> [x,…] -
          • -
          • new Array(x) ==> Array(x) - -
          • -
          - -
        • -
        • --max-line-len (default 32K characters) — add a newline after around - 32K characters. I've seen both FF and Chrome croak when all the code was - on a single line of around 670K. Pass –max-line-len 0 to disable this - safety feature. - -
        • -
        • --reserved-names — some libraries rely on certain names to be used, as - pointed out in issue #92 and #81, so this option allow you to exclude such - names from the mangler. For example, to keep names require and $super - intact you'd specify –reserved-names "require,$super". - -
        • -
        • --inline-script – when you want to include the output literally in an - HTML <script> tag you can use this option to prevent </script from - showing up in the output. - -
        • -
        • --lift-vars – when you pass this, UglifyJS will apply the following - transformations (see the notes in API, ast_lift_variables): - -
            -
          • put all var declarations at the start of the scope -
          • -
          • make sure a variable is declared only once -
          • -
          • discard unused function arguments -
          • -
          • discard unused inner (named) functions -
          • -
          • finally, try to merge assignments into that one var declaration, if - possible. -
          • -
          - -
        • -
        - - - -
        - -
        -

        2.4.1 API

        -
        - - -

        -To use the library from JavaScript, you'd do the following (example for -NodeJS): -

        - - - -
        var jsp = require("uglify-js").parser;
        -var pro = require("uglify-js").uglify;
        -
        -var orig_code = "... JS code here";
        -var ast = jsp.parse(orig_code); // parse code and get the initial AST
        -ast = pro.ast_mangle(ast); // get a new AST with mangled names
        -ast = pro.ast_squeeze(ast); // get an AST with compression optimizations
        -var final_code = pro.gen_code(ast); // compressed code here
        -
        - - -

        -The above performs the full compression that is possible right now. As you -can see, there are a sequence of steps which you can apply. For example if -you want compressed output but for some reason you don't want to mangle -variable names, you would simply skip the line that calls -pro.ast_mangle(ast). -

        -

        -Some of these functions take optional arguments. Here's a description: -

        -
          -
        • jsp.parse(code, strict_semicolons) – parses JS code and returns an AST. - strict_semicolons is optional and defaults to false. If you pass - true then the parser will throw an error when it expects a semicolon and - it doesn't find it. For most JS code you don't want that, but it's useful - if you want to strictly sanitize your code. - -
        • -
        • pro.ast_lift_variables(ast) – merge and move var declarations to the - scop of the scope; discard unused function arguments or variables; discard - unused (named) inner functions. It also tries to merge assignments - following the var declaration into it. - -

          - If your code is very hand-optimized concerning var declarations, this - lifting variable declarations might actually increase size. For me it - helps out. On jQuery it adds 865 bytes (243 after gzip). YMMV. Also - note that (since it's not enabled by default) this operation isn't yet - heavily tested (please report if you find issues!). -

          -

          - Note that although it might increase the image size (on jQuery it gains - 865 bytes, 243 after gzip) it's technically more correct: in certain - situations, dead code removal might drop variable declarations, which - would not happen if the variables are lifted in advance. -

          -

          - Here's an example of what it does: -

        • -
        - - - - - -
        function f(a, b, c, d, e) {
        -    var q;
        -    var w;
        -    w = 10;
        -    q = 20;
        -    for (var i = 1; i < 10; ++i) {
        -        var boo = foo(a);
        -    }
        -    for (var i = 0; i < 1; ++i) {
        -        var boo = bar(c);
        -    }
        -    function foo(){ ... }
        -    function bar(){ ... }
        -    function baz(){ ... }
        -}
        -
        -// transforms into ==>
        -
        -function f(a, b, c) {
        -    var i, boo, w = 10, q = 20;
        -    for (i = 1; i < 10; ++i) {
        -        boo = foo(a);
        -    }
        -    for (i = 0; i < 1; ++i) {
        -        boo = bar(c);
        -    }
        -    function foo() { ... }
        -    function bar() { ... }
        -}
        -
        - - -
          -
        • pro.ast_mangle(ast, options) – generates a new AST containing mangled - (compressed) variable and function names. It supports the following - options: - -
            -
          • toplevel – mangle toplevel names (by default we don't touch them). -
          • -
          • except – an array of names to exclude from compression. -
          • -
          • defines – an object with properties named after symbols to - replace (see the --define option for the script) and the values - representing the AST replacement value. - -
          • -
          - -
        • -
        • pro.ast_squeeze(ast, options) – employs further optimizations designed - to reduce the size of the code that gen_code would generate from the - AST. Returns a new AST. options can be a hash; the supported options - are: - -
            -
          • make_seqs (default true) which will cause consecutive statements in a - block to be merged using the "sequence" (comma) operator - -
          • -
          • dead_code (default true) which will remove unreachable code. - -
          • -
          - -
        • -
        • pro.gen_code(ast, options) – generates JS code from the AST. By - default it's minified, but using the options argument you can get nicely - formatted output. options is, well, optional :-) and if you pass it it - must be an object and supports the following properties (below you can see - the default values): - -
            -
          • beautify: false – pass true if you want indented output -
          • -
          • indent_start: 0 (only applies when beautify is true) – initial - indentation in spaces -
          • -
          • indent_level: 4 (only applies when beautify is true) -- - indentation level, in spaces (pass an even number) -
          • -
          • quote_keys: false – if you pass true it will quote all keys in - literal objects -
          • -
          • space_colon: false (only applies when beautify is true) – wether - to put a space before the colon in object literals -
          • -
          • ascii_only: false – pass true if you want to encode non-ASCII - characters as \uXXXX. -
          • -
          • inline_script: false – pass true to escape occurrences of - </script in strings -
          • -
          - -
        • -
        - - -
        - -
        - -
        -

        2.4.2 Beautifier shortcoming – no more comments

        -
        - - -

        -The beautifier can be used as a general purpose indentation tool. It's -useful when you want to make a minified file readable. One limitation, -though, is that it discards all comments, so you don't really want to use it -to reformat your code, unless you don't have, or don't care about, comments. -

        -

        -In fact it's not the beautifier who discards comments — they are dumped at -the parsing stage, when we build the initial AST. Comments don't really -make sense in the AST, and while we could add nodes for them, it would be -inconvenient because we'd have to add special rules to ignore them at all -the processing stages. -

        -
        - -
        - -
        -

        2.4.3 Use as a code pre-processor

        -
        - - -

        -The --define option can be used, particularly when combined with the -constant folding logic, as a form of pre-processor to enable or remove -particular constructions, such as might be used for instrumenting -development code, or to produce variations aimed at a specific -platform. -

        -

        -The code below illustrates the way this can be done, and how the -symbol replacement is performed. -

        - - - -
        CLAUSE1: if (typeof DEVMODE === 'undefined') {
        -    DEVMODE = true;
        -}
        -
        -CLAUSE2: function init() {
        -    if (DEVMODE) {
        -        console.log("init() called");
        -    }
        -    ....
        -    DEVMODE &amp;&amp; console.log("init() complete");
        -}
        -
        -CLAUSE3: function reportDeviceStatus(device) {
        -    var DEVMODE = device.mode, DEVNAME = device.name;
        -    if (DEVMODE === 'open') {
        -        ....
        -    }
        -}
        -
        - - -

        -When the above code is normally executed, the undeclared global -variable DEVMODE will be assigned the value true (see CLAUSE1) -and so the init() function (CLAUSE2) will write messages to the -console log when executed, but in CLAUSE3 a locally declared -variable will mask access to the DEVMODE global symbol. -

        -

        -If the above code is processed by UglifyJS with an argument of ---define DEVMODE=false then UglifyJS will replace DEVMODE with the -boolean constant value false within CLAUSE1 and CLAUSE2, but it -will leave CLAUSE3 as it stands because there DEVMODE resolves to -a validly declared variable. -

        -

        -And more so, the constant-folding features of UglifyJS will recognise -that the if condition of CLAUSE1 is thus always false, and so will -remove the test and body of CLAUSE1 altogether (including the -otherwise slightly problematical statement false = true; which it -will have formed by replacing DEVMODE in the body). Similarly, -within CLAUSE2 both calls to console.log() will be removed -altogether. -

        -

        -In this way you can mimic, to a limited degree, the functionality of -the C/C++ pre-processor to enable or completely remove blocks -depending on how certain symbols are defined - perhaps using UglifyJS -to generate different versions of source aimed at different -environments -

        -

        -It is recommmended (but not made mandatory) that symbols designed for -this purpose are given names consisting of UPPER_CASE_LETTERS to -distinguish them from other (normal) symbols and avoid the sort of -clash that CLAUSE3 above illustrates. -

        -
        -
        - -
        - -
        -

        2.5 Compression – how good is it?

        -
        - - -

        -Here are updated statistics. (I also updated my Google Closure and YUI -installations). -

        -

        -We're still a lot better than YUI in terms of compression, though slightly -slower. We're still a lot faster than Closure, and compression after gzip -is comparable. -

        - - -- - - - - - - - - - -
        FileUglifyJSUglifyJS+gzipClosureClosure+gzipYUIYUI+gzip
        jquery-1.6.2.js91001 (0:01.59)3189690678 (0:07.40)31979101527 (0:01.82)34646
        paper.js142023 (0:01.65)43334134301 (0:07.42)42495173383 (0:01.58)48785
        prototype.js88544 (0:01.09)2668086955 (0:06.97)2632692130 (0:00.79)28624
        thelib-full.js (DynarchLIB)251939 (0:02.55)72535249911 (0:09.05)72696258869 (0:01.94)76584
        - - -
        - -
        - -
        -

        2.6 Bugs?

        -
        - - -

        -Unfortunately, for the time being there is no automated test suite. But I -ran the compressor manually on non-trivial code, and then I tested that the -generated code works as expected. A few hundred times. -

        -

        -DynarchLIB was started in times when there was no good JS minifier. -Therefore I was quite religious about trying to write short code manually, -and as such DL contains a lot of syntactic hacks1 such as “foo == bar ? a -= 10 : b = 20”, though the more readable version would clearly be to use -“if/else”. -

        -

        -Since the parser/compressor runs fine on DL and jQuery, I'm quite confident -that it's solid enough for production use. If you can identify any bugs, -I'd love to hear about them (use the Google Group or email me directly). -

        -
        - -
        - -
        -

        2.7 Links

        -
        - - - - - -
        - -
        - -
        -

        2.8 License

        -
        - - -

        -UglifyJS is released under the BSD license: -

        - - - -
        Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
        -Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
        -
        -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.
        -
        -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 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.
        -
        - - -
        -

        Footnotes:

        -
        -

        1 I even reported a few bugs and suggested some fixes in the original - parse-js library, and Marijn pushed fixes literally in minutes. -

        -
        -
        - -
        -
        -
        - -
        -

        Date: 2012-08-27 12:38:12 EEST

        -

        Author: Mihai Bazon

        -

        Org version 7.7 with Emacs version 23

        -Validate XHTML 1.0 - -
        - - diff --git a/node/node_modules/grunt/node_modules/uglify-js/README.org b/node/node_modules/grunt/node_modules/uglify-js/README.org deleted file mode 100644 index 25880884d..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/README.org +++ /dev/null @@ -1,593 +0,0 @@ -#+TITLE: UglifyJS -- a JavaScript parser/compressor/beautifier -#+KEYWORDS: javascript, js, parser, compiler, compressor, mangle, minify, minifier -#+DESCRIPTION: a JavaScript parser/compressor/beautifier in JavaScript -#+STYLE: -#+AUTHOR: Mihai Bazon -#+EMAIL: mihai.bazon@gmail.com - -* NEW: UglifyJS2 - -I started working on UglifyJS's successor, version 2. It's almost a full -rewrite (except for the parser which is heavily modified, everything else -starts from scratch). I've detailed my reasons in the README, see the -project page. - -[[https://github.com/mishoo/UglifyJS2][https://github.com/mishoo/UglifyJS2]] - -Version 1 will continue to be maintained for fixing show-stopper bugs, but -no new features should be expected. - -Please help me focus on version 2 by [[http://pledgie.com/campaigns/18110][making a donation]]! - -* UglifyJS --- a JavaScript parser/compressor/beautifier - -This package implements a general-purpose JavaScript -parser/compressor/beautifier toolkit. It is developed on [[http://nodejs.org/][NodeJS]], but it -should work on any JavaScript platform supporting the CommonJS module system -(and if your platform of choice doesn't support CommonJS, you can easily -implement it, or discard the =exports.*= lines from UglifyJS sources). - -The tokenizer/parser generates an abstract syntax tree from JS code. You -can then traverse the AST to learn more about the code, or do various -manipulations on it. This part is implemented in [[../lib/parse-js.js][parse-js.js]] and it's a -port to JavaScript of the excellent [[http://marijn.haverbeke.nl/parse-js/][parse-js]] Common Lisp library from [[http://marijn.haverbeke.nl/][Marijn -Haverbeke]]. - -( See [[http://github.com/mishoo/cl-uglify-js][cl-uglify-js]] if you're looking for the Common Lisp version of -UglifyJS. ) - -The second part of this package, implemented in [[../lib/process.js][process.js]], inspects and -manipulates the AST generated by the parser to provide the following: - -- ability to re-generate JavaScript code from the AST. Optionally - indented---you can use this if you want to “beautify” a program that has - been compressed, so that you can inspect the source. But you can also run - our code generator to print out an AST without any whitespace, so you - achieve compression as well. - -- shorten variable names (usually to single characters). Our mangler will - analyze the code and generate proper variable names, depending on scope - and usage, and is smart enough to deal with globals defined elsewhere, or - with =eval()= calls or =with{}= statements. In short, if =eval()= or - =with{}= are used in some scope, then all variables in that scope and any - variables in the parent scopes will remain unmangled, and any references - to such variables remain unmangled as well. - -- various small optimizations that may lead to faster code but certainly - lead to smaller code. Where possible, we do the following: - - - foo["bar"] ==> foo.bar - - - remove block brackets ={}= - - - join consecutive var declarations: - var a = 10; var b = 20; ==> var a=10,b=20; - - - resolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the - replacement if the result occupies less bytes; for example 1/3 would - translate to 0.333333333333, so in this case we don't replace it. - - - consecutive statements in blocks are merged into a sequence; in many - cases, this leaves blocks with a single statement, so then we can remove - the block brackets. - - - various optimizations for IF statements: - - - if (foo) bar(); else baz(); ==> foo?bar():baz(); - - if (!foo) bar(); else baz(); ==> foo?baz():bar(); - - if (foo) bar(); ==> foo&&bar(); - - if (!foo) bar(); ==> foo||bar(); - - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); - - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()} - - - remove some unreachable code and warn about it (code that follows a - =return=, =throw=, =break= or =continue= statement, except - function/variable declarations). - - - act a limited version of a pre-processor (c.f. the pre-processor of - C/C++) to allow you to safely replace selected global symbols with - specified values. When combined with the optimisations above this can - make UglifyJS operate slightly more like a compilation process, in - that when certain symbols are replaced by constant values, entire code - blocks may be optimised away as unreachable. - -** <> - -The following transformations can in theory break code, although they're -probably safe in most practical cases. To enable them you need to pass the -=--unsafe= flag. - -*** Calls involving the global Array constructor - -The following transformations occur: - -#+BEGIN_SRC js -new Array(1, 2, 3, 4) => [1,2,3,4] -Array(a, b, c) => [a,b,c] -new Array(5) => Array(5) -new Array(a) => Array(a) -#+END_SRC - -These are all safe if the Array name isn't redefined. JavaScript does allow -one to globally redefine Array (and pretty much everything, in fact) but I -personally don't see why would anyone do that. - -UglifyJS does handle the case where Array is redefined locally, or even -globally but with a =function= or =var= declaration. Therefore, in the -following cases UglifyJS *doesn't touch* calls or instantiations of Array: - -#+BEGIN_SRC js -// case 1. globally declared variable - var Array; - new Array(1, 2, 3); - Array(a, b); - - // or (can be declared later) - new Array(1, 2, 3); - var Array; - - // or (can be a function) - new Array(1, 2, 3); - function Array() { ... } - -// case 2. declared in a function - (function(){ - a = new Array(1, 2, 3); - b = Array(5, 6); - var Array; - })(); - - // or - (function(Array){ - return Array(5, 6, 7); - })(); - - // or - (function(){ - return new Array(1, 2, 3, 4); - function Array() { ... } - })(); - - // etc. -#+END_SRC - -*** =obj.toString()= ==> =obj+“”= - -** Install (NPM) - -UglifyJS is now available through NPM --- =npm install uglify-js= should do -the job. - -** Install latest code from GitHub - -#+BEGIN_SRC sh -## clone the repository -mkdir -p /where/you/wanna/put/it -cd /where/you/wanna/put/it -git clone git://github.com/mishoo/UglifyJS.git - -## make the module available to Node -mkdir -p ~/.node_libraries/ -cd ~/.node_libraries/ -ln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js - -## and if you want the CLI script too: -mkdir -p ~/bin -cd ~/bin -ln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs - # (then add ~/bin to your $PATH if it's not there already) -#+END_SRC - -** Usage - -There is a command-line tool that exposes the functionality of this library -for your shell-scripting needs: - -#+BEGIN_SRC sh -uglifyjs [ options... ] [ filename ] -#+END_SRC - -=filename= should be the last argument and should name the file from which -to read the JavaScript code. If you don't specify it, it will read code -from STDIN. - -Supported options: - -- =-b= or =--beautify= --- output indented code; when passed, additional - options control the beautifier: - - - =-i N= or =--indent N= --- indentation level (number of spaces) - - - =-q= or =--quote-keys= --- quote keys in literal objects (by default, - only keys that cannot be identifier names will be quotes). - -- =-c= or =----consolidate-primitive-values= --- consolidates null, Boolean, - and String values. Known as aliasing in the Closure Compiler. Worsens the - data compression ratio of gzip. - -- =--ascii= --- pass this argument to encode non-ASCII characters as - =\uXXXX= sequences. By default UglifyJS won't bother to do it and will - output Unicode characters instead. (the output is always encoded in UTF8, - but if you pass this option you'll only get ASCII). - -- =-nm= or =--no-mangle= --- don't mangle names. - -- =-nmf= or =--no-mangle-functions= -- in case you want to mangle variable - names, but not touch function names. - -- =-ns= or =--no-squeeze= --- don't call =ast_squeeze()= (which does various - optimizations that result in smaller, less readable code). - -- =-mt= or =--mangle-toplevel= --- mangle names in the toplevel scope too - (by default we don't do this). - -- =--no-seqs= --- when =ast_squeeze()= is called (thus, unless you pass - =--no-squeeze=) it will reduce consecutive statements in blocks into a - sequence. For example, "a = 10; b = 20; foo();" will be written as - "a=10,b=20,foo();". In various occasions, this allows us to discard the - block brackets (since the block becomes a single statement). This is ON - by default because it seems safe and saves a few hundred bytes on some - libs that I tested it on, but pass =--no-seqs= to disable it. - -- =--no-dead-code= --- by default, UglifyJS will remove code that is - obviously unreachable (code that follows a =return=, =throw=, =break= or - =continue= statement and is not a function/variable declaration). Pass - this option to disable this optimization. - -- =-nc= or =--no-copyright= --- by default, =uglifyjs= will keep the initial - comment tokens in the generated code (assumed to be copyright information - etc.). If you pass this it will discard it. - -- =-o filename= or =--output filename= --- put the result in =filename=. If - this isn't given, the result goes to standard output (or see next one). - -- =--overwrite= --- if the code is read from a file (not from STDIN) and you - pass =--overwrite= then the output will be written in the same file. - -- =--ast= --- pass this if you want to get the Abstract Syntax Tree instead - of JavaScript as output. Useful for debugging or learning more about the - internals. - -- =-v= or =--verbose= --- output some notes on STDERR (for now just how long - each operation takes). - -- =-d SYMBOL[=VALUE]= or =--define SYMBOL[=VALUE]= --- will replace - all instances of the specified symbol where used as an identifier - (except where symbol has properly declared by a var declaration or - use as function parameter or similar) with the specified value. This - argument may be specified multiple times to define multiple - symbols - if no value is specified the symbol will be replaced with - the value =true=, or you can specify a numeric value (such as - =1024=), a quoted string value (such as ="object"= or - ='https://github.com'=), or the name of another symbol or keyword - (such as =null= or =document=). - This allows you, for example, to assign meaningful names to key - constant values but discard the symbolic names in the uglified - version for brevity/efficiency, or when used wth care, allows - UglifyJS to operate as a form of *conditional compilation* - whereby defining appropriate values may, by dint of the constant - folding and dead code removal features above, remove entire - superfluous code blocks (e.g. completely remove instrumentation or - trace code for production use). - Where string values are being defined, the handling of quotes are - likely to be subject to the specifics of your command shell - environment, so you may need to experiment with quoting styles - depending on your platform, or you may find the option - =--define-from-module= more suitable for use. - -- =-define-from-module SOMEMODULE= --- will load the named module (as - per the NodeJS =require()= function) and iterate all the exported - properties of the module defining them as symbol names to be defined - (as if by the =--define= option) per the name of each property - (i.e. without the module name prefix) and given the value of the - property. This is a much easier way to handle and document groups of - symbols to be defined rather than a large number of =--define= - options. - -- =--unsafe= --- enable other additional optimizations that are known to be - unsafe in some contrived situations, but could still be generally useful. - For now only these: - - - foo.toString() ==> foo+"" - - new Array(x,...) ==> [x,...] - - new Array(x) ==> Array(x) - -- =--max-line-len= (default 32K characters) --- add a newline after around - 32K characters. I've seen both FF and Chrome croak when all the code was - on a single line of around 670K. Pass --max-line-len 0 to disable this - safety feature. - -- =--reserved-names= --- some libraries rely on certain names to be used, as - pointed out in issue #92 and #81, so this option allow you to exclude such - names from the mangler. For example, to keep names =require= and =$super= - intact you'd specify --reserved-names "require,$super". - -- =--inline-script= -- when you want to include the output literally in an - HTML =\n\n\n\n\n
        \n\n
        \n\n
        \n

        UglifyJS – a JavaScript parser/compressor/beautifier

        \n\n\n\n\n
        \n

        1 NEW: UglifyJS2

        \n
        \n\n\n

        \nI started working on UglifyJS's successor, version 2. It's almost a full\nrewrite (except for the parser which is heavily modified, everything else\nstarts from scratch). I've detailed my reasons in the README, see the\nproject page.\n

        \n

        \nhttps://github.com/mishoo/UglifyJS2\n

        \n

        \nVersion 1 will continue to be maintained for fixing show-stopper bugs, but\nno new features should be expected.\n

        \n

        \nPlease help me focus on version 2 by making a donation!\n

        \n
        \n\n
        \n\n
        \n

        2 UglifyJS — a JavaScript parser/compressor/beautifier

        \n
        \n\n\n

        \nThis package implements a general-purpose JavaScript\nparser/compressor/beautifier toolkit. It is developed on NodeJS, but it\nshould work on any JavaScript platform supporting the CommonJS module system\n(and if your platform of choice doesn't support CommonJS, you can easily\nimplement it, or discard the exports.* lines from UglifyJS sources).\n

        \n

        \nThe tokenizer/parser generates an abstract syntax tree from JS code. You\ncan then traverse the AST to learn more about the code, or do various\nmanipulations on it. This part is implemented in parse-js.js and it's a\nport to JavaScript of the excellent parse-js Common Lisp library from Marijn Haverbeke.\n

        \n

        \n( See cl-uglify-js if you're looking for the Common Lisp version of\nUglifyJS. )\n

        \n

        \nThe second part of this package, implemented in process.js, inspects and\nmanipulates the AST generated by the parser to provide the following:\n

        \n
          \n
        • ability to re-generate JavaScript code from the AST. Optionally\n indented—you can use this if you want to “beautify” a program that has\n been compressed, so that you can inspect the source. But you can also run\n our code generator to print out an AST without any whitespace, so you\n achieve compression as well.\n\n
        • \n
        • shorten variable names (usually to single characters). Our mangler will\n analyze the code and generate proper variable names, depending on scope\n and usage, and is smart enough to deal with globals defined elsewhere, or\n with eval() calls or with{} statements. In short, if eval() or\n with{} are used in some scope, then all variables in that scope and any\n variables in the parent scopes will remain unmangled, and any references\n to such variables remain unmangled as well.\n\n
        • \n
        • various small optimizations that may lead to faster code but certainly\n lead to smaller code. Where possible, we do the following:\n\n
            \n
          • foo[\"bar\"] ==> foo.bar\n\n
          • \n
          • remove block brackets {}\n\n
          • \n
          • join consecutive var declarations:\n var a = 10; var b = 20; ==> var a=10,b=20;\n\n
          • \n
          • resolve simple constant expressions: 1 +2 * 3 ==> 7. We only do the\n replacement if the result occupies less bytes; for example 1/3 would\n translate to 0.333333333333, so in this case we don't replace it.\n\n
          • \n
          • consecutive statements in blocks are merged into a sequence; in many\n cases, this leaves blocks with a single statement, so then we can remove\n the block brackets.\n\n
          • \n
          • various optimizations for IF statements:\n\n
              \n
            • if (foo) bar(); else baz(); ==> foo?bar():baz();\n
            • \n
            • if (!foo) bar(); else baz(); ==> foo?baz():bar();\n
            • \n
            • if (foo) bar(); ==> foo&&bar();\n
            • \n
            • if (!foo) bar(); ==> foo||bar();\n
            • \n
            • if (foo) return bar(); else return baz(); ==> return foo?bar():baz();\n
            • \n
            • if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}\n\n
            • \n
            \n\n
          • \n
          • remove some unreachable code and warn about it (code that follows a\n return, throw, break or continue statement, except\n function/variable declarations).\n\n
          • \n
          • act a limited version of a pre-processor (c.f. the pre-processor of\n C/C++) to allow you to safely replace selected global symbols with\n specified values. When combined with the optimisations above this can\n make UglifyJS operate slightly more like a compilation process, in\n that when certain symbols are replaced by constant values, entire code\n blocks may be optimised away as unreachable.\n
          • \n
          \n\n
        • \n
        \n\n\n\n
        \n\n
        \n

        2.1 Unsafe transformations

        \n
        \n\n\n

        \nThe following transformations can in theory break code, although they're\nprobably safe in most practical cases. To enable them you need to pass the\n--unsafe flag.\n

        \n\n
        \n\n
        \n

        2.1.1 Calls involving the global Array constructor

        \n
        \n\n\n

        \nThe following transformations occur:\n

        \n\n\n\n
        new Array(1, 2, 3, 4)  => [1,2,3,4]\nArray(a, b, c)         => [a,b,c]\nnew Array(5)           => Array(5)\nnew Array(a)           => Array(a)\n
        \n\n\n

        \nThese are all safe if the Array name isn't redefined. JavaScript does allow\none to globally redefine Array (and pretty much everything, in fact) but I\npersonally don't see why would anyone do that.\n

        \n

        \nUglifyJS does handle the case where Array is redefined locally, or even\nglobally but with a function or var declaration. Therefore, in the\nfollowing cases UglifyJS doesn't touch calls or instantiations of Array:\n

        \n\n\n\n
        // case 1.  globally declared variable\n  var Array;\n  new Array(1, 2, 3);\n  Array(a, b);\n\n  // or (can be declared later)\n  new Array(1, 2, 3);\n  var Array;\n\n  // or (can be a function)\n  new Array(1, 2, 3);\n  function Array() { ... }\n\n// case 2.  declared in a function\n  (function(){\n    a = new Array(1, 2, 3);\n    b = Array(5, 6);\n    var Array;\n  })();\n\n  // or\n  (function(Array){\n    return Array(5, 6, 7);\n  })();\n\n  // or\n  (function(){\n    return new Array(1, 2, 3, 4);\n    function Array() { ... }\n  })();\n\n  // etc.\n
        \n\n\n
        \n\n
        \n\n
        \n

        2.1.2 obj.toString() ==> obj+“”

        \n
        \n\n\n
        \n
        \n\n
        \n\n
        \n

        2.2 Install (NPM)

        \n
        \n\n\n

        \nUglifyJS is now available through NPM — npm install uglify-js should do\nthe job.\n

        \n
        \n\n
        \n\n
        \n

        2.3 Install latest code from GitHub

        \n
        \n\n\n\n\n\n
        ## clone the repository\nmkdir -p /where/you/wanna/put/it\ncd /where/you/wanna/put/it\ngit clone git://github.com/mishoo/UglifyJS.git\n\n## make the module available to Node\nmkdir -p ~/.node_libraries/\ncd ~/.node_libraries/\nln -s /where/you/wanna/put/it/UglifyJS/uglify-js.js\n\n## and if you want the CLI script too:\nmkdir -p ~/bin\ncd ~/bin\nln -s /where/you/wanna/put/it/UglifyJS/bin/uglifyjs\n  # (then add ~/bin to your $PATH if it's not there already)\n
        \n\n\n
        \n\n
        \n\n
        \n

        2.4 Usage

        \n
        \n\n\n

        \nThere is a command-line tool that exposes the functionality of this library\nfor your shell-scripting needs:\n

        \n\n\n\n
        uglifyjs [ options... ] [ filename ]\n
        \n\n\n

        \nfilename should be the last argument and should name the file from which\nto read the JavaScript code. If you don't specify it, it will read code\nfrom STDIN.\n

        \n

        \nSupported options:\n

        \n
          \n
        • -b or --beautify — output indented code; when passed, additional\n options control the beautifier:\n\n
            \n
          • -i N or --indent N — indentation level (number of spaces)\n\n
          • \n
          • -q or --quote-keys — quote keys in literal objects (by default,\n only keys that cannot be identifier names will be quotes).\n\n
          • \n
          \n\n
        • \n
        • -c or ----consolidate-primitive-values — consolidates null, Boolean,\n and String values. Known as aliasing in the Closure Compiler. Worsens the\n data compression ratio of gzip.\n\n
        • \n
        • --ascii — pass this argument to encode non-ASCII characters as\n \\uXXXX sequences. By default UglifyJS won't bother to do it and will\n output Unicode characters instead. (the output is always encoded in UTF8,\n but if you pass this option you'll only get ASCII).\n\n
        • \n
        • -nm or --no-mangle — don't mangle names.\n\n
        • \n
        • -nmf or --no-mangle-functions – in case you want to mangle variable\n names, but not touch function names.\n\n
        • \n
        • -ns or --no-squeeze — don't call ast_squeeze() (which does various\n optimizations that result in smaller, less readable code).\n\n
        • \n
        • -mt or --mangle-toplevel — mangle names in the toplevel scope too\n (by default we don't do this).\n\n
        • \n
        • --no-seqs — when ast_squeeze() is called (thus, unless you pass\n --no-squeeze) it will reduce consecutive statements in blocks into a\n sequence. For example, \"a = 10; b = 20; foo();\" will be written as\n \"a=10,b=20,foo();\". In various occasions, this allows us to discard the\n block brackets (since the block becomes a single statement). This is ON\n by default because it seems safe and saves a few hundred bytes on some\n libs that I tested it on, but pass --no-seqs to disable it.\n\n
        • \n
        • --no-dead-code — by default, UglifyJS will remove code that is\n obviously unreachable (code that follows a return, throw, break or\n continue statement and is not a function/variable declaration). Pass\n this option to disable this optimization.\n\n
        • \n
        • -nc or --no-copyright — by default, uglifyjs will keep the initial\n comment tokens in the generated code (assumed to be copyright information\n etc.). If you pass this it will discard it.\n\n
        • \n
        • -o filename or --output filename — put the result in filename. If\n this isn't given, the result goes to standard output (or see next one).\n\n
        • \n
        • --overwrite — if the code is read from a file (not from STDIN) and you\n pass --overwrite then the output will be written in the same file.\n\n
        • \n
        • --ast — pass this if you want to get the Abstract Syntax Tree instead\n of JavaScript as output. Useful for debugging or learning more about the\n internals.\n\n
        • \n
        • -v or --verbose — output some notes on STDERR (for now just how long\n each operation takes).\n\n
        • \n
        • -d SYMBOL[=VALUE] or --define SYMBOL[=VALUE] — will replace\n all instances of the specified symbol where used as an identifier\n (except where symbol has properly declared by a var declaration or\n use as function parameter or similar) with the specified value. This\n argument may be specified multiple times to define multiple\n symbols - if no value is specified the symbol will be replaced with\n the value true, or you can specify a numeric value (such as\n 1024), a quoted string value (such as =\"object\"= or\n ='https://github.com'), or the name of another symbol or keyword (such as =null or document).\n This allows you, for example, to assign meaningful names to key\n constant values but discard the symbolic names in the uglified\n version for brevity/efficiency, or when used wth care, allows\n UglifyJS to operate as a form of conditional compilation\n whereby defining appropriate values may, by dint of the constant\n folding and dead code removal features above, remove entire\n superfluous code blocks (e.g. completely remove instrumentation or\n trace code for production use).\n Where string values are being defined, the handling of quotes are\n likely to be subject to the specifics of your command shell\n environment, so you may need to experiment with quoting styles\n depending on your platform, or you may find the option\n --define-from-module more suitable for use.\n\n
        • \n
        • -define-from-module SOMEMODULE — will load the named module (as\n per the NodeJS require() function) and iterate all the exported\n properties of the module defining them as symbol names to be defined\n (as if by the --define option) per the name of each property\n (i.e. without the module name prefix) and given the value of the\n property. This is a much easier way to handle and document groups of\n symbols to be defined rather than a large number of --define\n options.\n\n
        • \n
        • --unsafe — enable other additional optimizations that are known to be\n unsafe in some contrived situations, but could still be generally useful.\n For now only these:\n\n
            \n
          • foo.toString() ==> foo+\"\"\n
          • \n
          • new Array(x,…) ==> [x,…]\n
          • \n
          • new Array(x) ==> Array(x)\n\n
          • \n
          \n\n
        • \n
        • --max-line-len (default 32K characters) — add a newline after around\n 32K characters. I've seen both FF and Chrome croak when all the code was\n on a single line of around 670K. Pass –max-line-len 0 to disable this\n safety feature.\n\n
        • \n
        • --reserved-names — some libraries rely on certain names to be used, as\n pointed out in issue #92 and #81, so this option allow you to exclude such\n names from the mangler. For example, to keep names require and $super\n intact you'd specify –reserved-names \"require,$super\".\n\n
        • \n
        • --inline-script – when you want to include the output literally in an\n HTML <script> tag you can use this option to prevent </script from\n showing up in the output.\n\n
        • \n
        • --lift-vars – when you pass this, UglifyJS will apply the following\n transformations (see the notes in API, ast_lift_variables):\n\n
            \n
          • put all var declarations at the start of the scope\n
          • \n
          • make sure a variable is declared only once\n
          • \n
          • discard unused function arguments\n
          • \n
          • discard unused inner (named) functions\n
          • \n
          • finally, try to merge assignments into that one var declaration, if\n possible.\n
          • \n
          \n\n
        • \n
        \n\n\n\n
        \n\n
        \n

        2.4.1 API

        \n
        \n\n\n

        \nTo use the library from JavaScript, you'd do the following (example for\nNodeJS):\n

        \n\n\n\n
        var jsp = require(\"uglify-js\").parser;\nvar pro = require(\"uglify-js\").uglify;\n\nvar orig_code = \"... JS code here\";\nvar ast = jsp.parse(orig_code); // parse code and get the initial AST\nast = pro.ast_mangle(ast); // get a new AST with mangled names\nast = pro.ast_squeeze(ast); // get an AST with compression optimizations\nvar final_code = pro.gen_code(ast); // compressed code here\n
        \n\n\n

        \nThe above performs the full compression that is possible right now. As you\ncan see, there are a sequence of steps which you can apply. For example if\nyou want compressed output but for some reason you don't want to mangle\nvariable names, you would simply skip the line that calls\npro.ast_mangle(ast).\n

        \n

        \nSome of these functions take optional arguments. Here's a description:\n

        \n
          \n
        • jsp.parse(code, strict_semicolons) – parses JS code and returns an AST.\n strict_semicolons is optional and defaults to false. If you pass\n true then the parser will throw an error when it expects a semicolon and\n it doesn't find it. For most JS code you don't want that, but it's useful\n if you want to strictly sanitize your code.\n\n
        • \n
        • pro.ast_lift_variables(ast) – merge and move var declarations to the\n scop of the scope; discard unused function arguments or variables; discard\n unused (named) inner functions. It also tries to merge assignments\n following the var declaration into it.\n\n

          \n If your code is very hand-optimized concerning var declarations, this\n lifting variable declarations might actually increase size. For me it\n helps out. On jQuery it adds 865 bytes (243 after gzip). YMMV. Also\n note that (since it's not enabled by default) this operation isn't yet\n heavily tested (please report if you find issues!).\n

          \n

          \n Note that although it might increase the image size (on jQuery it gains\n 865 bytes, 243 after gzip) it's technically more correct: in certain\n situations, dead code removal might drop variable declarations, which\n would not happen if the variables are lifted in advance.\n

          \n

          \n Here's an example of what it does:\n

        • \n
        \n\n\n\n\n\n
        function f(a, b, c, d, e) {\n    var q;\n    var w;\n    w = 10;\n    q = 20;\n    for (var i = 1; i < 10; ++i) {\n        var boo = foo(a);\n    }\n    for (var i = 0; i < 1; ++i) {\n        var boo = bar(c);\n    }\n    function foo(){ ... }\n    function bar(){ ... }\n    function baz(){ ... }\n}\n\n// transforms into ==>\n\nfunction f(a, b, c) {\n    var i, boo, w = 10, q = 20;\n    for (i = 1; i < 10; ++i) {\n        boo = foo(a);\n    }\n    for (i = 0; i < 1; ++i) {\n        boo = bar(c);\n    }\n    function foo() { ... }\n    function bar() { ... }\n}\n
        \n\n\n
          \n
        • pro.ast_mangle(ast, options) – generates a new AST containing mangled\n (compressed) variable and function names. It supports the following\n options:\n\n
            \n
          • toplevel – mangle toplevel names (by default we don't touch them).\n
          • \n
          • except – an array of names to exclude from compression.\n
          • \n
          • defines – an object with properties named after symbols to\n replace (see the --define option for the script) and the values\n representing the AST replacement value.\n\n
          • \n
          \n\n
        • \n
        • pro.ast_squeeze(ast, options) – employs further optimizations designed\n to reduce the size of the code that gen_code would generate from the\n AST. Returns a new AST. options can be a hash; the supported options\n are:\n\n
            \n
          • make_seqs (default true) which will cause consecutive statements in a\n block to be merged using the \"sequence\" (comma) operator\n\n
          • \n
          • dead_code (default true) which will remove unreachable code.\n\n
          • \n
          \n\n
        • \n
        • pro.gen_code(ast, options) – generates JS code from the AST. By\n default it's minified, but using the options argument you can get nicely\n formatted output. options is, well, optional :-) and if you pass it it\n must be an object and supports the following properties (below you can see\n the default values):\n\n
            \n
          • beautify: false – pass true if you want indented output\n
          • \n
          • indent_start: 0 (only applies when beautify is true) – initial\n indentation in spaces\n
          • \n
          • indent_level: 4 (only applies when beautify is true) --\n indentation level, in spaces (pass an even number)\n
          • \n
          • quote_keys: false – if you pass true it will quote all keys in\n literal objects\n
          • \n
          • space_colon: false (only applies when beautify is true) – wether\n to put a space before the colon in object literals\n
          • \n
          • ascii_only: false – pass true if you want to encode non-ASCII\n characters as \\uXXXX.\n
          • \n
          • inline_script: false – pass true to escape occurrences of\n </script in strings\n
          • \n
          \n\n
        • \n
        \n\n\n
        \n\n
        \n\n
        \n

        2.4.2 Beautifier shortcoming – no more comments

        \n
        \n\n\n

        \nThe beautifier can be used as a general purpose indentation tool. It's\nuseful when you want to make a minified file readable. One limitation,\nthough, is that it discards all comments, so you don't really want to use it\nto reformat your code, unless you don't have, or don't care about, comments.\n

        \n

        \nIn fact it's not the beautifier who discards comments — they are dumped at\nthe parsing stage, when we build the initial AST. Comments don't really\nmake sense in the AST, and while we could add nodes for them, it would be\ninconvenient because we'd have to add special rules to ignore them at all\nthe processing stages.\n

        \n
        \n\n
        \n\n
        \n

        2.4.3 Use as a code pre-processor

        \n
        \n\n\n

        \nThe --define option can be used, particularly when combined with the\nconstant folding logic, as a form of pre-processor to enable or remove\nparticular constructions, such as might be used for instrumenting\ndevelopment code, or to produce variations aimed at a specific\nplatform.\n

        \n

        \nThe code below illustrates the way this can be done, and how the\nsymbol replacement is performed.\n

        \n\n\n\n
        CLAUSE1: if (typeof DEVMODE === 'undefined') {\n    DEVMODE = true;\n}\n\nCLAUSE2: function init() {\n    if (DEVMODE) {\n        console.log(\"init() called\");\n    }\n    ....\n    DEVMODE &amp;&amp; console.log(\"init() complete\");\n}\n\nCLAUSE3: function reportDeviceStatus(device) {\n    var DEVMODE = device.mode, DEVNAME = device.name;\n    if (DEVMODE === 'open') {\n        ....\n    }\n}\n
        \n\n\n

        \nWhen the above code is normally executed, the undeclared global\nvariable DEVMODE will be assigned the value true (see CLAUSE1)\nand so the init() function (CLAUSE2) will write messages to the\nconsole log when executed, but in CLAUSE3 a locally declared\nvariable will mask access to the DEVMODE global symbol.\n

        \n

        \nIf the above code is processed by UglifyJS with an argument of\n--define DEVMODE=false then UglifyJS will replace DEVMODE with the\nboolean constant value false within CLAUSE1 and CLAUSE2, but it\nwill leave CLAUSE3 as it stands because there DEVMODE resolves to\na validly declared variable.\n

        \n

        \nAnd more so, the constant-folding features of UglifyJS will recognise\nthat the if condition of CLAUSE1 is thus always false, and so will\nremove the test and body of CLAUSE1 altogether (including the\notherwise slightly problematical statement false = true; which it\nwill have formed by replacing DEVMODE in the body). Similarly,\nwithin CLAUSE2 both calls to console.log() will be removed\naltogether.\n

        \n

        \nIn this way you can mimic, to a limited degree, the functionality of\nthe C/C++ pre-processor to enable or completely remove blocks\ndepending on how certain symbols are defined - perhaps using UglifyJS\nto generate different versions of source aimed at different\nenvironments\n

        \n

        \nIt is recommmended (but not made mandatory) that symbols designed for\nthis purpose are given names consisting of UPPER_CASE_LETTERS to\ndistinguish them from other (normal) symbols and avoid the sort of\nclash that CLAUSE3 above illustrates.\n

        \n
        \n
        \n\n
        \n\n
        \n

        2.5 Compression – how good is it?

        \n
        \n\n\n

        \nHere are updated statistics. (I also updated my Google Closure and YUI\ninstallations).\n

        \n

        \nWe're still a lot better than YUI in terms of compression, though slightly\nslower. We're still a lot faster than Closure, and compression after gzip\nis comparable.\n

        \n\n\n\n\n\n\n\n\n\n\n\n\n\n
        FileUglifyJSUglifyJS+gzipClosureClosure+gzipYUIYUI+gzip
        jquery-1.6.2.js91001 (0:01.59)3189690678 (0:07.40)31979101527 (0:01.82)34646
        paper.js142023 (0:01.65)43334134301 (0:07.42)42495173383 (0:01.58)48785
        prototype.js88544 (0:01.09)2668086955 (0:06.97)2632692130 (0:00.79)28624
        thelib-full.js (DynarchLIB)251939 (0:02.55)72535249911 (0:09.05)72696258869 (0:01.94)76584
        \n\n\n
        \n\n
        \n\n
        \n

        2.6 Bugs?

        \n
        \n\n\n

        \nUnfortunately, for the time being there is no automated test suite. But I\nran the compressor manually on non-trivial code, and then I tested that the\ngenerated code works as expected. A few hundred times.\n

        \n

        \nDynarchLIB was started in times when there was no good JS minifier.\nTherefore I was quite religious about trying to write short code manually,\nand as such DL contains a lot of syntactic hacks1 such as “foo == bar ? a\n= 10 : b = 20”, though the more readable version would clearly be to use\n“if/else”.\n

        \n

        \nSince the parser/compressor runs fine on DL and jQuery, I'm quite confident\nthat it's solid enough for production use. If you can identify any bugs,\nI'd love to hear about them (use the Google Group or email me directly).\n

        \n
        \n\n
        \n\n
        \n

        2.7 Links

        \n
        \n\n\n\n\n\n
        \n\n
        \n\n
        \n

        2.8 License

        \n
        \n\n\n

        \nUglifyJS is released under the BSD license:\n

        \n\n\n\n
        Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>\nBased on parse-js (http://marijn.haverbeke.nl/parse-js/).\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n    * Redistributions of source code must retain the above\n      copyright notice, this list of conditions and the following\n      disclaimer.\n\n    * Redistributions in binary form must reproduce the above\n      copyright notice, this list of conditions and the following\n      disclaimer in the documentation and/or other materials\n      provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY\nEXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,\nOR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\nPROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\nTORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF\nTHE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGE.\n
        \n\n\n
        \n

        Footnotes:

        \n
        \n

        1 I even reported a few bugs and suggested some fixes in the original\n parse-js library, and Marijn pushed fixes literally in minutes.\n

        \n
        \n
        \n\n
        \n
        \n
        \n\n
        \n

        Date: 2012-08-27 12:38:12 EEST

        \n

        Author: Mihai Bazon

        \n

        Org version 7.7 with Emacs version 23

        \nValidate XHTML 1.0\n\n
        \n\n\n", - "readmeFilename": "README.html", - "bugs": { - "url": "https://github.com/mishoo/UglifyJS/issues" - }, - "_id": "uglify-js@1.3.4", - "_from": "uglify-js@~1.3.3" -} diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/beautify.js b/node/node_modules/grunt/node_modules/uglify-js/test/beautify.js deleted file mode 100755 index f19369e3a..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/beautify.js +++ /dev/null @@ -1,28 +0,0 @@ -#! /usr/bin/env node - -global.sys = require("sys"); -var fs = require("fs"); - -var jsp = require("../lib/parse-js"); -var pro = require("../lib/process"); - -var filename = process.argv[2]; -fs.readFile(filename, "utf8", function(err, text){ - try { - var ast = time_it("parse", function(){ return jsp.parse(text); }); - ast = time_it("mangle", function(){ return pro.ast_mangle(ast); }); - ast = time_it("squeeze", function(){ return pro.ast_squeeze(ast); }); - var gen = time_it("generate", function(){ return pro.gen_code(ast, false); }); - sys.puts(gen); - } catch(ex) { - sys.debug(ex.stack); - sys.debug(sys.inspect(ex)); - sys.debug(JSON.stringify(ex)); - } -}); - -function time_it(name, cont) { - var t1 = new Date().getTime(); - try { return cont(); } - finally { sys.debug("// " + name + ": " + ((new Date().getTime() - t1) / 1000).toFixed(3) + " sec."); } -}; diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/testconsolidator.js b/node/node_modules/grunt/node_modules/uglify-js/test/testconsolidator.js deleted file mode 100755 index 08030129b..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/testconsolidator.js +++ /dev/null @@ -1,1391 +0,0 @@ -#! /usr/bin/env node -global.DIGITS_OVERRIDE_FOR_TESTING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789"; - -'use strict'; -/*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true, - latedef:true, newcap:true, noarge:true, noempty:true, nonew:true, - onevar:true, plusplus:true, regexp:true, undef:true, strict:true, - sub:false, trailing:true */ - -var _, - /** - * NodeJS module for unit testing. - * @namespace - * @type {!TAssert} - * @see http://nodejs.org/docs/v0.6.10/api/all.html#assert - */ - oAssert = (/** @type {!TAssert} */ require('assert')), - /** - * Consolidates null, Boolean, and String values found inside an - * AST. The object under test. - * @namespace - * @type {!TConsolidator} - */ - oConsolidator = (/** @type {!TConsolidator} */ require('../lib/consolidator')), - /** - * The parser of ECMA-262 found in UglifyJS. - * @namespace - * @type {!TParser} - */ - oParser = (/** @type {!TParser} */ require('../lib/parse-js')), - /** - * The processor of ASTs - * found in UglifyJS. - * @namespace - * @type {!TProcessor} - */ - oProcessor = (/** @type {!TProcessor} */ require('../lib/process')), - /** - * An instance of an object that allows the traversal of an AST. - * @type {!TWalker} - */ - oWalker, - /** - * A collection of functions for the removal of the scope information - * during the traversal of an AST. - * @namespace - * @type {!Object.} - */ - oWalkersPurifiers = { - /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys. - /** - * Deletes the scope information from the branch of the abstract - * syntax tree representing the encountered function declaration. - * @param {string} sIdentifier The identifier of the function. - * @param {!Array.} aFormalParameterList Formal parameters. - * @param {!TSyntacticCodeUnit} oFunctionBody Function code. - */ - 'defun': function( - sIdentifier, - aFormalParameterList, - oFunctionBody) { - delete oFunctionBody.scope; - }, - /** - * Deletes the scope information from the branch of the abstract - * syntax tree representing the encountered function expression. - * @param {?string} sIdentifier The optional identifier of the - * function. - * @param {!Array.} aFormalParameterList Formal parameters. - * @param {!TSyntacticCodeUnit} oFunctionBody Function code. - */ - 'function': function( - sIdentifier, - aFormalParameterList, - oFunctionBody) { - delete oFunctionBody.scope; - } - /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys. - }, - /** - * Initiates the traversal of a source element. - * @param {!TWalker} oWalker An instance of an object that allows the - * traversal of an abstract syntax tree. - * @param {!TSyntacticCodeUnit} oSourceElement A source element from - * which the traversal should commence. - * @return {function(): !TSyntacticCodeUnit} A function that is able to - * initiate the traversal from a given source element. - */ - cContext = function(oWalker, oSourceElement) { - /** - * @return {!TSyntacticCodeUnit} A function that is able to - * initiate the traversal from a given source element. - */ - var fLambda = function() { - return oWalker.walk(oSourceElement); - }; - - return fLambda; - }, - /** - * A record consisting of configuration for the code generation phase. - * @type {!Object} - */ - oCodeGenerationOptions = { - beautify: true - }, - /** - * A boolean to track whether all tests have passed. - * @type {boolean} - */ - bTestsPassed = true, - /** - * Tests whether consolidation of an ECMAScript program yields expected - * results. - * @param {{ - * sTitle: string, - * sInput: string, - * sOutput: string - * }} oUnitTest A record consisting of data about a unit test: its - * name, an ECMAScript program, and, if consolidation is to take - * place, the resulting ECMAScript program. - */ - cAssert = function(oUnitTest) { - var _, - /** - * An array-like object representing the AST obtained after consolidation. - * @type {!TSyntacticCodeUnit} - */ - oSyntacticCodeUnitActual = - oConsolidator.ast_consolidate(oParser.parse(oUnitTest.sInput)), - /** - * An array-like object representing the expected AST. - * @type {!TSyntacticCodeUnit} - */ - oSyntacticCodeUnitExpected = oParser.parse( - oUnitTest.hasOwnProperty('sOutput') ? - oUnitTest.sOutput : oUnitTest.sInput); - - delete oSyntacticCodeUnitActual.scope; - oWalker = oProcessor.ast_walker(); - oWalker.with_walkers( - oWalkersPurifiers, - cContext(oWalker, oSyntacticCodeUnitActual)); - try { - oAssert.deepEqual( - oSyntacticCodeUnitActual, - oSyntacticCodeUnitExpected); - } catch (oException) { - console.error( - '########## A unit test has failed.\n' + - oUnitTest.sTitle + '\n' + - '##### actual code (' + - oProcessor.gen_code(oSyntacticCodeUnitActual).length + - ' bytes)\n' + - oProcessor.gen_code( - oSyntacticCodeUnitActual, - oCodeGenerationOptions) + '\n' + - '##### expected code (' + - oProcessor.gen_code(oSyntacticCodeUnitExpected).length + - ' bytes)\n' + - oProcessor.gen_code( - oSyntacticCodeUnitExpected, - oCodeGenerationOptions)); - bTestsPassed = false; - } - }; - -[ - // 7.6.1 Reserved Words. - { - sTitle: - 'Omission of keywords while choosing an identifier name.', - sInput: - '(function() {' + - ' var a, b, c, d, e, f, g, h, i, j, k, l, m,' + - ' n, o, p, q, r, s, t, u, v, w, x, y, z,' + - ' A, B, C, D, E, F, G, H, I, J, K, L, M,' + - ' N, O, P, Q, R, S, T, U, V, W, X, Y, Z,' + - ' $, _,' + - ' aa, ab, ac, ad, ae, af, ag, ah, ai, aj, ak, al, am,' + - ' an, ao, ap, aq, ar, as, at, au, av, aw, ax, ay, az,' + - ' aA, aB, aC, aD, aE, aF, aG, aH, aI, aJ, aK, aL, aM,' + - ' aN, aO, aP, aQ, aR, aS, aT, aU, aV, aW, aX, aY, aZ,' + - ' a$, a_,' + - ' ba, bb, bc, bd, be, bf, bg, bh, bi, bj, bk, bl, bm,' + - ' bn, bo, bp, bq, br, bs, bt, bu, bv, bw, bx, by, bz,' + - ' bA, bB, bC, bD, bE, bF, bG, bH, bI, bJ, bK, bL, bM,' + - ' bN, bO, bP, bQ, bR, bS, bT, bU, bV, bW, bX, bY, bZ,' + - ' b$, b_,' + - ' ca, cb, cc, cd, ce, cf, cg, ch, ci, cj, ck, cl, cm,' + - ' cn, co, cp, cq, cr, cs, ct, cu, cv, cw, cx, cy, cz,' + - ' cA, cB, cC, cD, cE, cF, cG, cH, cI, cJ, cK, cL, cM,' + - ' cN, cO, cP, cQ, cR, cS, cT, cU, cV, cW, cX, cY, cZ,' + - ' c$, c_,' + - ' da, db, dc, dd, de, df, dg, dh, di, dj, dk, dl, dm,' + - ' dn, dq, dr, ds, dt, du, dv, dw, dx, dy, dz,' + - ' dA, dB, dC, dD, dE, dF, dG, dH, dI, dJ, dK, dL, dM,' + - ' dN, dO, dP, dQ, dR, dS, dT, dU, dV, dW, dX, dY, dZ,' + - ' d$, d_;' + - ' void ["abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",' + - ' "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"];' + - '}());', - sOutput: - '(function() {' + - ' var eb =' + - ' "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",' + - ' a, b, c, d, e, f, g, h, i, j, k, l, m,' + - ' n, o, p, q, r, s, t, u, v, w, x, y, z,' + - ' A, B, C, D, E, F, G, H, I, J, K, L, M,' + - ' N, O, P, Q, R, S, T, U, V, W, X, Y, Z,' + - ' $, _,' + - ' aa, ab, ac, ad, ae, af, ag, ah, ai, aj, ak, al, am,' + - ' an, ao, ap, aq, ar, as, at, au, av, aw, ax, ay, az,' + - ' aA, aB, aC, aD, aE, aF, aG, aH, aI, aJ, aK, aL, aM,' + - ' aN, aO, aP, aQ, aR, aS, aT, aU, aV, aW, aX, aY, aZ,' + - ' a$, a_,' + - ' ba, bb, bc, bd, be, bf, bg, bh, bi, bj, bk, bl, bm,' + - ' bn, bo, bp, bq, br, bs, bt, bu, bv, bw, bx, by, bz,' + - ' bA, bB, bC, bD, bE, bF, bG, bH, bI, bJ, bK, bL, bM,' + - ' bN, bO, bP, bQ, bR, bS, bT, bU, bV, bW, bX, bY, bZ,' + - ' b$, b_,' + - ' ca, cb, cc, cd, ce, cf, cg, ch, ci, cj, ck, cl, cm,' + - ' cn, co, cp, cq, cr, cs, ct, cu, cv, cw, cx, cy, cz,' + - ' cA, cB, cC, cD, cE, cF, cG, cH, cI, cJ, cK, cL, cM,' + - ' cN, cO, cP, cQ, cR, cS, cT, cU, cV, cW, cX, cY, cZ,' + - ' c$, c_,' + - ' da, db, dc, dd, de, df, dg, dh, di, dj, dk, dl, dm,' + - ' dn, dq, dr, ds, dt, du, dv, dw, dx, dy, dz,' + - ' dA, dB, dC, dD, dE, dF, dG, dH, dI, dJ, dK, dL, dM,' + - ' dN, dO, dP, dQ, dR, dS, dT, dU, dV, dW, dX, dY, dZ,' + - ' d$, d_;' + - ' void [eb, eb];' + - '}());' - }, - // 7.8.1 Null Literals. - { - sTitle: - 'Evaluation with regard to the null value.', - sInput: - '/*jshint evil:true */' + - '(function() {' + - ' var foo;' + - ' void [null, null, null];' + - '}());' + - 'eval("");' + - '(function() {' + - ' var foo;' + - ' void [null, null];' + - '}());', - sOutput: - '/*jshint evil:true */' + - '(function() {' + - ' var a = null, foo;' + - ' void [a, a, a];' + - '}());' + - 'eval("");' + - '(function() {' + - ' var foo;' + - ' void [null, null];' + - '}());' - }, - // 7.8.2 Boolean Literals. - { - sTitle: - 'Evaluation with regard to the false value.', - sInput: - '/*jshint evil:true */' + - '(function() {' + - ' var foo;' + - ' void [false, false, false];' + - '}());' + - 'eval("");' + - '(function() {' + - ' var foo;' + - ' void [false, false];' + - '}());', - sOutput: - '/*jshint evil:true */' + - '(function() {' + - ' var a = false, foo;' + - ' void [a, a, a];' + - '}());' + - 'eval("");' + - '(function() {' + - ' var foo;' + - ' void [false, false];' + - '}());' - }, - { - sTitle: - 'Evaluation with regard to the true value.', - sInput: - '/*jshint evil:true */' + - '(function() {' + - ' var foo;' + - ' void [true, true, true];' + - '}());' + - 'eval("");' + - '(function() {' + - ' var foo;' + - ' void [true, true];' + - '}());', - sOutput: - '/*jshint evil:true */' + - '(function() {' + - ' var a = true, foo;' + - ' void [a, a, a];' + - '}());' + - 'eval("");' + - '(function() {' + - ' var foo;' + - ' void [true, true];' + - '}());' - }, - // 7.8.4 String Literals. - { - sTitle: - 'Evaluation with regard to the String value of a string literal.', - sInput: - '(function() {' + - ' var foo;' + - ' void ["abcd", "abcd", "abc", "abc"];' + - '}());', - sOutput: - '(function() {' + - ' var a = "abcd", foo;' + - ' void [a, a, "abc", "abc"];' + - '}());' - }, - // 7.8.5 Regular Expression Literals. - { - sTitle: - 'Preservation of the pattern of a regular expression literal.', - sInput: - 'void [/abcdefghijklmnopqrstuvwxyz/, /abcdefghijklmnopqrstuvwxyz/];' - }, - { - sTitle: - 'Preservation of the flags of a regular expression literal.', - sInput: - 'void [/(?:)/gim, /(?:)/gim, /(?:)/gim, /(?:)/gim, /(?:)/gim,' + - ' /(?:)/gim, /(?:)/gim, /(?:)/gim, /(?:)/gim, /(?:)/gim,' + - ' /(?:)/gim, /(?:)/gim, /(?:)/gim, /(?:)/gim, /(?:)/gim];' - }, - // 10.2 Lexical Environments. - { - sTitle: - 'Preservation of identifier names in the same scope.', - sInput: - '/*jshint shadow:true */' + - 'var a;' + - 'function b(i) {' + - '}' + - 'for (var c; 0 === Math.random(););' + - 'for (var d in {});' + - 'void ["abcdefghijklmnopqrstuvwxyz"];' + - 'void [b(a), b(c), b(d)];' + - 'void [typeof e];' + - 'i: for (; 0 === Math.random();) {' + - ' if (42 === (new Date()).getMinutes()) {' + - ' continue i;' + - ' } else {' + - ' break i;' + - ' }' + - '}' + - 'try {' + - '} catch (f) {' + - '} finally {' + - '}' + - '(function g(h) {' + - '}());' + - 'void [{' + - ' i: 42,' + - ' "j": 42,' + - ' \'k\': 42' + - '}];' + - 'void ["abcdefghijklmnopqrstuvwxyz"];', - sOutput: - '/*jshint shadow:true */' + - 'var a;' + - 'function b(i) {' + - '}' + - 'for (var c; 0 === Math.random(););' + - 'for (var d in {});' + - '(function() {' + - ' var i = "abcdefghijklmnopqrstuvwxyz";' + - ' void [i];' + - ' void [b(a), b(c), b(d)];' + - ' void [typeof e];' + - ' i: for (; 0 === Math.random();) {' + - ' if (42 === (new Date()).getMinutes()) {' + - ' continue i;' + - ' } else {' + - ' break i;' + - ' }' + - ' }' + - ' try {' + - ' } catch (f) {' + - ' } finally {' + - ' }' + - ' (function g(h) {' + - ' }());' + - ' void [{' + - ' i: 42,' + - ' "j": 42,' + - ' \'k\': 42' + - ' }];' + - ' void [i];' + - '}());' - }, - { - sTitle: - 'Preservation of identifier names in nested function code.', - sInput: - '(function() {' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - ' (function() {' + - ' var a;' + - ' for (var b; 0 === Math.random(););' + - ' for (var c in {});' + - ' void [typeof d];' + - ' h: for (; 0 === Math.random();) {' + - ' if (42 === (new Date()).getMinutes()) {' + - ' continue h;' + - ' } else {' + - ' break h;' + - ' }' + - ' }' + - ' try {' + - ' } catch (e) {' + - ' } finally {' + - ' }' + - ' (function f(g) {' + - ' }());' + - ' void [{' + - ' h: 42,' + - ' "i": 42,' + - ' \'j\': 42' + - ' }];' + - ' }());' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - '}());', - sOutput: - '(function() {' + - ' var h = "abcdefghijklmnopqrstuvwxyz";' + - ' void [h];' + - ' (function() {' + - ' var a;' + - ' for (var b; 0 === Math.random(););' + - ' for (var c in {});' + - ' void [typeof d];' + - ' h: for (; 0 === Math.random();) {' + - ' if (42 === (new Date()).getMinutes()) {' + - ' continue h;' + - ' } else {' + - ' break h;' + - ' }' + - ' }' + - ' try {' + - ' } catch (e) {' + - ' } finally {' + - ' }' + - ' (function f(g) {' + - ' }());' + - ' void [{' + - ' h: 42,' + - ' "i": 42,' + - ' \'j\': 42' + - ' }];' + - ' }());' + - ' void [h];' + - '}());' - }, - { - sTitle: - 'Consolidation of a closure with other source elements.', - sInput: - '(function(foo) {' + - '}("abcdefghijklmnopqrstuvwxyz"));' + - 'void ["abcdefghijklmnopqrstuvwxyz"];', - sOutput: - '(function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' (function(foo) {' + - ' })(a);' + - ' void [a];' + - '}());' - }, - { - sTitle: - 'Consolidation of function code instead of a sole closure.', - sInput: - '(function(foo, bar) {' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - '}("abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz"));', - sOutput: - '(function(foo, bar) {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - '}("abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz"));' - }, - // 11.1.5 Object Initialiser. - { - sTitle: - 'Preservation of property names of an object initialiser.', - sInput: - 'var foo = {' + - ' abcdefghijklmnopqrstuvwxyz: 42,' + - ' "zyxwvutsrqponmlkjihgfedcba": 42,' + - ' \'mlkjihgfedcbanopqrstuvwxyz\': 42' + - '};' + - 'void [' + - ' foo.abcdefghijklmnopqrstuvwxyz,' + - ' "zyxwvutsrqponmlkjihgfedcba",' + - ' \'mlkjihgfedcbanopqrstuvwxyz\'' + - '];' - }, - { - sTitle: - 'Evaluation with regard to String values derived from identifier ' + - 'names used as property accessors.', - sInput: - '(function() {' + - ' var foo;' + - ' void [' + - ' Math.abcdefghij,' + - ' Math.abcdefghij,' + - ' Math.abcdefghi,' + - ' Math.abcdefghi' + - ' ];' + - '}());', - sOutput: - '(function() {' + - ' var a = "abcdefghij", foo;' + - ' void [' + - ' Math[a],' + - ' Math[a],' + - ' Math.abcdefghi,' + - ' Math.abcdefghi' + - ' ];' + - '}());' - }, - // 11.2.1 Property Accessors. - { - sTitle: - 'Preservation of identifiers in the nonterminal MemberExpression.', - sInput: - 'void [' + - ' Math.E,' + - ' Math.LN10,' + - ' Math.LN2,' + - ' Math.LOG2E,' + - ' Math.LOG10E,' + - ' Math.PI,' + - ' Math.SQRT1_2,' + - ' Math.SQRT2,' + - ' Math.abs,' + - ' Math.acos' + - '];' - }, - // 12.2 Variable Statement. - { - sTitle: - 'Preservation of the identifier of a variable that is being ' + - 'declared in a variable statement.', - sInput: - '(function() {' + - ' var abcdefghijklmnopqrstuvwxyz;' + - ' void [abcdefghijklmnopqrstuvwxyz];' + - '}());' - }, - { - sTitle: - 'Exclusion of a variable statement in global code.', - sInput: - 'void ["abcdefghijklmnopqrstuvwxyz"];' + - 'var foo = "abcdefghijklmnopqrstuvwxyz",' + - ' bar = "abcdefghijklmnopqrstuvwxyz";' + - 'void ["abcdefghijklmnopqrstuvwxyz"];' - }, - { - sTitle: - 'Exclusion of a variable statement in function code that ' + - 'contains a with statement.', - sInput: - '(function() {' + - ' with ({});' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - ' var foo;' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - '}());' - }, - { - sTitle: - 'Exclusion of a variable statement in function code that ' + - 'contains a direct call to the eval function.', - sInput: - '/*jshint evil:true */' + - 'void [' + - ' function() {' + - ' eval("");' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - ' var foo;' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - ' }' + - '];' - }, - { - sTitle: - 'Consolidation within a variable statement in global code.', - sInput: - 'var foo = function() {' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - '};', - sOutput: - 'var foo = function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - '};' - }, - { - sTitle: - 'Consolidation within a variable statement excluded in function ' + - 'code due to the presence of a with statement.', - sInput: - '(function() {' + - ' with ({});' + - ' var foo = function() {' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - ' };' + - '}());', - sOutput: - '(function() {' + - ' with ({});' + - ' var foo = function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - ' };' + - '}());' - }, - { - sTitle: - 'Consolidation within a variable statement excluded in function ' + - 'code due to the presence of a direct call to the eval function.', - sInput: - '/*jshint evil:true */' + - '(function() {' + - ' eval("");' + - ' var foo = function() {' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - ' };' + - '}());', - sOutput: - '/*jshint evil:true */' + - '(function() {' + - ' eval("");' + - ' var foo = function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - ' };' + - '}());' - }, - { - sTitle: - 'Inclusion of a variable statement in function code that ' + - 'contains no with statement and no direct call to the eval ' + - 'function.', - sInput: - '(function() {' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - ' var foo;' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - '}());', - sOutput: - '(function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a];' + - ' var foo;' + - ' void [a];' + - '}());' - }, - { - sTitle: - 'Ignorance with regard to a variable statement in global code.', - sInput: - 'var foo = "abcdefghijklmnopqrstuvwxyz";' + - 'void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];', - sOutput: - 'var foo = "abcdefghijklmnopqrstuvwxyz";' + - '(function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - '}());' - }, - // 12.4 Expression Statement. - { - sTitle: - 'Preservation of identifiers in an expression statement.', - sInput: - 'void [typeof abcdefghijklmnopqrstuvwxyz,' + - ' typeof abcdefghijklmnopqrstuvwxyz];' - }, - // 12.6.3 The {@code for} Statement. - { - sTitle: - 'Preservation of identifiers in the variable declaration list of ' + - 'a for statement.', - sInput: - 'for (var abcdefghijklmnopqrstuvwxyz; 0 === Math.random(););' + - 'for (var abcdefghijklmnopqrstuvwxyz; 0 === Math.random(););' - }, - // 12.6.4 The {@code for-in} Statement. - { - sTitle: - 'Preservation of identifiers in the variable declaration list of ' + - 'a for-in statement.', - sInput: - 'for (var abcdefghijklmnopqrstuvwxyz in {});' + - 'for (var abcdefghijklmnopqrstuvwxyz in {});' - }, - // 12.7 The {@code continue} Statement. - { - sTitle: - 'Preservation of the identifier in a continue statement.', - sInput: - 'abcdefghijklmnopqrstuvwxyz: for (; 0 === Math.random();) {' + - ' continue abcdefghijklmnopqrstuvwxyz;' + - '}' + - 'abcdefghijklmnopqrstuvwxyz: for (; 0 === Math.random();) {' + - ' continue abcdefghijklmnopqrstuvwxyz;' + - '}' - }, - // 12.8 The {@code break} Statement. - { - sTitle: - 'Preservation of the identifier in a break statement.', - sInput: - 'abcdefghijklmnopqrstuvwxyz: for (; 0 === Math.random();) {' + - ' break abcdefghijklmnopqrstuvwxyz;' + - '}' + - 'abcdefghijklmnopqrstuvwxyz: for (; 0 === Math.random();) {' + - ' break abcdefghijklmnopqrstuvwxyz;' + - '}' - }, - // 12.9 The {@code return} Statement. - { - sTitle: - 'Exclusion of a return statement in function code that contains ' + - 'a with statement.', - sInput: - '(function() {' + - ' with ({});' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - ' if (0 === Math.random()) {' + - ' return;' + - ' } else {' + - ' }' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - '}());' - }, - { - sTitle: - 'Exclusion of a return statement in function code that contains ' + - 'a direct call to the eval function.', - sInput: - '/*jshint evil:true */' + - '(function() {' + - ' eval("");' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - ' if (0 === Math.random()) {' + - ' return;' + - ' } else {' + - ' }' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - '}());' - }, - { - sTitle: - 'Consolidation within a return statement excluded in function ' + - 'code due to the presence of a with statement.', - sInput: - '(function() {' + - ' with ({});' + - ' return function() {' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - ' };' + - '}());', - sOutput: - '(function() {' + - ' with ({});' + - ' return function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - ' };' + - '}());' - }, - { - sTitle: - 'Consolidation within a return statement excluded in function ' + - 'code due to the presence of a direct call to the eval function.', - sInput: - '/*jshint evil:true */' + - '(function() {' + - ' eval("");' + - ' return function() {' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - ' };' + - '}());', - sOutput: - '/*jshint evil:true */' + - '(function() {' + - ' eval("");' + - ' return function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - ' };' + - '}());' - }, - { - sTitle: - 'Inclusion of a return statement in function code that contains ' + - 'no with statement and no direct call to the eval function.', - sInput: - '(function() {' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - ' if (0 === Math.random()) {' + - ' return;' + - ' } else {' + - ' }' + - ' void ["abcdefghijklmnopqrstuvwxyz"];' + - '}());', - sOutput: - '(function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a];' + - ' if (0 === Math.random()) {' + - ' return;' + - ' } else {' + - ' }' + - ' void [a];' + - '}());' - }, - // 12.10 The {@code with} Statement. - { - sTitle: - 'Preservation of the statement in a with statement.', - sInput: - 'with ({}) {' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - '}' - }, - { - sTitle: - 'Exclusion of a with statement in the same syntactic code unit.', - sInput: - 'void ["abcdefghijklmnopqrstuvwxyz"];' + - 'with ({' + - ' foo: "abcdefghijklmnopqrstuvwxyz",' + - ' bar: "abcdefghijklmnopqrstuvwxyz"' + - '}) {' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - '}' + - 'void ["abcdefghijklmnopqrstuvwxyz"];' - }, - { - sTitle: - 'Exclusion of a with statement in nested function code.', - sInput: - 'void ["abcdefghijklmnopqrstuvwxyz"];' + - '(function() {' + - ' with ({' + - ' foo: "abcdefghijklmnopqrstuvwxyz",' + - ' bar: "abcdefghijklmnopqrstuvwxyz"' + - ' }) {' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - ' }' + - '}());' + - 'void ["abcdefghijklmnopqrstuvwxyz"];' - }, - // 12.12 Labelled Statements. - { - sTitle: - 'Preservation of the label of a labelled statement.', - sInput: - 'abcdefghijklmnopqrstuvwxyz: for (; 0 === Math.random(););' + - 'abcdefghijklmnopqrstuvwxyz: for (; 0 === Math.random(););' - }, - // 12.14 The {@code try} Statement. - { - sTitle: - 'Preservation of the identifier in the catch clause of a try' + - 'statement.', - sInput: - 'try {' + - '} catch (abcdefghijklmnopqrstuvwxyz) {' + - '} finally {' + - '}' + - 'try {' + - '} catch (abcdefghijklmnopqrstuvwxyz) {' + - '} finally {' + - '}' - }, - // 13 Function Definition. - { - sTitle: - 'Preservation of the identifier of a function declaration.', - sInput: - 'function abcdefghijklmnopqrstuvwxyz() {' + - '}' + - 'void [abcdefghijklmnopqrstuvwxyz];' - }, - { - sTitle: - 'Preservation of the identifier of a function expression.', - sInput: - 'void [' + - ' function abcdefghijklmnopqrstuvwxyz() {' + - ' },' + - ' function abcdefghijklmnopqrstuvwxyz() {' + - ' }' + - '];' - }, - { - sTitle: - 'Preservation of a formal parameter of a function declaration.', - sInput: - 'function foo(abcdefghijklmnopqrstuvwxyz) {' + - '}' + - 'function bar(abcdefghijklmnopqrstuvwxyz) {' + - '}' - }, - { - sTitle: - 'Preservation of a formal parameter in a function expression.', - sInput: - 'void [' + - ' function(abcdefghijklmnopqrstuvwxyz) {' + - ' },' + - ' function(abcdefghijklmnopqrstuvwxyz) {' + - ' }' + - '];' - }, - { - sTitle: - 'Exclusion of a function declaration.', - sInput: - 'void ["abcdefghijklmnopqrstuvwxyz"];' + - 'function foo() {' + - '}' + - 'void ["abcdefghijklmnopqrstuvwxyz"];' - }, - { - sTitle: - 'Consolidation within a function declaration.', - sInput: - 'function foo() {' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - '}', - sOutput: - 'function foo() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - '}' - }, - // 14 Program. - { - sTitle: - 'Preservation of a program without source elements.', - sInput: - '' - }, - // 14.1 Directive Prologues and the Use Strict Directive. - { - sTitle: - 'Preservation of a Directive Prologue in global code.', - sInput: - '"abcdefghijklmnopqrstuvwxyz";' + - '\'zyxwvutsrqponmlkjihgfedcba\';' - }, - { - sTitle: - 'Preservation of a Directive Prologue in a function declaration.', - sInput: - 'function foo() {' + - ' "abcdefghijklmnopqrstuvwxyz";' + - ' \'zyxwvutsrqponmlkjihgfedcba\';' + - '}' - }, - { - sTitle: - 'Preservation of a Directive Prologue in a function expression.', - sInput: - 'void [' + - ' function() {' + - ' "abcdefghijklmnopqrstuvwxyz";' + - ' \'zyxwvutsrqponmlkjihgfedcba\';' + - ' }' + - '];' - }, - { - sTitle: - 'Ignorance with regard to a Directive Prologue in global code.', - sInput: - '"abcdefghijklmnopqrstuvwxyz";' + - 'void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];', - sOutput: - '"abcdefghijklmnopqrstuvwxyz";' + - '(function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - '}());' - }, - { - sTitle: - 'Ignorance with regard to a Directive Prologue in a function' + - 'declaration.', - sInput: - 'function foo() {' + - ' "abcdefghijklmnopqrstuvwxyz";' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - '}', - sOutput: - 'function foo() {' + - ' "abcdefghijklmnopqrstuvwxyz";' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - '}' - }, - { - sTitle: - 'Ignorance with regard to a Directive Prologue in a function' + - 'expression.', - sInput: - '(function() {' + - ' "abcdefghijklmnopqrstuvwxyz";' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - '}());', - sOutput: - '(function() {' + - ' "abcdefghijklmnopqrstuvwxyz";' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - '}());' - }, - // 15.1 The Global Object. - { - sTitle: - 'Preservation of a property of the global object.', - sInput: - 'void [undefined, undefined, undefined, undefined, undefined];' - }, - // 15.1.2.1.1 Direct Call to Eval. - { - sTitle: - 'Exclusion of a direct call to the eval function in the same ' + - 'syntactic code unit.', - sInput: - '/*jshint evil:true */' + - 'void ["abcdefghijklmnopqrstuvwxyz"];' + - 'eval("");' + - 'void ["abcdefghijklmnopqrstuvwxyz"];' - }, - { - sTitle: - 'Exclusion of a direct call to the eval function in nested ' + - 'function code.', - sInput: - '/*jshint evil:true */' + - 'void ["abcdefghijklmnopqrstuvwxyz"];' + - '(function() {' + - ' eval("");' + - '}());' + - 'void ["abcdefghijklmnopqrstuvwxyz"];' - }, - { - sTitle: - 'Consolidation within a direct call to the eval function.', - sInput: - '/*jshint evil:true */' + - 'eval(function() {' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - '}());', - sOutput: - '/*jshint evil:true */' + - 'eval(function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - '}());' - }, - // Consolidation proper. - { - sTitle: - 'No consolidation if it does not result in a reduction of the ' + - 'number of source characters.', - sInput: - '(function() {' + - ' var foo;' + - ' void ["ab", "ab", "abc", "abc"];' + - '}());' - }, - { - sTitle: - 'Identification of a range of source elements at the beginning ' + - 'of global code.', - sInput: - '/*jshint evil:true */' + - '"abcdefghijklmnopqrstuvwxyz";' + - 'void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - 'eval("");', - sOutput: - '/*jshint evil:true */' + - '"abcdefghijklmnopqrstuvwxyz";' + - '(function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - '}());' + - 'eval("");' - }, - { - sTitle: - 'Identification of a range of source elements in the middle of ' + - 'global code.', - sInput: - '/*jshint evil:true */' + - '"abcdefghijklmnopqrstuvwxyz";' + - 'eval("");' + - 'void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - 'eval("");', - sOutput: - '/*jshint evil:true */' + - '"abcdefghijklmnopqrstuvwxyz";' + - 'eval("");' + - '(function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - '}());' + - 'eval("");' - }, - { - sTitle: - 'Identification of a range of source elements at the end of ' + - 'global code.', - sInput: - '/*jshint evil:true */' + - '"abcdefghijklmnopqrstuvwxyz";' + - 'eval("");' + - 'void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];', - sOutput: - '/*jshint evil:true */' + - '"abcdefghijklmnopqrstuvwxyz";' + - 'eval("");' + - '(function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - '}());' - }, - { - sTitle: - 'Identification of a range of source elements at the beginning ' + - 'of function code.', - sInput: - '/*jshint evil:true */' + - '(function() {' + - ' "abcdefghijklmnopqrstuvwxyz";' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - ' eval("");' + - '}());', - sOutput: - '/*jshint evil:true */' + - '(function() {' + - ' "abcdefghijklmnopqrstuvwxyz";' + - ' (function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - ' }());' + - ' eval("");' + - '}());' - }, - { - sTitle: - 'Identification of a range of source elements in the middle of ' + - 'function code.', - sInput: - '/*jshint evil:true */' + - '(function() {' + - ' "abcdefghijklmnopqrstuvwxyz";' + - ' eval("");' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - ' eval("");' + - '}());', - sOutput: - '/*jshint evil:true */' + - '(function() {' + - ' "abcdefghijklmnopqrstuvwxyz";' + - ' eval("");' + - ' (function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - ' }());' + - ' eval("");' + - '}());' - }, - { - sTitle: - 'Identification of a range of source elements at the end of ' + - 'function code.', - sInput: - '/*jshint evil:true */' + - '(function() {' + - ' "abcdefghijklmnopqrstuvwxyz";' + - ' eval("");' + - ' void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];' + - '}());', - sOutput: - '/*jshint evil:true */' + - '(function() {' + - ' "abcdefghijklmnopqrstuvwxyz";' + - ' eval("");' + - ' (function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - ' }());' + - '}());' - }, - { - sTitle: - 'Evaluation with regard to String values of String literals and ' + - 'String values derived from identifier names used as property' + - 'accessors.', - sInput: - '(function() {' + - ' var foo;' + - ' void ["abcdefg", Math.abcdefg, "abcdef", Math.abcdef];' + - '}());', - sOutput: - '(function() {' + - ' var a = "abcdefg", foo;' + - ' void [a, Math[a], "abcdef", Math.abcdef];' + - '}());' - }, - { - sTitle: - 'Evaluation with regard to the necessity of adding a variable ' + - 'statement.', - sInput: - '/*jshint evil:true */' + - '(function() {' + - ' void ["abcdefgh", "abcdefgh"];' + - '}());' + - 'eval("");' + - '(function() {' + - ' void ["abcdefg", "abcdefg"];' + - '}());' + - 'eval("");' + - '(function() {' + - ' var foo;' + - ' void ["abcd", "abcd"];' + - '}());', - sOutput: - '/*jshint evil:true */' + - '(function() {' + - ' var a = "abcdefgh";' + - ' void [a, a];' + - '}());' + - 'eval("");' + - '(function() {' + - ' void ["abcdefg", "abcdefg"];' + - '}());' + - 'eval("");' + - '(function() {' + - ' var a = "abcd", foo;' + - ' void [a, a];' + - '}());' - }, - { - sTitle: - 'Evaluation with regard to the necessity of enclosing source ' + - 'elements.', - sInput: - '/*jshint evil:true */' + - 'void ["abcdefghijklmnopqrstuvwxy", "abcdefghijklmnopqrstuvwxy"];' + - 'eval("");' + - 'void ["abcdefghijklmnopqrstuvwx", "abcdefghijklmnopqrstuvwx"];' + - 'eval("");' + - '(function() {' + - ' void ["abcdefgh", "abcdefgh"];' + - '}());' + - '(function() {' + - ' void ["abcdefghijklmnopqrstuvwxy",' + - ' "abcdefghijklmnopqrstuvwxy"];' + - ' eval("");' + - ' void ["abcdefghijklmnopqrstuvwx",' + - ' "abcdefghijklmnopqrstuvwx"];' + - ' eval("");' + - ' (function() {' + - ' void ["abcdefgh", "abcdefgh"];' + - ' }());' + - '}());', - sOutput: - '/*jshint evil:true */' + - '(function() {' + - ' var a = "abcdefghijklmnopqrstuvwxy";' + - ' void [a, a];' + - '}());' + - 'eval("");' + - 'void ["abcdefghijklmnopqrstuvwx", "abcdefghijklmnopqrstuvwx"];' + - 'eval("");' + - '(function() {' + - ' var a = "abcdefgh";' + - ' void [a, a];' + - '}());' + - '(function() {' + - ' (function() {' + - ' var a = "abcdefghijklmnopqrstuvwxy";' + - ' void [a, a];' + - ' }());' + - ' eval("");' + - ' void ["abcdefghijklmnopqrstuvwx", "abcdefghijklmnopqrstuvwx"];' + - ' eval("");' + - ' (function() {' + - ' var a = "abcdefgh";' + - ' void [a, a];' + - ' }());' + - '}());' - }, - { - sTitle: - 'Employment of a closure while consolidating in global code.', - sInput: - 'void ["abcdefghijklmnopqrstuvwxyz",' + - ' "abcdefghijklmnopqrstuvwxyz"];', - sOutput: - '(function() {' + - ' var a = "abcdefghijklmnopqrstuvwxyz";' + - ' void [a, a];' + - '}());' - }, - { - sTitle: - 'Assignment of a shorter identifier to a value whose ' + - 'consolidation results in a greater reduction of the number of ' + - 'source characters.', - sInput: - '(function() {' + - ' var b, c, d, e, f, g, h, i, j, k, l, m,' + - ' n, o, p, q, r, s, t, u, v, w, x, y, z,' + - ' A, B, C, D, E, F, G, H, I, J, K, L, M,' + - ' N, O, P, Q, R, S, T, U, V, W, X, Y, Z,' + - ' $, _;' + - ' void ["abcde", "abcde", "edcba", "edcba", "edcba"];' + - '}());', - sOutput: - '(function() {' + - ' var a = "edcba",' + - ' b, c, d, e, f, g, h, i, j, k, l, m,' + - ' n, o, p, q, r, s, t, u, v, w, x, y, z,' + - ' A, B, C, D, E, F, G, H, I, J, K, L, M,' + - ' N, O, P, Q, R, S, T, U, V, W, X, Y, Z,' + - ' $, _;' + - ' void ["abcde", "abcde", a, a, a];' + - '}());' - } -].forEach(cAssert); - -process.exit(bTestsPassed ? 0 : 1); - diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/testparser.js b/node/node_modules/grunt/node_modules/uglify-js/test/testparser.js deleted file mode 100755 index a0f9f28f9..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/testparser.js +++ /dev/null @@ -1,409 +0,0 @@ -#! /usr/bin/env node -global.DIGITS_OVERRIDE_FOR_TESTING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789"; - -var parseJS = require("../lib/parse-js"); -var sys = require("util"); - -// write debug in a very straightforward manner -var debug = function(){ - sys.log(Array.prototype.slice.call(arguments).join(', ')); -}; - -var testsPassed = true; - -ParserTestSuite(function(i, input, desc){ - try { - parseJS.parse(input); - debug("ok " + i + ": " + desc); - } catch(e){ - debug("FAIL " + i + " " + desc + " (" + e + ")"); - testsPassed = false; - } -}); - -process.exit(testsPassed ? 0 : 1); - -function ParserTestSuite(callback){ - var inps = [ - ["var abc;", "Regular variable statement w/o assignment"], - ["var abc = 5;", "Regular variable statement with assignment"], - ["/* */;", "Multiline comment"], - ['/** **/;', 'Double star multiline comment'], - ["var f = function(){;};", "Function expression in var assignment"], - ['hi; // moo\n;', 'single line comment'], - ['var varwithfunction;', 'Dont match keywords as substrings'], // difference between `var withsomevar` and `"str"` (local search and lits) - ['a + b;', 'addition'], - ["'a';", 'single string literal'], - ["'a\\n';", 'single string literal with escaped return'], - ['"a";', 'double string literal'], - ['"a\\n";', 'double string literal with escaped return'], - ['"var";', 'string is a keyword'], - ['"variable";', 'string starts with a keyword'], - ['"somevariable";', 'string contains a keyword'], - ['"somevar";', 'string ends with a keyword'], - ['500;', 'int literal'], - ['500.;', 'float literal w/o decimals'], - ['500.432;', 'float literal with decimals'], - ['.432432;', 'float literal w/o int'], - ['(a,b,c);', 'parens and comma'], - ['[1,2,abc];', 'array literal'], - ['var o = {a:1};', 'object literal unquoted key'], - ['var o = {"b":2};', 'object literal quoted key'], // opening curly may not be at the start of a statement... - ['var o = {c:c};', 'object literal keyname is identifier'], - ['var o = {a:1,"b":2,c:c};', 'object literal combinations'], - ['var x;\nvar y;', 'two lines'], - ['var x;\nfunction n(){; }', 'function def'], - ['var x;\nfunction n(abc){; }', 'function def with arg'], - ['var x;\nfunction n(abc, def){ ;}', 'function def with args'], - ['function n(){ "hello"; }', 'function def with body'], - ['/a/;', 'regex literal'], - ['/a/b;', 'regex literal with flag'], - ['/a/ / /b/;', 'regex div regex'], - ['a/b/c;', 'triple division looks like regex'], - ['+function(){/regex/;};', 'regex at start of function body'], - // http://code.google.com/p/es-lab/source/browse/trunk/tests/parser/parsertests.js?r=86 - // http://code.google.com/p/es-lab/source/browse/trunk/tests/parser/parsertests.js?r=430 - - // first tests for the lexer, should also parse as program (when you append a semi) - - // comments - ['//foo!@#^&$1234\nbar;', 'single line comment'], - ['/* abcd!@#@$* { } && null*/;', 'single line multi line comment'], - ['/*foo\nbar*/;','multi line comment'], - ['/*x*x*/;','multi line comment with *'], - ['/**/;','empty comment'], - // identifiers - ["x;",'1 identifier'], - ["_x;",'2 identifier'], - ["xyz;",'3 identifier'], - ["$x;",'4 identifier'], - ["x$;",'5 identifier'], - ["_;",'6 identifier'], - ["x5;",'7 identifier'], - ["x_y;",'8 identifier'], - ["x+5;",'9 identifier'], - ["xyz123;",'10 identifier'], - ["x1y1z1;",'11 identifier'], - ["foo\\u00D8bar;",'12 identifier unicode escape'], - //["foo�bar;",'13 identifier unicode embedded (might fail)'], - // numbers - ["5;", '1 number'], - ["5.5;", '2 number'], - ["0;", '3 number'], - ["0.0;", '4 number'], - ["0.001;", '5 number'], - ["1.e2;", '6 number'], - ["1.e-2;", '7 number'], - ["1.E2;", '8 number'], - ["1.E-2;", '9 number'], - [".5;", '10 number'], - [".5e3;", '11 number'], - [".5e-3;", '12 number'], - ["0.5e3;", '13 number'], - ["55;", '14 number'], - ["123;", '15 number'], - ["55.55;", '16 number'], - ["55.55e10;", '17 number'], - ["123.456;", '18 number'], - ["1+e;", '20 number'], - ["0x01;", '22 number'], - ["0XCAFE;", '23 number'], - ["0x12345678;", '24 number'], - ["0x1234ABCD;", '25 number'], - ["0x0001;", '26 number'], - // strings - ["\"foo\";", '1 string'], - ["\'foo\';", '2 string'], - ["\"x\";", '3 string'], - ["\'\';", '4 string'], - ["\"foo\\tbar\";", '5 string'], - ["\"!@#$%^&*()_+{}[]\";", '6 string'], - ["\"/*test*/\";", '7 string'], - ["\"//test\";", '8 string'], - ["\"\\\\\";", '9 string'], - ["\"\\u0001\";", '10 string'], - ["\"\\uFEFF\";", '11 string'], - ["\"\\u10002\";", '12 string'], - ["\"\\x55\";", '13 string'], - ["\"\\x55a\";", '14 string'], - ["\"a\\\\nb\";", '15 string'], - ['";"', '16 string: semi in a string'], - ['"a\\\nb";', '17 string: line terminator escape'], - // literals - ["null;", "null"], - ["true;", "true"], - ["false;", "false"], - // regex - ["/a/;", "1 regex"], - ["/abc/;", "2 regex"], - ["/abc[a-z]*def/g;", "3 regex"], - ["/\\b/;", "4 regex"], - ["/[a-zA-Z]/;", "5 regex"], - - // program tests (for as far as they havent been covered above) - - // regexp - ["/foo(.*)/g;", "another regexp"], - // arrays - ["[];", "1 array"], - ["[ ];", "2 array"], - ["[1];", "3 array"], - ["[1,2];", "4 array"], - ["[1,2,,];", "5 array"], - ["[1,2,3];", "6 array"], - ["[1,2,3,,,];", "7 array"], - // objects - ["{};", "1 object"], - ["({x:5});", "2 object"], - ["({x:5,y:6});", "3 object"], - ["({x:5,});", "4 object"], - ["({if:5});", "5 object"], - ["({ get x() {42;} });", "6 object"], - ["({ set y(a) {1;} });", "7 object"], - // member expression - ["o.m;", "1 member expression"], - ["o['m'];", "2 member expression"], - ["o['n']['m'];", "3 member expression"], - ["o.n.m;", "4 member expression"], - ["o.if;", "5 member expression"], - // call and invoke expressions - ["f();", "1 call/invoke expression"], - ["f(x);", "2 call/invoke expression"], - ["f(x,y);", "3 call/invoke expression"], - ["o.m();", "4 call/invoke expression"], - ["o['m'];", "5 call/invoke expression"], - ["o.m(x);", "6 call/invoke expression"], - ["o['m'](x);", "7 call/invoke expression"], - ["o.m(x,y);", "8 call/invoke expression"], - ["o['m'](x,y);", "9 call/invoke expression"], - ["f(x)(y);", "10 call/invoke expression"], - ["f().x;", "11 call/invoke expression"], - - // eval - ["eval('x');", "1 eval"], - ["(eval)('x');", "2 eval"], - ["(1,eval)('x');", "3 eval"], - ["eval(x,y);", "4 eval"], - // new expression - ["new f();", "1 new expression"], - ["new o;", "2 new expression"], - ["new o.m;", "3 new expression"], - ["new o.m(x);", "4 new expression"], - ["new o.m(x,y);", "5 new expression"], - // prefix/postfix - ["++x;", "1 pre/postfix"], - ["x++;", "2 pre/postfix"], - ["--x;", "3 pre/postfix"], - ["x--;", "4 pre/postfix"], - ["x ++;", "5 pre/postfix"], - ["x /* comment */ ++;", "6 pre/postfix"], - ["++ /* comment */ x;", "7 pre/postfix"], - // unary operators - ["delete x;", "1 unary operator"], - ["void x;", "2 unary operator"], - ["+ x;", "3 unary operator"], - ["-x;", "4 unary operator"], - ["~x;", "5 unary operator"], - ["!x;", "6 unary operator"], - // meh - ["new Date++;", "new date ++"], - ["+x++;", " + x ++"], - // expression expressions - ["1 * 2;", "1 expression expressions"], - ["1 / 2;", "2 expression expressions"], - ["1 % 2;", "3 expression expressions"], - ["1 + 2;", "4 expression expressions"], - ["1 - 2;", "5 expression expressions"], - ["1 << 2;", "6 expression expressions"], - ["1 >>> 2;", "7 expression expressions"], - ["1 >> 2;", "8 expression expressions"], - ["1 * 2 + 3;", "9 expression expressions"], - ["(1+2)*3;", "10 expression expressions"], - ["1*(2+3);", "11 expression expressions"], - ["xy;", "13 expression expressions"], - ["x<=y;", "14 expression expressions"], - ["x>=y;", "15 expression expressions"], - ["x instanceof y;", "16 expression expressions"], - ["x in y;", "17 expression expressions"], - ["x&y;", "18 expression expressions"], - ["x^y;", "19 expression expressions"], - ["x|y;", "20 expression expressions"], - ["x+y>>= y;", "1 assignment"], - ["x <<= y;", "2 assignment"], - ["x = y;", "3 assignment"], - ["x += y;", "4 assignment"], - ["x /= y;", "5 assignment"], - // comma - ["x, y;", "comma"], - // block - ["{};", "1 block"], - ["{x;};", "2 block"], - ["{x;y;};", "3 block"], - // vars - ["var x;", "1 var"], - ["var x,y;", "2 var"], - ["var x=1,y=2;", "3 var"], - ["var x,y=2;", "4 var"], - // empty - [";", "1 empty"], - ["\n;", "2 empty"], - // expression statement - ["x;", "1 expression statement"], - ["5;", "2 expression statement"], - ["1+2;", "3 expression statement"], - // if - ["if (c) x; else y;", "1 if statement"], - ["if (c) x;", "2 if statement"], - ["if (c) {} else {};", "3 if statement"], - ["if (c1) if (c2) s1; else s2;", "4 if statement"], - // while - ["do s; while (e);", "1 while statement"], - ["do { s; } while (e);", "2 while statement"], - ["while (e) s;", "3 while statement"], - ["while (e) { s; };", "4 while statement"], - // for - ["for (;;) ;", "1 for statement"], - ["for (;c;x++) x;", "2 for statement"], - ["for (i;i> 1; -var c = 8 >>> 1; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue34.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue34.js deleted file mode 100644 index 022f7a31b..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue34.js +++ /dev/null @@ -1,3 +0,0 @@ -var a = {}; -a["this"] = 1; -a["that"] = 2; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue349.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue349.js deleted file mode 100644 index 71241f665..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue349.js +++ /dev/null @@ -1,25 +0,0 @@ -(function () { - var cake - if (noFreeCakes) return /* I would - insert something - there, but I'm sort - of lazy so whatever. - */ cake = new FreeCake() - return cake -})() - -(function () { - var cake - if (noFreeCakes) return /* I would insert something there, */ /* - but I'm sort of lazy so - */ /* whatever. */ cake = new FreeCake() - return cake -})() - -(function () { - var cake - if (noFreeCakes) return // I would insert something there, but I'm sort of lazy so whatever. - cake = new FreeCake() - return cake -})() - diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue353.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue353.js deleted file mode 100644 index 11ec1165b..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue353.js +++ /dev/null @@ -1,4 +0,0 @@ -function test() { - debugger; - return; -} diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue372.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue372.js deleted file mode 100644 index 3791ce882..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue372.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -"use strict"; - -function a() { - void "a"; - function b() { - "use strict"; - void "b"; - function c() { - "use strict"; - void "c"; - } - function d() { - "salmon"; - void "d"; - } - } - function e() { - "salmon"; - void "e"; - function f() { - "use strict"; - "salmon"; - void "f"; - for (var i = 0; i < 10; i++) var g = function() { - "use strict"; - "salmon"; - void "g"; - }(); - } - } -}; diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue4.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue4.js deleted file mode 100644 index 0b7610379..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue4.js +++ /dev/null @@ -1,3 +0,0 @@ -var a = 2e3; -var b = 2e-3; -var c = 2e-5; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue48.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue48.js deleted file mode 100644 index 031e85b39..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue48.js +++ /dev/null @@ -1 +0,0 @@ -var s, i; s = ''; i = 0; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue50.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue50.js deleted file mode 100644 index 060f9df82..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue50.js +++ /dev/null @@ -1,9 +0,0 @@ -function bar(a) { - try { - foo(); - } catch(e) { - alert("Exception caught (foo not defined)"); - } - alert(a); // 10 in FF, "[object Error]" in IE -} -bar(10); diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue53.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue53.js deleted file mode 100644 index 4f8b32f11..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue53.js +++ /dev/null @@ -1 +0,0 @@ -x = (y, z) diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue54.1.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue54.1.js deleted file mode 100644 index 967052e85..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue54.1.js +++ /dev/null @@ -1,3 +0,0 @@ -foo.toString(); -a.toString(16); -b.toString.call(c); diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue68.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue68.js deleted file mode 100644 index 14054d01e..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue68.js +++ /dev/null @@ -1,5 +0,0 @@ -function f() { - if (a) return; - g(); - function g(){} -}; diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue69.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue69.js deleted file mode 100644 index d25ecd671..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue69.js +++ /dev/null @@ -1 +0,0 @@ -[(a,b)] diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue9.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue9.js deleted file mode 100644 index 61588614b..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issue9.js +++ /dev/null @@ -1,4 +0,0 @@ -var a = { - a: 1, - b: 2, // <-- trailing comma -}; diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issues222_324.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issues222_324.js deleted file mode 100644 index 58b0d3c76..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/issues222_324.js +++ /dev/null @@ -1,82 +0,0 @@ -!function() { - 'use strict'; - - var 七, // issue #222 - $1, // issue #222 - ლ_ಠ益ಠ_ლ; // issue #324 -}; - -!function() { - 'use strict'; - - // test if Unicode canonical equivalence is ignored - var \u006E\u0303, - \u00F1; -}; - -!function() { - 'use strict'; - - var \uFF38, // X Lu (third to last) - \uFF58, // x Ll (third to last) - \u1FBC, // ᾼ Lt (third to last) - \uFF70, // ー Lm (third to last) - \u4DB3, // 䶳 Lo (third to last within a range) - \u97CA, // 韊 Lo (third to last within a range) - \uD7A1, // 힡 Lo (third to last within a range) - \uFFDA, // ᅳ Lo (third to last) - \uA6ED, // ꛭ Nl (third to last) - \u0024, // $ - \u005F, // _ - \u0024\uFF38, // X Lu (third to last) - \u0024\uFF58, // x Ll (third to last) - \u0024\u1FBC, // ᾼ Lt (third to last) - \u0024\uFF70, // ー Lm (third to last) - \u0024\u4DB3, // 䶳 Lo (third to last within a range) - \u0024\u97CA, // 韊 Lo (third to last within a range) - \u0024\uD7A1, // 힡 Lo (third to last within a range) - \u0024\uFFDA, // ᅳ Lo (third to last) - \u0024\uA6ED, // ꛭ Nl (third to last) - \u0024\uFE24, // ︤ Mn (third to last) - \u0024\uABE9, // ꯩ Mc (third to last) - \u0024\uFF17, // 7 Nd (third to last) - \u0024\uFE4E, // ﹎ Pc (third to last) - \u0024\u200C, // ZERO WIDTH NON-JOINER - \u0024\u200D, // ZERO WIDTH JOINER - \u0024\u0024, // $ - \u0024\u005F; // _ -}; - -!function() { - 'use strict'; - - var X, - x, - ᾼ, - ー, - 䶳, - 韊, - 힡, - ᅳ, - ꛭ, - $, - _, - $X, - $x, - $ᾼ, - $ー, - $䶳, - $韊, - $힡, - $ᅳ, - $ꛭ, - $︤, - $ꯩ, - $7, - $﹎, - $‌, - $‍, - $$, - $_; -}; - diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/mangle.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/mangle.js deleted file mode 100644 index c271a26dc..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/mangle.js +++ /dev/null @@ -1,5 +0,0 @@ -(function() { - var x = function fun(a, fun, b) { - return fun; - }; -}()); diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/null_string.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/null_string.js deleted file mode 100644 index a675b1c5c..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/null_string.js +++ /dev/null @@ -1 +0,0 @@ -var nullString = "\0" \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/strict-equals.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/strict-equals.js deleted file mode 100644 index b631f4c35..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/strict-equals.js +++ /dev/null @@ -1,3 +0,0 @@ -typeof a === 'string' -b + "" !== c + "" -d < e === f < g diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/var.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/var.js deleted file mode 100644 index 609a35d2a..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/var.js +++ /dev/null @@ -1,3 +0,0 @@ -// var declarations after each other should be combined -var a = 1; -var b = 2; \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/whitespace.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/whitespace.js deleted file mode 100644 index 6a15c464f..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/whitespace.js +++ /dev/null @@ -1,21 +0,0 @@ -function id(a) { - // Form-Feed - // Vertical Tab - // No-Break Space - ᠎// Mongolian Vowel Separator -  // En quad -  // Em quad -  // En space -  // Em space -  // Three-Per-Em Space -  // Four-Per-Em Space -  // Six-Per-Em Space -  // Figure Space -  // Punctuation Space -  // Thin Space -  // Hair Space -  // Narrow No-Break Space -  // Medium Mathematical Space -  // Ideographic Space - return a; -} diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/with.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/with.js deleted file mode 100644 index de266ed54..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/compress/test/with.js +++ /dev/null @@ -1,2 +0,0 @@ -with({}) { -}; diff --git a/node/node_modules/grunt/node_modules/uglify-js/test/unit/scripts.js b/node/node_modules/grunt/node_modules/uglify-js/test/unit/scripts.js deleted file mode 100644 index 564abd3ff..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/test/unit/scripts.js +++ /dev/null @@ -1,57 +0,0 @@ -global.DIGITS_OVERRIDE_FOR_TESTING = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789"; - -var fs = require('fs'), - uglify = require('../../uglify-js'), - jsp = uglify.parser, - nodeunit = require('nodeunit'), - path = require('path'), - pro = uglify.uglify; - -var Script = process.binding('evals').Script; - -var scriptsPath = __dirname; - -function compress(code) { - var ast = jsp.parse(code); - ast = pro.ast_mangle(ast, { mangle: true }); - ast = pro.ast_squeeze(ast, { no_warnings: true }); - ast = pro.ast_squeeze_more(ast); - return pro.gen_code(ast); -}; - -var testDir = path.join(scriptsPath, "compress", "test"); -var expectedDir = path.join(scriptsPath, "compress", "expected"); - -function getTester(script) { - return function(test) { - var testPath = path.join(testDir, script); - var expectedPath = path.join(expectedDir, script); - var content = fs.readFileSync(testPath, 'utf-8'); - var outputCompress = compress(content); - - // Check if the noncompressdata is larger or same size as the compressed data - test.ok(content.length >= outputCompress.length); - - // Check that a recompress gives the same result - var outputReCompress = compress(content); - test.equal(outputCompress, outputReCompress); - - // Check if the compressed output is what is expected - var expected = fs.readFileSync(expectedPath, 'utf-8'); - test.equal(outputCompress, expected.replace(/(\r?\n)+$/, "")); - - test.done(); - }; -}; - -var tests = {}; - -var scripts = fs.readdirSync(testDir); -for (var i in scripts) { - var script = scripts[i]; - if (/\.js$/.test(script)) { - tests[script] = getTester(script); - } -} - -module.exports = nodeunit.testCase(tests); diff --git a/node/node_modules/grunt/node_modules/uglify-js/tmp/hoist.js b/node/node_modules/grunt/node_modules/uglify-js/tmp/hoist.js deleted file mode 100644 index 4bf2b94de..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/tmp/hoist.js +++ /dev/null @@ -1,33 +0,0 @@ -function foo(arg1, arg2, arg3, arg4, arg5, arg6) { - var a = 5; - { - var d = 10, mak = 20, buz = 30; - var q = buz * 2; - } - if (moo) { - var a, b, c; - } - for (var arg1 = 0, d = 20; arg1 < 10; ++arg1) - console.log(arg3); - for (var i in mak) {} - for (j in d) {} - var d; - - function test() { - - }; - - //test(); - - (function moo(first, second){ - console.log(first); - })(1); - - (function moo(first, second){ - console.log(moo()); - })(1); -} - - -var foo; -var bar; diff --git a/node/node_modules/grunt/node_modules/uglify-js/tmp/instrument.js b/node/node_modules/grunt/node_modules/uglify-js/tmp/instrument.js deleted file mode 100644 index c6a9d798a..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/tmp/instrument.js +++ /dev/null @@ -1,97 +0,0 @@ -// sample on how to use the parser and walker API to instrument some code - -var jsp = require("uglify-js").parser; -var pro = require("uglify-js").uglify; - -function instrument(code) { - var ast = jsp.parse(code, false, true); // true for the third arg specifies that we want - // to have start/end tokens embedded in the - // statements - var w = pro.ast_walker(); - - // we're gonna need this to push elements that we're currently looking at, to avoid - // endless recursion. - var analyzing = []; - function do_stat() { - var ret; - if (this[0].start && analyzing.indexOf(this) < 0) { - // without the `analyzing' hack, w.walk(this) would re-enter here leading - // to infinite recursion - analyzing.push(this); - ret = [ "splice", // XXX: "block" is safer - [ [ "stat", - [ "call", [ "name", "trace" ], - [ [ "string", this[0].toString() ], - [ "num", this[0].start.line ], - [ "num", this[0].start.col ], - [ "num", this[0].end.line ], - [ "num", this[0].end.col ]]]], - w.walk(this) ]]; - analyzing.pop(this); - } - return ret; - }; - var new_ast = w.with_walkers({ - "stat" : do_stat, - "label" : do_stat, - "break" : do_stat, - "continue" : do_stat, - "debugger" : do_stat, - "var" : do_stat, - "const" : do_stat, - "return" : do_stat, - "throw" : do_stat, - "try" : do_stat, - "defun" : do_stat, - "if" : do_stat, - "while" : do_stat, - "do" : do_stat, - "for" : do_stat, - "for-in" : do_stat, - "switch" : do_stat, - "with" : do_stat - }, function(){ - return w.walk(ast); - }); - return pro.gen_code(new_ast, { beautify: true }); -} - - - - -////// test code follows. - -var code = instrument(test.toString()); -console.log(code); - -function test() { - // simple stats - a = 5; - c += a + b; - "foo"; - - // var - var foo = 5; - const bar = 6, baz = 7; - - // switch block. note we can't track case lines the same way. - switch ("foo") { - case "foo": - return 1; - case "bar": - return 2; - } - - // for/for in - for (var i = 0; i < 5; ++i) { - console.log("Hello " + i); - } - for (var i in [ 1, 2, 3]) { - console.log(i); - } - - // note however that the following is broken. I guess we - // should add the block brackets in this case... - for (var i = 0; i < 5; ++i) - console.log("foo"); -} diff --git a/node/node_modules/grunt/node_modules/uglify-js/tmp/test.js b/node/node_modules/grunt/node_modules/uglify-js/tmp/test.js deleted file mode 100755 index f295fba84..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/tmp/test.js +++ /dev/null @@ -1,30 +0,0 @@ -#! /usr/bin/env node - -global.sys = require(/^v0\.[012]/.test(process.version) ? "sys" : "util"); -var fs = require("fs"); -var uglify = require("uglify-js"), // symlink ~/.node_libraries/uglify-js.js to ../uglify-js.js - jsp = uglify.parser, - pro = uglify.uglify; - -var code = fs.readFileSync("hoist.js", "utf8"); -var ast = jsp.parse(code); - -ast = pro.ast_lift_variables(ast); - -var w = pro.ast_walker(); -ast = w.with_walkers({ - "function": function() { - var node = w.dive(this); // walk depth first - console.log(pro.gen_code(node, { beautify: true })); - return node; - }, - "name": function(name) { - return [ this[0], "X" ]; - } -}, function(){ - return w.walk(ast); -}); - -console.log(pro.gen_code(ast, { - beautify: true -})); diff --git a/node/node_modules/grunt/node_modules/uglify-js/uglify-js.js b/node/node_modules/grunt/node_modules/uglify-js/uglify-js.js deleted file mode 100644 index 6e14a637e..000000000 --- a/node/node_modules/grunt/node_modules/uglify-js/uglify-js.js +++ /dev/null @@ -1,18 +0,0 @@ -//convienence function(src, [options]); -function uglify(orig_code, options){ - options || (options = {}); - var jsp = uglify.parser; - var pro = uglify.uglify; - - var ast = jsp.parse(orig_code, options.strict_semicolons); // parse code and get the initial AST - ast = pro.ast_mangle(ast, options.mangle_options); // get a new AST with mangled names - ast = pro.ast_squeeze(ast, options.squeeze_options); // get an AST with compression optimizations - var final_code = pro.gen_code(ast, options.gen_options); // compressed code here - return final_code; -}; - -uglify.parser = require("./lib/parse-js"); -uglify.uglify = require("./lib/process"); -uglify.consolidator = require("./lib/consolidator"); - -module.exports = uglify diff --git a/node/node_modules/grunt/node_modules/underscore.string/Gemfile.lock b/node/node_modules/grunt/node_modules/underscore.string/Gemfile.lock index 6b49945f0..a6bb1e73a 100644 --- a/node/node_modules/grunt/node_modules/underscore.string/Gemfile.lock +++ b/node/node_modules/grunt/node_modules/underscore.string/Gemfile.lock @@ -1,13 +1,13 @@ GEM remote: http://rubygems.org/ specs: - activesupport (3.2.1) + activesupport (3.2.3) i18n (~> 0.6) multi_json (~> 1.0) execjs (1.3.0) multi_json (~> 1.0) i18n (0.6.0) - multi_json (1.1.0) + multi_json (1.2.0) rack (1.4.1) rack-test (0.6.1) rack (>= 1.0) @@ -20,8 +20,8 @@ GEM tilt (~> 1.3) tzinfo tilt (1.3.3) - tzinfo (0.3.31) - uglifier (1.2.3) + tzinfo (0.3.33) + uglifier (1.2.4) execjs (>= 0.3.0) multi_json (>= 1.0.2) diff --git a/node/node_modules/grunt/node_modules/underscore.string/README.markdown b/node/node_modules/grunt/node_modules/underscore.string/README.markdown index d744a57b6..d2244b578 100644 --- a/node/node_modules/grunt/node_modules/underscore.string/README.markdown +++ b/node/node_modules/grunt/node_modules/underscore.string/README.markdown @@ -70,11 +70,11 @@ _.str.capitalize('epeli') **capitalize** _.capitalize(string) -Converts first letter of the string to uppercase and the rest of the string to lower case. +Converts first letter of the string to uppercase. ```javascript _.capitalize("foo Bar") -=> "Foo bar" +=> "Foo Bar" ``` **chop** _.chop(string, step) @@ -566,6 +566,11 @@ But of course you can just reassign `_` variable with `_.string` ```javascript _ = _.string ``` +### 2.2.0 ### + +* Capitalize method behavior changed +* Various perfomance tweaks + ### 2.1.1### * Fixed words method bug diff --git a/node/node_modules/grunt/node_modules/underscore.string/Rakefile b/node/node_modules/grunt/node_modules/underscore.string/Rakefile index 9fecdfe85..baa164cd9 100644 --- a/node/node_modules/grunt/node_modules/underscore.string/Rakefile +++ b/node/node_modules/grunt/node_modules/underscore.string/Rakefile @@ -11,10 +11,9 @@ task :build do puts "compressed dist/underscore.string.min.js: #{compressed.length}/#{source.length} #{(compression_rate * 100).round}%" end - desc 'Run tests' task :test do - system %{bundle exec serve 2>/dev/null &} + pid = spawn('bundle exec serve', err: '/dev/null') sleep 2 puts "Running underscore.string test suite." @@ -22,6 +21,8 @@ task :test do puts "Running Underscore test suite." result2 = system %{phantomjs ./test/run-qunit.js "http://localhost:4000/test/test_underscore/test.html"} - + + Process.kill 'INT', pid + exit(result1 && result2 ? 0 : 1) end \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/underscore.string/dist/underscore.string.min.js b/node/node_modules/grunt/node_modules/underscore.string/dist/underscore.string.min.js index 553869477..cd436e192 100644 --- a/node/node_modules/grunt/node_modules/underscore.string/dist/underscore.string.min.js +++ b/node/node_modules/grunt/node_modules/underscore.string/dist/underscore.string.min.js @@ -1 +1 @@ -(function(a){"use strict";var b=String.prototype.trim,c=String.prototype.trimRight,d=String.prototype.trimLeft,e=function(a){return a*1||0},f=function(a,b,c){a+="",b=~~b;for(var d=[];b>0;d[--b]=a);return d.join(c==null?"":c)},g=function(a){return Array.prototype.slice.call(a)},h=function(a){return a!=null?"["+j.escapeRegExp(""+a)+"]":"\\s"},i=function(){function a(a){return Object.prototype.toString.call(a).slice(8,-1).toLowerCase()}var b=f,c=function(){return c.cache.hasOwnProperty(arguments[0])||(c.cache[arguments[0]]=c.parse(arguments[0])),c.format.call(null,c.cache[arguments[0]],arguments)};return c.format=function(c,d){var e=1,f=c.length,g="",h,j=[],k,l,m,n,o,p;for(k=0;k=0?"+"+h:h,o=m[4]?m[4]=="0"?"0":m[4].charAt(1):" ",p=m[6]-String(h).length,n=m[6]?b(o,p):"",j.push(m[5]?h+n:n+h)}}return j.join("")},c.cache={},c.parse=function(a){var b=a,c=[],d=[],e=0;while(b){if((c=/^[^\x25]+/.exec(b))!==null)d.push(c[0]);else if((c=/^\x25{2}/.exec(b))!==null)d.push("%");else{if((c=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(b))===null)throw new Error("[_.sprintf] huh?");if(c[2]){e|=1;var f=[],g=c[2],h=[];if((h=/^([a-z_][a-z_\d]*)/i.exec(g))===null)throw new Error("[_.sprintf] huh?");f.push(h[1]);while((g=g.substring(h[0].length))!=="")if((h=/^\.([a-z_][a-z_\d]*)/i.exec(g))!==null)f.push(h[1]);else{if((h=/^\[(\d+)\]/.exec(g))===null)throw new Error("[_.sprintf] huh?");f.push(h[1])}c[2]=f}else e|=2;if(e===3)throw new Error("[_.sprintf] mixing positional and named placeholders is not (yet) supported");d.push(c)}b=b.substring(c[0].length)}return d},c}(),j={VERSION:"2.1.1",isBlank:function(a){return/^\s*$/.test(a)},stripTags:function(a){return(""+a).replace(/<\/?[^>]+>/ig,"")},capitalize:function(a){return a+="",a.charAt(0).toUpperCase()+a.substring(1).toLowerCase()},chop:function(a,b){a+="",b=~~b||a.length;var c=[];for(var d=0;d/g,">").replace(/"/g,""").replace(/'/g,"'")},unescapeHTML:function(a){return(""+a).replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&")},escapeRegExp:function(a){return a.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1")},insert:function(a,b,c){var d=(""+a).split("");return d.splice(~~b,0,""+c),d.join("")},include:function(a,b){return(""+a).indexOf(b)!==-1},join:function(a){var b=g(arguments);return b.join(b.shift())},lines:function(a){return(""+a).split("\n")},reverse:function(a){return Array.prototype.reverse.apply(String(a).split("")).join("")},splice:function(a,b,c,d){var e=(""+a).split("");return e.splice(~~b,~~c,d),e.join("")},startsWith:function(a,b){return a+="",b+="",a.length>=b.length&&a.substring(0,b.length)===b},endsWith:function(a,b){return a+="",b+="",a.length>=b.length&&a.substring(a.length-b.length)===b},succ:function(a){a+="";var b=a.split("");return b.splice(a.length-1,1,String.fromCharCode(a.charCodeAt(a.length-1)+1)),b.join("")},titleize:function(a){return(""+a).replace(/\b./g,function(a){return a.toUpperCase()})},camelize:function(a){return j.trim(a).replace(/(\-|_|\s)+(.)?/g,function(a,b,c){return c?c.toUpperCase():""})},underscored:function(a){return j.trim(a).replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()},dasherize:function(a){return j.trim(a).replace(/[_\s]+/g,"-").replace(/([A-Z])/g,"-$1").replace(/-+/g,"-").toLowerCase()},classify:function(a){return j.titleize(a.replace(/_/g," ")).replace(/\s/g,"")},humanize:function(a){return j.capitalize(this.underscored(a).replace(/_id$/,"").replace(/_/g," "))},trim:function(a,c){return a+="",!c&&b?b.call(a):(c=h(c),a.replace(new RegExp("^"+c+"+|"+c+"+$","g"),""))},ltrim:function(a,b){return!b&&d?d.call(a):(b=h(b),(""+a).replace(new RegExp("^"+b+"+","g"),""))},rtrim:function(a,b){return!b&&c?c.call(a):(b=h(b),(""+a).replace(new RegExp(b+"+$","g"),""))},truncate:function(a,b,c){return a+="",c=c||"...",b=~~b,a.length>b?a.slice(0,b)+c:a},prune:function(a,b,c){a+="",b=~~b,c=c!=null?""+c:"...";var d,e,f=a.replace(/\W/g,function(a){return a.toUpperCase()!==a.toLowerCase()?"A":" "});return e=f.charAt(b),d=f.slice(0,b),e&&e.match(/\S/)&&(d=d.replace(/\s\S+$/,"")),d=j.rtrim(d),(d+c).length>a.length?a:a.substring(0,d.length)+c},words:function(a,b){return j.trim(a,b).split(b||/\s+/)},pad:function(a,b,c,d){a+="";var e="",g=0;b=~~b,c?c.length>1&&(c=c.charAt(0)):c=" ";switch(d){case"right":g=b-a.length,e=f(c,g),a+=e;break;case"both":g=b-a.length,e={left:f(c,Math.ceil(g/2)),right:f(c,Math.floor(g/2))},a=e.left+a+e.right;break;default:g=b-a.length,e=f(c,g),a=e+a}return a},lpad:function(a,b,c){return j.pad(a,b,c)},rpad:function(a,b,c){return j.pad(a,b,c,"right")},lrpad:function(a,b,c){return j.pad(a,b,c,"both")},sprintf:i,vsprintf:function(a,b){return b.unshift(a),i.apply(null,b)},toNumber:function(a,b){var c=e(e(a).toFixed(~~b));return c===0&&""+a!="0"?Number.NaN:c},strRight:function(a,b){a+="",b=b!=null?""+b:b;var c=b?a.indexOf(b):-1;return c!=-1?a.slice(c+b.length,a.length):a},strRightBack:function(a,b){a+="",b=b!=null?""+b:b;var c=b?a.lastIndexOf(b):-1;return c!=-1?a.slice(c+b.length,a.length):a},strLeft:function(a,b){a+="",b=b!=null?""+b:b;var c=b?a.indexOf(b):-1;return c!=-1?a.slice(0,c):a},strLeftBack:function(a,b){a+="",b=b!=null?""+b:b;var c=a.lastIndexOf(b);return c!=-1?a.slice(0,c):a},toSentence:function(a,b,c){b||(b=", "),c||(c=" and ");var d=a.length,e="";for(var f=0;f0;d[--b]=a);return d.join(c==null?"":c)},g=function(a){return Array.prototype.slice.call(a)},h=function(a){return a!=null?"["+m.escapeRegExp(""+a)+"]":"\\s"},i={lt:"<",gt:">",quot:'"',apos:"'",amp:"&"},j={};for(var k in i)j[i[k]]=k;var l=function(){function a(a){return Object.prototype.toString.call(a).slice(8,-1).toLowerCase()}var b=f,c=function(){return c.cache.hasOwnProperty(arguments[0])||(c.cache[arguments[0]]=c.parse(arguments[0])),c.format.call(null,c.cache[arguments[0]],arguments)};return c.format=function(c,d){var e=1,f=c.length,g="",h,i=[],j,k,m,n,o,p;for(j=0;j=0?"+"+h:h,o=m[4]?m[4]=="0"?"0":m[4].charAt(1):" ",p=m[6]-String(h).length,n=m[6]?b(o,p):"",i.push(m[5]?h+n:n+h)}}return i.join("")},c.cache={},c.parse=function(a){var b=a,c=[],d=[],e=0;while(b){if((c=/^[^\x25]+/.exec(b))!==null)d.push(c[0]);else if((c=/^\x25{2}/.exec(b))!==null)d.push("%");else{if((c=/^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(b))===null)throw new Error("[_.sprintf] huh?");if(c[2]){e|=1;var f=[],g=c[2],h=[];if((h=/^([a-z_][a-z_\d]*)/i.exec(g))===null)throw new Error("[_.sprintf] huh?");f.push(h[1]);while((g=g.substring(h[0].length))!=="")if((h=/^\.([a-z_][a-z_\d]*)/i.exec(g))!==null)f.push(h[1]);else{if((h=/^\[(\d+)\]/.exec(g))===null)throw new Error("[_.sprintf] huh?");f.push(h[1])}c[2]=f}else e|=2;if(e===3)throw new Error("[_.sprintf] mixing positional and named placeholders is not (yet) supported");d.push(c)}b=b.substring(c[0].length)}return d},c}(),m={VERSION:"2.1.1",isBlank:function(a){return/^\s*$/.test(a)},stripTags:function(a){return(""+a).replace(/<\/?[^>]+>/g,"")},capitalize:function(a){return a+="",a.charAt(0).toUpperCase()+a.substring(1)},chop:function(a,b){a+="",b=~~b||a.length;var c=[];for(var d=0;d"']/g,function(a){return"&"+j[a]+";"})},unescapeHTML:function(a){return(""+a).replace(/\&([^;]+);/g,function(a,b){var c;return b in i?i[b]:(c=b.match(/^#x([\da-fA-F]+)$/))?String.fromCharCode(parseInt(c[1],16)):(c=b.match(/^#(\d+)$/))?String.fromCharCode(~~c[1]):a})},escapeRegExp:function(a){return a.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1")},insert:function(a,b,c){var d=m.chars(a);return d.splice(~~b,0,""+c),d.join("")},include:function(a,b){return!!~(""+a).indexOf(b)},join:function(){var a=g(arguments);return a.join(a.shift())},lines:function(a){return(""+a).split("\n")},reverse:function(a){return m.chars(a).reverse().join("")},splice:function(a,b,c,d){var e=m.chars(a);return e.splice(~~b,~~c,d),e.join("")},startsWith:function(a,b){return a+="",b+="",a.length>=b.length&&a.substring(0,b.length)===b},endsWith:function(a,b){return a+="",b+="",a.length>=b.length&&a.substring(a.length-b.length)===b},succ:function(a){a+="";var b=m.chars(a);return b.splice(a.length-1,1,String.fromCharCode(a.charCodeAt(a.length-1)+1)),b.join("")},titleize:function(a){return(""+a).replace(/\b./g,function(a){return a.toUpperCase()})},camelize:function(a){return m.trim(a).replace(/[-_\s]+(.)?/g,function(a,b){return b&&b.toUpperCase()})},underscored:function(a){return m.trim(a).replace(/([a-z\d])([A-Z]+)/g,"$1_$2").replace(/[-\s]+/g,"_").toLowerCase()},dasherize:function(a){return m.trim(a).replace(/[_\s]+/g,"-").replace(/([A-Z])/g,"-$1").replace(/-+/g,"-").toLowerCase()},classify:function(a){return a+="",m.titleize(a.replace(/_/g," ")).replace(/\s/g,"")},humanize:function(a){return m.capitalize(this.underscored(a).replace(/_id$/,"").replace(/_/g," "))},trim:function(a,c){return a+="",!c&&b?b.call(a):(c=h(c),a.replace(new RegExp("^"+c+"+|"+c+"+$","g"),""))},ltrim:function(a,b){return a+="",!b&&d?d.call(a):(b=h(b),a.replace(new RegExp("^"+b+"+"),""))},rtrim:function(a,b){return a+="",!b&&c?c.call(a):(b=h(b),a.replace(new RegExp(b+"+$"),""))},truncate:function(a,b,c){return a+="",c=c||"...",b=~~b,a.length>b?a.slice(0,b)+c:a},prune:function(a,b,c){a+="",b=~~b,c=c!=null?""+c:"...";var d,e,f=a.replace(/\W/g,function(a){return a.toUpperCase()!==a.toLowerCase()?"A":" "});return e=f.charAt(b),d=f.slice(0,b),e&&e.match(/\S/)&&(d=d.replace(/\s\S+$/,"")),d=m.rtrim(d),(d+c).length>a.length?a:a.substring(0,d.length)+c},words:function(a,b){return m.trim(a,b).split(b||/\s+/)},pad:function(a,b,c,d){a+="";var e=0;b=~~b,c?c.length>1&&(c=c.charAt(0)):c=" ";switch(d){case"right":return e=b-a.length,a+f(c,e);case"both":return e=b-a.length,f(c,Math.ceil(e/2))+a+f(c,Math.floor(e/2));default:return e=b-a.length,f(c,e)+a}},lpad:function(a,b,c){return m.pad(a,b,c)},rpad:function(a,b,c){return m.pad(a,b,c,"right")},lrpad:function(a,b,c){return m.pad(a,b,c,"both")},sprintf:l,vsprintf:function(a,b){return b.unshift(a),l.apply(null,b)},toNumber:function(a,b){a+="";var c=e(e(a).toFixed(~~b));return c===0&&!a.match(/^0+$/)?Number.NaN:c},strRight:function(a,b){a+="",b=b!=null?""+b:b;var c=b?a.indexOf(b):-1;return~c?a.slice(c+b.length,a.length):a},strRightBack:function(a,b){a+="",b=b!=null?""+b:b;var c=b?a.lastIndexOf(b):-1;return~c?a.slice(c+b.length,a.length):a},strLeft:function(a,b){a+="",b=b!=null?""+b:b;var c=b?a.indexOf(b):-1;return~c?a.slice(0,c):a},strLeftBack:function(a,b){a+="",b=b!=null?""+b:b;var c=a.lastIndexOf(b);return~c?a.slice(0,c):a},toSentence:function(a,b,c){b||(b=", "),c||(c=" and ");var d=a.length,e="";for(var f=0;f', + quot: '"', + apos: "'", + amp: '&' + }; + + var reversedEscapeChars = {}; + for(var key in escapeChars){ reversedEscapeChars[escapeChars[key]] = key; } // sprintf() for JavaScript 0.7-beta1 // http://www.diveintojavascript.com/projects/javascript-sprintf @@ -164,34 +175,32 @@ var _s = { - VERSION: '2.1.1', + VERSION: '2.2.0rc', isBlank: function(str){ return (/^\s*$/).test(str); }, stripTags: function(str){ - return (''+str).replace(/<\/?[^>]+>/ig, ''); + return (''+str).replace(/<\/?[^>]+>/g, ''); }, capitalize : function(str) { str += ''; - return str.charAt(0).toUpperCase() + str.substring(1).toLowerCase(); + return str.charAt(0).toUpperCase() + str.substring(1); }, chop: function(str, step){ str = str+''; step = ~~step || str.length; var arr = []; - for (var i = 0; i < str.length;) { + for (var i = 0; i < str.length; i += step) arr.push(str.slice(i,i + step)); - i = i + step; - } return arr; }, clean: function(str){ - return _s.strip((''+str).replace(/\s+/g, ' ')); + return _s.strip(str).replace(/\s+/g, ' '); }, count: function(str, substr){ @@ -204,13 +213,23 @@ }, escapeHTML: function(str) { - return (''+str).replace(/&/g,'&').replace(//g,'>') - .replace(/"/g, '"').replace(/'/g, "'"); + return (''+str).replace(/[&<>"']/g, function(match){ return '&' + reversedEscapeChars[match] + ';'; }); }, unescapeHTML: function(str) { - return (''+str).replace(/</g, '<').replace(/>/g, '>') - .replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&'); + return (''+str).replace(/\&([^;]+);/g, function(entity, entityCode){ + var match; + + if (entityCode in escapeChars) { + return escapeChars[entityCode]; + } else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) { + return String.fromCharCode(parseInt(match[1], 16)); + } else if (match = entityCode.match(/^#(\d+)$/)) { + return String.fromCharCode(~~match[1]); + } else { + return entity; + } + }); }, escapeRegExp: function(str){ @@ -219,16 +238,16 @@ }, insert: function(str, i, substr){ - var arr = (''+str).split(''); + var arr = _s.chars(str); arr.splice(~~i, 0, ''+substr); return arr.join(''); }, include: function(str, needle){ - return (''+str).indexOf(needle) !== -1; + return !!~(''+str).indexOf(needle); }, - join: function(sep) { + join: function() { var args = slice(arguments); return args.join(args.shift()); }, @@ -238,11 +257,11 @@ }, reverse: function(str){ - return Array.prototype.reverse.apply(String(str).split('')).join(''); + return _s.chars(str).reverse().join(''); }, splice: function(str, i, howmany, substr){ - var arr = (''+str).split(''); + var arr = _s.chars(str); arr.splice(~~i, ~~howmany, substr); return arr.join(''); }, @@ -259,7 +278,7 @@ succ: function(str){ str += ''; - var arr = str.split(''); + var arr = _s.chars(str); arr.splice(str.length-1, 1, String.fromCharCode(str.charCodeAt(str.length-1) + 1)); return arr.join(''); }, @@ -269,8 +288,8 @@ }, camelize: function(str){ - return _s.trim(str).replace(/(\-|_|\s)+(.)?/g, function(match, separator, chr) { - return chr ? chr.toUpperCase() : ''; + return _s.trim(str).replace(/[-_\s]+(.)?/g, function(match, chr){ + return chr && chr.toUpperCase(); }); }, @@ -283,6 +302,7 @@ }, classify: function(str){ + str += ''; return _s.titleize(str.replace(/_/g, ' ')).replace(/\s/g, '') }, @@ -292,27 +312,27 @@ trim: function(str, characters){ str += ''; - if (!characters && nativeTrim) { - return nativeTrim.call(str); - } + if (!characters && nativeTrim) { return nativeTrim.call(str); } characters = defaultToWhiteSpace(characters); return str.replace(new RegExp('\^' + characters + '+|' + characters + '+$', 'g'), ''); }, ltrim: function(str, characters){ + str+=''; if (!characters && nativeTrimLeft) { return nativeTrimLeft.call(str); } characters = defaultToWhiteSpace(characters); - return (''+str).replace(new RegExp('\^' + characters + '+', 'g'), ''); + return str.replace(new RegExp('^' + characters + '+'), ''); }, rtrim: function(str, characters){ + str+=''; if (!characters && nativeTrimRight) { return nativeTrimRight.call(str); } characters = defaultToWhiteSpace(characters); - return (''+str).replace(new RegExp(characters + '+$', 'g'), ''); + return str.replace(new RegExp(characters + '+$'), ''); }, truncate: function(str, length, truncateStr){ @@ -354,7 +374,7 @@ pad: function(str, length, padStr, type) { str += ''; - var padding = '', padlen = 0; + var padlen = 0; length = ~~length; @@ -367,23 +387,16 @@ switch(type) { case 'right': padlen = (length - str.length); - padding = strRepeat(padStr, padlen); - str = str+padding; - break; + return str + strRepeat(padStr, padlen); case 'both': padlen = (length - str.length); - padding = { - 'left' : strRepeat(padStr, Math.ceil(padlen/2)), - 'right': strRepeat(padStr, Math.floor(padlen/2)) - }; - str = padding.left+str+padding.right; - break; + return strRepeat(padStr, Math.ceil(padlen/2)) + + str + + strRepeat(padStr, Math.floor(padlen/2)); default: // 'left' padlen = (length - str.length); - padding = strRepeat(padStr, padlen);; - str = padding+str; + return strRepeat(padStr, padlen) + str; } - return str; }, lpad: function(str, length, padStr) { @@ -406,32 +419,33 @@ }, toNumber: function(str, decimals) { + str += ''; var num = parseNumber(parseNumber(str).toFixed(~~decimals)); - return num === 0 && ''+str !== '0' ? Number.NaN : num; + return num === 0 && !str.match(/^0+$/) ? Number.NaN : num; }, strRight: function(str, sep){ str += ''; sep = sep != null ? ''+sep : sep; - var pos = (!sep) ? -1 : str.indexOf(sep); - return (pos != -1) ? str.slice(pos+sep.length, str.length) : str; + var pos = !sep ? -1 : str.indexOf(sep); + return ~pos ? str.slice(pos+sep.length, str.length) : str; }, strRightBack: function(str, sep){ str += ''; sep = sep != null ? ''+sep : sep; - var pos = (!sep) ? -1 : str.lastIndexOf(sep); - return (pos != -1) ? str.slice(pos+sep.length, str.length) : str; + var pos = !sep ? -1 : str.lastIndexOf(sep); + return ~pos ? str.slice(pos+sep.length, str.length) : str; }, strLeft: function(str, sep){ str += ''; sep = sep != null ? ''+sep : sep; - var pos = (!sep) ? -1 : str.indexOf(sep); - return (pos != -1) ? str.slice(0, pos) : str; + var pos = !sep ? -1 : str.indexOf(sep); + return ~pos ? str.slice(0, pos) : str; }, strLeftBack: function(str, sep){ str += ''; sep = sep != null ? ''+sep : sep; var pos = str.lastIndexOf(sep); - return (pos != -1) ? str.slice(0, pos) : str; + return ~pos ? str.slice(0, pos) : str; }, toSentence: function(array, separator, lastSeparator) { @@ -449,7 +463,7 @@ }, slugify: function(str) { - var from = "ąàáäâãćęèéëêìíïîłńòóöôõùúüûñçżź·/_:;", + var from = "ąàáäâãćęèéëêìíïîłńòóöôõùúüûñçżź", to = "aaaaaaceeeeeiiiilnooooouuuunczz", regex = new RegExp(defaultToWhiteSpace(from), 'g'); @@ -467,7 +481,7 @@ var result = {}; for (var prop in this) { - if (!this.hasOwnProperty(prop) || prop == 'include' || prop == 'contains' || prop == 'reverse') continue; + if (!this.hasOwnProperty(prop) || ~_s.words('include contains reverse').indexOf(prop)) continue; result[prop] = this[prop]; } @@ -475,7 +489,6 @@ }, repeat: strRepeat - }; // Aliases @@ -501,19 +514,12 @@ define('underscore.string', function() { return _s; }); - - // Integrate with Underscore.js - } else if (typeof root._ !== 'undefined') { - // root._.mixin(_s); - root._.string = _s; - root._.str = root._.string; - - // Or define it + } else { - root._ = { - string: _s, - str: _s - }; + // Integrate with Underscore.js if defined + // or create our own underscore object. + root._ = root._ || {}; + root._.string = root._.str = _s; } }(this || window)); diff --git a/node/node_modules/grunt/node_modules/underscore.string/package.json b/node/node_modules/grunt/node_modules/underscore.string/package.json index af696ca77..ffccdacc3 100644 --- a/node/node_modules/grunt/node_modules/underscore.string/package.json +++ b/node/node_modules/grunt/node_modules/underscore.string/package.json @@ -1,6 +1,6 @@ { "name": "underscore.string", - "version": "2.1.1", + "version": "2.2.0rc", "description": "String manipulation extensions for Underscore.js javascript library.", "homepage": "http://epeli.github.com/underscore.string/", "contributors": [ @@ -65,8 +65,8 @@ "type": "MIT" } ], - "readme": "# Underscore.string [![Build Status](https://secure.travis-ci.org/epeli/underscore.string.png?branch=master)](http://travis-ci.org/epeli/underscore.string) #\n\n\n\nJavascript lacks complete string manipulation operations.\nThis an attempt to fill that gap. List of build-in methods can be found\nfor example from [Dive Into JavaScript][d].\n\n[d]: http://www.diveintojavascript.com/core-javascript-reference/the-string-object\n\n\nAs name states this an extension for [Underscore.js][u], but it can be used\nindependently from **_s**-global variable. But with Underscore.js you can\nuse Object-Oriented style and chaining:\n\n[u]: http://documentcloud.github.com/underscore/\n\n```javascript\n_(\" epeli \").chain().trim().capitalize().value()\n=> \"Epeli\"\n```\n\n## Download ##\n\n * [Development version](https://raw.github.com/epeli/underscore.string/master/lib/underscore.string.js) *Uncompressed with Comments 18kb*\n * [Production version](https://github.com/epeli/underscore.string/raw/master/dist/underscore.string.min.js) *Minified 7kb*\n\n\n## Node.js installation ##\n\n**npm package**\n\n npm install underscore.string\n\n**Standalone usage**:\n\n```javascript\nvar _s = require('underscore.string');\n```\n\n**Integrate with Underscore.js**:\n\n```javascript\nvar _ = require('underscore');\n\n// Import Underscore.string to separate object, because there are conflict functions (include, reverse, contains)\n_.str = require('underscore.string');\n\n// Mix in non-conflict functions to Underscore namespace if you want\n_.mixin(_.str.exports());\n\n// All functions, include conflict, will be available through _.str object\n_.str.include('Underscore.string', 'string'); // => true\n```\n\n## String Functions ##\n\nFor availability of functions in this way you need to mix in Underscore.string functions:\n\n```javascript\n_.mixin(_.string.exports());\n```\n\notherwise functions from examples will be available through _.string or _.str objects:\n\n```javascript\n_.str.capitalize('epeli')\n=> \"Epeli\"\n```\n\n**capitalize** _.capitalize(string)\n\nConverts first letter of the string to uppercase and the rest of the string to lower case.\n\n```javascript\n_.capitalize(\"foo Bar\")\n=> \"Foo bar\"\n```\n\n**chop** _.chop(string, step)\n\n```javascript\n_.chop('whitespace', 3)\n=> ['whi','tes','pac','e']\n```\n\n**clean** _.clean(str)\n\nCompress some whitespaces to one.\n\n```javascript\n_.clean(\" foo bar \")\n=> 'foo bar'\n```\n\n**chars** _.chars(str)\n\n```javascript\n_.chars('Hello')\n=> ['H','e','l','l','o']\n```\n\n**includes** _.includes(string, substring)\n\nTests if string contains a substring.\n\n```javascript\n_.includes(\"foobar\", \"ob\")\n=> true\n```\n\n**include** available only through _.str object, because Underscore has function with the same name.\n\n```javascript\n_.str.include(\"foobar\", \"ob\")\n=> true\n```\n\n**includes** function was removed\n\nBut you can create it in this way, for compatibility with previous versions:\n\n```javascript\n_.includes = _.str.include\n```\n\n**count** _.count(string, substring)\n\n```javascript\n_('Hello world').count('l')\n=> 3\n```\n\n**escapeHTML** _.escapeHTML(string)\n\nConverts HTML special characters to their entity equivalents.\n\n```javascript\n_('
        Blah blah blah
        ').escapeHTML();\n=> '<div>Blah blah blah</div>'\n```\n\n**unescapeHTML** _.unescapeHTML(string)\n\nConverts entity characters to HTML equivalents.\n\n```javascript\n_('<div>Blah blah blah</div>').unescapeHTML();\n=> '
        Blah blah blah
        '\n```\n\n**insert** _.insert(string, index, substing)\n\n```javascript\n_('Hello ').insert(6, 'world')\n=> 'Hello world'\n```\n\n**isBlank** _.isBlank(string)\n\n```javascript\n_('').isBlank(); // => true\n_('\\n').isBlank(); // => true\n_(' ').isBlank(); // => true\n_('a').isBlank(); // => false\n```\n\n**join** _.join(separator, *strings)\n\nJoins strings together with given separator\n\n```javascript\n_.join(\" \", \"foo\", \"bar\")\n=> \"foo bar\"\n```\n\n**lines** _.lines(str)\n\n```javascript\n_.lines(\"Hello\\nWorld\")\n=> [\"Hello\", \"World\"]\n```\n\n**reverse** available only through _.str object, because Underscore has function with the same name.\n\nReturn reversed string:\n\n```javascript\n_.str.reverse(\"foobar\")\n=> 'raboof'\n```\n\n**splice** _.splice(string, index, howmany, substring)\n\nLike a array splice.\n\n```javascript\n_('https://edtsech@bitbucket.org/edtsech/underscore.strings').splice(30, 7, 'epeli')\n=> 'https://edtsech@bitbucket.org/epeli/underscore.strings'\n```\n\n**startsWith** _.startsWith(string, starts)\n\nThis method checks whether string starts with starts.\n\n```javascript\n_(\"image.gif\").startsWith(\"image\")\n=> true\n```\n\n**endsWith** _.endsWith(string, ends)\n\nThis method checks whether string ends with ends.\n\n```javascript\n_(\"image.gif\").endsWith(\"gif\")\n=> true\n```\n\n**succ** _.succ(str)\n\nReturns the successor to str.\n\n```javascript\n_('a').succ()\n=> 'b'\n\n_('A').succ()\n=> 'B'\n```\n\n**supplant**\n\nSupplant function was removed, use Underscore.js [template function][p].\n\n[p]: http://documentcloud.github.com/underscore/#template\n\n**strip** alias for *trim*\n\n**lstrip** alias for *ltrim*\n\n**rstrip** alias for *rtrim*\n\n**titleize** _.titleize(string)\n\n```javascript\n_('my name is epeli').titleize()\n=> 'My Name Is Epeli'\n```\n\n**camelize** _.camelize(string)\n\nConverts underscored or dasherized string to a camelized one\n\n```javascript\n_('-moz-transform').camelize()\n=> 'MozTransform'\n```\n\n**classify** _.classify(string)\n\nConverts string to camelized class name\n\n```javascript\n_('some_class_name').classify()\n=> 'SomeClassName'\n```\n\n**underscored** _.underscored(string)\n\nConverts a camelized or dasherized string into an underscored one\n\n```javascript\n_('MozTransform').underscored()\n=> 'moz_transform'\n```\n\n**dasherize** _.dasherize(string)\n\nConverts a underscored or camelized string into an dasherized one\n\n```javascript\n_('MozTransform').dasherize()\n=> '-moz-transform'\n```\n\n**humanize** _.humanize(string)\n\nConverts an underscored, camelized, or dasherized string into a humanized one.\nAlso removes beginning and ending whitespace, and removes the postfix '_id'.\n\n```javascript\n_(' capitalize dash-CamelCase_underscore trim ').humanize()\n=> 'Capitalize dash camel case underscore trim'\n```\n\n**trim** _.trim(string, [characters])\n\ntrims defined characters from begining and ending of the string.\nDefaults to whitespace characters.\n\n```javascript\n_.trim(\" foobar \")\n=> \"foobar\"\n\n_.trim(\"_-foobar-_\", \"_-\")\n=> \"foobar\"\n```\n\n\n**ltrim** _.ltrim(string, [characters])\n\nLeft trim. Similar to trim, but only for left side.\n\n\n**rtrim** _.rtrim(string, [characters])\n\nRight trim. Similar to trim, but only for right side.\n\n**truncate** _.truncate(string, length, truncateString)\n\n```javascript\n_('Hello world').truncate(5)\n=> 'Hello...'\n\n_('Hello').truncate(10)\n=> 'Hello'\n```\n\n**prune** _.prune(string, length, pruneString)\n\nElegant version of truncate.\nMakes sure the pruned string does not exceed the original length.\nAvoid half-chopped words when truncating.\n\n```javascript\n_('Hello, world').prune(5)\n=> 'Hello...'\n\n_('Hello, world').prune(8)\n=> 'Hello...'\n\n_('Hello, world').prune(5, ' (read a lot more)')\n=> 'Hello, world' (as adding \"(read a lot more)\" would be longer than the original string)\n\n_('Hello, cruel world').prune(15)\n=> 'Hello, cruel...'\n\n_('Hello').prune(10)\n=> 'Hello'\n```\n\n**words** _.words(str, delimiter=\" \")\n\nSplit string by delimiter (String or RegExp), ' ' by default.\n\n```javascript\n_.words(\"I love you\")\n=> [\"I\",\"love\",\"you\"]\n\n_.words(\"I_love_you\", \"_\")\n=> [\"I\",\"love\",\"you\"]\n\n_.words(\"I-love-you\", /-/)\n=> [\"I\",\"love\",\"you\"]\n```\n\n**sprintf** _.sprintf(string format, *arguments)\n\nC like string formatting.\nCredits goes to [Alexandru Marasteanu][o].\nFor more detailed documentation, see the [original page][o].\n\n[o]: http://www.diveintojavascript.com/projects/sprintf-for-javascript\n\n```javascript\n_.sprintf(\"%.1f\", 1.17)\n\"1.2\"\n```\n\n**pad** _.pad(str, length, [padStr, type])\n\npads the `str` with characters until the total string length is equal to the passed `length` parameter. By default, pads on the **left** with the space char (`\" \"`). `padStr` is truncated to a single character if necessary.\n\n```javascript\n_.pad(\"1\", 8)\n-> \" 1\";\n\n_.pad(\"1\", 8, '0')\n-> \"00000001\";\n\n_.pad(\"1\", 8, '0', 'right')\n-> \"10000000\";\n\n_.pad(\"1\", 8, '0', 'both')\n-> \"00001000\";\n\n_.pad(\"1\", 8, 'bleepblorp', 'both')\n-> \"bbbb1bbb\";\n```\n\n**lpad** _.lpad(str, length, [padStr])\n\nleft-pad a string. Alias for `pad(str, length, padStr, 'left')`\n\n```javascript\n_.lpad(\"1\", 8, '0')\n-> \"00000001\";\n```\n\n**rpad** _.rpad(str, length, [padStr])\n\nright-pad a string. Alias for `pad(str, length, padStr, 'right')`\n\n```javascript\n_.rpad(\"1\", 8, '0')\n-> \"10000000\";\n```\n\n**lrpad** _.lrpad(str, length, [padStr])\n\nleft/right-pad a string. Alias for `pad(str, length, padStr, 'both')`\n\n```javascript\n_.lrpad(\"1\", 8, '0')\n-> \"00001000\";\n```\n\n**center** alias for **lrpad**\n\n**ljust** alias for *rpad*\n\n**rjust** alias for *lpad*\n\n**toNumber** _.toNumber(string, [decimals])\n\nParse string to number. Returns NaN if string can't be parsed to number.\n\n```javascript\n_('2.556').toNumber()\n=> 3\n\n_('2.556').toNumber(1)\n=> 2.6\n```\n\n**strRight** _.strRight(string, pattern)\n\nSearches a string from left to right for a pattern and returns a substring consisting of the characters in the string that are to the right of the pattern or all string if no match found.\n\n```javascript\n_('This_is_a_test_string').strRight('_')\n=> \"is_a_test_string\";\n```\n\n**strRightBack** _.strRightBack(string, pattern)\n\nSearches a string from right to left for a pattern and returns a substring consisting of the characters in the string that are to the right of the pattern or all string if no match found.\n\n```javascript\n_('This_is_a_test_string').strRightBack('_')\n=> \"string\";\n```\n\n**strLeft** _.strLeft(string, pattern)\n\nSearches a string from left to right for a pattern and returns a substring consisting of the characters in the string that are to the left of the pattern or all string if no match found.\n\n```javascript\n_('This_is_a_test_string').strLeft('_')\n=> \"This\";\n```\n\n**strLeftBack** _.strLeftBack(string, pattern)\n\nSearches a string from right to left for a pattern and returns a substring consisting of the characters in the string that are to the left of the pattern or all string if no match found.\n\n```javascript\n_('This_is_a_test_string').strLeftBack('_')\n=> \"This_is_a_test\";\n```\n\n**stripTags**\n\nRemoves all html tags from string.\n\n```javascript\n_('a link').stripTags()\n=> 'a link'\n\n_('a link').stripTags()\n=> 'a linkalert(\"hello world!\")'\n```\n\n**toSentence** _.toSentence(array, [delimiter, lastDelimiter])\n\nJoin an array into a human readable sentence.\n\n```javascript\n_.toSentence(['jQuery', 'Mootools', 'Prototype'])\n=> 'jQuery, Mootools and Prototype';\n\n_.toSentence(['jQuery', 'Mootools', 'Prototype'], ', ', ' unt ')\n=> 'jQuery, Mootools unt Prototype';\n```\n\n**repeat** _.repeat(string, count, [separator])\n\nRepeats a string count times.\n\n```javascript\n_.repeat(\"foo\", 3)\n=> 'foofoofoo';\n\n_.repeat(\"foo\", 3, \"bar\")\n=> 'foobarfoobarfoo'\n```\n\n**slugify** _.slugify(string)\n\nTransform text into a URL slug. Replaces whitespaces, accentuated, and special characters with a dash.\n\n```javascript\n_.slugify(\"Un éléphant à l'orée du bois\")\n=> 'un-elephant-a-loree-du-bois';\n```\n\n***Caution: this function is charset dependent***\n\n## Roadmap ##\n\nAny suggestions or bug reports are welcome. Just email me or more preferably open an issue.\n\n## Changelog ##\n\n### 2.0.0 ###\n\n* Added prune, humanize functions\n* Added _.string (_.str) namespace for Underscore.string library\n* Removed includes function\n\n#### Problems\n\nWe lose two things for `include` and `reverse` methods from `_.string`:\n\n* Calls like `_('foobar').include('bar')` aren't available;\n* Chaining isn't available too.\n\nBut if you need this functionality you can create aliases for conflict functions which will be convenient for you:\n\n```javascript\n_.mixin({\n includeString: _.str.include,\n reverseString: _.str.reverse\n})\n\n// Now wrapper calls and chaining are available.\n_('foobar').chain().reverseString().includeString('rab').value()\n```\n\n#### Standalone Usage\n\nIf you are using Underscore.string without Underscore. You also have `_.string` namespace for it and `_.str` alias\nBut of course you can just reassign `_` variable with `_.string`\n\n```javascript\n_ = _.string\n```\n### 2.1.1###\n\n* Fixed words method bug\n* Added classify method\n\n### 2.1.0 ###\n\n* AMD support\n* Added toSentence method\n* Added slugify method\n* Lots of speed optimizations\n\n### 2.0.0 ###\n\nFor upgrading to this version you need to mix in Underscore.string library to Underscore object:\n\n```javascript\n_.mixin(_.string.exports());\n```\n\nand all non-conflict Underscore.string functions will be available through Underscore object.\nAlso function `includes` has been removed, you should replace this function by `_.str.include`\nor create alias `_.includes = _.str.include` and all your code will work fine.\n\n### 1.1.6 ###\n\n* Fixed reverse and truncate\n* Added isBlank, stripTags, inlude(alias for includes)\n* Added uglifier compression\n\n### 1.1.5 ###\n\n* Added strRight, strRightBack, strLeft, strLeftBack\n\n### 1.1.4 ###\n\n* Added pad, lpad, rpad, lrpad methods and aliases center, ljust, rjust\n* Integration with Underscore 1.1.6\n\n### 1.1.3 ###\n\n* Added methods: underscored, camelize, dasherize\n* Support newer version of npm\n\n### 1.1.2 ###\n\n* Created functions: lines, chars, words functions\n\n### 1.0.2 ###\n\n* Created integration test suite with underscore.js 1.1.4 (now it's absolutely compatible)\n* Removed 'reverse' function, because this function override underscore.js 'reverse'\n\n## Contribute ##\n\n* Fork & pull request. Don't forget about tests.\n* If you planning add some feature please create issue before.\n\nOtherwise changes will be rejected.\n\n## Contributors list ##\n\n* Esa-Matti Suuronen (),\n* Edward Tsech ,\n* Sasha Koss (),\n* Vladimir Dronnikov ,\n* Pete Kruckenberg (),\n* Paul Chavard (),\n* Ed Finkler ()\n* Pavel Pravosud \n* Anton Lindqvist ()\n\n## Licence ##\n\nThe MIT License\n\nCopyright (c) 2011 Esa-Matti Suuronen esa-matti@suuronen.org\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n", + "readme": "# Underscore.string [![Build Status](https://secure.travis-ci.org/epeli/underscore.string.png?branch=master)](http://travis-ci.org/epeli/underscore.string) #\n\n\n\nJavascript lacks complete string manipulation operations.\nThis an attempt to fill that gap. List of build-in methods can be found\nfor example from [Dive Into JavaScript][d].\n\n[d]: http://www.diveintojavascript.com/core-javascript-reference/the-string-object\n\n\nAs name states this an extension for [Underscore.js][u], but it can be used\nindependently from **_s**-global variable. But with Underscore.js you can\nuse Object-Oriented style and chaining:\n\n[u]: http://documentcloud.github.com/underscore/\n\n```javascript\n_(\" epeli \").chain().trim().capitalize().value()\n=> \"Epeli\"\n```\n\n## Download ##\n\n * [Development version](https://raw.github.com/epeli/underscore.string/master/lib/underscore.string.js) *Uncompressed with Comments 18kb*\n * [Production version](https://github.com/epeli/underscore.string/raw/master/dist/underscore.string.min.js) *Minified 7kb*\n\n\n## Node.js installation ##\n\n**npm package**\n\n npm install underscore.string\n\n**Standalone usage**:\n\n```javascript\nvar _s = require('underscore.string');\n```\n\n**Integrate with Underscore.js**:\n\n```javascript\nvar _ = require('underscore');\n\n// Import Underscore.string to separate object, because there are conflict functions (include, reverse, contains)\n_.str = require('underscore.string');\n\n// Mix in non-conflict functions to Underscore namespace if you want\n_.mixin(_.str.exports());\n\n// All functions, include conflict, will be available through _.str object\n_.str.include('Underscore.string', 'string'); // => true\n```\n\n## String Functions ##\n\nFor availability of functions in this way you need to mix in Underscore.string functions:\n\n```javascript\n_.mixin(_.string.exports());\n```\n\notherwise functions from examples will be available through _.string or _.str objects:\n\n```javascript\n_.str.capitalize('epeli')\n=> \"Epeli\"\n```\n\n**capitalize** _.capitalize(string)\n\nConverts first letter of the string to uppercase.\n\n```javascript\n_.capitalize(\"foo Bar\")\n=> \"Foo Bar\"\n```\n\n**chop** _.chop(string, step)\n\n```javascript\n_.chop('whitespace', 3)\n=> ['whi','tes','pac','e']\n```\n\n**clean** _.clean(str)\n\nCompress some whitespaces to one.\n\n```javascript\n_.clean(\" foo bar \")\n=> 'foo bar'\n```\n\n**chars** _.chars(str)\n\n```javascript\n_.chars('Hello')\n=> ['H','e','l','l','o']\n```\n\n**includes** _.includes(string, substring)\n\nTests if string contains a substring.\n\n```javascript\n_.includes(\"foobar\", \"ob\")\n=> true\n```\n\n**include** available only through _.str object, because Underscore has function with the same name.\n\n```javascript\n_.str.include(\"foobar\", \"ob\")\n=> true\n```\n\n**includes** function was removed\n\nBut you can create it in this way, for compatibility with previous versions:\n\n```javascript\n_.includes = _.str.include\n```\n\n**count** _.count(string, substring)\n\n```javascript\n_('Hello world').count('l')\n=> 3\n```\n\n**escapeHTML** _.escapeHTML(string)\n\nConverts HTML special characters to their entity equivalents.\n\n```javascript\n_('
        Blah blah blah
        ').escapeHTML();\n=> '<div>Blah blah blah</div>'\n```\n\n**unescapeHTML** _.unescapeHTML(string)\n\nConverts entity characters to HTML equivalents.\n\n```javascript\n_('<div>Blah blah blah</div>').unescapeHTML();\n=> '
        Blah blah blah
        '\n```\n\n**insert** _.insert(string, index, substing)\n\n```javascript\n_('Hello ').insert(6, 'world')\n=> 'Hello world'\n```\n\n**isBlank** _.isBlank(string)\n\n```javascript\n_('').isBlank(); // => true\n_('\\n').isBlank(); // => true\n_(' ').isBlank(); // => true\n_('a').isBlank(); // => false\n```\n\n**join** _.join(separator, *strings)\n\nJoins strings together with given separator\n\n```javascript\n_.join(\" \", \"foo\", \"bar\")\n=> \"foo bar\"\n```\n\n**lines** _.lines(str)\n\n```javascript\n_.lines(\"Hello\\nWorld\")\n=> [\"Hello\", \"World\"]\n```\n\n**reverse** available only through _.str object, because Underscore has function with the same name.\n\nReturn reversed string:\n\n```javascript\n_.str.reverse(\"foobar\")\n=> 'raboof'\n```\n\n**splice** _.splice(string, index, howmany, substring)\n\nLike a array splice.\n\n```javascript\n_('https://edtsech@bitbucket.org/edtsech/underscore.strings').splice(30, 7, 'epeli')\n=> 'https://edtsech@bitbucket.org/epeli/underscore.strings'\n```\n\n**startsWith** _.startsWith(string, starts)\n\nThis method checks whether string starts with starts.\n\n```javascript\n_(\"image.gif\").startsWith(\"image\")\n=> true\n```\n\n**endsWith** _.endsWith(string, ends)\n\nThis method checks whether string ends with ends.\n\n```javascript\n_(\"image.gif\").endsWith(\"gif\")\n=> true\n```\n\n**succ** _.succ(str)\n\nReturns the successor to str.\n\n```javascript\n_('a').succ()\n=> 'b'\n\n_('A').succ()\n=> 'B'\n```\n\n**supplant**\n\nSupplant function was removed, use Underscore.js [template function][p].\n\n[p]: http://documentcloud.github.com/underscore/#template\n\n**strip** alias for *trim*\n\n**lstrip** alias for *ltrim*\n\n**rstrip** alias for *rtrim*\n\n**titleize** _.titleize(string)\n\n```javascript\n_('my name is epeli').titleize()\n=> 'My Name Is Epeli'\n```\n\n**camelize** _.camelize(string)\n\nConverts underscored or dasherized string to a camelized one\n\n```javascript\n_('-moz-transform').camelize()\n=> 'MozTransform'\n```\n\n**classify** _.classify(string)\n\nConverts string to camelized class name\n\n```javascript\n_('some_class_name').classify()\n=> 'SomeClassName'\n```\n\n**underscored** _.underscored(string)\n\nConverts a camelized or dasherized string into an underscored one\n\n```javascript\n_('MozTransform').underscored()\n=> 'moz_transform'\n```\n\n**dasherize** _.dasherize(string)\n\nConverts a underscored or camelized string into an dasherized one\n\n```javascript\n_('MozTransform').dasherize()\n=> '-moz-transform'\n```\n\n**humanize** _.humanize(string)\n\nConverts an underscored, camelized, or dasherized string into a humanized one.\nAlso removes beginning and ending whitespace, and removes the postfix '_id'.\n\n```javascript\n_(' capitalize dash-CamelCase_underscore trim ').humanize()\n=> 'Capitalize dash camel case underscore trim'\n```\n\n**trim** _.trim(string, [characters])\n\ntrims defined characters from begining and ending of the string.\nDefaults to whitespace characters.\n\n```javascript\n_.trim(\" foobar \")\n=> \"foobar\"\n\n_.trim(\"_-foobar-_\", \"_-\")\n=> \"foobar\"\n```\n\n\n**ltrim** _.ltrim(string, [characters])\n\nLeft trim. Similar to trim, but only for left side.\n\n\n**rtrim** _.rtrim(string, [characters])\n\nRight trim. Similar to trim, but only for right side.\n\n**truncate** _.truncate(string, length, truncateString)\n\n```javascript\n_('Hello world').truncate(5)\n=> 'Hello...'\n\n_('Hello').truncate(10)\n=> 'Hello'\n```\n\n**prune** _.prune(string, length, pruneString)\n\nElegant version of truncate.\nMakes sure the pruned string does not exceed the original length.\nAvoid half-chopped words when truncating.\n\n```javascript\n_('Hello, world').prune(5)\n=> 'Hello...'\n\n_('Hello, world').prune(8)\n=> 'Hello...'\n\n_('Hello, world').prune(5, ' (read a lot more)')\n=> 'Hello, world' (as adding \"(read a lot more)\" would be longer than the original string)\n\n_('Hello, cruel world').prune(15)\n=> 'Hello, cruel...'\n\n_('Hello').prune(10)\n=> 'Hello'\n```\n\n**words** _.words(str, delimiter=\" \")\n\nSplit string by delimiter (String or RegExp), ' ' by default.\n\n```javascript\n_.words(\"I love you\")\n=> [\"I\",\"love\",\"you\"]\n\n_.words(\"I_love_you\", \"_\")\n=> [\"I\",\"love\",\"you\"]\n\n_.words(\"I-love-you\", /-/)\n=> [\"I\",\"love\",\"you\"]\n```\n\n**sprintf** _.sprintf(string format, *arguments)\n\nC like string formatting.\nCredits goes to [Alexandru Marasteanu][o].\nFor more detailed documentation, see the [original page][o].\n\n[o]: http://www.diveintojavascript.com/projects/sprintf-for-javascript\n\n```javascript\n_.sprintf(\"%.1f\", 1.17)\n\"1.2\"\n```\n\n**pad** _.pad(str, length, [padStr, type])\n\npads the `str` with characters until the total string length is equal to the passed `length` parameter. By default, pads on the **left** with the space char (`\" \"`). `padStr` is truncated to a single character if necessary.\n\n```javascript\n_.pad(\"1\", 8)\n-> \" 1\";\n\n_.pad(\"1\", 8, '0')\n-> \"00000001\";\n\n_.pad(\"1\", 8, '0', 'right')\n-> \"10000000\";\n\n_.pad(\"1\", 8, '0', 'both')\n-> \"00001000\";\n\n_.pad(\"1\", 8, 'bleepblorp', 'both')\n-> \"bbbb1bbb\";\n```\n\n**lpad** _.lpad(str, length, [padStr])\n\nleft-pad a string. Alias for `pad(str, length, padStr, 'left')`\n\n```javascript\n_.lpad(\"1\", 8, '0')\n-> \"00000001\";\n```\n\n**rpad** _.rpad(str, length, [padStr])\n\nright-pad a string. Alias for `pad(str, length, padStr, 'right')`\n\n```javascript\n_.rpad(\"1\", 8, '0')\n-> \"10000000\";\n```\n\n**lrpad** _.lrpad(str, length, [padStr])\n\nleft/right-pad a string. Alias for `pad(str, length, padStr, 'both')`\n\n```javascript\n_.lrpad(\"1\", 8, '0')\n-> \"00001000\";\n```\n\n**center** alias for **lrpad**\n\n**ljust** alias for *rpad*\n\n**rjust** alias for *lpad*\n\n**toNumber** _.toNumber(string, [decimals])\n\nParse string to number. Returns NaN if string can't be parsed to number.\n\n```javascript\n_('2.556').toNumber()\n=> 3\n\n_('2.556').toNumber(1)\n=> 2.6\n```\n\n**strRight** _.strRight(string, pattern)\n\nSearches a string from left to right for a pattern and returns a substring consisting of the characters in the string that are to the right of the pattern or all string if no match found.\n\n```javascript\n_('This_is_a_test_string').strRight('_')\n=> \"is_a_test_string\";\n```\n\n**strRightBack** _.strRightBack(string, pattern)\n\nSearches a string from right to left for a pattern and returns a substring consisting of the characters in the string that are to the right of the pattern or all string if no match found.\n\n```javascript\n_('This_is_a_test_string').strRightBack('_')\n=> \"string\";\n```\n\n**strLeft** _.strLeft(string, pattern)\n\nSearches a string from left to right for a pattern and returns a substring consisting of the characters in the string that are to the left of the pattern or all string if no match found.\n\n```javascript\n_('This_is_a_test_string').strLeft('_')\n=> \"This\";\n```\n\n**strLeftBack** _.strLeftBack(string, pattern)\n\nSearches a string from right to left for a pattern and returns a substring consisting of the characters in the string that are to the left of the pattern or all string if no match found.\n\n```javascript\n_('This_is_a_test_string').strLeftBack('_')\n=> \"This_is_a_test\";\n```\n\n**stripTags**\n\nRemoves all html tags from string.\n\n```javascript\n_('a link').stripTags()\n=> 'a link'\n\n_('a link').stripTags()\n=> 'a linkalert(\"hello world!\")'\n```\n\n**toSentence** _.toSentence(array, [delimiter, lastDelimiter])\n\nJoin an array into a human readable sentence.\n\n```javascript\n_.toSentence(['jQuery', 'Mootools', 'Prototype'])\n=> 'jQuery, Mootools and Prototype';\n\n_.toSentence(['jQuery', 'Mootools', 'Prototype'], ', ', ' unt ')\n=> 'jQuery, Mootools unt Prototype';\n```\n\n**repeat** _.repeat(string, count, [separator])\n\nRepeats a string count times.\n\n```javascript\n_.repeat(\"foo\", 3)\n=> 'foofoofoo';\n\n_.repeat(\"foo\", 3, \"bar\")\n=> 'foobarfoobarfoo'\n```\n\n**slugify** _.slugify(string)\n\nTransform text into a URL slug. Replaces whitespaces, accentuated, and special characters with a dash.\n\n```javascript\n_.slugify(\"Un éléphant à l'orée du bois\")\n=> 'un-elephant-a-loree-du-bois';\n```\n\n***Caution: this function is charset dependent***\n\n## Roadmap ##\n\nAny suggestions or bug reports are welcome. Just email me or more preferably open an issue.\n\n## Changelog ##\n\n### 2.0.0 ###\n\n* Added prune, humanize functions\n* Added _.string (_.str) namespace for Underscore.string library\n* Removed includes function\n\n#### Problems\n\nWe lose two things for `include` and `reverse` methods from `_.string`:\n\n* Calls like `_('foobar').include('bar')` aren't available;\n* Chaining isn't available too.\n\nBut if you need this functionality you can create aliases for conflict functions which will be convenient for you:\n\n```javascript\n_.mixin({\n includeString: _.str.include,\n reverseString: _.str.reverse\n})\n\n// Now wrapper calls and chaining are available.\n_('foobar').chain().reverseString().includeString('rab').value()\n```\n\n#### Standalone Usage\n\nIf you are using Underscore.string without Underscore. You also have `_.string` namespace for it and `_.str` alias\nBut of course you can just reassign `_` variable with `_.string`\n\n```javascript\n_ = _.string\n```\n### 2.2.0 ###\n\n* Capitalize method behavior changed\n* Various perfomance tweaks\n\n### 2.1.1###\n\n* Fixed words method bug\n* Added classify method\n\n### 2.1.0 ###\n\n* AMD support\n* Added toSentence method\n* Added slugify method\n* Lots of speed optimizations\n\n### 2.0.0 ###\n\nFor upgrading to this version you need to mix in Underscore.string library to Underscore object:\n\n```javascript\n_.mixin(_.string.exports());\n```\n\nand all non-conflict Underscore.string functions will be available through Underscore object.\nAlso function `includes` has been removed, you should replace this function by `_.str.include`\nor create alias `_.includes = _.str.include` and all your code will work fine.\n\n### 1.1.6 ###\n\n* Fixed reverse and truncate\n* Added isBlank, stripTags, inlude(alias for includes)\n* Added uglifier compression\n\n### 1.1.5 ###\n\n* Added strRight, strRightBack, strLeft, strLeftBack\n\n### 1.1.4 ###\n\n* Added pad, lpad, rpad, lrpad methods and aliases center, ljust, rjust\n* Integration with Underscore 1.1.6\n\n### 1.1.3 ###\n\n* Added methods: underscored, camelize, dasherize\n* Support newer version of npm\n\n### 1.1.2 ###\n\n* Created functions: lines, chars, words functions\n\n### 1.0.2 ###\n\n* Created integration test suite with underscore.js 1.1.4 (now it's absolutely compatible)\n* Removed 'reverse' function, because this function override underscore.js 'reverse'\n\n## Contribute ##\n\n* Fork & pull request. Don't forget about tests.\n* If you planning add some feature please create issue before.\n\nOtherwise changes will be rejected.\n\n## Contributors list ##\n\n* Esa-Matti Suuronen (),\n* Edward Tsech ,\n* Sasha Koss (),\n* Vladimir Dronnikov ,\n* Pete Kruckenberg (),\n* Paul Chavard (),\n* Ed Finkler ()\n* Pavel Pravosud \n* Anton Lindqvist ()\n\n## Licence ##\n\nThe MIT License\n\nCopyright (c) 2011 Esa-Matti Suuronen esa-matti@suuronen.org\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n", "readmeFilename": "README.markdown", - "_id": "underscore.string@2.1.1", - "_from": "underscore.string@~2.1.1" + "_id": "underscore.string@2.2.0rc", + "_from": "underscore.string@~2.2.0rc" } diff --git a/node/node_modules/grunt/node_modules/underscore.string/test/strings.js b/node/node_modules/grunt/node_modules/underscore.string/test/strings.js index c9df79ea1..f700abf10 100644 --- a/node/node_modules/grunt/node_modules/underscore.string/test/strings.js +++ b/node/node_modules/grunt/node_modules/underscore.string/test/strings.js @@ -63,6 +63,7 @@ $(document).ready(function() { test("Strings: capitalize", function() { equals(_("fabio").capitalize(), "Fabio", 'First letter is upper case'); equals(_.capitalize("fabio"), "Fabio", 'First letter is upper case'); + equals(_.capitalize('FOO'), 'FOO', 'Other letters unchanged'); equals(_(123).capitalize(), "123", "Non string"); }); @@ -141,6 +142,11 @@ $(document).ready(function() { ok(_('whitespace').chop()[0].length === 10, "output ['whitespace']"); ok(_(12345).chop(1).length === 5, "output ['1','2','3','4','5']"); }); + + test('String: clean', function(){ + equals(_.clean(' foo bar '), 'foo bar'); + equals(_.clean(1), '1'); + }); test('String: count', function(){ equals(_('Hello world').count('l'), 3); @@ -206,8 +212,21 @@ $(document).ready(function() { equals(_('foo$bar').dasherize(), 'foo$bar'); equals(_(123).dasherize(), '123'); }); + + test('String: camelize', function(){ + equals(_.camelize('-moz-transform'), 'MozTransform'); + equals(_.camelize('webkit-transform'), 'webkitTransform'); + equals(_.camelize('under_scored'), 'underScored'); + equals(_.camelize(' with spaces'), 'withSpaces'); + }); + + test('String: join', function(){ + equals(_.join(1, 2, 3, 4), '21314'); + equals(_.join('|', 'foo', 'bar', 'baz'), 'foo|bar|baz'); + }); test('String: classify', function(){ + equals(_.classify(1), '1'); equals(_('some_class_name').classify(), 'SomeClassName'); }); @@ -266,6 +285,15 @@ $(document).ready(function() { equals(_('<div>Blah & "blah" & 'blah'</div>').unescapeHTML(), '
        Blah & "blah" & \'blah\'
        '); equals(_('&lt;').unescapeHTML(), '<'); + equals(_(''').unescapeHTML(), "'"); + equals(_(''').unescapeHTML(), "'"); + equals(_('J').unescapeHTML(), "J"); + equals(_('J').unescapeHTML(), "J"); + equals(_('J').unescapeHTML(), "J"); + equals(_('&_#39;').unescapeHTML(), "&_#39;"); + equals(_(''_;').unescapeHTML(), "'_;"); + equals(_('&#38;').unescapeHTML(), "&"); + equals(_('&amp;').unescapeHTML(), "&"); equals(_(5).unescapeHTML(), '5'); // equals(_(undefined).unescapeHTML(), ''); }); @@ -327,8 +355,9 @@ $(document).ready(function() { test('String: toNumber', function() { deepEqual(_("not a number").toNumber(), Number.NaN); - equals(_(0).toNumber(), 0); - equals(_("0").toNumber(), 0); + equals(_(0).toNumber(), 0); + equals(_("0").toNumber(), 0); + equals(_("0000").toNumber(), 0); equals(_("2.345").toNumber(), 2); equals(_("2.345").toNumber(NaN), 2); equals(_("2.345").toNumber(2), 2.35); diff --git a/node/node_modules/grunt/node_modules/underscore/.npmignore b/node/node_modules/grunt/node_modules/underscore/.npmignore deleted file mode 100644 index 2ce268489..000000000 --- a/node/node_modules/grunt/node_modules/underscore/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -test/ -Rakefile -docs/ \ No newline at end of file diff --git a/node/node_modules/grunt/node_modules/underscore/README b/node/node_modules/grunt/node_modules/underscore/README deleted file mode 100644 index ba19f1d70..000000000 --- a/node/node_modules/grunt/node_modules/underscore/README +++ /dev/null @@ -1,19 +0,0 @@ - __ - /\ \ - __ __ ___ \_\ \ __ _ __ ____ ___ ___ _ __ __ -/\ \/\ \ /' _ `\ /'_ \ /'__`\/\ __\/ ,__\ / ___\ / __`\/\ __\/'__`\ -\ \ \_\ \/\ \/\ \/\ \ \ \/\ __/\ \ \//\__, `\/\ \__//\ \ \ \ \ \//\ __/ - \ \____/\ \_\ \_\ \___,_\ \____\\ \_\\/\____/\ \____\ \____/\ \_\\ \____\ - \/___/ \/_/\/_/\/__,_ /\/____/ \/_/ \/___/ \/____/\/___/ \/_/ \/____/ - - - -Underscore.js is a utility-belt library for JavaScript that provides -support for the usual functional suspects (each, map, reduce, filter...) -without extending any core JavaScript objects. - -For Docs, License, Tests, and pre-packed downloads, see: -http://documentcloud.github.com/underscore/ - -Many thanks to our contributors: -https://github.com/documentcloud/underscore/contributors diff --git a/node/node_modules/grunt/node_modules/underscore/index.html b/node/node_modules/grunt/node_modules/underscore/index.html deleted file mode 100644 index ebcb46603..000000000 --- a/node/node_modules/grunt/node_modules/underscore/index.html +++ /dev/null @@ -1,1919 +0,0 @@ - - - - - - Underscore.js - - - - - - -
        - -

        - Underscore.js -

        - -

        - Underscore is a - utility-belt library for JavaScript that provides a lot of the - functional programming support that you would expect in - Prototype.js - (or Ruby), - but without extending any of the built-in JavaScript objects. It's the - tie to go along with jQuery's tux, - and Backbone.js's suspenders. -

        - -

        - Underscore provides 60-odd functions that support both the usual - functional suspects: map, select, invoke — - as well as more specialized helpers: function binding, javascript - templating, deep equality testing, and so on. It delegates to built-in - functions, if present, so modern browsers will use the - native implementations of forEach, map, reduce, - filter, every, some and indexOf. -

        - -

        - A complete Test & Benchmark Suite - is included for your perusal. -

        - -

        - You may also read through the annotated source code. -

        - -

        - The project is - hosted on GitHub. - You can report bugs and discuss features on the - issues page, - on Freenode in the #documentcloud channel, - or send tweets to @documentcloud. -

        - -

        - Underscore is an open-source component of DocumentCloud. -

        - -

        Downloads (Right-click, and use "Save As")

        - - - - - - - - - - -
        Development Version (1.2.4)34kb, Uncompressed with Comments
        Production Version (1.2.4)< 4kb, Minified and Gzipped
        - -
        - -

        Collection Functions (Arrays or Objects)

        - -

        - each_.each(list, iterator, [context]) - Alias: forEach -
        - Iterates over a list of elements, yielding each in turn to an iterator - function. The iterator is bound to the context object, if one is - passed. Each invocation of iterator is called with three arguments: - (element, index, list). If list is a JavaScript object, iterator's - arguments will be (value, key, list). Delegates to the native - forEach function if it exists. -

        -
        -_.each([1, 2, 3], function(num){ alert(num); });
        -=> alerts each number in turn...
        -_.each({one : 1, two : 2, three : 3}, function(num, key){ alert(num); });
        -=> alerts each number in turn...
        - -

        - map_.map(list, iterator, [context]) -
        - Produces a new array of values by mapping each value in list - through a transformation function (iterator). If the native map method - exists, it will be used instead. If list is a JavaScript object, - iterator's arguments will be (value, key, list). -

        -
        -_.map([1, 2, 3], function(num){ return num * 3; });
        -=> [3, 6, 9]
        -_.map({one : 1, two : 2, three : 3}, function(num, key){ return num * 3; });
        -=> [3, 6, 9]
        - -

        - reduce_.reduce(list, iterator, memo, [context]) - Aliases: inject, foldl -
        - Also known as inject and foldl, reduce boils down a - list of values into a single value. Memo is the initial state - of the reduction, and each successive step of it should be returned by - iterator. -

        -
        -var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
        -=> 6
        -
        - -

        - reduceRight_.reduceRight(list, iterator, memo, [context]) - Alias: foldr -
        - The right-associative version of reduce. Delegates to the - JavaScript 1.8 version of reduceRight, if it exists. Foldr - is not as useful in JavaScript as it would be in a language with lazy - evaluation. -

        -
        -var list = [[0, 1], [2, 3], [4, 5]];
        -var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
        -=> [4, 5, 2, 3, 0, 1]
        -
        - -

        - find_.find(list, iterator, [context]) - Alias: detect -
        - Looks through each value in the list, returning the first one that - passes a truth test (iterator). The function returns as - soon as it finds an acceptable element, and doesn't traverse the - entire list. -

        -
        -var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
        -=> 2
        -
        - -

        - filter_.filter(list, iterator, [context]) - Alias: select -
        - Looks through each value in the list, returning an array of all - the values that pass a truth test (iterator). Delegates to the - native filter method, if it exists. -

        -
        -var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
        -=> [2, 4, 6]
        -
        - -

        - reject_.reject(list, iterator, [context]) -
        - Returns the values in list without the elements that the truth - test (iterator) passes. The opposite of filter. -

        -
        -var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
        -=> [1, 3, 5]
        -
        - -

        - all_.all(list, iterator, [context]) - Alias: every -
        - Returns true if all of the values in the list pass the iterator - truth test. Delegates to the native method every, if present. -

        -
        -_.all([true, 1, null, 'yes'], _.identity);
        -=> false
        -
        - -

        - any_.any(list, [iterator], [context]) - Alias: some -
        - Returns true if any of the values in the list pass the - iterator truth test. Short-circuits and stops traversing the list - if a true element is found. Delegates to the native method some, - if present. -

        -
        -_.any([null, 0, 'yes', false]);
        -=> true
        -
        - -

        - include_.include(list, value) - Alias: contains -
        - Returns true if the value is present in the list, using - === to test equality. Uses indexOf internally, if list - is an Array. -

        -
        -_.include([1, 2, 3], 3);
        -=> true
        -
        - -

        - invoke_.invoke(list, methodName, [*arguments]) -
        - Calls the method named by methodName on each value in the list. - Any extra arguments passed to invoke will be forwarded on to the - method invocation. -

        -
        -_.invoke([[5, 1, 7], [3, 2, 1]], 'sort');
        -=> [[1, 5, 7], [1, 2, 3]]
        -
        - -

        - pluck_.pluck(list, propertyName) -
        - A convenient version of what is perhaps the most common use-case for - map: extracting a list of property values. -

        -
        -var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
        -_.pluck(stooges, 'name');
        -=> ["moe", "larry", "curly"]
        -
        - -

        - max_.max(list, [iterator], [context]) -
        - Returns the maximum value in list. If iterator is passed, - it will be used on each value to generate the criterion by which the - value is ranked. -

        -
        -var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
        -_.max(stooges, function(stooge){ return stooge.age; });
        -=> {name : 'curly', age : 60};
        -
        - -

        - min_.min(list, [iterator], [context]) -
        - Returns the minimum value in list. If iterator is passed, - it will be used on each value to generate the criterion by which the - value is ranked. -

        -
        -var numbers = [10, 5, 100, 2, 1000];
        -_.min(numbers);
        -=> 2
        -
        - -

        - sortBy_.sortBy(list, iterator, [context]) -
        - Returns a sorted copy of list, ranked by the results of running - each value through iterator. -

        -
        -_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
        -=> [5, 4, 6, 3, 1, 2]
        -
        - -

        - groupBy_.groupBy(list, iterator) -
        - Splits a collection into sets, grouped by the result of running each - value through iterator. If iterator is a string instead of - a function, groups by the property named by iterator on each of - the values. -

        -
        -_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
        -=> {1: [1.3], 2: [2.1, 2.4]}
        -
        -_.groupBy(['one', 'two', 'three'], 'length');
        -=> {3: ["one", "two"], 5: ["three"]}
        -
        - -

        - sortedIndex_.sortedIndex(list, value, [iterator]) -
        - Uses a binary search to determine the index at which the value - should be inserted into the list in order to maintain the list's - sorted order. If an iterator is passed, it will be used to compute - the sort ranking of each value. -

        -
        -_.sortedIndex([10, 20, 30, 40, 50], 35);
        -=> 3
        -
        - -

        - shuffle_.shuffle(list) -
        - Returns a shuffled copy of the list, using a version of the - Fisher-Yates shuffle. -

        -
        -_.shuffle([1, 2, 3, 4, 5, 6]);
        -=> [4, 1, 6, 3, 5, 2]
        -
        - -

        - toArray_.toArray(list) -
        - Converts the list (anything that can be iterated over), into a - real Array. Useful for transmuting the arguments object. -

        -
        -(function(){ return _.toArray(arguments).slice(0); })(1, 2, 3);
        -=> [1, 2, 3]
        -
        - -

        - size_.size(list) -
        - Return the number of values in the list. -

        -
        -_.size({one : 1, two : 2, three : 3});
        -=> 3
        -
        - -

        Array Functions

        - -

        - Note: All array functions will also work on the arguments object. -

        - -

        - first_.first(array, [n]) - Alias: head -
        - Returns the first element of an array. Passing n will - return the first n elements of the array. -

        -
        -_.first([5, 4, 3, 2, 1]);
        -=> 5
        -
        - -

        - initial_.initial(array, [n]) -
        - Returns everything but the last entry of the array. Especially useful on - the arguments object. Pass n to exclude the last n elements - from the result. -

        -
        -_.initial([5, 4, 3, 2, 1]);
        -=> [5, 4, 3, 2]
        -
        - -

        - last_.last(array, [n]) -
        - Returns the last element of an array. Passing n will return - the last n elements of the array. -

        -
        -_.last([5, 4, 3, 2, 1]);
        -=> 1
        -
        - -

        - rest_.rest(array, [index]) - Alias: tail -
        - Returns the rest of the elements in an array. Pass an index - to return the values of the array from that index onward. -

        -
        -_.rest([5, 4, 3, 2, 1]);
        -=> [4, 3, 2, 1]
        -
        - -

        - compact_.compact(array) -
        - Returns a copy of the array with all falsy values removed. - In JavaScript, false, null, 0, "", - undefined and NaN are all falsy. -

        -
        -_.compact([0, 1, false, 2, '', 3]);
        -=> [1, 2, 3]
        -
        - -

        - flatten_.flatten(array) -
        - Flattens a nested array (the nesting can be to any depth). -

        -
        -_.flatten([1, [2], [3, [[[4]]]]]);
        -=> [1, 2, 3, 4];
        -
        - -

        - without_.without(array, [*values]) -
        - Returns a copy of the array with all instances of the values - removed. === is used for the equality test. -

        -
        -_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
        -=> [2, 3, 4]
        -
        - -

        - union_.union(*arrays) -
        - Computes the union of the passed-in arrays: the list of unique items, - in order, that are present in one or more of the arrays. -

        -
        -_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
        -=> [1, 2, 3, 101, 10]
        -
        - -

        - intersection_.intersection(*arrays) -
        - Computes the list of values that are the intersection of all the arrays. - Each value in the result is present in each of the arrays. -

        -
        -_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
        -=> [1, 2]
        -
        - -

        - difference_.difference(array, *others) -
        - Similar to without, but returns the values from array that - are not present in the other arrays. -

        -
        -_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
        -=> [1, 3, 4]
        -
        - -

        - uniq_.uniq(array, [isSorted], [iterator]) - Alias: unique -
        - Produces a duplicate-free version of the array, using === to test - object equality. If you know in advance that the array is sorted, - passing true for isSorted will run a much faster algorithm. - If you want to compute unique items based on a transformation, pass an - iterator function. -

        -
        -_.uniq([1, 2, 1, 3, 1, 4]);
        -=> [1, 2, 3, 4]
        -
        - -

        - zip_.zip(*arrays) -
        - Merges together the values of each of the arrays with the - values at the corresponding position. Useful when you have separate - data sources that are coordinated through matching array indexes. - If you're working with a matrix of nested arrays, zip.apply - can transpose the matrix in a similar fashion. -

        -
        -_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
        -=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
        -
        - -

        - indexOf_.indexOf(array, value, [isSorted]) -
        - Returns the index at which value can be found in the array, - or -1 if value is not present in the array. Uses the native - indexOf function unless it's missing. If you're working with a - large array, and you know that the array is already sorted, pass true - for isSorted to use a faster binary search. -

        -
        -_.indexOf([1, 2, 3], 2);
        -=> 1
        -
        - -

        - lastIndexOf_.lastIndexOf(array, value) -
        - Returns the index of the last occurrence of value in the array, - or -1 if value is not present. Uses the native lastIndexOf - function if possible. -

        -
        -_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
        -=> 4
        -
        - -

        - range_.range([start], stop, [step]) -
        - A function to create flexibly-numbered lists of integers, handy for - each and map loops. start, if omitted, defaults - to 0; step defaults to 1. Returns a list of integers - from start to stop, incremented (or decremented) by step, - exclusive. -

        -
        -_.range(10);
        -=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
        -_.range(1, 11);
        -=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        -_.range(0, 30, 5);
        -=> [0, 5, 10, 15, 20, 25]
        -_.range(0, -10, -1);
        -=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
        -_.range(0);
        -=> []
        -
        - -

        Function (uh, ahem) Functions

        - -

        - bind_.bind(function, object, [*arguments]) -
        - Bind a function to an object, meaning that whenever - the function is called, the value of this will be the object. - Optionally, bind arguments to the function to pre-fill them, - also known as partial application. -

        -
        -var func = function(greeting){ return greeting + ': ' + this.name };
        -func = _.bind(func, {name : 'moe'}, 'hi');
        -func();
        -=> 'hi: moe'
        -
        - -

        - bindAll_.bindAll(object, [*methodNames]) -
        - Binds a number of methods on the object, specified by - methodNames, to be run in the context of that object whenever they - are invoked. Very handy for binding functions that are going to be used - as event handlers, which would otherwise be invoked with a fairly useless - this. If no methodNames are provided, all of the object's - function properties will be bound to it. -

        -
        -var buttonView = {
        -  label   : 'underscore',
        -  onClick : function(){ alert('clicked: ' + this.label); },
        -  onHover : function(){ console.log('hovering: ' + this.label); }
        -};
        -_.bindAll(buttonView);
        -jQuery('#underscore_button').bind('click', buttonView.onClick);
        -=> When the button is clicked, this.label will have the correct value...
        -
        - -

        - memoize_.memoize(function, [hashFunction]) -
        - Memoizes a given function by caching the computed result. Useful - for speeding up slow-running computations. If passed an optional - hashFunction, it will be used to compute the hash key for storing - the result, based on the arguments to the original function. The default - hashFunction just uses the first argument to the memoized function - as the key. -

        -
        -var fibonacci = _.memoize(function(n) {
        -  return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
        -});
        -
        - -

        - delay_.delay(function, wait, [*arguments]) -
        - Much like setTimeout, invokes function after wait - milliseconds. If you pass the optional arguments, they will be - forwarded on to the function when it is invoked. -

        -
        -var log = _.bind(console.log, console);
        -_.delay(log, 1000, 'logged later');
        -=> 'logged later' // Appears after one second.
        -
        - -

        - defer_.defer(function) -
        - Defers invoking the function until the current call stack has cleared, - similar to using setTimeout with a delay of 0. Useful for performing - expensive computations or HTML rendering in chunks without blocking the UI thread - from updating. -

        -
        -_.defer(function(){ alert('deferred'); });
        -// Returns from the function before the alert runs.
        -
        - -

        - throttle_.throttle(function, wait) -
        - Creates and returns a new, throttled version of the passed function, - that, when invoked repeatedly, will only actually call the original function - at most once per every wait - milliseconds. Useful for rate-limiting events that occur faster than you - can keep up with. -

        -
        -var throttled = _.throttle(updatePosition, 100);
        -$(window).scroll(throttled);
        -
        - -

        - debounce_.debounce(function, wait) -
        - Creates and returns a new debounced version of the passed function that - will postpone its execution until after - wait milliseconds have elapsed since the last time it - was invoked. Useful for implementing behavior that should only happen - after the input has stopped arriving. For example: rendering a - preview of a Markdown comment, recalculating a layout after the window - has stopped being resized, and so on. -

        -
        -var lazyLayout = _.debounce(calculateLayout, 300);
        -$(window).resize(lazyLayout);
        -
        - -

        - once_.once(function) -
        - Creates a version of the function that can only be called one time. - Repeated calls to the modified function will have no effect, returning - the value from the original call. Useful for initialization functions, - instead of having to set a boolean flag and then check it later. -

        -
        -var initialize = _.once(createApplication);
        -initialize();
        -initialize();
        -// Application is only created once.
        -
        - -

        - after_.after(count, function) -
        - Creates a version of the function that will only be run after first - being called count times. Useful for grouping asynchronous responses, - where you want to be sure that all the async calls have finished, before - proceeding. -

        -
        -var renderNotes = _.after(notes.length, render);
        -_.each(notes, function(note) {
        -  note.asyncSave({success: renderNotes}); 
        -});
        -// renderNotes is run once, after all notes have saved.
        -
        - -

        - wrap_.wrap(function, wrapper) -
        - Wraps the first function inside of the wrapper function, - passing it as the first argument. This allows the wrapper to - execute code before and after the function runs, adjust the arguments, - and execute it conditionally. -

        -
        -var hello = function(name) { return "hello: " + name; };
        -hello = _.wrap(hello, function(func) {
        -  return "before, " + func("moe") + ", after";
        -});
        -hello();
        -=> 'before, hello: moe, after'
        -
        - -

        - compose_.compose(*functions) -
        - Returns the composition of a list of functions, where each function - consumes the return value of the function that follows. In math terms, - composing the functions f(), g(), and h() produces - f(g(h())). -

        -
        -var greet    = function(name){ return "hi: " + name; };
        -var exclaim  = function(statement){ return statement + "!"; };
        -var welcome = _.compose(exclaim, greet);
        -welcome('moe');
        -=> 'hi: moe!'
        -
        - -

        Object Functions

        - -

        - keys_.keys(object) -
        - Retrieve all the names of the object's properties. -

        -
        -_.keys({one : 1, two : 2, three : 3});
        -=> ["one", "two", "three"]
        -
        - -

        - values_.values(object) -
        - Return all of the values of the object's properties. -

        -
        -_.values({one : 1, two : 2, three : 3});
        -=> [1, 2, 3]
        -
        - -

        - functions_.functions(object) - Alias: methods -
        - Returns a sorted list of the names of every method in an object — - that is to say, the name of every function property of the object. -

        -
        -_.functions(_);
        -=> ["all", "any", "bind", "bindAll", "clone", "compact", "compose" ...
        -
        - -

        - extend_.extend(destination, *sources) -
        - Copy all of the properties in the source objects over to the - destination object. It's in-order, so the last source will override - properties of the same name in previous arguments. -

        -
        -_.extend({name : 'moe'}, {age : 50});
        -=> {name : 'moe', age : 50}
        -
        - -

        - defaults_.defaults(object, *defaults) -
        - Fill in missing properties in object with default values from the - defaults objects. As soon as the property is filled, further defaults - will have no effect. -

        -
        -var iceCream = {flavor : "chocolate"};
        -_.defaults(iceCream, {flavor : "vanilla", sprinkles : "lots"});
        -=> {flavor : "chocolate", sprinkles : "lots"}
        -
        - -

        - clone_.clone(object) -
        - Create a shallow-copied clone of the object. Any nested objects - or arrays will be copied by reference, not duplicated. -

        -
        -_.clone({name : 'moe'});
        -=> {name : 'moe'};
        -
        - -

        - tap_.tap(object, interceptor) -
        - Invokes interceptor with the object, and then returns object. - The primary purpose of this method is to "tap into" a method chain, in order to perform operations on intermediate results within the chain. -

        -
        -_.chain([1,2,3,200])
        -  .filter(function(num) { return num % 2 == 0; })
        -  .tap(console.log)
        -  .map(function(num) { return num * num })
        -  .value();
        -=> [2, 200]
        -=> [4, 40000]
        -
        - -

        - isEqual_.isEqual(object, other) -
        - Performs an optimized deep comparison between the two objects, to determine - if they should be considered equal. -

        -
        -var moe   = {name : 'moe', luckyNumbers : [13, 27, 34]};
        -var clone = {name : 'moe', luckyNumbers : [13, 27, 34]};
        -moe == clone;
        -=> false
        -_.isEqual(moe, clone);
        -=> true
        -
        - -

        - isEmpty_.isEmpty(object) -
        - Returns true if object contains no values. -

        -
        -_.isEmpty([1, 2, 3]);
        -=> false
        -_.isEmpty({});
        -=> true
        -
        - -

        - isElement_.isElement(object) -
        - Returns true if object is a DOM element. -

        -
        -_.isElement(jQuery('body')[0]);
        -=> true
        -
        - -

        - isArray_.isArray(object) -
        - Returns true if object is an Array. -

        -
        -(function(){ return _.isArray(arguments); })();
        -=> false
        -_.isArray([1,2,3]);
        -=> true
        -
        - -

        - isArguments_.isArguments(object) -
        - Returns true if object is an Arguments object. -

        -
        -(function(){ return _.isArguments(arguments); })(1, 2, 3);
        -=> true
        -_.isArguments([1,2,3]);
        -=> false
        -
        - -

        - isFunction_.isFunction(object) -
        - Returns true if object is a Function. -

        -
        -_.isFunction(alert);
        -=> true
        -
        - -

        - isString_.isString(object) -
        - Returns true if object is a String. -

        -
        -_.isString("moe");
        -=> true
        -
        - -

        - isNumber_.isNumber(object) -
        - Returns true if object is a Number (including NaN). -

        -
        -_.isNumber(8.4 * 5);
        -=> true
        -
        - -

        - isBoolean_.isBoolean(object) -
        - Returns true if object is either true or false. -

        -
        -_.isBoolean(null);
        -=> false
        -
        - -

        - isDate_.isDate(object) -
        - Returns true if object is a Date. -

        -
        -_.isDate(new Date());
        -=> true
        -
        - -

        - isRegExp_.isRegExp(object) -
        - Returns true if object is a RegExp. -

        -
        -_.isRegExp(/moe/);
        -=> true
        -
        - -

        - isNaN_.isNaN(object) -
        - Returns true if object is NaN.
        Note: this is not - the same as the native isNaN function, which will also return - true if the variable is undefined. -

        -
        -_.isNaN(NaN);
        -=> true
        -isNaN(undefined);
        -=> true
        -_.isNaN(undefined);
        -=> false
        -
        - -

        - isNull_.isNull(object) -
        - Returns true if the value of object is null. -

        -
        -_.isNull(null);
        -=> true
        -_.isNull(undefined);
        -=> false
        -
        - -

        - isUndefined_.isUndefined(variable) -
        - Returns true if variable is undefined. -

        -
        -_.isUndefined(window.missingVariable);
        -=> true
        -
        - -

        Utility Functions

        - -

        - noConflict_.noConflict() -
        - Give control of the "_" variable back to its previous owner. Returns - a reference to the Underscore object. -

        -
        -var underscore = _.noConflict();
        - -

        - identity_.identity(value) -
        - Returns the same value that is used as the argument. In math: - f(x) = x
        - This function looks useless, but is used throughout Underscore as - a default iterator. -

        -
        -var moe = {name : 'moe'};
        -moe === _.identity(moe);
        -=> true
        - -

        - times_.times(n, iterator) -
        - Invokes the given iterator function n times. -

        -
        -_(3).times(function(){ genie.grantWish(); });
        - -

        - mixin_.mixin(object) -
        - Allows you to extend Underscore with your own utility functions. Pass - a hash of {name: function} definitions to have your functions - added to the Underscore object, as well as the OOP wrapper. -

        -
        -_.mixin({
        -  capitalize : function(string) {
        -    return string.charAt(0).toUpperCase() + string.substring(1).toLowerCase();
        -  }
        -});
        -_("fabio").capitalize();
        -=> "Fabio"
        -
        - -

        - uniqueId_.uniqueId([prefix]) -
        - Generate a globally-unique id for client-side models or DOM elements - that need one. If prefix is passed, the id will be appended to it. -

        -
        -_.uniqueId('contact_');
        -=> 'contact_104'
        - -

        - escape_.escape(string) -
        - Escapes a string for insertion into HTML, replacing - &, <, >, ", ', and / characters. -

        -
        -_.escape('Curly, Larry & Moe');
        -=> "Curly, Larry &amp; Moe"
        - -

        - template_.template(templateString, [context]) -
        - Compiles JavaScript templates into functions that can be evaluated - for rendering. Useful for rendering complicated bits of HTML from JSON - data sources. Template functions can both interpolate variables, using
        - <%= … %>, as well as execute arbitrary JavaScript code, with - <% … %>. If you wish to interpolate a value, and have - it be HTML-escaped, use <%- … %> When you evaluate a template function, pass in a - context object that has properties corresponding to the template's free - variables. If you're writing a one-off, you can pass the context - object as the second parameter to template in order to render - immediately instead of returning a template function. -

        -
        -var compiled = _.template("hello: <%= name %>");
        -compiled({name : 'moe'});
        -=> "hello: moe"
        -
        -var list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
        -_.template(list, {people : ['moe', 'curly', 'larry']});
        -=> "<li>moe</li><li>curly</li><li>larry</li>"
        -
        -var template = _.template("<b><%- value %></b>");
        -template({value : '<script>'});
        -=> "<b>&lt;script&gt;</b>"
        - -

        - You can also use print from within JavaScript code. This is - sometimes more convenient than using <%= ... %>. -

        - -
        -var compiled = _.template("<% print('Hello ' + epithet); %>");
        -compiled({epithet: "stooge"});
        -=> "Hello stooge."
        - -

        - If ERB-style delimiters aren't your cup of tea, you can change Underscore's - template settings to use different symbols to set off interpolated code. - Define an interpolate regex to match expressions that should be - interpolated verbatim, an escape regex to match expressions that should - be inserted after being HTML escaped, and an evaluate regex to match - expressions that should be evaluated without insertion into the resulting - string. You may define or omit any combination of the three. - For example, to perform - Mustache.js - style templating: -

        - -
        -_.templateSettings = {
        -  interpolate : /\{\{(.+?)\}\}/g
        -};
        -
        -var template = _.template("Hello {{ name }}!");
        -template({name : "Mustache"});
        -=> "Hello Mustache!"
        - - -

        Chaining

        - -

        - You can use Underscore in either an object-oriented or a functional style, - depending on your preference. The following two lines of code are - identical ways to double a list of numbers. -

        - -
        -_.map([1, 2, 3], function(n){ return n * 2; });
        -_([1, 2, 3]).map(function(n){ return n * 2; });
        - -

        - Using the object-oriented style allows you to chain together methods. Calling - chain on a wrapped object will cause all future method calls to - return wrapped objects as well. When you've finished the computation, - use value to retrieve the final value. Here's an example of chaining - together a map/flatten/reduce, in order to get the word count of - every word in a song. -

        - -
        -var lyrics = [
        -  {line : 1, words : "I'm a lumberjack and I'm okay"},
        -  {line : 2, words : "I sleep all night and I work all day"},
        -  {line : 3, words : "He's a lumberjack and he's okay"},
        -  {line : 4, words : "He sleeps all night and he works all day"}
        -];
        -
        -_.chain(lyrics)
        -  .map(function(line) { return line.words.split(' '); })
        -  .flatten()
        -  .reduce(function(counts, word) {
        -    counts[word] = (counts[word] || 0) + 1;
        -    return counts;
        -}, {}).value();
        -
        -=> {lumberjack : 2, all : 4, night : 2 ... }
        - -

        - In addition, the - Array prototype's methods - are proxied through the chained Underscore object, so you can slip a - reverse or a push into your chain, and continue to - modify the array. -

        - -

        - chain_.chain(obj) -
        - Returns a wrapped object. Calling methods on this object will continue - to return wrapped objects until value is used. -

        -
        -var stooges = [{name : 'curly', age : 25}, {name : 'moe', age : 21}, {name : 'larry', age : 23}];
        -var youngest = _.chain(stooges)
        -  .sortBy(function(stooge){ return stooge.age; })
        -  .map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
        -  .first()
        -  .value();
        -=> "moe is 21"
        -
        - -

        - value_(obj).value() -
        - Extracts the value of a wrapped object. -

        -
        -_([1, 2, 3]).value();
        -=> [1, 2, 3]
        -
        - - - -

        - Underscore.lua, - a Lua port of the functions that are applicable in both languages. - Includes OOP-wrapping and chaining. - The source is - available on GitHub. -

        - -

        - Underscore.php, - a PHP port of the functions that are applicable in both languages. - Includes OOP-wrapping and chaining. - The source is - available on GitHub. -

        - -

        - Underscore-perl, - a Perl port of many of the Underscore.js functions, - aimed at on Perl hashes and arrays, also - available on GitHub. -

        - -

        - Underscore.string, - an Underscore extension that adds functions for string-manipulation: - trim, startsWith, contains, capitalize, - reverse, sprintf, and more. -

        - -

        - Ruby's Enumerable module. -

        - -

        - Prototype.js, which provides - JavaScript with collection functions in the manner closest to Ruby's Enumerable. -

        - -

        - Oliver Steele's - Functional JavaScript, - which includes comprehensive higher-order function support as well as string lambdas. -

        - -

        - Michael Aufreiter's Data.js, - a data manipulation + persistence library for JavaScript. -

        - -

        - Python's itertools. -

        - -

        Change Log

        - -

        - 1.2.4Jan. 4, 2012
        -

          -
        • - You now can (and probably should) write _.chain(list) - instead of _(list).chain(). -
        • -
        • - Fix for escaped characters in Underscore templates, and for supporting - customizations of _.templateSettings that only define one or - two of the required regexes. -
        • -
        • - Fix for passing an array as the first argument to an _.wrap'd function. -
        • -
        • - Improved compatibility with ClojureScript, which adds a call - function to String.prototype. -
        • -
        -

        - -

        - 1.2.3Dec. 7, 2011
        -

          -
        • - Dynamic scope is now preserved for compiled _.template functions, - so you can use the value of this if you like. -
        • -
        • - Sparse array support of _.indexOf, _.lastIndexOf. -
        • -
        • - Both _.reduce and _.reduceRight can now be passed an - explicitly undefined value. (There's no reason why you'd - want to do this.) -
        • -
        -

        - -

        - 1.2.2Nov. 14, 2011
        -

          -
        • - Continued tweaks to _.isEqual semantics. Now JS primitives are - considered equivalent to their wrapped versions, and arrays are compared - by their numeric properties only (#351). -
        • -
        • - _.escape no longer tries to be smart about not double-escaping - already-escaped HTML entities. Now it just escapes regardless (#350). -
        • -
        • - In _.template, you may now leave semicolons out of evaluated - statements if you wish: <% }) %> (#369). -
        • -
        • - _.after(callback, 0) will now trigger the callback immediately, - making "after" easier to use with asynchronous APIs (#366). -
        • -
        -

        - -

        - 1.2.1Oct. 24, 2011
        -

          -
        • - Several important bug fixes for _.isEqual, which should now - do better on mutated Arrays, and on non-Array objects with - length properties. (#329) -
        • -
        • - jrburke contributed Underscore exporting for AMD module loaders, - and tonylukasavage for Appcelerator Titanium. - (#335, #338) -
        • -
        • - You can now _.groupBy(list, 'property') as a shortcut for - grouping values by a particular common property. -
        • -
        • - _.throttle'd functions now fire immediately upon invocation, - and are rate-limited thereafter (#170, #266). -
        • -
        • - Most of the _.is[Type] checks no longer ducktype. -
        • -
        • - The _.bind function now also works on constructors, a-la - ES5 ... but you would never want to use _.bind on a - constructor function. -
        • -
        • - _.clone no longer wraps non-object types in Objects. -
        • -
        • - _.find and _.filter are now the preferred names for - _.detect and _.select. -
        • -
        -

        - -

        - 1.2.0Oct. 5, 2011
        -

          -
        • - The _.isEqual function now - supports true deep equality comparisons, with checks for cyclic structures, - thanks to Kit Cambridge. -
        • -
        • - Underscore templates now support HTML escaping interpolations, using - <%- ... %> syntax. -
        • -
        • - Ryan Tenney contributed _.shuffle, which uses a modified - Fisher-Yates to give you a shuffled copy of an array. -
        • -
        • - _.uniq can now be passed an optional iterator, to determine by - what criteria an object should be considered unique. -
        • -
        • - _.last now takes an optional argument which will return the last - N elements of the list. -
        • -
        • - A new _.initial function was added, as a mirror of _.rest, - which returns all the initial values of a list (except the last N). -
        • -
        -

        - -

        - 1.1.7July 13, 2011
        - Added _.groupBy, which aggregates a collection into groups of like items. - Added _.union and _.difference, to complement the - (re-named) _.intersection. - Various improvements for support of sparse arrays. - _.toArray now returns a clone, if directly passed an array. - _.functions now also returns the names of functions that are present - in the prototype chain. -

        - -

        - 1.1.6April 18, 2011
        - Added _.after, which will return a function that only runs after - first being called a specified number of times. - _.invoke can now take a direct function reference. - _.every now requires an iterator function to be passed, which - mirrors the ECMA5 API. - _.extend no longer copies keys when the value is undefined. - _.bind now errors when trying to bind an undefined value. -

        - -

        - 1.1.5Mar 20, 2011
        - Added an _.defaults function, for use merging together JS objects - representing default options. - Added an _.once function, for manufacturing functions that should - only ever execute a single time. - _.bind now delegates to the native ECMAScript 5 version, - where available. - _.keys now throws an error when used on non-Object values, as in - ECMAScript 5. - Fixed a bug with _.keys when used over sparse arrays. -

        - -

        - 1.1.4Jan 9, 2011
        - Improved compliance with ES5's Array methods when passing null - as a value. _.wrap now correctly sets this for the - wrapped function. _.indexOf now takes an optional flag for - finding the insertion index in an array that is guaranteed to already - be sorted. Avoiding the use of .callee, to allow _.isArray - to work properly in ES5's strict mode. -

        - -

        - 1.1.3Dec 1, 2010
        - In CommonJS, Underscore may now be required with just:
        - var _ = require("underscore"). - Added _.throttle and _.debounce functions. - Removed _.breakLoop, in favor of an ECMA5-style un-break-able - each implementation — this removes the try/catch, and you'll now have - better stack traces for exceptions that are thrown within an Underscore iterator. - Improved the isType family of functions for better interoperability - with Internet Explorer host objects. - _.template now correctly escapes backslashes in templates. - Improved _.reduce compatibility with the ECMA5 version: - if you don't pass an initial value, the first item in the collection is used. - _.each no longer returns the iterated collection, for improved - consistency with ES5's forEach. -

        - -

        - 1.1.2
        - Fixed _.contains, which was mistakenly pointing at - _.intersect instead of _.include, like it should - have been. Added _.unique as an alias for _.uniq. -

        - -

        - 1.1.1
        - Improved the speed of _.template, and its handling of multiline - interpolations. Ryan Tenney contributed optimizations to many Underscore - functions. An annotated version of the source code is now available. -

        - -

        - 1.1.0
        - The method signature of _.reduce has been changed to match - the ECMAScript 5 signature, instead of the Ruby/Prototype.js version. - This is a backwards-incompatible change. _.template may now be - called with no arguments, and preserves whitespace. _.contains - is a new alias for _.include. -

        - -

        - 1.0.4
        - Andri Möll contributed the _.memoize - function, which can be used to speed up expensive repeated computations - by caching the results. -

        - -

        - 1.0.3
        - Patch that makes _.isEqual return false if any property - of the compared object has a NaN value. Technically the correct - thing to do, but of questionable semantics. Watch out for NaN comparisons. -

        - -

        - 1.0.2
        - Fixes _.isArguments in recent versions of Opera, which have - arguments objects as real Arrays. -

        - -

        - 1.0.1
        - Bugfix for _.isEqual, when comparing two objects with the same - number of undefined keys, but with different names. -

        - -

        - 1.0.0
        - Things have been stable for many months now, so Underscore is now - considered to be out of beta, at 1.0. Improvements since 0.6 - include _.isBoolean, and the ability to have _.extend - take multiple source objects. -

        - -

        - 0.6.0
        - Major release. Incorporates a number of - Mile Frawley's refactors for - safer duck-typing on collection functions, and cleaner internals. A new - _.mixin method that allows you to extend Underscore with utility - functions of your own. Added _.times, which works the same as in - Ruby or Prototype.js. Native support for ECMAScript 5's Array.isArray, - and Object.keys. -

        - -

        - 0.5.8
        - Fixed Underscore's collection functions to work on - NodeLists and - HTMLCollections - once more, thanks to - Justin Tulloss. -

        - -

        - 0.5.7
        - A safer implementation of _.isArguments, and a - faster _.isNumber,
        thanks to - Jed Schmidt. -

        - -

        - 0.5.6
        - Customizable delimiters for _.template, contributed by - Noah Sloan. -

        - -

        - 0.5.5
        - Fix for a bug in MobileSafari's OOP-wrapper, with the arguments object. -

        - -

        - 0.5.4
        - Fix for multiple single quotes within a template string for - _.template. See: - Rick Strahl's blog post. -

        - -

        - 0.5.2
        - New implementations of isArray, isDate, isFunction, - isNumber, isRegExp, and isString, thanks to - a suggestion from - Robert Kieffer. - Instead of doing Object#toString - comparisons, they now check for expected properties, which is less safe, - but more than an order of magnitude faster. Most other Underscore - functions saw minor speed improvements as a result. - Evgeniy Dolzhenko - contributed _.tap, - similar to Ruby 1.9's, - which is handy for injecting side effects (like logging) into chained calls. -

        - -

        - 0.5.1
        - Added an _.isArguments function. Lots of little safety checks - and optimizations contributed by - Noah Sloan and - Andri Möll. -

        - -

        - 0.5.0
        - [API Changes] _.bindAll now takes the context object as - its first parameter. If no method names are passed, all of the context - object's methods are bound to it, enabling chaining and easier binding. - _.functions now takes a single argument and returns the names - of its Function properties. Calling _.functions(_) will get you - the previous behavior. - Added _.isRegExp so that isEqual can now test for RegExp equality. - All of the "is" functions have been shrunk down into a single definition. - Karl Guertin contributed patches. -

        - -

        - 0.4.7
        - Added isDate, isNaN, and isNull, for completeness. - Optimizations for isEqual when checking equality between Arrays - or Dates. _.keys is now 25%–2X faster (depending on your - browser) which speeds up the functions that rely on it, such as _.each. -

        - -

        - 0.4.6
        - Added the range function, a port of the - Python - function of the same name, for generating flexibly-numbered lists - of integers. Original patch contributed by - Kirill Ishanov. -

        - -

        - 0.4.5
        - Added rest for Arrays and arguments objects, and aliased - first as head, and rest as tail, - thanks to Luke Sutton's patches. - Added tests ensuring that all Underscore Array functions also work on - arguments objects. -

        - -

        - 0.4.4
        - Added isString, and isNumber, for consistency. Fixed - _.isEqual(NaN, NaN) to return true (which is debatable). -

        - -

        - 0.4.3
        - Started using the native StopIteration object in browsers that support it. - Fixed Underscore setup for CommonJS environments. -

        - -

        - 0.4.2
        - Renamed the unwrapping function to value, for clarity. -

        - -

        - 0.4.1
        - Chained Underscore objects now support the Array prototype methods, so - that you can perform the full range of operations on a wrapped array - without having to break your chain. Added a breakLoop method - to break in the middle of any Underscore iteration. Added an - isEmpty function that works on arrays and objects. -

        - -

        - 0.4.0
        - All Underscore functions can now be called in an object-oriented style, - like so: _([1, 2, 3]).map(...);. Original patch provided by - Marc-André Cournoyer. - Wrapped objects can be chained through multiple - method invocations. A functions method - was added, providing a sorted list of all the functions in Underscore. -

        - -

        - 0.3.3
        - Added the JavaScript 1.8 function reduceRight. Aliased it - as foldr, and aliased reduce as foldl. -

        - -

        - 0.3.2
        - Now runs on stock Rhino - interpreters with: load("underscore.js"). - Added identity as a utility function. -

        - -

        - 0.3.1
        - All iterators are now passed in the original collection as their third - argument, the same as JavaScript 1.6's forEach. Iterating over - objects is now called with (value, key, collection), for details - see _.each. -

        - -

        - 0.3.0
        - Added Dmitry Baranovskiy's - comprehensive optimizations, merged in - Kris Kowal's patches to make Underscore - CommonJS and - Narwhal compliant. -

        - -

        - 0.2.0
        - Added compose and lastIndexOf, renamed inject to - reduce, added aliases for inject, filter, - every, some, and forEach. -

        - -

        - 0.1.1
        - Added noConflict, so that the "Underscore" object can be assigned to - other variables. -

        - -

        - 0.1.0
        - Initial release of Underscore.js. -

        - -

        - - A DocumentCloud Project - -

        - -
        - -
        - - - - - - diff --git a/node/node_modules/grunt/node_modules/underscore/index.js b/node/node_modules/grunt/node_modules/underscore/index.js deleted file mode 100644 index 2cf0ca5b0..000000000 --- a/node/node_modules/grunt/node_modules/underscore/index.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('./underscore'); diff --git a/node/node_modules/grunt/node_modules/underscore/package.json b/node/node_modules/grunt/node_modules/underscore/package.json deleted file mode 100644 index cdbe4dd71..000000000 --- a/node/node_modules/grunt/node_modules/underscore/package.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "name": "underscore", - "description": "JavaScript's functional programming helper library.", - "homepage": "http://documentcloud.github.com/underscore/", - "keywords": [ - "util", - "functional", - "server", - "client", - "browser" - ], - "author": { - "name": "Jeremy Ashkenas", - "email": "jeremy@documentcloud.org" - }, - "contributors": [], - "repository": { - "type": "git", - "url": "git://github.com/documentcloud/underscore.git" - }, - "main": "underscore.js", - "version": "1.2.4", - "readme": " __ \n /\\ \\ \n __ __ ___ \\_\\ \\ __ _ __ ____ ___ ___ _ __ __ \n/\\ \\/\\ \\ /' _ `\\ /'_ \\ /'__`\\/\\ __\\/ ,__\\ / ___\\ / __`\\/\\ __\\/'__`\\ \n\\ \\ \\_\\ \\/\\ \\/\\ \\/\\ \\ \\ \\/\\ __/\\ \\ \\//\\__, `\\/\\ \\__//\\ \\ \\ \\ \\ \\//\\ __/ \n \\ \\____/\\ \\_\\ \\_\\ \\___,_\\ \\____\\\\ \\_\\\\/\\____/\\ \\____\\ \\____/\\ \\_\\\\ \\____\\\n \\/___/ \\/_/\\/_/\\/__,_ /\\/____/ \\/_/ \\/___/ \\/____/\\/___/ \\/_/ \\/____/\n \n \n\nUnderscore.js is a utility-belt library for JavaScript that provides \nsupport for the usual functional suspects (each, map, reduce, filter...) \nwithout extending any core JavaScript objects.\n\nFor Docs, License, Tests, and pre-packed downloads, see:\nhttp://documentcloud.github.com/underscore/\n\nMany thanks to our contributors:\nhttps://github.com/documentcloud/underscore/contributors\n", - "readmeFilename": "README", - "bugs": { - "url": "https://github.com/documentcloud/underscore/issues" - }, - "_id": "underscore@1.2.4", - "_from": "underscore@~1.2.4" -} diff --git a/node/node_modules/grunt/node_modules/underscore/raw/underscore.psd b/node/node_modules/grunt/node_modules/underscore/raw/underscore.psd deleted file mode 100644 index 73ad2d7c8..000000000 Binary files a/node/node_modules/grunt/node_modules/underscore/raw/underscore.psd and /dev/null differ diff --git a/node/node_modules/grunt/node_modules/underscore/underscore-min.js b/node/node_modules/grunt/node_modules/underscore/underscore-min.js deleted file mode 100644 index 122914e24..000000000 --- a/node/node_modules/grunt/node_modules/underscore/underscore-min.js +++ /dev/null @@ -1,31 +0,0 @@ -// Underscore.js 1.2.4 -// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. -// Underscore is freely distributable under the MIT license. -// Portions of Underscore are inspired or borrowed from Prototype, -// Oliver Steele's Functional, and John Resig's Micro-Templating. -// For all details and documentation: -// http://documentcloud.github.com/underscore -(function(){function r(a,c,d){if(a===c)return a!==0||1/a==1/c;if(a==null||c==null)return a===c;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(a.isEqual&&b.isFunction(a.isEqual))return a.isEqual(c);if(c.isEqual&&b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return false;switch(e){case "[object String]":return a==String(c);case "[object Number]":return a!=+a?c!=+c:a==0?1/a==1/c:a==+c;case "[object Date]":case "[object Boolean]":return+a==+c;case "[object RegExp]":return a.source== -c.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if(typeof a!="object"||typeof c!="object")return false;for(var f=d.length;f--;)if(d[f]==a)return true;d.push(a);var f=0,g=true;if(e=="[object Array]"){if(f=a.length,g=f==c.length)for(;f--;)if(!(g=f in a==f in c&&r(a[f],c[f],d)))break}else{if("constructor"in a!="constructor"in c||a.constructor!=c.constructor)return false;for(var h in a)if(m.call(a,h)&&(f++,!(g=m.call(c,h)&&r(a[h],c[h],d))))break;if(g){for(h in c)if(m.call(c, -h)&&!f--)break;g=!f}}d.pop();return g}var s=this,G=s._,o={},k=Array.prototype,p=Object.prototype,i=k.slice,H=k.unshift,l=p.toString,m=p.hasOwnProperty,w=k.forEach,x=k.map,y=k.reduce,z=k.reduceRight,A=k.filter,B=k.every,C=k.some,q=k.indexOf,D=k.lastIndexOf,p=Array.isArray,I=Object.keys,t=Function.prototype.bind,b=function(a){return new n(a)};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=b;exports._=b}else typeof define==="function"&&define.amd? -define("underscore",function(){return b}):s._=b;b.VERSION="1.2.4";var j=b.each=b.forEach=function(a,c,b){if(a!=null)if(w&&a.forEach===w)a.forEach(c,b);else if(a.length===+a.length)for(var e=0,f=a.length;e2;a==null&&(a=[]);if(y&&a.reduce===y)return e&&(c=b.bind(c,e)),f?a.reduce(c,d):a.reduce(c);j(a,function(a,b,i){f?d=c.call(e,d,a,b,i):(d=a,f=true)});if(!f)throw new TypeError("Reduce of empty array with no initial value");return d};b.reduceRight=b.foldr=function(a,c,d,e){var f=arguments.length>2;a==null&&(a=[]);if(z&&a.reduceRight===z)return e&&(c=b.bind(c,e)),f?a.reduceRight(c,d):a.reduceRight(c);var g=b.toArray(a).reverse();e&&!f&& -(c=b.bind(c,e));return f?b.reduce(g,c,d,e):b.reduce(g,c)};b.find=b.detect=function(a,c,b){var e;E(a,function(a,g,h){if(c.call(b,a,g,h))return e=a,true});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(A&&a.filter===A)return a.filter(c,b);j(a,function(a,g,h){c.call(b,a,g,h)&&(e[e.length]=a)});return e};b.reject=function(a,c,b){var e=[];if(a==null)return e;j(a,function(a,g,h){c.call(b,a,g,h)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=true;if(a==null)return e; -if(B&&a.every===B)return a.every(c,b);j(a,function(a,g,h){if(!(e=e&&c.call(b,a,g,h)))return o});return e};var E=b.some=b.any=function(a,c,d){c||(c=b.identity);var e=false;if(a==null)return e;if(C&&a.some===C)return a.some(c,d);j(a,function(a,b,h){if(e||(e=c.call(d,a,b,h)))return o});return!!e};b.include=b.contains=function(a,c){var b=false;if(a==null)return b;return q&&a.indexOf===q?a.indexOf(c)!=-1:b=E(a,function(a){return a===c})};b.invoke=function(a,c){var d=i.call(arguments,2);return b.map(a, -function(a){return(b.isFunction(c)?c||a:a[c]).apply(a,d)})};b.pluck=function(a,c){return b.map(a,function(a){return a[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);if(!c&&b.isEmpty(a))return-Infinity;var e={computed:-Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a, -b,h){b=c?c.call(d,a,b,h):a;bd?1:0}),"value")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]};j(a,function(a,b){var c= -e(a,b);(d[c]||(d[c]=[])).push(a)});return d};b.sortedIndex=function(a,c,d){d||(d=b.identity);for(var e=0,f=a.length;e>1;d(a[g])=0})})};b.difference=function(a){var c=b.flatten(i.call(arguments,1));return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=i.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e= -0;e= -0;d--)b=[a[d].apply(this,b)];return b[0]}};b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=I||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var b=[],d;for(d in a)m.call(a,d)&&(b[b.length]=d);return b};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)b[d]!== -void 0&&(a[d]=b[d])});return a};b.defaults=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)?a:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return r(a,b,[])};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(m.call(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=p||function(a){return l.call(a)== -"[object Array]"};b.isObject=function(a){return a===Object(a)};b.isArguments=function(a){return l.call(a)=="[object Arguments]"};if(!b.isArguments(arguments))b.isArguments=function(a){return!(!a||!m.call(a,"callee"))};b.isFunction=function(a){return l.call(a)=="[object Function]"};b.isString=function(a){return l.call(a)=="[object String]"};b.isNumber=function(a){return l.call(a)=="[object Number]"};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)=="[object Boolean]"}; -b.isDate=function(a){return l.call(a)=="[object Date]"};b.isRegExp=function(a){return l.call(a)=="[object RegExp]"};b.isNull=function(a){return a===null};b.isUndefined=function(a){return a===void 0};b.noConflict=function(){s._=G;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}; -b.mixin=function(a){j(b.functions(a),function(c){J(c,b[c]=a[c])})};var K=0;b.uniqueId=function(a){var b=K++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var u=/.^/;b.template=function(a,c){var d=b.templateSettings,d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.escape||u,function(a,b){return"',_.escape("+b.replace(/\\'/g,"'")+"),'"}).replace(d.interpolate|| -u,function(a,b){return"',"+b.replace(/\\'/g,"'")+",'"}).replace(d.evaluate||u,function(a,b){return"');"+b.replace(/\\'/g,"'").replace(/[\r\n\t]/g," ").replace(/\\\\/g,"\\")+";__p.push('"}).replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');",e=new Function("obj","_",d);return c?e(c,b):function(a){return e.call(this,a,b)}};b.chain=function(a){return b(a).chain()};var n=function(a){this._wrapped=a};b.prototype=n.prototype;var v=function(a,c){return c?b(a).chain(): -a},J=function(a,c){n.prototype[a]=function(){var a=i.call(arguments);H.call(a,this._wrapped);return v(c.apply(b,a),this._chain)}};b.mixin(b);j("pop,push,reverse,shift,sort,splice,unshift".split(","),function(a){var b=k[a];n.prototype[a]=function(){var d=this._wrapped;b.apply(d,arguments);var e=d.length;(a=="shift"||a=="splice")&&e===0&&delete d[0];return v(d,this._chain)}});j(["concat","join","slice"],function(a){var b=k[a];n.prototype[a]=function(){return v(b.apply(this._wrapped,arguments),this._chain)}}); -n.prototype.chain=function(){this._chain=true;return this};n.prototype.value=function(){return this._wrapped}}).call(this); diff --git a/node/node_modules/grunt/node_modules/underscore/underscore.js b/node/node_modules/grunt/node_modules/underscore/underscore.js deleted file mode 100644 index c8cd1fd0e..000000000 --- a/node/node_modules/grunt/node_modules/underscore/underscore.js +++ /dev/null @@ -1,995 +0,0 @@ -// Underscore.js 1.2.4 -// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc. -// Underscore is freely distributable under the MIT license. -// Portions of Underscore are inspired or borrowed from Prototype, -// Oliver Steele's Functional, and John Resig's Micro-Templating. -// For all details and documentation: -// http://documentcloud.github.com/underscore - -(function() { - - // Baseline setup - // -------------- - - // Establish the root object, `window` in the browser, or `global` on the server. - var root = this; - - // Save the previous value of the `_` variable. - var previousUnderscore = root._; - - // Establish the object that gets returned to break out of a loop iteration. - var breaker = {}; - - // Save bytes in the minified (but not gzipped) version: - var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; - - // Create quick reference variables for speed access to core prototypes. - var slice = ArrayProto.slice, - unshift = ArrayProto.unshift, - toString = ObjProto.toString, - hasOwnProperty = ObjProto.hasOwnProperty; - - // All **ECMAScript 5** native function implementations that we hope to use - // are declared here. - var - nativeForEach = ArrayProto.forEach, - nativeMap = ArrayProto.map, - nativeReduce = ArrayProto.reduce, - nativeReduceRight = ArrayProto.reduceRight, - nativeFilter = ArrayProto.filter, - nativeEvery = ArrayProto.every, - nativeSome = ArrayProto.some, - nativeIndexOf = ArrayProto.indexOf, - nativeLastIndexOf = ArrayProto.lastIndexOf, - nativeIsArray = Array.isArray, - nativeKeys = Object.keys, - nativeBind = FuncProto.bind; - - // Create a safe reference to the Underscore object for use below. - var _ = function(obj) { return new wrapper(obj); }; - - // Export the Underscore object for **Node.js** and **"CommonJS"**, with - // backwards-compatibility for the old `require()` API. If we're not in - // CommonJS, add `_` to the global object. - if (typeof exports !== 'undefined') { - if (typeof module !== 'undefined' && module.exports) { - exports = module.exports = _; - } - exports._ = _; - } else if (typeof define === 'function' && define.amd) { - // Register as a named module with AMD. - define('underscore', function() { - return _; - }); - } else { - // Exported as a string, for Closure Compiler "advanced" mode. - root['_'] = _; - } - - // Current version. - _.VERSION = '1.2.4'; - - // Collection Functions - // -------------------- - - // The cornerstone, an `each` implementation, aka `forEach`. - // Handles objects with the built-in `forEach`, arrays, and raw objects. - // Delegates to **ECMAScript 5**'s native `forEach` if available. - var each = _.each = _.forEach = function(obj, iterator, context) { - if (obj == null) return; - if (nativeForEach && obj.forEach === nativeForEach) { - obj.forEach(iterator, context); - } else if (obj.length === +obj.length) { - for (var i = 0, l = obj.length; i < l; i++) { - if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return; - } - } else { - for (var key in obj) { - if (hasOwnProperty.call(obj, key)) { - if (iterator.call(context, obj[key], key, obj) === breaker) return; - } - } - } - }; - - // Return the results of applying the iterator to each element. - // Delegates to **ECMAScript 5**'s native `map` if available. - _.map = function(obj, iterator, context) { - var results = []; - if (obj == null) return results; - if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); - each(obj, function(value, index, list) { - results[results.length] = iterator.call(context, value, index, list); - }); - if (obj.length === +obj.length) results.length = obj.length; - return results; - }; - - // **Reduce** builds up a single result from a list of values, aka `inject`, - // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. - _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { - var initial = arguments.length > 2; - if (obj == null) obj = []; - if (nativeReduce && obj.reduce === nativeReduce) { - if (context) iterator = _.bind(iterator, context); - return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); - } - each(obj, function(value, index, list) { - if (!initial) { - memo = value; - initial = true; - } else { - memo = iterator.call(context, memo, value, index, list); - } - }); - if (!initial) throw new TypeError('Reduce of empty array with no initial value'); - return memo; - }; - - // The right-associative version of reduce, also known as `foldr`. - // Delegates to **ECMAScript 5**'s native `reduceRight` if available. - _.reduceRight = _.foldr = function(obj, iterator, memo, context) { - var initial = arguments.length > 2; - if (obj == null) obj = []; - if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { - if (context) iterator = _.bind(iterator, context); - return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); - } - var reversed = _.toArray(obj).reverse(); - if (context && !initial) iterator = _.bind(iterator, context); - return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator); - }; - - // Return the first value which passes a truth test. Aliased as `detect`. - _.find = _.detect = function(obj, iterator, context) { - var result; - any(obj, function(value, index, list) { - if (iterator.call(context, value, index, list)) { - result = value; - return true; - } - }); - return result; - }; - - // Return all the elements that pass a truth test. - // Delegates to **ECMAScript 5**'s native `filter` if available. - // Aliased as `select`. - _.filter = _.select = function(obj, iterator, context) { - var results = []; - if (obj == null) return results; - if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); - each(obj, function(value, index, list) { - if (iterator.call(context, value, index, list)) results[results.length] = value; - }); - return results; - }; - - // Return all the elements for which a truth test fails. - _.reject = function(obj, iterator, context) { - var results = []; - if (obj == null) return results; - each(obj, function(value, index, list) { - if (!iterator.call(context, value, index, list)) results[results.length] = value; - }); - return results; - }; - - // Determine whether all of the elements match a truth test. - // Delegates to **ECMAScript 5**'s native `every` if available. - // Aliased as `all`. - _.every = _.all = function(obj, iterator, context) { - var result = true; - if (obj == null) return result; - if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); - each(obj, function(value, index, list) { - if (!(result = result && iterator.call(context, value, index, list))) return breaker; - }); - return result; - }; - - // Determine if at least one element in the object matches a truth test. - // Delegates to **ECMAScript 5**'s native `some` if available. - // Aliased as `any`. - var any = _.some = _.any = function(obj, iterator, context) { - iterator || (iterator = _.identity); - var result = false; - if (obj == null) return result; - if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); - each(obj, function(value, index, list) { - if (result || (result = iterator.call(context, value, index, list))) return breaker; - }); - return !!result; - }; - - // Determine if a given value is included in the array or object using `===`. - // Aliased as `contains`. - _.include = _.contains = function(obj, target) { - var found = false; - if (obj == null) return found; - if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; - found = any(obj, function(value) { - return value === target; - }); - return found; - }; - - // Invoke a method (with arguments) on every item in a collection. - _.invoke = function(obj, method) { - var args = slice.call(arguments, 2); - return _.map(obj, function(value) { - return (_.isFunction(method) ? method || value : value[method]).apply(value, args); - }); - }; - - // Convenience version of a common use case of `map`: fetching a property. - _.pluck = function(obj, key) { - return _.map(obj, function(value){ return value[key]; }); - }; - - // Return the maximum element or (element-based computation). - _.max = function(obj, iterator, context) { - if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj); - if (!iterator && _.isEmpty(obj)) return -Infinity; - var result = {computed : -Infinity}; - each(obj, function(value, index, list) { - var computed = iterator ? iterator.call(context, value, index, list) : value; - computed >= result.computed && (result = {value : value, computed : computed}); - }); - return result.value; - }; - - // Return the minimum element (or element-based computation). - _.min = function(obj, iterator, context) { - if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj); - if (!iterator && _.isEmpty(obj)) return Infinity; - var result = {computed : Infinity}; - each(obj, function(value, index, list) { - var computed = iterator ? iterator.call(context, value, index, list) : value; - computed < result.computed && (result = {value : value, computed : computed}); - }); - return result.value; - }; - - // Shuffle an array. - _.shuffle = function(obj) { - var shuffled = [], rand; - each(obj, function(value, index, list) { - if (index == 0) { - shuffled[0] = value; - } else { - rand = Math.floor(Math.random() * (index + 1)); - shuffled[index] = shuffled[rand]; - shuffled[rand] = value; - } - }); - return shuffled; - }; - - // Sort the object's values by a criterion produced by an iterator. - _.sortBy = function(obj, iterator, context) { - return _.pluck(_.map(obj, function(value, index, list) { - return { - value : value, - criteria : iterator.call(context, value, index, list) - }; - }).sort(function(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }), 'value'); - }; - - // Groups the object's values by a criterion. Pass either a string attribute - // to group by, or a function that returns the criterion. - _.groupBy = function(obj, val) { - var result = {}; - var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; }; - each(obj, function(value, index) { - var key = iterator(value, index); - (result[key] || (result[key] = [])).push(value); - }); - return result; - }; - - // Use a comparator function to figure out at what index an object should - // be inserted so as to maintain order. Uses binary search. - _.sortedIndex = function(array, obj, iterator) { - iterator || (iterator = _.identity); - var low = 0, high = array.length; - while (low < high) { - var mid = (low + high) >> 1; - iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid; - } - return low; - }; - - // Safely convert anything iterable into a real, live array. - _.toArray = function(iterable) { - if (!iterable) return []; - if (iterable.toArray) return iterable.toArray(); - if (_.isArray(iterable)) return slice.call(iterable); - if (_.isArguments(iterable)) return slice.call(iterable); - return _.values(iterable); - }; - - // Return the number of elements in an object. - _.size = function(obj) { - return _.toArray(obj).length; - }; - - // Array Functions - // --------------- - - // Get the first element of an array. Passing **n** will return the first N - // values in the array. Aliased as `head`. The **guard** check allows it to work - // with `_.map`. - _.first = _.head = function(array, n, guard) { - return (n != null) && !guard ? slice.call(array, 0, n) : array[0]; - }; - - // Returns everything but the last entry of the array. Especcialy useful on - // the arguments object. Passing **n** will return all the values in - // the array, excluding the last N. The **guard** check allows it to work with - // `_.map`. - _.initial = function(array, n, guard) { - return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); - }; - - // Get the last element of an array. Passing **n** will return the last N - // values in the array. The **guard** check allows it to work with `_.map`. - _.last = function(array, n, guard) { - if ((n != null) && !guard) { - return slice.call(array, Math.max(array.length - n, 0)); - } else { - return array[array.length - 1]; - } - }; - - // Returns everything but the first entry of the array. Aliased as `tail`. - // Especially useful on the arguments object. Passing an **index** will return - // the rest of the values in the array from that index onward. The **guard** - // check allows it to work with `_.map`. - _.rest = _.tail = function(array, index, guard) { - return slice.call(array, (index == null) || guard ? 1 : index); - }; - - // Trim out all falsy values from an array. - _.compact = function(array) { - return _.filter(array, function(value){ return !!value; }); - }; - - // Return a completely flattened version of an array. - _.flatten = function(array, shallow) { - return _.reduce(array, function(memo, value) { - if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value)); - memo[memo.length] = value; - return memo; - }, []); - }; - - // Return a version of the array that does not contain the specified value(s). - _.without = function(array) { - return _.difference(array, slice.call(arguments, 1)); - }; - - // Produce a duplicate-free version of the array. If the array has already - // been sorted, you have the option of using a faster algorithm. - // Aliased as `unique`. - _.uniq = _.unique = function(array, isSorted, iterator) { - var initial = iterator ? _.map(array, iterator) : array; - var result = []; - _.reduce(initial, function(memo, el, i) { - if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) { - memo[memo.length] = el; - result[result.length] = array[i]; - } - return memo; - }, []); - return result; - }; - - // Produce an array that contains the union: each distinct element from all of - // the passed-in arrays. - _.union = function() { - return _.uniq(_.flatten(arguments, true)); - }; - - // Produce an array that contains every item shared between all the - // passed-in arrays. (Aliased as "intersect" for back-compat.) - _.intersection = _.intersect = function(array) { - var rest = slice.call(arguments, 1); - return _.filter(_.uniq(array), function(item) { - return _.every(rest, function(other) { - return _.indexOf(other, item) >= 0; - }); - }); - }; - - // Take the difference between one array and a number of other arrays. - // Only the elements present in just the first array will remain. - _.difference = function(array) { - var rest = _.flatten(slice.call(arguments, 1)); - return _.filter(array, function(value){ return !_.include(rest, value); }); - }; - - // Zip together multiple lists into a single array -- elements that share - // an index go together. - _.zip = function() { - var args = slice.call(arguments); - var length = _.max(_.pluck(args, 'length')); - var results = new Array(length); - for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i); - return results; - }; - - // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), - // we need this function. Return the position of the first occurrence of an - // item in an array, or -1 if the item is not included in the array. - // Delegates to **ECMAScript 5**'s native `indexOf` if available. - // If the array is large and already in sort order, pass `true` - // for **isSorted** to use binary search. - _.indexOf = function(array, item, isSorted) { - if (array == null) return -1; - var i, l; - if (isSorted) { - i = _.sortedIndex(array, item); - return array[i] === item ? i : -1; - } - if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item); - for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i; - return -1; - }; - - // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. - _.lastIndexOf = function(array, item) { - if (array == null) return -1; - if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item); - var i = array.length; - while (i--) if (i in array && array[i] === item) return i; - return -1; - }; - - // Generate an integer Array containing an arithmetic progression. A port of - // the native Python `range()` function. See - // [the Python documentation](http://docs.python.org/library/functions.html#range). - _.range = function(start, stop, step) { - if (arguments.length <= 1) { - stop = start || 0; - start = 0; - } - step = arguments[2] || 1; - - var len = Math.max(Math.ceil((stop - start) / step), 0); - var idx = 0; - var range = new Array(len); - - while(idx < len) { - range[idx++] = start; - start += step; - } - - return range; - }; - - // Function (ahem) Functions - // ------------------ - - // Reusable constructor function for prototype setting. - var ctor = function(){}; - - // Create a function bound to a given object (assigning `this`, and arguments, - // optionally). Binding with arguments is also known as `curry`. - // Delegates to **ECMAScript 5**'s native `Function.bind` if available. - // We check for `func.bind` first, to fail fast when `func` is undefined. - _.bind = function bind(func, context) { - var bound, args; - if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); - if (!_.isFunction(func)) throw new TypeError; - args = slice.call(arguments, 2); - return bound = function() { - if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); - ctor.prototype = func.prototype; - var self = new ctor; - var result = func.apply(self, args.concat(slice.call(arguments))); - if (Object(result) === result) return result; - return self; - }; - }; - - // Bind all of an object's methods to that object. Useful for ensuring that - // all callbacks defined on an object belong to it. - _.bindAll = function(obj) { - var funcs = slice.call(arguments, 1); - if (funcs.length == 0) funcs = _.functions(obj); - each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); - return obj; - }; - - // Memoize an expensive function by storing its results. - _.memoize = function(func, hasher) { - var memo = {}; - hasher || (hasher = _.identity); - return function() { - var key = hasher.apply(this, arguments); - return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); - }; - }; - - // Delays a function for the given number of milliseconds, and then calls - // it with the arguments supplied. - _.delay = function(func, wait) { - var args = slice.call(arguments, 2); - return setTimeout(function(){ return func.apply(func, args); }, wait); - }; - - // Defers a function, scheduling it to run after the current call stack has - // cleared. - _.defer = function(func) { - return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); - }; - - // Returns a function, that, when invoked, will only be triggered at most once - // during a given window of time. - _.throttle = function(func, wait) { - var context, args, timeout, throttling, more; - var whenDone = _.debounce(function(){ more = throttling = false; }, wait); - return function() { - context = this; args = arguments; - var later = function() { - timeout = null; - if (more) func.apply(context, args); - whenDone(); - }; - if (!timeout) timeout = setTimeout(later, wait); - if (throttling) { - more = true; - } else { - func.apply(context, args); - } - whenDone(); - throttling = true; - }; - }; - - // Returns a function, that, as long as it continues to be invoked, will not - // be triggered. The function will be called after it stops being called for - // N milliseconds. - _.debounce = function(func, wait) { - var timeout; - return function() { - var context = this, args = arguments; - var later = function() { - timeout = null; - func.apply(context, args); - }; - clearTimeout(timeout); - timeout = setTimeout(later, wait); - }; - }; - - // Returns a function that will be executed at most one time, no matter how - // often you call it. Useful for lazy initialization. - _.once = function(func) { - var ran = false, memo; - return function() { - if (ran) return memo; - ran = true; - return memo = func.apply(this, arguments); - }; - }; - - // Returns the first function passed as an argument to the second, - // allowing you to adjust arguments, run code before and after, and - // conditionally execute the original function. - _.wrap = function(func, wrapper) { - return function() { - var args = [func].concat(slice.call(arguments, 0)); - return wrapper.apply(this, args); - }; - }; - - // Returns a function that is the composition of a list of functions, each - // consuming the return value of the function that follows. - _.compose = function() { - var funcs = arguments; - return function() { - var args = arguments; - for (var i = funcs.length - 1; i >= 0; i--) { - args = [funcs[i].apply(this, args)]; - } - return args[0]; - }; - }; - - // Returns a function that will only be executed after being called N times. - _.after = function(times, func) { - if (times <= 0) return func(); - return function() { - if (--times < 1) { return func.apply(this, arguments); } - }; - }; - - // Object Functions - // ---------------- - - // Retrieve the names of an object's properties. - // Delegates to **ECMAScript 5**'s native `Object.keys` - _.keys = nativeKeys || function(obj) { - if (obj !== Object(obj)) throw new TypeError('Invalid object'); - var keys = []; - for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key; - return keys; - }; - - // Retrieve the values of an object's properties. - _.values = function(obj) { - return _.map(obj, _.identity); - }; - - // Return a sorted list of the function names available on the object. - // Aliased as `methods` - _.functions = _.methods = function(obj) { - var names = []; - for (var key in obj) { - if (_.isFunction(obj[key])) names.push(key); - } - return names.sort(); - }; - - // Extend a given object with all the properties in passed-in object(s). - _.extend = function(obj) { - each(slice.call(arguments, 1), function(source) { - for (var prop in source) { - if (source[prop] !== void 0) obj[prop] = source[prop]; - } - }); - return obj; - }; - - // Fill in a given object with default properties. - _.defaults = function(obj) { - each(slice.call(arguments, 1), function(source) { - for (var prop in source) { - if (obj[prop] == null) obj[prop] = source[prop]; - } - }); - return obj; - }; - - // Create a (shallow-cloned) duplicate of an object. - _.clone = function(obj) { - if (!_.isObject(obj)) return obj; - return _.isArray(obj) ? obj.slice() : _.extend({}, obj); - }; - - // Invokes interceptor with the obj, and then returns obj. - // The primary purpose of this method is to "tap into" a method chain, in - // order to perform operations on intermediate results within the chain. - _.tap = function(obj, interceptor) { - interceptor(obj); - return obj; - }; - - // Internal recursive comparison function. - function eq(a, b, stack) { - // Identical objects are equal. `0 === -0`, but they aren't identical. - // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal. - if (a === b) return a !== 0 || 1 / a == 1 / b; - // A strict comparison is necessary because `null == undefined`. - if (a == null || b == null) return a === b; - // Unwrap any wrapped objects. - if (a._chain) a = a._wrapped; - if (b._chain) b = b._wrapped; - // Invoke a custom `isEqual` method if one is provided. - if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b); - if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a); - // Compare `[[Class]]` names. - var className = toString.call(a); - if (className != toString.call(b)) return false; - switch (className) { - // Strings, numbers, dates, and booleans are compared by value. - case '[object String]': - // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is - // equivalent to `new String("5")`. - return a == String(b); - case '[object Number]': - // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for - // other numeric values. - return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); - case '[object Date]': - case '[object Boolean]': - // Coerce dates and booleans to numeric primitive values. Dates are compared by their - // millisecond representations. Note that invalid dates with millisecond representations - // of `NaN` are not equivalent. - return +a == +b; - // RegExps are compared by their source patterns and flags. - case '[object RegExp]': - return a.source == b.source && - a.global == b.global && - a.multiline == b.multiline && - a.ignoreCase == b.ignoreCase; - } - if (typeof a != 'object' || typeof b != 'object') return false; - // Assume equality for cyclic structures. The algorithm for detecting cyclic - // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. - var length = stack.length; - while (length--) { - // Linear search. Performance is inversely proportional to the number of - // unique nested structures. - if (stack[length] == a) return true; - } - // Add the first object to the stack of traversed objects. - stack.push(a); - var size = 0, result = true; - // Recursively compare objects and arrays. - if (className == '[object Array]') { - // Compare array lengths to determine if a deep comparison is necessary. - size = a.length; - result = size == b.length; - if (result) { - // Deep compare the contents, ignoring non-numeric properties. - while (size--) { - // Ensure commutative equality for sparse arrays. - if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break; - } - } - } else { - // Objects with different constructors are not equivalent. - if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false; - // Deep compare objects. - for (var key in a) { - if (hasOwnProperty.call(a, key)) { - // Count the expected number of properties. - size++; - // Deep compare each member. - if (!(result = hasOwnProperty.call(b, key) && eq(a[key], b[key], stack))) break; - } - } - // Ensure that both objects contain the same number of properties. - if (result) { - for (key in b) { - if (hasOwnProperty.call(b, key) && !(size--)) break; - } - result = !size; - } - } - // Remove the first object from the stack of traversed objects. - stack.pop(); - return result; - } - - // Perform a deep comparison to check if two objects are equal. - _.isEqual = function(a, b) { - return eq(a, b, []); - }; - - // Is a given array, string, or object empty? - // An "empty" object has no enumerable own-properties. - _.isEmpty = function(obj) { - if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; - for (var key in obj) if (hasOwnProperty.call(obj, key)) return false; - return true; - }; - - // Is a given value a DOM element? - _.isElement = function(obj) { - return !!(obj && obj.nodeType == 1); - }; - - // Is a given value an array? - // Delegates to ECMA5's native Array.isArray - _.isArray = nativeIsArray || function(obj) { - return toString.call(obj) == '[object Array]'; - }; - - // Is a given variable an object? - _.isObject = function(obj) { - return obj === Object(obj); - }; - - // Is a given variable an arguments object? - _.isArguments = function(obj) { - return toString.call(obj) == '[object Arguments]'; - }; - if (!_.isArguments(arguments)) { - _.isArguments = function(obj) { - return !!(obj && hasOwnProperty.call(obj, 'callee')); - }; - } - - // Is a given value a function? - _.isFunction = function(obj) { - return toString.call(obj) == '[object Function]'; - }; - - // Is a given value a string? - _.isString = function(obj) { - return toString.call(obj) == '[object String]'; - }; - - // Is a given value a number? - _.isNumber = function(obj) { - return toString.call(obj) == '[object Number]'; - }; - - // Is the given value `NaN`? - _.isNaN = function(obj) { - // `NaN` is the only value for which `===` is not reflexive. - return obj !== obj; - }; - - // Is a given value a boolean? - _.isBoolean = function(obj) { - return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; - }; - - // Is a given value a date? - _.isDate = function(obj) { - return toString.call(obj) == '[object Date]'; - }; - - // Is the given value a regular expression? - _.isRegExp = function(obj) { - return toString.call(obj) == '[object RegExp]'; - }; - - // Is a given value equal to null? - _.isNull = function(obj) { - return obj === null; - }; - - // Is a given variable undefined? - _.isUndefined = function(obj) { - return obj === void 0; - }; - - // Utility Functions - // ----------------- - - // Run Underscore.js in *noConflict* mode, returning the `_` variable to its - // previous owner. Returns a reference to the Underscore object. - _.noConflict = function() { - root._ = previousUnderscore; - return this; - }; - - // Keep the identity function around for default iterators. - _.identity = function(value) { - return value; - }; - - // Run a function **n** times. - _.times = function (n, iterator, context) { - for (var i = 0; i < n; i++) iterator.call(context, i); - }; - - // Escape a string for HTML interpolation. - _.escape = function(string) { - return (''+string).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/'); - }; - - // Add your own custom functions to the Underscore object, ensuring that - // they're correctly added to the OOP wrapper as well. - _.mixin = function(obj) { - each(_.functions(obj), function(name){ - addToWrapper(name, _[name] = obj[name]); - }); - }; - - // Generate a unique integer id (unique within the entire client session). - // Useful for temporary DOM ids. - var idCounter = 0; - _.uniqueId = function(prefix) { - var id = idCounter++; - return prefix ? prefix + id : id; - }; - - // By default, Underscore uses ERB-style template delimiters, change the - // following template settings to use alternative delimiters. - _.templateSettings = { - evaluate : /<%([\s\S]+?)%>/g, - interpolate : /<%=([\s\S]+?)%>/g, - escape : /<%-([\s\S]+?)%>/g - }; - - // When customizing `templateSettings`, if you don't want to define an - // interpolation, evaluation or escaping regex, we need one that is - // guaranteed not to match. - var noMatch = /.^/; - - // JavaScript micro-templating, similar to John Resig's implementation. - // Underscore templating handles arbitrary delimiters, preserves whitespace, - // and correctly escapes quotes within interpolated code. - _.template = function(str, data) { - var c = _.templateSettings; - var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' + - 'with(obj||{}){__p.push(\'' + - str.replace(/\\/g, '\\\\') - .replace(/'/g, "\\'") - .replace(c.escape || noMatch, function(match, code) { - return "',_.escape(" + code.replace(/\\'/g, "'") + "),'"; - }) - .replace(c.interpolate || noMatch, function(match, code) { - return "'," + code.replace(/\\'/g, "'") + ",'"; - }) - .replace(c.evaluate || noMatch, function(match, code) { - return "');" + code.replace(/\\'/g, "'") - .replace(/[\r\n\t]/g, ' ') - .replace(/\\\\/g, '\\') + ";__p.push('"; - }) - .replace(/\r/g, '\\r') - .replace(/\n/g, '\\n') - .replace(/\t/g, '\\t') - + "');}return __p.join('');"; - var func = new Function('obj', '_', tmpl); - if (data) return func(data, _); - return function(data) { - return func.call(this, data, _); - }; - }; - - // Add a "chain" function, which will delegate to the wrapper. - _.chain = function(obj) { - return _(obj).chain(); - }; - - // The OOP Wrapper - // --------------- - - // If Underscore is called as a function, it returns a wrapped object that - // can be used OO-style. This wrapper holds altered versions of all the - // underscore functions. Wrapped objects may be chained. - var wrapper = function(obj) { this._wrapped = obj; }; - - // Expose `wrapper.prototype` as `_.prototype` - _.prototype = wrapper.prototype; - - // Helper function to continue chaining intermediate results. - var result = function(obj, chain) { - return chain ? _(obj).chain() : obj; - }; - - // A method to easily add functions to the OOP wrapper. - var addToWrapper = function(name, func) { - wrapper.prototype[name] = function() { - var args = slice.call(arguments); - unshift.call(args, this._wrapped); - return result(func.apply(_, args), this._chain); - }; - }; - - // Add all of the Underscore functions to the wrapper object. - _.mixin(_); - - // Add all mutator Array functions to the wrapper. - each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { - var method = ArrayProto[name]; - wrapper.prototype[name] = function() { - var wrapped = this._wrapped; - method.apply(wrapped, arguments); - var length = wrapped.length; - if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0]; - return result(wrapped, this._chain); - }; - }); - - // Add all accessor Array functions to the wrapper. - each(['concat', 'join', 'slice'], function(name) { - var method = ArrayProto[name]; - wrapper.prototype[name] = function() { - return result(method.apply(this._wrapped, arguments), this._chain); - }; - }); - - // Start chaining a wrapped Underscore object. - wrapper.prototype.chain = function() { - this._chain = true; - return this; - }; - - // Extracts the result from a wrapped and chained object. - wrapper.prototype.value = function() { - return this._wrapped; - }; - -}).call(this); diff --git a/node/node_modules/grunt/node_modules/which/LICENSE b/node/node_modules/grunt/node_modules/which/LICENSE new file mode 100644 index 000000000..05a401094 --- /dev/null +++ b/node/node_modules/grunt/node_modules/which/LICENSE @@ -0,0 +1,23 @@ +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/node_modules/grunt/node_modules/which/README.md b/node/node_modules/grunt/node_modules/which/README.md new file mode 100644 index 000000000..ff1eb531a --- /dev/null +++ b/node/node_modules/grunt/node_modules/which/README.md @@ -0,0 +1,5 @@ +The "which" util from npm's guts. + +Finds the first instance of a specified executable in the PATH +environment variable. Does not cache the results, so `hash -r` is not +needed when the PATH changes. diff --git a/node/node_modules/grunt/node_modules/which/bin/which b/node/node_modules/grunt/node_modules/which/bin/which new file mode 100755 index 000000000..8432ce2f6 --- /dev/null +++ b/node/node_modules/grunt/node_modules/which/bin/which @@ -0,0 +1,14 @@ +#!/usr/bin/env node +var which = require("../") +if (process.argv.length < 3) { + console.error("Usage: which ") + process.exit(1) +} + +which(process.argv[2], function (er, thing) { + if (er) { + console.error(er.message) + process.exit(er.errno || 127) + } + console.log(thing) +}) diff --git a/node/node_modules/grunt/node_modules/which/package.json b/node/node_modules/grunt/node_modules/which/package.json new file mode 100644 index 000000000..c39246a36 --- /dev/null +++ b/node/node_modules/grunt/node_modules/which/package.json @@ -0,0 +1,27 @@ +{ + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + "name": "which", + "description": "Like which(1) unix command. Find the first instance of an executable in the PATH.", + "version": "1.0.5", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-which.git" + }, + "main": "which.js", + "bin": { + "which": "./bin/which" + }, + "engines": { + "node": "*" + }, + "dependencies": {}, + "devDependencies": {}, + "readme": "The \"which\" util from npm's guts.\n\nFinds the first instance of a specified executable in the PATH\nenvironment variable. Does not cache the results, so `hash -r` is not\nneeded when the PATH changes.\n", + "readmeFilename": "README.md", + "_id": "which@1.0.5", + "_from": "which@~1.0.5" +} diff --git a/node/node_modules/grunt/node_modules/which/which.js b/node/node_modules/grunt/node_modules/which/which.js new file mode 100644 index 000000000..db7e8f74d --- /dev/null +++ b/node/node_modules/grunt/node_modules/which/which.js @@ -0,0 +1,104 @@ +module.exports = which +which.sync = whichSync + +var path = require("path") + , fs + , COLON = process.platform === "win32" ? ";" : ":" + , isExe + +try { + fs = require("graceful-fs") +} catch (ex) { + fs = require("fs") +} + +if (process.platform == "win32") { + // On windows, there is no good way to check that a file is executable + isExe = function isExe () { return true } +} else { + isExe = function isExe (mod, uid, gid) { + //console.error(mod, uid, gid); + //console.error("isExe?", (mod & 0111).toString(8)) + var ret = (mod & 0001) + || (mod & 0010) && process.getgid && gid === process.getgid() + || (mod & 0100) && process.getuid && uid === process.getuid() + //console.error("isExe?", ret) + return ret + } +} + + + +function which (cmd, cb) { + if (isAbsolute(cmd)) return cb(null, cmd) + var pathEnv = (process.env.PATH || "").split(COLON) + , pathExt = [""] + if (process.platform === "win32") { + pathEnv.push(process.cwd()) + pathExt = (process.env.PATHEXT || ".EXE").split(COLON) + if (cmd.indexOf(".") !== -1) pathExt.unshift("") + } + //console.error("pathEnv", pathEnv) + ;(function F (i, l) { + if (i === l) return cb(new Error("not found: "+cmd)) + var p = path.resolve(pathEnv[i], cmd) + ;(function E (ii, ll) { + if (ii === ll) return F(i + 1, l) + var ext = pathExt[ii] + //console.error(p + ext) + fs.stat(p + ext, function (er, stat) { + if (!er && + stat && + stat.isFile() && + isExe(stat.mode, stat.uid, stat.gid)) { + //console.error("yes, exe!", p + ext) + return cb(null, p + ext) + } + return E(ii + 1, ll) + }) + })(0, pathExt.length) + })(0, pathEnv.length) +} + +function whichSync (cmd) { + if (isAbsolute(cmd)) return cmd + var pathEnv = (process.env.PATH || "").split(COLON) + , pathExt = [""] + if (process.platform === "win32") { + pathEnv.push(process.cwd()) + pathExt = (process.env.PATHEXT || ".EXE").split(COLON) + if (cmd.indexOf(".") !== -1) pathExt.unshift("") + } + for (var i = 0, l = pathEnv.length; i < l; i ++) { + var p = path.join(pathEnv[i], cmd) + for (var j = 0, ll = pathExt.length; j < ll; j ++) { + var cur = p + pathExt[j] + var stat + try { stat = fs.statSync(cur) } catch (ex) {} + if (stat && + stat.isFile() && + isExe(stat.mode, stat.uid, stat.gid)) return cur + } + } + throw new Error("not found: "+cmd) +} + +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}[^\\\/]+[\\\/][^\\\/]+)?([\\\/])?/ + , 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/node_modules/grunt/package.json b/node/node_modules/grunt/package.json index bae4c5303..a818e6abf 100644 --- a/node/node_modules/grunt/package.json +++ b/node/node_modules/grunt/package.json @@ -1,12 +1,12 @@ { "name": "grunt", - "description": "A task-based command line build tool for JavaScript projects.", - "version": "0.3.17", + "description": "The JavaScript Task Runner", + "version": "0.4.1", "author": { "name": "\"Cowboy\" Ben Alman", "url": "http://benalman.com/" }, - "homepage": "http://github.com/gruntjs/grunt", + "homepage": "http://gruntjs.com/", "repository": { "type": "git", "url": "git://github.com/gruntjs/grunt.git" @@ -21,23 +21,20 @@ } ], "main": "lib/grunt", - "bin": { - "grunt": "bin/grunt" - }, "scripts": { "test": "grunt test" }, "engines": { - "node": ">= 0.6.0" + "node": ">= 0.8.0" }, - "preferGlobal": true, "keywords": [ + "task", "async", "cli", "minify", "uglify", "build", - "underscore", + "lodash", "unit", "test", "qunit", @@ -50,26 +47,50 @@ "tool" ], "dependencies": { - "async": "~0.1.18", - "colors": "~0.6.0", - "connect": "~2.4.4", + "async": "~0.1.22", + "coffee-script": "~1.3.3", + "colors": "~0.6.0-1", "dateformat": "1.0.2-1.2.3", - "glob-whatev": "~0.1.4", + "eventemitter2": "~0.4.9", + "findup-sync": "~0.1.0", + "glob": "~3.1.21", "hooker": "~0.2.3", - "jshint": "~0.9.1", - "nodeunit": "~0.7.4", + "iconv-lite": "~0.2.5", + "minimatch": "~0.2.6", "nopt": "~1.0.10", - "prompt": "~0.1.12", - "semver": "~1.0.13", - "uglify-js": "~1.3.3", - "underscore": "~1.2.4", - "underscore.string": "~2.1.1", + "rimraf": "~2.0.2", + "lodash": "~0.9.0", + "underscore.string": "~2.2.0rc", + "which": "~1.0.5", + "js-yaml": "~2.0.2" + }, + "devDependencies": { "temporary": "~0.0.4", - "gzip-js": "~0.3.1" + "grunt-contrib-jshint": "~0.1.1", + "grunt-contrib-nodeunit": "~0.1.2", + "grunt-contrib-watch": "~0.2.0", + "difflet": "~0.2.3" }, - "devDependencies": {}, - "readme": "# grunt\nGrunt is a task-based command line build tool for JavaScript projects.\n\n_Grunt is currently in beta. While I'm already using it on multiple projects, it might have a minor issue or two. And things might change before its final release, based on your feedback. Please try it out in a project, and [make suggestions][issues] or [report bugs][issues]!_\n\n## Getting started\nBe sure to read the [getting started guide](/gruntjs/grunt/blob/master/docs/getting_started.md), which is a complete guide to configuring grunt for your project. In addition, check out the [example gruntfiles](/gruntjs/grunt/blob/master/docs/example_gruntfiles.md) which highlight a number of fairly common configurations.\n\n## Built-in tasks\nAs of now, grunt has the following predefined tasks that you can use in your project:\n\n* [concat](/gruntjs/grunt/blob/master/docs/task_concat.md) - Concatenate files.\n* [init](/gruntjs/grunt/blob/master/docs/task_init.md) - Generate project scaffolding from a predefined template.\n* [lint](/gruntjs/grunt/blob/master/docs/task_lint.md) - Validate files with [JSHint][jshint].\n* [min](/gruntjs/grunt/blob/master/docs/task_min.md) - Minify files with [UglifyJS][uglify].\n* [qunit](/gruntjs/grunt/blob/master/docs/task_qunit.md) - Run [QUnit][qunit] unit tests in a headless [PhantomJS][phantom] instance.\n* [server](/gruntjs/grunt/blob/master/docs/task_server.md) - Start a static web server.\n* test - Run unit tests with [nodeunit][nodeunit].\n* watch - Run predefined tasks whenever watched files change.\n\n_(More documentation forthcoming)_\n\n## Custom tasks\nIn addition to the built-in tasks, you can create your own tasks. Don't like a built-in task's default behavior? Override it. Check out the [grunt API documentation](/gruntjs/grunt/blob/master/docs/api.md) and the [built-in tasks source](/gruntjs/grunt/blob/master/tasks) for everything you need to know about creating custom tasks.\n\n## Documentation\nTake a look at the [documentation table of contents][docs] for all the things.\n\n## Why does grunt exist?\nDoing all this stuff manually is a total pain, and building all this stuff into a gigantic Makefile / Jakefile / Cakefile / Rakefile / ?akefile that's maintained across all my projects was also becoming a total pain. Since I always found myself performing the same tasks over and over again, for every project, it made sense to build a task-based build tool.\n\nBeing primarily a JavaScript developer, I decided to use [Node.js][node] and [npm][npm] because the dependencies I most care about ([JSHint][jshint] and [UglifyJS][uglify]) were already npm modules. That being said, while Node.js was designed to support highly-concurrent asynchronous-IO-driven web servers, it was clearly NOT designed to make command-line build tools. But none of that matters, because grunt works. Just install it and see.\n\n## Installing grunt\n\nGrunt is available as an [npm][npm] module. If you install grunt globally via `npm install -g grunt`, it will be available for use in all of your projects. Once grunt has been installed, you can type `grunt --help` at the command line for more information. And if you want to see grunt \"grunt\" itself, cd into grunt's directory and type `grunt`\n\n_Note: in Windows, you may need to run grunt as `grunt.cmd`. See the [FAQ](/gruntjs/grunt/blob/master/docs/faq.md) for more Windows-specific information._\n\nFor projects already using grunt, you're done. Otherwise, if you're adding grunt to an existing project or starting from scratch, check out the [getting started guide](/gruntjs/grunt/blob/master/docs/getting_started.md), which is a complete guide to configuring grunt for your project.\n\n## Release History\n_(Until v1.0.0, this will only be updated when major or breaking changes are made)_\n\n* 2012/10/15 - v0.3.17 - Updating JSHint to 0.9.1. Better stack traces. And a few QUnit task fixes.\n* 2012/10/01 - v0.3.16 - Updated URLs to reflect new website and source location. Tweaks to the \"jquery\" and \"commonjs\" init templates. Fixed an issue when exiting due to warning or fatal error.\n* 2012/09/04 - v0.3.15 - Fixing a minor problem with renaming multi tasks.\n* 2012/08/29 - v0.3.14 - Grunt plugins lacking package.json keywords should work again.\n* 2012/08/27 - v0.3.13 - Fixed Node.js 0.8.x path.existsSync warning. Updated connect, nodeunit, uglify-js deps to latest. Updated docs. Grunt plugins generated with init:gruntplugin no longer include grunt as a dependency. Added preliminary support for \"collection\" plugins.\n* 2012/07/30 - v0.3.12 - Fixing a bug in node 0.8.x where utils.spawn would terminate before receiving all child stdout.\n* 2012/06/25 - v0.3.10 - Updating a few dependencies to work with node 0.8.x (0.6.x should still work).\n* 2012/04/18 - v0.3.9 - The min task (via the uglify helper) now appends a semicolon to the end of the generated source.\n* 2012/04/06 - v0.3.8 - Init template tweaks. Anchor links added to docs, along with grunt-internal docs task to generate them. The watch task now supports multiple targets with separate wildcards and tasks. Locally-installed grunt will override global grunt even when run from global \"grunt\" script.\n* 2012/04/01 - v0.3.7 - Tweaked the behavior of the init template `exports.warnOn` property and added more init template documentation. Fixed duplicate PhantomJS debug output in qunit task. Added useful nodeunit and qunit comments into init template generated test .js files.\n* 2012/03/28 - v0.3.6 - Fixed a `--help` screen issue, a few grunt plugin related issues, and attempted to improve the overall grunt plugin docs and API.\n* 2012/03/27 - v0.3.5 - Fixed a handful of weird Windows issues. Changed default m/d/yyyy dates to yyyy-mm-dd ISO 8601. Fixed some init task bugs, docs errata, and added a lot more content to the init task docs.\n* 2012/03/26 - v0.3.3 - Added a \"gruntfile\" init template. Create a basic gruntfile in seconds with `grunt init:gruntfile`. A few other minor fixes.\n* 2012/03/25 - v0.3.2 - Init tasks can now specify a file matching wildcard for the initial \"files exist\" warning. The jQuery init template now has jQuery 1.7.2. Fixed a bug in the `task.expand*` methods.\n* 2012/03/25 - v0.3.1 - Added a few methods. Substantially reworked the init task and templates.\n* 2012/03/23 - v0.3.0 - Too many changes to list. But in brief: completely reorganized the API, removed all globals, added docs and examples for nearly everything, built a preliminary plugin system (that still needs to be tested). PLEASE RTFM OK? THX U.\n* 2012/02/03 - v0.2.14 - Added a server task (which starts a static webserver for your tasks). The qunit task now uses PhantomJS instead of Zombie.js (4768 of 4971 jQuery unit test pass, neat), and supports both file wildcards as well as http:// or https:// urls. (static webserver, anyone?). Grunt should no longer \"hang\" when done.\n* 2012/01/29 - v0.2.5 - Added a \"qunit\" task as well as an init \"jquery\" template (as of now, there are also \"node\" and \"commonjs\" init templates).\n* 2012/01/22 - v0.2.1 - Removed handlebars, templates are universally handled by underscore now. Changed init task template tags from <% %> to {% %}. Banners beginning with /*! will no longer be stripped.\n* 2012/01/22 - v0.2.0 - Added \"init\" task with a sample template, reworked a lot of code. Hopefully it's backwards-compatible.\n* 2012/01/11 - v0.1.0 - Initial release.\n\n## License\nCopyright (c) 2012 \"Cowboy\" Ben Alman \nLicensed under the MIT license. \n\n\n\n[docs]: /gruntjs/grunt/blob/master/docs/toc.md\n[docs-init]: /gruntjs/grunt/blob/master/docs/task_init.md\n[issues]: /gruntjs/grunt/issues\n\n[node]: http://nodejs.org/\n[npm]: http://npmjs.org/\n[jshint]: http://www.jshint.com/\n[uglify]: https://github.com/mishoo/UglifyJS/\n[nodeunit]: https://github.com/caolan/nodeunit\n[qunit]: http://docs.jquery.com/QUnit\n[phantom]: http://www.phantomjs.org/\n", + "contributors": [ + { + "name": "\"Cowboy\" Ben Alman", + "url": "http://benalman.com/" + }, + { + "name": "Kyle Robinson Young", + "url": "http://dontkry.com/" + }, + { + "name": "Tyler Kellen", + "url": "http://goingslowly.com" + }, + { + "name": "Sindre Sorhus", + "url": "http://sindresorhus.com" + } + ], + "readme": "# Grunt: The JavaScript Task Runner [![Build Status](https://secure.travis-ci.org/gruntjs/grunt.png?branch=master)](http://travis-ci.org/gruntjs/grunt)\n\n### Documentation\n\nVisit the [gruntjs.com](http://gruntjs.com/) website for all the things.\n\n### Support / Contributing\nBefore you make an issue, please read our [Contributing](http://gruntjs.com/contributing) guide.\n\nYou can find the grunt team in [#grunt on irc.freenode.net](irc://irc.freenode.net/#grunt).\n\n### Release History\nSee the [CHANGELOG](CHANGELOG).\n", "readmeFilename": "README.md", - "_id": "grunt@0.3.17", - "_from": "grunt@~0.3.17" + "_id": "grunt@0.4.1", + "_from": "grunt@~0.4.0" } diff --git a/node/node_modules/grunt/tasks/concat.js b/node/node_modules/grunt/tasks/concat.js deleted file mode 100644 index edd562e12..000000000 --- a/node/node_modules/grunt/tasks/concat.js +++ /dev/null @@ -1,43 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -module.exports = function(grunt) { - - // ========================================================================== - // TASKS - // ========================================================================== - - grunt.registerMultiTask('concat', 'Concatenate files.', function() { - var files = grunt.file.expandFiles(this.file.src); - // Concat specified files. - var src = grunt.helper('concat', files, {separator: this.data.separator}); - grunt.file.write(this.file.dest, src); - - // Fail task if errors were logged. - if (this.errorCount) { return false; } - - // Otherwise, print a success message. - grunt.log.writeln('File "' + this.file.dest + '" created.'); - }); - - // ========================================================================== - // HELPERS - // ========================================================================== - - // Concat source files and/or directives. - grunt.registerHelper('concat', function(files, options) { - options = grunt.utils._.defaults(options || {}, { - separator: grunt.utils.linefeed - }); - return files ? files.map(function(filepath) { - return grunt.task.directive(filepath, grunt.file.read); - }).join(grunt.utils.normalizelf(options.separator)) : ''; - }); - -}; diff --git a/node/node_modules/grunt/tasks/init.js b/node/node_modules/grunt/tasks/init.js deleted file mode 100644 index f21684c6b..000000000 --- a/node/node_modules/grunt/tasks/init.js +++ /dev/null @@ -1,617 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -module.exports = function(grunt) { - - // Nodejs libs. - var fs = require('fs'); - var path = require('path'); - - // External libs. - var semver = require('semver'); - - var prompt = require('prompt'); - prompt.message = '[' + '?'.green + ']'; - prompt.delimiter = ' '; - - // ========================================================================== - // TASKS - // ========================================================================== - - // An array of all available license files. - function availableLicenses() { - return grunt.task.expandFiles('init/licenses/*').map(function(obj) { - return path.basename(String(obj)).replace(/^LICENSE-/, ''); - }); - } - - grunt.registerInitTask('init', 'Generate project scaffolding from a predefined template.', function() { - // Extra arguments will be applied to the template file. - var args = grunt.utils.toArray(arguments); - // Template name. - var name = args.shift(); - // Default to last-specified grunt.npmTasks plugin name if template name - // was omitted. Note that specifying just a : after init like "grunt init:" - // will allow all available templates to be listed. - if (name == null) { - name = grunt._npmTasks[grunt._npmTasks.length - 1]; - } - // Valid init templates (.js files). - var templates = {}; - grunt.task.expandFiles('init/*.js').forEach(function(fileobj) { - // Add template (plus its path) to the templates object. - templates[path.basename(fileobj.abs, '.js')] = require(fileobj.abs); - }); - var initTemplate = templates[name]; - - // Give the user a little help. - grunt.log.writelns( - 'This task will create one or more files in the current directory, ' + - 'based on the environment and the answers to a few questions. ' + - 'Note that answering "?" to any question will show question-specific ' + - 'help and answering "none" to most questions will leave its value blank.' - ); - - // Abort if a valid template was not specified. - if (!initTemplate) { - grunt.log.writeln().write('Loading' + (name ? ' "' + name + '"' : '') + ' init template...').error(); - grunt.log.errorlns('A valid template name must be specified, eg. "grunt ' + - 'init:commonjs". The currently-available init templates are: '); - Object.keys(templates).forEach(function(name) { - var description = templates[name].description || '(no description)'; - grunt.log.errorlns(name.cyan + ' - ' + description); - }); - return false; - } - - // Abort if matching files or directories were found (to avoid accidentally - // nuking them). - if (initTemplate.warnOn && grunt.file.expand(initTemplate.warnOn).length > 0) { - grunt.log.writeln(); - grunt.warn('Existing files may be overwritten!'); - } - - // This task is asynchronous. - var taskDone = this.async(); - - var pathPrefix = 'init/' + name + '/root/'; - - // Useful init sub-task-specific utilities. - var init = { - // Expose any user-specified default init values. - defaults: grunt.task.readDefaults('init/defaults.json'), - // Expose rename rules for this template. - renames: grunt.task.readDefaults('init', name, 'rename.json'), - // Return an object containing files to copy with their absolute source path - // and relative destination path, renamed (or omitted) according to rules in - // rename.json (if it exists). - filesToCopy: function(props) { - var files = {}; - // Iterate over all source files. - grunt.task.expandFiles({dot: true}, pathPrefix + '**').forEach(function(obj) { - // Get the path relative to the template root. - var relpath = obj.rel.slice(pathPrefix.length); - var rule = init.renames[relpath]; - // Omit files that have an empty / false rule value. - if (!rule && relpath in init.renames) { return; } - // Create a property for this file. - files[rule ? grunt.template.process(rule, props, 'init') : relpath] = obj.rel; - }); - return files; - }, - // Search init template paths for filename. - srcpath: function(arg1) { - if (arg1 == null) { return null; } - var args = ['init', name, 'root'].concat(grunt.utils.toArray(arguments)); - return grunt.task.getFile.apply(grunt.file, args); - }, - // Determine absolute destination file path. - destpath: path.join.bind(path, process.cwd()), - // Given some number of licenses, add properly-named license files to the - // files object. - addLicenseFiles: function(files, licenses) { - var available = availableLicenses(); - licenses.forEach(function(license) { - var fileobj = grunt.task.expandFiles('init/licenses/LICENSE-' + license)[0]; - files['LICENSE-' + license] = fileobj ? fileobj.rel : null; - }); - }, - // Given an absolute or relative source path, and an optional relative - // destination path, copy a file, optionally processing it through the - // passed callback. - copy: function(srcpath, destpath, options) { - // Destpath is optional. - if (typeof destpath !== 'string') { - options = destpath; - destpath = srcpath; - } - // Ensure srcpath is absolute. - if (!grunt.file.isPathAbsolute(srcpath)) { - srcpath = init.srcpath(srcpath); - } - // Use placeholder file if no src exists. - if (!srcpath) { - srcpath = grunt.task.getFile('init/misc/placeholder'); - } - grunt.verbose.or.write('Writing ' + destpath + '...'); - try { - grunt.file.copy(srcpath, init.destpath(destpath), options); - grunt.verbose.or.ok(); - } catch(e) { - grunt.verbose.or.error().error(e); - throw e; - } - }, - // Iterate over all files in the passed object, copying the source file to - // the destination, processing the contents. - copyAndProcess: function(files, props, options) { - options = grunt.utils._.defaults(options || {}, { - process: function(contents) { - return grunt.template.process(contents, props, 'init'); - } - }); - Object.keys(files).forEach(function(destpath) { - var o = Object.create(options); - var srcpath = files[destpath]; - // If srcpath is relative, match it against options.noProcess if - // necessary, then make srcpath absolute. - var relpath; - if (srcpath && !grunt.file.isPathAbsolute(srcpath)) { - if (o.noProcess) { - relpath = srcpath.slice(pathPrefix.length); - o.noProcess = grunt.file.isMatch(o.noProcess, relpath); - } - srcpath = grunt.task.getFile(srcpath); - } - // Copy! - init.copy(srcpath, destpath, o); - }); - }, - // Save a package.json file in the destination directory. The callback - // can be used to post-process properties to add/remove/whatever. - writePackageJSON: function(filename, props, callback) { - var pkg = {}; - // Basic values. - ['name', 'title', 'description', 'version', 'homepage'].forEach(function(prop) { - if (prop in props) { pkg[prop] = props[prop]; } - }); - // Author. - var hasAuthor = Object.keys(props).some(function(prop) { - return (/^author_/).test(prop); - }); - if (hasAuthor) { - pkg.author = {}; - ['name', 'email', 'url'].forEach(function(prop) { - if (props['author_' + prop]) { - pkg.author[prop] = props['author_' + prop]; - } - }); - } - // Other stuff. - if ('repository' in props) { pkg.repository = {type: 'git', url: props.repository}; } - if ('bugs' in props) { pkg.bugs = {url: props.bugs}; } - if (props.licenses) { - pkg.licenses = props.licenses.map(function(license) { - return {type: license, url: props.homepage + '/blob/master/LICENSE-' + license}; - }); - } - - // Node/npm-specific (?) - if (props.main) { pkg.main = props.main; } - if (props.bin) { pkg.bin = props.bin; } - if (props.node_version) { pkg.engines = {node: props.node_version}; } - if (props.npm_test) { - pkg.scripts = {test: props.npm_test}; - if (props.npm_test.split(' ')[0] === 'grunt') { - if (!props.devDependencies) { props.devDependencies = {}; } - props.devDependencies.grunt = '~' + grunt.version; - } - } - - if (props.dependencies) { pkg.dependencies = props.dependencies; } - if (props.devDependencies) { pkg.devDependencies = props.devDependencies; } - if (props.keywords) { pkg.keywords = props.keywords; } - - // Allow final tweaks to the pkg object. - if (callback) { pkg = callback(pkg, props); } - - // Write file. - grunt.file.write(init.destpath(filename), JSON.stringify(pkg, null, 2)); - } - }; - - // Make args available as flags. - init.flags = {}; - args.forEach(function(flag) { init.flags[flag] = true; }); - - // Show any template-specific notes. - if (initTemplate.notes) { - grunt.log.subhead('"' + name + '" template notes:').writelns(initTemplate.notes); - } - - // Execute template code, passing in the init object, done function, and any - // other arguments specified after the init:name:???. - initTemplate.template.apply(this, [grunt, init, function() { - // Fail task if errors were logged. - if (grunt.task.current.errorCount) { taskDone(false); } - // Otherwise, print a success message. - grunt.log.writeln().writeln('Initialized from template "' + name + '".'); - // All done! - taskDone(); - }].concat(args)); - }); - - // ========================================================================== - // HELPERS - // ========================================================================== - - // Prompt user to override default values passed in obj. - grunt.registerHelper('prompt', function(defaults, options, done) { - // If defaults are omitted, shuffle arguments a bit. - if (grunt.utils.kindOf(defaults) === 'array') { - done = options; - options = defaults; - defaults = {}; - } - - // Keep track of any "sanitize" functions for later use. - var sanitize = {}; - options.forEach(function(option) { - if (option.sanitize) { - sanitize[option.name] = option.sanitize; - } - }); - - // Add one final "are you sure?" prompt. - if (options.length > 0) { - options.push({ - message: 'Do you need to make any changes to the above before continuing?'.green, - name: 'ANSWERS_VALID', - default: 'y/N' - }); - } - - // Ask user for input. This is in an IIFE because it has to execute at least - // once, and might be repeated. - (function ask() { - grunt.log.subhead('Please answer the following:'); - var result = grunt.utils._.clone(defaults); - // Loop over each prompt option. - grunt.utils.async.forEachSeries(options, function(option, done) { - var defaultValue; - grunt.utils.async.forEachSeries(['default', 'altDefault'], function(prop, next) { - if (typeof option[prop] === 'function') { - // If the value is a function, execute that function, using the - // value passed into the return callback as the new default value. - option[prop](defaultValue, result, function(err, value) { - defaultValue = String(value); - next(); - }); - } else { - // Otherwise, if the value actually exists, use it. - if (prop in option) { - defaultValue = option[prop]; - } - next(); - } - }, function() { - // Handle errors (there should never be errors). - option.default = defaultValue; - delete option.altDefault; - // Wrap validator so that answering '?' always fails. - var validator = option.validator; - option.validator = function(line, next) { - if (line === '?') { - return next(false); - } else if (validator) { - if (validator.test) { - return next(validator.test(line)); - } else if (typeof validator === 'function') { - return validator.length < 2 ? next(validator(line)) : validator(line, next); - } - } - next(true); - }; - // Actually get user input. - prompt.start(); - prompt.getInput(option, function(err, line) { - if (err) { return done(err); } - option.validator = validator; - result[option.name] = line; - done(); - }); - }); - }, function(err) { - // After all prompt questions have been answered... - if (/n/i.test(result.ANSWERS_VALID)) { - // User accepted all answers. Suspend prompt. - prompt.pause(); - // Clean up. - delete result.ANSWERS_VALID; - // Iterate over all results. - grunt.utils.async.forEachSeries(Object.keys(result), function(name, next) { - // If this value needs to be sanitized, process it now. - if (sanitize[name]) { - sanitize[name](result[name], result, function(err, value) { - if (err) { - result[name] = err; - } else if (arguments.length === 2) { - result[name] = value === 'none' ? '' : value; - } - next(); - }); - } else { - if (result[name] === 'none') { result[name] = ''; } - next(); - } - }, function(err) { - // Done! - grunt.log.writeln(); - done(err, result); - }); - } else { - // Otherwise update the default value for each user prompt option... - options.slice(0, -1).forEach(function(option) { - option.default = result[option.name]; - }); - // ...and start over again. - ask(); - } - }); - }()); - }); - - // Built-in prompt options for the prompt_for helper. - // These generally follow the node "prompt" module convention, except: - // * The "default" value can be a function which is executed at run-time. - // * An optional "sanitize" function has been added to post-process data. - var prompts = { - name: { - message: 'Project name', - default: function(value, data, done) { - var types = ['javascript', 'js']; - if (data.type) { types.push(data.type); } - var type = '(?:' + types.join('|') + ')'; - // This regexp matches: - // leading type- type. type_ - // trailing -type .type _type and/or -js .js _js - var re = new RegExp('^' + type + '[\\-\\._]?|(?:[\\-\\._]?' + type + ')?(?:[\\-\\._]?js)?$', 'ig'); - // Strip the above stuff from the current dirname. - var name = path.basename(process.cwd()).replace(re, ''); - // Remove anything not a letter, number, dash, dot or underscore. - name = name.replace(/[^\w\-\.]/g, ''); - done(null, name); - }, - validator: /^[\w\-\.]+$/, - warning: 'Must be only letters, numbers, dashes, dots or underscores.', - sanitize: function(value, data, done) { - // An additional value, safe to use as a JavaScript identifier. - data.js_safe_name = value.replace(/[\W_]+/g, '_').replace(/^(\d)/, '_$1'); - // If no value is passed to `done`, the original property isn't modified. - done(); - } - }, - title: { - message: 'Project title', - default: function(value, data, done) { - var title = data.name || ''; - title = title.replace(/[\W_]+/g, ' '); - title = title.replace(/\w+/g, function(word) { - return word[0].toUpperCase() + word.slice(1).toLowerCase(); - }); - done(null, title); - }, - warning: 'May consist of any characters.' - }, - description: { - message: 'Description', - default: 'The best project ever.', - warning: 'May consist of any characters.' - }, - version: { - message: 'Version', - default: function(value, data, done) { - // Get a valid semver tag from `git describe --tags` if possible. - grunt.utils.spawn({ - cmd: 'git', - args: ['describe', '--tags'], - fallback: '' - }, function(err, result, code) { - result = result.split('-')[0]; - done(null, semver.valid(result) || '0.1.0'); - }); - }, - validator: semver.valid, - warning: 'Must be a valid semantic version (semver.org).' - }, - repository: { - message: 'Project git repository', - default: function(value, data, done) { - // Change any git@...:... uri to git://.../... format. - grunt.helper('git_origin', function(err, result) { - if (err) { - // Attempt to guess at the repo name. Maybe we'll get lucky! - result = 'git://github.com/' + (process.env.USER || process.env.USERNAME || '???') + '/' + - data.name + '.git'; - } else { - result = result.replace(/^git@([^:]+):/, 'git://$1/'); - } - done(null, result); - }); - }, - sanitize: function(value, data, done) { - // An additional computed "git_user" property. - var repo = grunt.helper('github_web_url', data.repository); - var parts; - if (repo != null) { - parts = repo.split('/'); - data.git_user = parts[parts.length - 2]; - data.git_repo = parts[parts.length - 1]; - done(); - } else { - // Attempt to pull the data from the user's git config. - grunt.utils.spawn({ - cmd: 'git', - args: ['config', '--get', 'github.user'], - fallback: '' - }, function(err, result, code) { - data.git_user = result || process.env.USER || process.env.USERNAME || '???'; - data.git_repo = path.basename(process.cwd()); - done(); - }); - } - }, - warning: 'Should be a public git:// URI.' - }, - homepage: { - message: 'Project homepage', - // If GitHub is the origin, the (potential) homepage is easy to figure out. - default: function(value, data, done) { - done(null, grunt.helper('github_web_url', data.repository) || 'none'); - }, - warning: 'Should be a public URL.' - }, - bugs: { - message: 'Project issues tracker', - // If GitHub is the origin, the issues tracker is easy to figure out. - default: function(value, data, done) { - done(null, grunt.helper('github_web_url', data.repository, 'issues') || 'none'); - }, - warning: 'Should be a public URL.' - }, - licenses: { - message: 'Licenses', - default: 'MIT', - validator: /^[\w\-]+(?:\s+[\w\-]+)*$/, - warning: 'Must be zero or more space-separated licenses. Built-in ' + - 'licenses are: ' + availableLicenses().join(' ') + ', but you may ' + - 'specify any number of custom licenses.', - // Split the string on spaces. - sanitize: function(value, data, done) { done(value.split(/\s+/)); } - }, - author_name: { - message: 'Author name', - default: function(value, data, done) { - // Attempt to pull the data from the user's git config. - grunt.utils.spawn({ - cmd: 'git', - args: ['config', '--get', 'user.name'], - fallback: 'none' - }, done); - }, - warning: 'May consist of any characters.' - }, - author_email: { - message: 'Author email', - default: function(value, data, done) { - // Attempt to pull the data from the user's git config. - grunt.utils.spawn({ - cmd: 'git', - args: ['config', '--get', 'user.email'], - fallback: 'none' - }, done); - }, - warning: 'Should be a valid email address.' - }, - author_url: { - message: 'Author url', - default: 'none', - warning: 'Should be a public URL.' - }, - jquery_version: { - message: 'Required jQuery version', - default: '*', - warning: 'Must be a valid semantic version range descriptor.' - }, - node_version: { - message: 'What versions of node does it run on?', - // TODO: pull from grunt's package.json - default: '>= 0.6.0', - warning: 'Must be a valid semantic version range descriptor.' - }, - main: { - message: 'Main module/entry point', - default: function(value, data, done) { - done(null, 'lib/' + data.name); - }, - warning: 'Must be a path relative to the project root.' - }, - bin: { - message: 'CLI script', - default: function(value, data, done) { - done(null, 'bin/' + data.name); - }, - warning: 'Must be a path relative to the project root.' - }, - npm_test: { - message: 'Npm test command', - default: 'grunt test', - warning: 'Must be an executable command.' - }, - grunt_version: { - message: 'What versions of grunt does it require?', - default: '~' + grunt.version, - warning: 'Must be a valid semantic version range descriptor.' - } - }; - - // Expose prompts object so that prompt_for prompts can be added or modified. - grunt.registerHelper('prompt_for_obj', function() { - return prompts; - }); - - // Commonly-used prompt options with meaningful default values. - grunt.registerHelper('prompt_for', function(name, altDefault) { - // Clone the option so the original options object doesn't get modified. - var option = grunt.utils._.clone(prompts[name]); - option.name = name; - - var defaults = grunt.task.readDefaults('init/defaults.json'); - if (name in defaults) { - // A user default was specified for this option, so use its value. - option.default = defaults[name]; - } else if (arguments.length === 2) { - // An alternate default was specified, so use it. - option.altDefault = altDefault; - } - return option; - }); - - // Get the git origin url from the current repo (if possible). - grunt.registerHelper('git_origin', function(done) { - grunt.utils.spawn({ - cmd: 'git', - args: ['remote', '-v'] - }, function(err, result, code) { - var re = /^origin\s/; - var lines; - if (!err) { - lines = result.split('\n').filter(re.test, re); - if (lines.length > 0) { - done(null, lines[0].split(/\s/)[1]); - return; - } - } - done(true, 'none'); - }); - }); - - // Generate a GitHub web URL from a GitHub repo URI. - var githubWebUrlRe = /^.+(?:@|:\/\/)(github.com)[:\/](.+?)(?:\.git|\/)?$/; - grunt.registerHelper('github_web_url', function(uri, suffix) { - var matches = githubWebUrlRe.exec(uri); - if (!matches) { return null; } - var url = 'https://' + matches[1] + '/' + matches[2]; - if (suffix) { - url += '/' + suffix.replace(/^\//, ''); - } - return url; - }); - -}; diff --git a/node/node_modules/grunt/tasks/init/commonjs.js b/node/node_modules/grunt/tasks/init/commonjs.js deleted file mode 100644 index 7863dd441..000000000 --- a/node/node_modules/grunt/tasks/init/commonjs.js +++ /dev/null @@ -1,56 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -// Basic template description. -exports.description = 'Create a commonjs module, including Nodeunit unit tests.'; - -// Template-specific notes to be displayed before question prompts. -exports.notes = ''; - -// Any existing file or directory matching this wildcard will cause a warning. -exports.warnOn = '*'; - -// The actual init template. -exports.template = function(grunt, init, done) { - - grunt.helper('prompt', {}, [ - // Prompt for these values. - grunt.helper('prompt_for', 'name'), - grunt.helper('prompt_for', 'description'), - grunt.helper('prompt_for', 'version'), - grunt.helper('prompt_for', 'repository'), - grunt.helper('prompt_for', 'homepage'), - grunt.helper('prompt_for', 'bugs'), - grunt.helper('prompt_for', 'licenses'), - grunt.helper('prompt_for', 'author_name'), - grunt.helper('prompt_for', 'author_email'), - grunt.helper('prompt_for', 'author_url'), - grunt.helper('prompt_for', 'node_version', '*'), - grunt.helper('prompt_for', 'main'), - grunt.helper('prompt_for', 'npm_test') - ], function(err, props) { - props.keywords = []; - - // Files to copy (and process). - var files = init.filesToCopy(props); - - // Add properly-named license files. - init.addLicenseFiles(files, props.licenses); - - // Actually copy (and process) files. - init.copyAndProcess(files, props); - - // Generate package.json file. - init.writePackageJSON('package.json', props); - - // All done! - done(); - }); - -}; diff --git a/node/node_modules/grunt/tasks/init/commonjs/rename.json b/node/node_modules/grunt/tasks/init/commonjs/rename.json deleted file mode 100644 index 69305eeef..000000000 --- a/node/node_modules/grunt/tasks/init/commonjs/rename.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "lib/name.js": "lib/{%= name %}.js", - "test/name_test.js": "test/{%= name %}_test.js" -} diff --git a/node/node_modules/grunt/tasks/init/commonjs/root/.npmignore b/node/node_modules/grunt/tasks/init/commonjs/root/.npmignore deleted file mode 100644 index 2ccbe4656..000000000 --- a/node/node_modules/grunt/tasks/init/commonjs/root/.npmignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules/ diff --git a/node/node_modules/grunt/tasks/init/commonjs/root/README.md b/node/node_modules/grunt/tasks/init/commonjs/root/README.md deleted file mode 100644 index 01dfdb217..000000000 --- a/node/node_modules/grunt/tasks/init/commonjs/root/README.md +++ /dev/null @@ -1,57 +0,0 @@ -# {%= name %} - -{%= description %} - -## Getting Started -### On the server -Install the module with: `npm install {%= name %}` - -```javascript -var {%= js_safe_name %} = require('{%= name %}'); -{%= js_safe_name %}.awesome(); // "awesome" -``` - -### In the browser -Download the [production version][min] or the [development version][max]. - -[min]: https://raw.github.com/{%= git_user %}/{%= git_repo %}/master/dist/{%= name %}.min.js -[max]: https://raw.github.com/{%= git_user %}/{%= git_repo %}/master/dist/{%= name %}.js - -In your web page: - -```html - - -``` - -In your code, you can attach {%= name %}'s methods to any object. - -```html - - - -``` - -## Documentation -_(Coming soon)_ - -## Examples -_(Coming soon)_ - -## Contributing -In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt](http://gruntjs.com/). - -_Also, please don't edit files in the "dist" subdirectory as they are generated via grunt. You'll find source code in the "lib" subdirectory!_ - -## Release History -_(Nothing yet)_ - -## License -Copyright (c) {%= grunt.template.today('yyyy') %} {%= author_name %} -Licensed under the {%= licenses.join(', ') %} license{%= licenses.length === 1 ? '' : 's' %}. diff --git a/node/node_modules/grunt/tasks/init/commonjs/root/grunt.js b/node/node_modules/grunt/tasks/init/commonjs/root/grunt.js deleted file mode 100644 index 344790f3d..000000000 --- a/node/node_modules/grunt/tasks/init/commonjs/root/grunt.js +++ /dev/null @@ -1,59 +0,0 @@ -module.exports = function(grunt) { - - // Project configuration. - grunt.initConfig({ - pkg: '', - meta: { - banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' + - '<%= grunt.template.today("yyyy-mm-dd") %>\n' + - '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' + - '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + - ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */' - }, - concat: { - dist: { - src: ['', '.js>'], - dest: 'dist/<%= pkg.name %>.js' - } - }, - min: { - dist: { - src: ['', ''], - dest: 'dist/<%= pkg.name %>.min.js' - } - }, - test: { - files: ['test/**/*.js'] - }, - lint: { - files: ['grunt.js', 'lib/**/*.js', 'test/**/*.js'] - }, - watch: { - files: '', - tasks: 'lint test' - }, - jshint: { - options: { - curly: true, - eqeqeq: true, - immed: true, - latedef: true, - newcap: true, - noarg: true, - sub: true, - undef: true, - boss: true, - eqnull: true - }, - globals: { - exports: true, - module: false - } - }, - uglify: {} - }); - - // Default task. - grunt.registerTask('default', 'lint test concat min'); - -}; diff --git a/node/node_modules/grunt/tasks/init/commonjs/root/lib/name.js b/node/node_modules/grunt/tasks/init/commonjs/root/lib/name.js deleted file mode 100644 index dadc70f66..000000000 --- a/node/node_modules/grunt/tasks/init/commonjs/root/lib/name.js +++ /dev/null @@ -1,15 +0,0 @@ -/* - * {%= name %} - * {%= homepage %} - * - * Copyright (c) {%= grunt.template.today('yyyy') %} {%= author_name %} - * Licensed under the {%= licenses.join(', ') %} license{%= licenses.length === 1 ? '' : 's' %}. - */ - -(function(exports) { - - exports.awesome = function() { - return 'awesome'; - }; - -}(typeof exports === 'object' && exports || this)); diff --git a/node/node_modules/grunt/tasks/init/commonjs/root/test/name_test.js b/node/node_modules/grunt/tasks/init/commonjs/root/test/name_test.js deleted file mode 100644 index aaec812d0..000000000 --- a/node/node_modules/grunt/tasks/init/commonjs/root/test/name_test.js +++ /dev/null @@ -1,35 +0,0 @@ -/*global require:true */ -var {%= js_safe_name %} = require('../lib/{%= name %}.js'); - -/* - ======== A Handy Little Nodeunit Reference ======== - https://github.com/caolan/nodeunit - - Test methods: - test.expect(numAssertions) - test.done() - Test assertions: - test.ok(value, [message]) - test.equal(actual, expected, [message]) - test.notEqual(actual, expected, [message]) - test.deepEqual(actual, expected, [message]) - test.notDeepEqual(actual, expected, [message]) - test.strictEqual(actual, expected, [message]) - test.notStrictEqual(actual, expected, [message]) - test.throws(block, [error], [message]) - test.doesNotThrow(block, [error], [message]) - test.ifError(value) -*/ - -exports['awesome'] = { - setUp: function(done) { - // setup here - done(); - }, - 'no args': function(test) { - test.expect(1); - // tests here - test.equal({%= js_safe_name %}.awesome(), 'awesome', 'should be awesome.'); - test.done(); - } -}; diff --git a/node/node_modules/grunt/tasks/init/gruntfile.js b/node/node_modules/grunt/tasks/init/gruntfile.js deleted file mode 100644 index 007b26781..000000000 --- a/node/node_modules/grunt/tasks/init/gruntfile.js +++ /dev/null @@ -1,80 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -// Basic template description. -exports.description = 'Create a basic grunt.js gruntfile.'; - -// Template-specific notes to be displayed before question prompts. -exports.notes = 'This template tries to guess file and directory paths, but ' + - 'you will most likely need to edit the generated grunt.js file before ' + - 'running grunt. _If you run grunt after generating grunt.js, and grunt ' + - 'exits with errors, edit the grunt.js file!_'; - -// Any existing file or directory matching this wildcard will cause a warning. -exports.warnOn = 'grunt.js'; - -// The actual init template. -exports.template = function(grunt, init, done) { - - grunt.helper('prompt', {}, [ - // Prompt for these values. - { - name: 'dom', - message: 'Is the DOM involved in ANY way?', - default: 'Y/n', - warning: 'Yes: QUnit unit tests + JSHint "browser" globals. No: Nodeunit unit tests.' - }, - { - name: 'min_concat', - message: 'Will files be concatenated or minified?', - default: 'Y/n', - warning: 'Yes: min + concat tasks. No: nothing to see here.' - }, - { - name: 'package_json', - message: 'Will you have a package.json file?', - default: 'Y/n', - warning: 'This changes how filenames are determined and banners are generated.' - } - ], function(err, props) { - props.dom = /y/i.test(props.dom); - props.min_concat = /y/i.test(props.min_concat); - props.package_json = /y/i.test(props.package_json); - props.test_task = props.dom ? 'qunit' : 'test'; - props.file_name = props.package_json ? '<%= pkg.name %>' : 'FILE_NAME'; - - // Find the first `preferred` item existing in `arr`. - function prefer(arr, preferred) { - for (var i = 0; i < preferred.length; i++) { - if (arr.indexOf(preferred[i]) !== -1) { - return preferred[i]; - } - } - return preferred[0]; - } - - // Guess at some directories, if they exist. - var dirs = grunt.file.expandDirs('*').map(function(d) { return d.slice(0, -1); }); - props.lib_dir = prefer(dirs, ['lib', 'src']); - props.test_dir = prefer(dirs, ['test', 'tests', 'unit', 'spec']); - - // Maybe this should be extended to support more libraries. Patches welcome! - props.jquery = grunt.file.expandFiles('**/jquery*.js').length > 0; - - // Files to copy (and process). - var files = init.filesToCopy(props); - - // Actually copy (and process) files. - init.copyAndProcess(files, props); - - // All done! - done(); - }); - -}; diff --git a/node/node_modules/grunt/tasks/init/gruntfile/root/grunt.js b/node/node_modules/grunt/tasks/init/gruntfile/root/grunt.js deleted file mode 100644 index fda2e9136..000000000 --- a/node/node_modules/grunt/tasks/init/gruntfile/root/grunt.js +++ /dev/null @@ -1,71 +0,0 @@ -/*global module:false*/ -module.exports = function(grunt) { - - // Project configuration. - grunt.initConfig({{% if (min_concat) { if (package_json) { %} - pkg: '', - meta: { - banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + - '<%= grunt.template.today("yyyy-mm-dd") %>\n' + - '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' + - '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + - ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */' - },{% } else { %} - meta: { - version: '0.1.0', - banner: '/*! PROJECT_NAME - v<%= meta.version %> - ' + - '<%= grunt.template.today("yyyy-mm-dd") %>\n' + - '* http://PROJECT_WEBSITE/\n' + - '* Copyright (c) <%= grunt.template.today("yyyy") %> ' + - 'YOUR_NAME; Licensed MIT */' - },{% } } %} - lint: { - files: ['grunt.js', '{%= lib_dir %}/**/*.js', '{%= test_dir %}/**/*.js'] - },{% if (dom) { %} - qunit: { - files: ['{%= test_dir %}/**/*.html'] - },{% } else { %} - test: { - files: ['{%= test_dir %}/**/*.js'] - },{% } %}{% if (min_concat) { %} - concat: { - dist: { - src: ['', ''], - dest: 'dist/{%= file_name %}.js' - } - }, - min: { - dist: { - src: ['', ''], - dest: 'dist/{%= file_name %}.min.js' - } - },{% } %} - watch: { - files: '', - tasks: 'lint {%= test_task %}' - }, - jshint: { - options: { - curly: true, - eqeqeq: true, - immed: true, - latedef: true, - newcap: true, - noarg: true, - sub: true, - undef: true, - boss: true, - eqnull: true{% if (dom) { %}, - browser: true{% } %} - }, - globals: {{% if (jquery) { %} - jQuery: true - {% } %}} - }{% if (min_concat) { %}, - uglify: {}{% } %} - }); - - // Default task. - grunt.registerTask('default', 'lint {%= test_task %}{%= min_concat ? " concat min" : "" %}'); - -}; diff --git a/node/node_modules/grunt/tasks/init/gruntplugin.js b/node/node_modules/grunt/tasks/init/gruntplugin.js deleted file mode 100644 index b7ec6a498..000000000 --- a/node/node_modules/grunt/tasks/init/gruntplugin.js +++ /dev/null @@ -1,66 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -// Basic template description. -exports.description = 'Create a grunt plugin, including Nodeunit unit tests.'; - -// Template-specific notes to be displayed before question prompts. -exports.notes = 'The grunt plugin system is still under development. For ' + - 'more information, see the docs at https://github.com/gruntjs/grunt/blob/master/docs/plugins.md'; - -// Any existing file or directory matching this wildcard will cause a warning. -exports.warnOn = '*'; - -// The actual init template. -exports.template = function(grunt, init, done) { - - grunt.helper('prompt', {type: 'grunt'}, [ - // Prompt for these values. - grunt.helper('prompt_for', 'name', function(value, data, done) { - // Prepend "grunt-" to default name if not already there. - data.short_name = value; - value = data.full_name = 'grunt-' + value; - // if (!/^grunt-/.test(value)) { value = 'grunt-' + value; } - done(null, value); - }), - grunt.helper('prompt_for', 'description', 'The best sample grunt tasks ever.'), - grunt.helper('prompt_for', 'version'), - grunt.helper('prompt_for', 'repository'), - grunt.helper('prompt_for', 'homepage'), - grunt.helper('prompt_for', 'bugs'), - grunt.helper('prompt_for', 'licenses'), - grunt.helper('prompt_for', 'author_name'), - grunt.helper('prompt_for', 'author_email'), - grunt.helper('prompt_for', 'author_url'), - grunt.helper('prompt_for', 'grunt_version'), - grunt.helper('prompt_for', 'node_version', '*') - ], function(err, props) { - // Set a few grunt-plugin-specific properties. - props.main = 'grunt.js'; - props.npm_test = 'grunt test'; - props.bin = 'bin/' + props.name; - props.keywords = ['gruntplugin']; - - // Files to copy (and process). - var files = init.filesToCopy(props); - - // Add properly-named license files. - init.addLicenseFiles(files, props.licenses); - - // Actually copy (and process) files. - init.copyAndProcess(files, props); - - // Generate package.json file. - init.writePackageJSON('package.json', props); - - // All done! - done(); - }); - -}; diff --git a/node/node_modules/grunt/tasks/init/gruntplugin/rename.json b/node/node_modules/grunt/tasks/init/gruntplugin/rename.json deleted file mode 100644 index 181cfaa86..000000000 --- a/node/node_modules/grunt/tasks/init/gruntplugin/rename.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "bin/name": "bin/{%= full_name %}", - "tasks/name.js": "tasks/{%= short_name %}.js", - "test/name_test.js": "test/{%= short_name %}_test.js" -} diff --git a/node/node_modules/grunt/tasks/init/gruntplugin/root/.npmignore b/node/node_modules/grunt/tasks/init/gruntplugin/root/.npmignore deleted file mode 100644 index 2ccbe4656..000000000 --- a/node/node_modules/grunt/tasks/init/gruntplugin/root/.npmignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules/ diff --git a/node/node_modules/grunt/tasks/init/gruntplugin/root/README.md b/node/node_modules/grunt/tasks/init/gruntplugin/root/README.md deleted file mode 100644 index b0aba016f..000000000 --- a/node/node_modules/grunt/tasks/init/gruntplugin/root/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# {%= full_name %} - -{%= description %} - -## Getting Started -Install this grunt plugin next to your project's [grunt.js gruntfile][getting_started] with: `npm install {%= full_name %}` - -Then add this line to your project's `grunt.js` gruntfile: - -```javascript -grunt.loadNpmTasks('{%= full_name %}'); -``` - -[grunt]: http://gruntjs.com/ -[getting_started]: https://github.com/gruntjs/grunt/blob/master/docs/getting_started.md - -## Documentation -_(Coming soon)_ - -## Contributing -In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt][grunt]. - -## Release History -_(Nothing yet)_ - -## License -Copyright (c) {%= grunt.template.today('yyyy') %} {%= author_name %} -Licensed under the {%= licenses.join(', ') %} license{%= licenses.length === 1 ? '' : 's' %}. diff --git a/node/node_modules/grunt/tasks/init/gruntplugin/root/bin/name b/node/node_modules/grunt/tasks/init/gruntplugin/root/bin/name deleted file mode 100755 index 07a6c9f91..000000000 --- a/node/node_modules/grunt/tasks/init/gruntplugin/root/bin/name +++ /dev/null @@ -1,2 +0,0 @@ -#!/usr/bin/env node -require('grunt').npmTasks('{%= full_name %}').cli(); diff --git a/node/node_modules/grunt/tasks/init/gruntplugin/root/grunt.js b/node/node_modules/grunt/tasks/init/gruntplugin/root/grunt.js deleted file mode 100644 index 008da4039..000000000 --- a/node/node_modules/grunt/tasks/init/gruntplugin/root/grunt.js +++ /dev/null @@ -1,40 +0,0 @@ -module.exports = function(grunt) { - - // Project configuration. - grunt.initConfig({ - test: { - files: ['test/**/*.js'] - }, - lint: { - files: ['grunt.js', 'tasks/**/*.js', 'test/**/*.js'] - }, - watch: { - files: '', - tasks: 'default' - }, - jshint: { - options: { - curly: true, - eqeqeq: true, - immed: true, - latedef: true, - newcap: true, - noarg: true, - sub: true, - undef: true, - boss: true, - eqnull: true, - node: true, - es5: true - }, - globals: {} - } - }); - - // Load local tasks. - grunt.loadTasks('tasks'); - - // Default task. - grunt.registerTask('default', 'lint test'); - -}; diff --git a/node/node_modules/grunt/tasks/init/gruntplugin/root/tasks/name.js b/node/node_modules/grunt/tasks/init/gruntplugin/root/tasks/name.js deleted file mode 100644 index 9c0f861de..000000000 --- a/node/node_modules/grunt/tasks/init/gruntplugin/root/tasks/name.js +++ /dev/null @@ -1,30 +0,0 @@ -/* - * {%= full_name %} - * {%= homepage %} - * - * Copyright (c) {%= grunt.template.today('yyyy') %} {%= author_name %} - * Licensed under the {%= licenses.join(', ') %} license{%= licenses.length === 1 ? '' : 's' %}. - */ - -module.exports = function(grunt) { - - // Please see the grunt documentation for more information regarding task and - // helper creation: https://github.com/gruntjs/grunt/blob/master/docs/toc.md - - // ========================================================================== - // TASKS - // ========================================================================== - - grunt.registerTask('{%= short_name %}', 'Your task description goes here.', function() { - grunt.log.write(grunt.helper('{%= short_name %}')); - }); - - // ========================================================================== - // HELPERS - // ========================================================================== - - grunt.registerHelper('{%= short_name %}', function() { - return '{%= short_name %}!!!'; - }); - -}; diff --git a/node/node_modules/grunt/tasks/init/gruntplugin/root/test/name_test.js b/node/node_modules/grunt/tasks/init/gruntplugin/root/test/name_test.js deleted file mode 100644 index 122b358fb..000000000 --- a/node/node_modules/grunt/tasks/init/gruntplugin/root/test/name_test.js +++ /dev/null @@ -1,34 +0,0 @@ -var grunt = require('grunt'); - -/* - ======== A Handy Little Nodeunit Reference ======== - https://github.com/caolan/nodeunit - - Test methods: - test.expect(numAssertions) - test.done() - Test assertions: - test.ok(value, [message]) - test.equal(actual, expected, [message]) - test.notEqual(actual, expected, [message]) - test.deepEqual(actual, expected, [message]) - test.notDeepEqual(actual, expected, [message]) - test.strictEqual(actual, expected, [message]) - test.notStrictEqual(actual, expected, [message]) - test.throws(block, [error], [message]) - test.doesNotThrow(block, [error], [message]) - test.ifError(value) -*/ - -exports['{%= short_name %}'] = { - setUp: function(done) { - // setup here - done(); - }, - 'helper': function(test) { - test.expect(1); - // tests here - test.equal(grunt.helper('{%= short_name %}'), '{%= short_name %}!!!', 'should return the correct value.'); - test.done(); - } -}; diff --git a/node/node_modules/grunt/tasks/init/jquery.js b/node/node_modules/grunt/tasks/init/jquery.js deleted file mode 100644 index 410da687b..000000000 --- a/node/node_modules/grunt/tasks/init/jquery.js +++ /dev/null @@ -1,77 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -// Basic template description. -exports.description = 'Create a jQuery plugin, including QUnit unit tests.'; - -// Template-specific notes to be displayed before question prompts. -exports.notes = '_Project name_ should not contain "jquery" or "js" and ' + - 'should be a unique ID not already in use at plugins.jquery.com. _Project ' + - 'title_ should be a human-readable title, and doesn\'t need to contain ' + - 'the word "jQuery", although it may. For example, a plugin titled "Awesome ' + - 'jQuery Plugin" might have the name "awesome-plugin". For more information ' + - 'please see the documentation at ' + - 'https://github.com/jquery/plugins.jquery.com/blob/master/docs/manifest.md'; - -// Any existing file or directory matching this wildcard will cause a warning. -exports.warnOn = '*'; - -// The actual init template. -exports.template = function(grunt, init, done) { - - grunt.helper('prompt', {type: 'jquery'}, [ - // Prompt for these values. - grunt.helper('prompt_for', 'name'), - grunt.helper('prompt_for', 'title', function(value, data, done) { - // Fix jQuery capitalization. - value = value.replace(/jquery/gi, 'jQuery'); - done(null, value); - }), - grunt.helper('prompt_for', 'description', 'The best jQuery plugin ever.'), - grunt.helper('prompt_for', 'version'), - grunt.helper('prompt_for', 'repository'), - grunt.helper('prompt_for', 'homepage'), - grunt.helper('prompt_for', 'bugs'), - grunt.helper('prompt_for', 'licenses', 'MIT'), - grunt.helper('prompt_for', 'author_name'), - grunt.helper('prompt_for', 'author_email'), - grunt.helper('prompt_for', 'author_url'), - grunt.helper('prompt_for', 'jquery_version') - ], function(err, props) { - // A few additional properties. - props.jqueryjson = props.name + '.jquery.json'; - props.dependencies = {jquery: props.jquery_version || '>= 1'}; - props.keywords = []; - - // Files to copy (and process). - var files = init.filesToCopy(props); - - // Add properly-named license files. - init.addLicenseFiles(files, props.licenses); - - // Actually copy (and process) files. - init.copyAndProcess(files, props, {noProcess: 'libs/**'}); - - // Generate package.json file, used by npm and grunt. - init.writePackageJSON('package.json', { - name: 'jquery-plugin', - version: '0.0.0-ignored', - npm_test: 'grunt qunit', - // TODO: pull from grunt's package.json - node_version: '>= 0.6.0', - }); - - // Generate jquery.json file. - init.writePackageJSON(props.jqueryjson, props); - - // All done! - done(); - }); - -}; diff --git a/node/node_modules/grunt/tasks/init/jquery/rename.json b/node/node_modules/grunt/tasks/init/jquery/rename.json deleted file mode 100644 index 28ca1e5c7..000000000 --- a/node/node_modules/grunt/tasks/init/jquery/rename.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "src/name.js": "src/{%= name %}.js", - "test/name_test.js": "test/{%= name %}_test.js", - "test/name.html": "test/{%= name %}.html" -} diff --git a/node/node_modules/grunt/tasks/init/jquery/root/CONTRIBUTING.md b/node/node_modules/grunt/tasks/init/jquery/root/CONTRIBUTING.md deleted file mode 100644 index 94af4724d..000000000 --- a/node/node_modules/grunt/tasks/init/jquery/root/CONTRIBUTING.md +++ /dev/null @@ -1,35 +0,0 @@ -# Contributing - -## Important notes -Please don't edit files in the `dist` subdirectory as they are generated via grunt. You'll find source code in the `src` subdirectory! - -### Code style -Regarding code style like indentation and whitespace, **follow the conventions you see used in the source already.** - -### PhantomJS -While grunt can run the included unit tests via [PhantomJS](http://phantomjs.org/), this shouldn't be considered a substitute for the real thing. Please be sure to test the `test/*.html` unit test file(s) in _actual_ browsers. - -See the [Why does grunt complain that PhantomJS isn't installed?](https://github.com/gruntjs/grunt/blob/master/docs/faq.md#why-does-grunt-complain-that-phantomjs-isnt-installed) guide in the [Grunt FAQ](https://github.com/gruntjs/grunt/blob/master/docs/faq.md) for help with installing or troubleshooting PhantomJS. - -## Modifying the code -First, ensure that you have the latest [Node.js](http://nodejs.org/) and [npm](http://npmjs.org/) installed. - -Test that grunt is installed globally by running `grunt --version` at the command-line. If grunt isn't installed globally, run `npm install -g grunt` to install the latest version. _You may need to run `sudo npm install -g grunt`._ - -_Note that in Windows, you may have to run `grunt.cmd` instead of `grunt`._ - -1. Fork and clone the repo. -1. Run `npm install` to install all dependencies (including grunt). -1. Run `grunt` to grunt this project. - -Assuming that you don't see any red, you're ready to go. Just be sure to run `grunt` after making any changes, to ensure that nothing is broken. - -## Submitting pull requests - -1. Create a new branch, please don't work in your `master` branch directly. -1. Add failing tests for the change you want to make. Run `grunt` to see the tests fail. -1. Fix stuff. -1. Run `grunt` to see if the tests pass. Repeat steps 2-4 until done. -1. Open `test/*.html` unit test file(s) in actual browser to ensure tests pass everywhere. -1. Update the documentation to reflect any changes. -1. Push to your fork and submit a pull request. diff --git a/node/node_modules/grunt/tasks/init/jquery/root/README.md b/node/node_modules/grunt/tasks/init/jquery/root/README.md deleted file mode 100644 index 2b5c59aa8..000000000 --- a/node/node_modules/grunt/tasks/init/jquery/root/README.md +++ /dev/null @@ -1,30 +0,0 @@ -# {%= title || name %} - -{%= description %} - -## Getting Started -Download the [production version][min] or the [development version][max]. - -[min]: https://raw.github.com/{%= git_user %}/{%= git_repo %}/master/dist/{%= name %}.min.js -[max]: https://raw.github.com/{%= git_user %}/{%= git_repo %}/master/dist/{%= name %}.js - -In your web page: - -```html - - - -``` - -## Documentation -_(Coming soon)_ - -## Examples -_(Coming soon)_ - -## Release History -_(Nothing yet)_ diff --git a/node/node_modules/grunt/tasks/init/jquery/root/grunt.js b/node/node_modules/grunt/tasks/init/jquery/root/grunt.js deleted file mode 100644 index 87d6f1893..000000000 --- a/node/node_modules/grunt/tasks/init/jquery/root/grunt.js +++ /dev/null @@ -1,60 +0,0 @@ -/*global module:false*/ -module.exports = function(grunt) { - - // Project configuration. - grunt.initConfig({ - pkg: '', - meta: { - banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + - '<%= grunt.template.today("yyyy-mm-dd") %>\n' + - '<%= pkg.homepage ? "* " + pkg.homepage + "\n" : "" %>' + - '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + - ' Licensed <%= _.pluck(pkg.licenses, "type").join(", ") %> */' - }, - concat: { - dist: { - src: ['', '.js>'], - dest: 'dist/<%= pkg.name %>.js' - } - }, - min: { - dist: { - src: ['', ''], - dest: 'dist/<%= pkg.name %>.min.js' - } - }, - qunit: { - files: ['test/**/*.html'] - }, - lint: { - files: ['grunt.js', 'src/**/*.js', 'test/**/*.js'] - }, - watch: { - files: '', - tasks: 'lint qunit' - }, - jshint: { - options: { - curly: true, - eqeqeq: true, - immed: true, - latedef: true, - newcap: true, - noarg: true, - sub: true, - undef: true, - boss: true, - eqnull: true, - browser: true - }, - globals: { - jQuery: true - } - }, - uglify: {} - }); - - // Default task. - grunt.registerTask('default', 'lint qunit concat min'); - -}; diff --git a/node/node_modules/grunt/tasks/init/jquery/root/libs/jquery-loader.js b/node/node_modules/grunt/tasks/init/jquery/root/libs/jquery-loader.js deleted file mode 100644 index e7356a131..000000000 --- a/node/node_modules/grunt/tasks/init/jquery/root/libs/jquery-loader.js +++ /dev/null @@ -1,14 +0,0 @@ -(function() { - // Get any jquery=___ param from the query string. - var jqversion = location.search.match(/[?&]jquery=(.*?)(?=&|$)/); - var path; - if (jqversion) { - // A version was specified, load that version from code.jquery.com. - path = 'http://code.jquery.com/jquery-' + jqversion[1] + '.js'; - } else { - // No version was specified, load the local version. - path = '../libs/jquery/jquery.js'; - } - // This is the only time I'll ever use document.write, I promise! - document.write(''); -}()); diff --git a/node/node_modules/grunt/tasks/init/jquery/root/libs/qunit/qunit.css b/node/node_modules/grunt/tasks/init/jquery/root/libs/qunit/qunit.css deleted file mode 100644 index 4be7e3643..000000000 --- a/node/node_modules/grunt/tasks/init/jquery/root/libs/qunit/qunit.css +++ /dev/null @@ -1,232 +0,0 @@ -/** - * QUnit v1.4.0 - A JavaScript Unit Testing Framework - * - * http://docs.jquery.com/QUnit - * - * Copyright (c) 2012 John Resig, Jörn Zaefferer - * Dual licensed under the MIT (MIT-LICENSE.txt) - * or GPL (GPL-LICENSE.txt) licenses. - */ - -/** Font Family and Sizes */ - -#qunit-tests, #qunit-header, #qunit-banner, #qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult { - font-family: "Helvetica Neue Light", "HelveticaNeue-Light", "Helvetica Neue", Calibri, Helvetica, Arial, sans-serif; -} - -#qunit-testrunner-toolbar, #qunit-userAgent, #qunit-testresult, #qunit-tests li { font-size: small; } -#qunit-tests { font-size: smaller; } - - -/** Resets */ - -#qunit-tests, #qunit-tests ol, #qunit-header, #qunit-banner, #qunit-userAgent, #qunit-testresult { - margin: 0; - padding: 0; -} - - -/** Header */ - -#qunit-header { - padding: 0.5em 0 0.5em 1em; - - color: #8699a4; - background-color: #0d3349; - - font-size: 1.5em; - line-height: 1em; - font-weight: normal; - - border-radius: 15px 15px 0 0; - -moz-border-radius: 15px 15px 0 0; - -webkit-border-top-right-radius: 15px; - -webkit-border-top-left-radius: 15px; -} - -#qunit-header a { - text-decoration: none; - color: #c2ccd1; -} - -#qunit-header a:hover, -#qunit-header a:focus { - color: #fff; -} - -#qunit-header label { - display: inline-block; -} - -#qunit-banner { - height: 5px; -} - -#qunit-testrunner-toolbar { - padding: 0.5em 0 0.5em 2em; - color: #5E740B; - background-color: #eee; -} - -#qunit-userAgent { - padding: 0.5em 0 0.5em 2.5em; - background-color: #2b81af; - color: #fff; - text-shadow: rgba(0, 0, 0, 0.5) 2px 2px 1px; -} - - -/** Tests: Pass/Fail */ - -#qunit-tests { - list-style-position: inside; -} - -#qunit-tests li { - padding: 0.4em 0.5em 0.4em 2.5em; - border-bottom: 1px solid #fff; - list-style-position: inside; -} - -#qunit-tests.hidepass li.pass, #qunit-tests.hidepass li.running { - display: none; -} - -#qunit-tests li strong { - cursor: pointer; -} - -#qunit-tests li a { - padding: 0.5em; - color: #c2ccd1; - text-decoration: none; -} -#qunit-tests li a:hover, -#qunit-tests li a:focus { - color: #000; -} - -#qunit-tests ol { - margin-top: 0.5em; - padding: 0.5em; - - background-color: #fff; - - border-radius: 15px; - -moz-border-radius: 15px; - -webkit-border-radius: 15px; - - box-shadow: inset 0px 2px 13px #999; - -moz-box-shadow: inset 0px 2px 13px #999; - -webkit-box-shadow: inset 0px 2px 13px #999; -} - -#qunit-tests table { - border-collapse: collapse; - margin-top: .2em; -} - -#qunit-tests th { - text-align: right; - vertical-align: top; - padding: 0 .5em 0 0; -} - -#qunit-tests td { - vertical-align: top; -} - -#qunit-tests pre { - margin: 0; - white-space: pre-wrap; - word-wrap: break-word; -} - -#qunit-tests del { - background-color: #e0f2be; - color: #374e0c; - text-decoration: none; -} - -#qunit-tests ins { - background-color: #ffcaca; - color: #500; - text-decoration: none; -} - -/*** Test Counts */ - -#qunit-tests b.counts { color: black; } -#qunit-tests b.passed { color: #5E740B; } -#qunit-tests b.failed { color: #710909; } - -#qunit-tests li li { - margin: 0.5em; - padding: 0.4em 0.5em 0.4em 0.5em; - background-color: #fff; - border-bottom: none; - list-style-position: inside; -} - -/*** Passing Styles */ - -#qunit-tests li li.pass { - color: #5E740B; - background-color: #fff; - border-left: 26px solid #C6E746; -} - -#qunit-tests .pass { color: #528CE0; background-color: #D2E0E6; } -#qunit-tests .pass .test-name { color: #366097; } - -#qunit-tests .pass .test-actual, -#qunit-tests .pass .test-expected { color: #999999; } - -#qunit-banner.qunit-pass { background-color: #C6E746; } - -/*** Failing Styles */ - -#qunit-tests li li.fail { - color: #710909; - background-color: #fff; - border-left: 26px solid #EE5757; - white-space: pre; -} - -#qunit-tests > li:last-child { - border-radius: 0 0 15px 15px; - -moz-border-radius: 0 0 15px 15px; - -webkit-border-bottom-right-radius: 15px; - -webkit-border-bottom-left-radius: 15px; -} - -#qunit-tests .fail { color: #000000; background-color: #EE5757; } -#qunit-tests .fail .test-name, -#qunit-tests .fail .module-name { color: #000000; } - -#qunit-tests .fail .test-actual { color: #EE5757; } -#qunit-tests .fail .test-expected { color: green; } - -#qunit-banner.qunit-fail { background-color: #EE5757; } - - -/** Result */ - -#qunit-testresult { - padding: 0.5em 0.5em 0.5em 2.5em; - - color: #2b81af; - background-color: #D2E0E6; - - border-bottom: 1px solid white; -} - -/** Fixture */ - -#qunit-fixture { - position: absolute; - top: -10000px; - left: -10000px; - width: 1000px; - height: 1000px; -} diff --git a/node/node_modules/grunt/tasks/init/jquery/root/libs/qunit/qunit.js b/node/node_modules/grunt/tasks/init/jquery/root/libs/qunit/qunit.js deleted file mode 100644 index f50407ae5..000000000 --- a/node/node_modules/grunt/tasks/init/jquery/root/libs/qunit/qunit.js +++ /dev/null @@ -1,1659 +0,0 @@ -/** - * QUnit v1.4.0 - A JavaScript Unit Testing Framework - * - * http://docs.jquery.com/QUnit - * - * Copyright (c) 2012 John Resig, Jörn Zaefferer - * Dual licensed under the MIT (MIT-LICENSE.txt) - * or GPL (GPL-LICENSE.txt) licenses. - */ - -(function(window) { - -var defined = { - setTimeout: typeof window.setTimeout !== "undefined", - sessionStorage: (function() { - var x = "qunit-test-string"; - try { - sessionStorage.setItem(x, x); - sessionStorage.removeItem(x); - return true; - } catch(e) { - return false; - } - }()) -}; - -var testId = 0, - toString = Object.prototype.toString, - hasOwn = Object.prototype.hasOwnProperty; - -var Test = function(name, testName, expected, async, callback) { - this.name = name; - this.testName = testName; - this.expected = expected; - this.async = async; - this.callback = callback; - this.assertions = []; -}; -Test.prototype = { - init: function() { - var tests = id("qunit-tests"); - if (tests) { - var b = document.createElement("strong"); - b.innerHTML = "Running " + this.name; - var li = document.createElement("li"); - li.appendChild( b ); - li.className = "running"; - li.id = this.id = "test-output" + testId++; - tests.appendChild( li ); - } - }, - setup: function() { - if (this.module != config.previousModule) { - if ( config.previousModule ) { - runLoggingCallbacks('moduleDone', QUnit, { - name: config.previousModule, - failed: config.moduleStats.bad, - passed: config.moduleStats.all - config.moduleStats.bad, - total: config.moduleStats.all - } ); - } - config.previousModule = this.module; - config.moduleStats = { all: 0, bad: 0 }; - runLoggingCallbacks( 'moduleStart', QUnit, { - name: this.module - } ); - } else if (config.autorun) { - runLoggingCallbacks( 'moduleStart', QUnit, { - name: this.module - } ); - } - - config.current = this; - this.testEnvironment = extend({ - setup: function() {}, - teardown: function() {} - }, this.moduleTestEnvironment); - - runLoggingCallbacks( 'testStart', QUnit, { - name: this.testName, - module: this.module - }); - - // allow utility functions to access the current test environment - // TODO why?? - QUnit.current_testEnvironment = this.testEnvironment; - - if ( !config.pollution ) { - saveGlobal(); - } - if ( config.notrycatch ) { - this.testEnvironment.setup.call(this.testEnvironment); - return; - } - try { - this.testEnvironment.setup.call(this.testEnvironment); - } catch(e) { - QUnit.pushFailure( "Setup failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) ); - } - }, - run: function() { - config.current = this; - if ( this.async ) { - QUnit.stop(); - } - - if ( config.notrycatch ) { - this.callback.call(this.testEnvironment); - return; - } - try { - this.callback.call(this.testEnvironment); - } catch(e) { - QUnit.pushFailure( "Died on test #" + (this.assertions.length + 1) + ": " + e.message, extractStacktrace( e, 1 ) ); - // else next test will carry the responsibility - saveGlobal(); - - // Restart the tests if they're blocking - if ( config.blocking ) { - QUnit.start(); - } - } - }, - teardown: function() { - config.current = this; - if ( config.notrycatch ) { - this.testEnvironment.teardown.call(this.testEnvironment); - return; - } else { - try { - this.testEnvironment.teardown.call(this.testEnvironment); - } catch(e) { - QUnit.pushFailure( "Teardown failed on " + this.testName + ": " + e.message, extractStacktrace( e, 1 ) ); - } - } - checkPollution(); - }, - finish: function() { - config.current = this; - if ( this.expected != null && this.expected != this.assertions.length ) { - QUnit.pushFailure( "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run" ); - } else if ( this.expected == null && !this.assertions.length ) { - QUnit.pushFailure( "Expected at least one assertion, but none were run - call expect(0) to accept zero assertions." ); - } - - var good = 0, bad = 0, - li, i, - tests = id("qunit-tests"); - - config.stats.all += this.assertions.length; - config.moduleStats.all += this.assertions.length; - - if ( tests ) { - var ol = document.createElement("ol"); - - for ( i = 0; i < this.assertions.length; i++ ) { - var assertion = this.assertions[i]; - - li = document.createElement("li"); - li.className = assertion.result ? "pass" : "fail"; - li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); - ol.appendChild( li ); - - if ( assertion.result ) { - good++; - } else { - bad++; - config.stats.bad++; - config.moduleStats.bad++; - } - } - - // store result when possible - if ( QUnit.config.reorder && defined.sessionStorage ) { - if (bad) { - sessionStorage.setItem("qunit-test-" + this.module + "-" + this.testName, bad); - } else { - sessionStorage.removeItem("qunit-test-" + this.module + "-" + this.testName); - } - } - - if (bad === 0) { - ol.style.display = "none"; - } - - var b = document.createElement("strong"); - b.innerHTML = this.name + " (" + bad + ", " + good + ", " + this.assertions.length + ")"; - - var a = document.createElement("a"); - a.innerHTML = "Rerun"; - a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); - - addEvent(b, "click", function() { - var next = b.nextSibling.nextSibling, - display = next.style.display; - next.style.display = display === "none" ? "block" : "none"; - }); - - addEvent(b, "dblclick", function(e) { - var target = e && e.target ? e.target : window.event.srcElement; - if ( target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b" ) { - target = target.parentNode; - } - if ( window.location && target.nodeName.toLowerCase() === "strong" ) { - window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); - } - }); - - li = id(this.id); - li.className = bad ? "fail" : "pass"; - li.removeChild( li.firstChild ); - li.appendChild( b ); - li.appendChild( a ); - li.appendChild( ol ); - - } else { - for ( i = 0; i < this.assertions.length; i++ ) { - if ( !this.assertions[i].result ) { - bad++; - config.stats.bad++; - config.moduleStats.bad++; - } - } - } - - QUnit.reset(); - - runLoggingCallbacks( 'testDone', QUnit, { - name: this.testName, - module: this.module, - failed: bad, - passed: this.assertions.length - bad, - total: this.assertions.length - } ); - }, - - queue: function() { - var test = this; - synchronize(function() { - test.init(); - }); - function run() { - // each of these can by async - synchronize(function() { - test.setup(); - }); - synchronize(function() { - test.run(); - }); - synchronize(function() { - test.teardown(); - }); - synchronize(function() { - test.finish(); - }); - } - // defer when previous test run passed, if storage is available - var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-test-" + this.module + "-" + this.testName); - if (bad) { - run(); - } else { - synchronize(run, true); - } - } - -}; - -var QUnit = { - - // call on start of module test to prepend name to all tests - module: function(name, testEnvironment) { - config.currentModule = name; - config.currentModuleTestEnviroment = testEnvironment; - }, - - asyncTest: function(testName, expected, callback) { - if ( arguments.length === 2 ) { - callback = expected; - expected = null; - } - - QUnit.test(testName, expected, callback, true); - }, - - test: function(testName, expected, callback, async) { - var name = '' + escapeInnerText(testName) + ''; - - if ( arguments.length === 2 ) { - callback = expected; - expected = null; - } - - if ( config.currentModule ) { - name = '' + config.currentModule + ": " + name; - } - - if ( !validTest(config.currentModule + ": " + testName) ) { - return; - } - - var test = new Test(name, testName, expected, async, callback); - test.module = config.currentModule; - test.moduleTestEnvironment = config.currentModuleTestEnviroment; - test.queue(); - }, - - // Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. - expect: function(asserts) { - config.current.expected = asserts; - }, - - // Asserts true. - // @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); - ok: function(result, msg) { - if (!config.current) { - throw new Error("ok() assertion outside test context, was " + sourceFromStacktrace(2)); - } - result = !!result; - var details = { - result: result, - message: msg - }; - msg = escapeInnerText(msg || (result ? "okay" : "failed")); - if ( !result ) { - var source = sourceFromStacktrace(2); - if (source) { - details.source = source; - msg += '
        Source:
        ' + escapeInnerText(source) + '
        '; - } - } - runLoggingCallbacks( 'log', QUnit, details ); - config.current.assertions.push({ - result: result, - message: msg - }); - }, - - // Checks that the first two arguments are equal, with an optional message. Prints out both actual and expected values. - // @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); - equal: function(actual, expected, message) { - QUnit.push(expected == actual, actual, expected, message); - }, - - notEqual: function(actual, expected, message) { - QUnit.push(expected != actual, actual, expected, message); - }, - - deepEqual: function(actual, expected, message) { - QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); - }, - - notDeepEqual: function(actual, expected, message) { - QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message); - }, - - strictEqual: function(actual, expected, message) { - QUnit.push(expected === actual, actual, expected, message); - }, - - notStrictEqual: function(actual, expected, message) { - QUnit.push(expected !== actual, actual, expected, message); - }, - - raises: function(block, expected, message) { - var actual, ok = false; - - if (typeof expected === 'string') { - message = expected; - expected = null; - } - - try { - block(); - } catch (e) { - actual = e; - } - - if (actual) { - // we don't want to validate thrown error - if (!expected) { - ok = true; - // expected is a regexp - } else if (QUnit.objectType(expected) === "regexp") { - ok = expected.test(actual); - // expected is a constructor - } else if (actual instanceof expected) { - ok = true; - // expected is a validation function which returns true is validation passed - } else if (expected.call({}, actual) === true) { - ok = true; - } - } - - QUnit.ok(ok, message); - }, - - start: function(count) { - config.semaphore -= count || 1; - if (config.semaphore > 0) { - // don't start until equal number of stop-calls - return; - } - if (config.semaphore < 0) { - // ignore if start is called more often then stop - config.semaphore = 0; - } - // A slight delay, to avoid any current callbacks - if ( defined.setTimeout ) { - window.setTimeout(function() { - if (config.semaphore > 0) { - return; - } - if ( config.timeout ) { - clearTimeout(config.timeout); - } - - config.blocking = false; - process(true); - }, 13); - } else { - config.blocking = false; - process(true); - } - }, - - stop: function(count) { - config.semaphore += count || 1; - config.blocking = true; - - if ( config.testTimeout && defined.setTimeout ) { - clearTimeout(config.timeout); - config.timeout = window.setTimeout(function() { - QUnit.ok( false, "Test timed out" ); - config.semaphore = 1; - QUnit.start(); - }, config.testTimeout); - } - } -}; - -//We want access to the constructor's prototype -(function() { - function F(){} - F.prototype = QUnit; - QUnit = new F(); - //Make F QUnit's constructor so that we can add to the prototype later - QUnit.constructor = F; -}()); - -// deprecated; still export them to window to provide clear error messages -// next step: remove entirely -QUnit.equals = function() { - QUnit.push(false, false, false, "QUnit.equals has been deprecated since 2009 (e88049a0), use QUnit.equal instead"); -}; -QUnit.same = function() { - QUnit.push(false, false, false, "QUnit.same has been deprecated since 2009 (e88049a0), use QUnit.deepEqual instead"); -}; - -// Maintain internal state -var config = { - // The queue of tests to run - queue: [], - - // block until document ready - blocking: true, - - // when enabled, show only failing tests - // gets persisted through sessionStorage and can be changed in UI via checkbox - hidepassed: false, - - // by default, run previously failed tests first - // very useful in combination with "Hide passed tests" checked - reorder: true, - - // by default, modify document.title when suite is done - altertitle: true, - - urlConfig: ['noglobals', 'notrycatch'], - - //logging callback queues - begin: [], - done: [], - log: [], - testStart: [], - testDone: [], - moduleStart: [], - moduleDone: [] -}; - -// Load paramaters -(function() { - var location = window.location || { search: "", protocol: "file:" }, - params = location.search.slice( 1 ).split( "&" ), - length = params.length, - urlParams = {}, - current; - - if ( params[ 0 ] ) { - for ( var i = 0; i < length; i++ ) { - current = params[ i ].split( "=" ); - current[ 0 ] = decodeURIComponent( current[ 0 ] ); - // allow just a key to turn on a flag, e.g., test.html?noglobals - current[ 1 ] = current[ 1 ] ? decodeURIComponent( current[ 1 ] ) : true; - urlParams[ current[ 0 ] ] = current[ 1 ]; - } - } - - QUnit.urlParams = urlParams; - config.filter = urlParams.filter; - - // Figure out if we're running the tests from a server or not - QUnit.isLocal = location.protocol === 'file:'; -}()); - -// Expose the API as global variables, unless an 'exports' -// object exists, in that case we assume we're in CommonJS - export everything at the end -if ( typeof exports === "undefined" || typeof require === "undefined" ) { - extend(window, QUnit); - window.QUnit = QUnit; -} - -// define these after exposing globals to keep them in these QUnit namespace only -extend(QUnit, { - config: config, - - // Initialize the configuration options - init: function() { - extend(config, { - stats: { all: 0, bad: 0 }, - moduleStats: { all: 0, bad: 0 }, - started: +new Date(), - updateRate: 1000, - blocking: false, - autostart: true, - autorun: false, - filter: "", - queue: [], - semaphore: 0 - }); - - var qunit = id( "qunit" ); - if ( qunit ) { - qunit.innerHTML = - '

        ' + escapeInnerText( document.title ) + '

        ' + - '

        ' + - '
        ' + - '

        ' + - '
          '; - } - - var tests = id( "qunit-tests" ), - banner = id( "qunit-banner" ), - result = id( "qunit-testresult" ); - - if ( tests ) { - tests.innerHTML = ""; - } - - if ( banner ) { - banner.className = ""; - } - - if ( result ) { - result.parentNode.removeChild( result ); - } - - if ( tests ) { - result = document.createElement( "p" ); - result.id = "qunit-testresult"; - result.className = "result"; - tests.parentNode.insertBefore( result, tests ); - result.innerHTML = 'Running...
           '; - } - }, - - // Resets the test setup. Useful for tests that modify the DOM. - // If jQuery is available, uses jQuery's html(), otherwise just innerHTML. - reset: function() { - if ( window.jQuery ) { - jQuery( "#qunit-fixture" ).html( config.fixture ); - } else { - var main = id( 'qunit-fixture' ); - if ( main ) { - main.innerHTML = config.fixture; - } - } - }, - - // Trigger an event on an element. - // @example triggerEvent( document.body, "click" ); - triggerEvent: function( elem, type, event ) { - if ( document.createEvent ) { - event = document.createEvent("MouseEvents"); - event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, - 0, 0, 0, 0, 0, false, false, false, false, 0, null); - elem.dispatchEvent( event ); - - } else if ( elem.fireEvent ) { - elem.fireEvent("on"+type); - } - }, - - // Safe object type checking - is: function( type, obj ) { - return QUnit.objectType( obj ) == type; - }, - - objectType: function( obj ) { - if (typeof obj === "undefined") { - return "undefined"; - - // consider: typeof null === object - } - if (obj === null) { - return "null"; - } - - var type = toString.call( obj ).match(/^\[object\s(.*)\]$/)[1] || ''; - - switch (type) { - case 'Number': - if (isNaN(obj)) { - return "nan"; - } - return "number"; - case 'String': - case 'Boolean': - case 'Array': - case 'Date': - case 'RegExp': - case 'Function': - return type.toLowerCase(); - } - if (typeof obj === "object") { - return "object"; - } - return undefined; - }, - - push: function(result, actual, expected, message) { - if (!config.current) { - throw new Error("assertion outside test context, was " + sourceFromStacktrace()); - } - var details = { - result: result, - message: message, - actual: actual, - expected: expected - }; - - message = escapeInnerText(message) || (result ? "okay" : "failed"); - message = '' + message + ""; - var output = message; - if (!result) { - expected = escapeInnerText(QUnit.jsDump.parse(expected)); - actual = escapeInnerText(QUnit.jsDump.parse(actual)); - output += ''; - if (actual != expected) { - output += ''; - output += ''; - } - var source = sourceFromStacktrace(); - if (source) { - details.source = source; - output += ''; - } - output += "
          Expected:
          ' + expected + '
          Result:
          ' + actual + '
          Diff:
          ' + QUnit.diff(expected, actual) +'
          Source:
          ' + escapeInnerText(source) + '
          "; - } - - runLoggingCallbacks( 'log', QUnit, details ); - - config.current.assertions.push({ - result: !!result, - message: output - }); - }, - - pushFailure: function(message, source) { - var details = { - result: false, - message: message - }; - var output = escapeInnerText(message); - if (source) { - details.source = source; - output += '
          Source:
          ' + escapeInnerText(source) + '
          '; - } - runLoggingCallbacks( 'log', QUnit, details ); - config.current.assertions.push({ - result: false, - message: output - }); - }, - - url: function( params ) { - params = extend( extend( {}, QUnit.urlParams ), params ); - var querystring = "?", - key; - for ( key in params ) { - if ( !hasOwn.call( params, key ) ) { - continue; - } - querystring += encodeURIComponent( key ) + "=" + - encodeURIComponent( params[ key ] ) + "&"; - } - return window.location.pathname + querystring.slice( 0, -1 ); - }, - - extend: extend, - id: id, - addEvent: addEvent -}); - -//QUnit.constructor is set to the empty F() above so that we can add to it's prototype later -//Doing this allows us to tell if the following methods have been overwritten on the actual -//QUnit object, which is a deprecated way of using the callbacks. -extend(QUnit.constructor.prototype, { - // Logging callbacks; all receive a single argument with the listed properties - // run test/logs.html for any related changes - begin: registerLoggingCallback('begin'), - // done: { failed, passed, total, runtime } - done: registerLoggingCallback('done'), - // log: { result, actual, expected, message } - log: registerLoggingCallback('log'), - // testStart: { name } - testStart: registerLoggingCallback('testStart'), - // testDone: { name, failed, passed, total } - testDone: registerLoggingCallback('testDone'), - // moduleStart: { name } - moduleStart: registerLoggingCallback('moduleStart'), - // moduleDone: { name, failed, passed, total } - moduleDone: registerLoggingCallback('moduleDone') -}); - -if ( typeof document === "undefined" || document.readyState === "complete" ) { - config.autorun = true; -} - -QUnit.load = function() { - runLoggingCallbacks( 'begin', QUnit, {} ); - - // Initialize the config, saving the execution queue - var oldconfig = extend({}, config); - QUnit.init(); - extend(config, oldconfig); - - config.blocking = false; - - var urlConfigHtml = '', len = config.urlConfig.length; - for ( var i = 0, val; i < len; i++ ) { - val = config.urlConfig[i]; - config[val] = QUnit.urlParams[val]; - urlConfigHtml += ''; - } - - var userAgent = id("qunit-userAgent"); - if ( userAgent ) { - userAgent.innerHTML = navigator.userAgent; - } - var banner = id("qunit-header"); - if ( banner ) { - banner.innerHTML = ' ' + banner.innerHTML + ' ' + urlConfigHtml; - addEvent( banner, "change", function( event ) { - var params = {}; - params[ event.target.name ] = event.target.checked ? true : undefined; - window.location = QUnit.url( params ); - }); - } - - var toolbar = id("qunit-testrunner-toolbar"); - if ( toolbar ) { - var filter = document.createElement("input"); - filter.type = "checkbox"; - filter.id = "qunit-filter-pass"; - addEvent( filter, "click", function() { - var ol = document.getElementById("qunit-tests"); - if ( filter.checked ) { - ol.className = ol.className + " hidepass"; - } else { - var tmp = " " + ol.className.replace( /[\n\t\r]/g, " " ) + " "; - ol.className = tmp.replace(/ hidepass /, " "); - } - if ( defined.sessionStorage ) { - if (filter.checked) { - sessionStorage.setItem("qunit-filter-passed-tests", "true"); - } else { - sessionStorage.removeItem("qunit-filter-passed-tests"); - } - } - }); - if ( config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests") ) { - filter.checked = true; - var ol = document.getElementById("qunit-tests"); - ol.className = ol.className + " hidepass"; - } - toolbar.appendChild( filter ); - - var label = document.createElement("label"); - label.setAttribute("for", "qunit-filter-pass"); - label.innerHTML = "Hide passed tests"; - toolbar.appendChild( label ); - } - - var main = id('qunit-fixture'); - if ( main ) { - config.fixture = main.innerHTML; - } - - if (config.autostart) { - QUnit.start(); - } -}; - -addEvent(window, "load", QUnit.load); - -// addEvent(window, "error") gives us a useless event object -window.onerror = function( message, file, line ) { - if ( QUnit.config.current ) { - QUnit.pushFailure( message, file + ":" + line ); - } else { - QUnit.test( "global failure", function() { - QUnit.pushFailure( message, file + ":" + line ); - }); - } -}; - -function done() { - config.autorun = true; - - // Log the last module results - if ( config.currentModule ) { - runLoggingCallbacks( 'moduleDone', QUnit, { - name: config.currentModule, - failed: config.moduleStats.bad, - passed: config.moduleStats.all - config.moduleStats.bad, - total: config.moduleStats.all - } ); - } - - var banner = id("qunit-banner"), - tests = id("qunit-tests"), - runtime = +new Date() - config.started, - passed = config.stats.all - config.stats.bad, - html = [ - 'Tests completed in ', - runtime, - ' milliseconds.
          ', - '', - passed, - ' tests of ', - config.stats.all, - ' passed, ', - config.stats.bad, - ' failed.' - ].join(''); - - if ( banner ) { - banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); - } - - if ( tests ) { - id( "qunit-testresult" ).innerHTML = html; - } - - if ( config.altertitle && typeof document !== "undefined" && document.title ) { - // show ✖ for good, ✔ for bad suite result in title - // use escape sequences in case file gets loaded with non-utf-8-charset - document.title = [ - (config.stats.bad ? "\u2716" : "\u2714"), - document.title.replace(/^[\u2714\u2716] /i, "") - ].join(" "); - } - - // clear own sessionStorage items if all tests passed - if ( config.reorder && defined.sessionStorage && config.stats.bad === 0 ) { - for (var key in sessionStorage) { - if (sessionStorage.hasOwnProperty(key) && key.indexOf("qunit-test-") === 0 ) { - sessionStorage.removeItem(key); - } - } - } - - runLoggingCallbacks( 'done', QUnit, { - failed: config.stats.bad, - passed: passed, - total: config.stats.all, - runtime: runtime - } ); -} - -function validTest( name ) { - var filter = config.filter, - run = false; - - if ( !filter ) { - return true; - } - - var not = filter.charAt( 0 ) === "!"; - if ( not ) { - filter = filter.slice( 1 ); - } - - if ( name.indexOf( filter ) !== -1 ) { - return !not; - } - - if ( not ) { - run = true; - } - - return run; -} - -// so far supports only Firefox, Chrome and Opera (buggy) -// could be extended in the future to use something like https://github.com/csnover/TraceKit -function extractStacktrace( e, offset ) { - offset = offset || 3; - if (e.stacktrace) { - // Opera - return e.stacktrace.split("\n")[offset + 3]; - } else if (e.stack) { - // Firefox, Chrome - var stack = e.stack.split("\n"); - if (/^error$/i.test(stack[0])) { - stack.shift(); - } - return stack[offset]; - } else if (e.sourceURL) { - // Safari, PhantomJS - // hopefully one day Safari provides actual stacktraces - // exclude useless self-reference for generated Error objects - if ( /qunit.js$/.test( e.sourceURL ) ) { - return; - } - // for actual exceptions, this is useful - return e.sourceURL + ":" + e.line; - } -} -function sourceFromStacktrace(offset) { - try { - throw new Error(); - } catch ( e ) { - return extractStacktrace( e, offset ); - } -} - -function escapeInnerText(s) { - if (!s) { - return ""; - } - s = s + ""; - return s.replace(/[\&<>]/g, function(s) { - switch(s) { - case "&": return "&"; - case "<": return "<"; - case ">": return ">"; - default: return s; - } - }); -} - -function synchronize( callback, last ) { - config.queue.push( callback ); - - if ( config.autorun && !config.blocking ) { - process(last); - } -} - -function process( last ) { - function next() { - process( last ); - } - var start = new Date().getTime(); - config.depth = config.depth ? config.depth + 1 : 1; - - while ( config.queue.length && !config.blocking ) { - if ( !defined.setTimeout || config.updateRate <= 0 || ( ( new Date().getTime() - start ) < config.updateRate ) ) { - config.queue.shift()(); - } else { - window.setTimeout( next, 13 ); - break; - } - } - config.depth--; - if ( last && !config.blocking && !config.queue.length && config.depth === 0 ) { - done(); - } -} - -function saveGlobal() { - config.pollution = []; - - if ( config.noglobals ) { - for ( var key in window ) { - if ( !hasOwn.call( window, key ) ) { - continue; - } - config.pollution.push( key ); - } - } -} - -function checkPollution( name ) { - var old = config.pollution; - saveGlobal(); - - var newGlobals = diff( config.pollution, old ); - if ( newGlobals.length > 0 ) { - QUnit.pushFailure( "Introduced global variable(s): " + newGlobals.join(", ") ); - } - - var deletedGlobals = diff( old, config.pollution ); - if ( deletedGlobals.length > 0 ) { - QUnit.pushFailure( "Deleted global variable(s): " + deletedGlobals.join(", ") ); - } -} - -// returns a new Array with the elements that are in a but not in b -function diff( a, b ) { - var result = a.slice(); - for ( var i = 0; i < result.length; i++ ) { - for ( var j = 0; j < b.length; j++ ) { - if ( result[i] === b[j] ) { - result.splice(i, 1); - i--; - break; - } - } - } - return result; -} - -function extend(a, b) { - for ( var prop in b ) { - if ( b[prop] === undefined ) { - delete a[prop]; - - // Avoid "Member not found" error in IE8 caused by setting window.constructor - } else if ( prop !== "constructor" || a !== window ) { - a[prop] = b[prop]; - } - } - - return a; -} - -function addEvent(elem, type, fn) { - if ( elem.addEventListener ) { - elem.addEventListener( type, fn, false ); - } else if ( elem.attachEvent ) { - elem.attachEvent( "on" + type, fn ); - } else { - fn(); - } -} - -function id(name) { - return !!(typeof document !== "undefined" && document && document.getElementById) && - document.getElementById( name ); -} - -function registerLoggingCallback(key){ - return function(callback){ - config[key].push( callback ); - }; -} - -// Supports deprecated method of completely overwriting logging callbacks -function runLoggingCallbacks(key, scope, args) { - //debugger; - var callbacks; - if ( QUnit.hasOwnProperty(key) ) { - QUnit[key].call(scope, args); - } else { - callbacks = config[key]; - for( var i = 0; i < callbacks.length; i++ ) { - callbacks[i].call( scope, args ); - } - } -} - -// Test for equality any JavaScript type. -// Author: Philippe Rathé -QUnit.equiv = (function() { - - var innerEquiv; // the real equiv function - var callers = []; // stack to decide between skip/abort functions - var parents = []; // stack to avoiding loops from circular referencing - - // Call the o related callback with the given arguments. - function bindCallbacks(o, callbacks, args) { - var prop = QUnit.objectType(o); - if (prop) { - if (QUnit.objectType(callbacks[prop]) === "function") { - return callbacks[prop].apply(callbacks, args); - } else { - return callbacks[prop]; // or undefined - } - } - } - - var getProto = Object.getPrototypeOf || function (obj) { - return obj.__proto__; - }; - - var callbacks = (function () { - - // for string, boolean, number and null - function useStrictEquality(b, a) { - if (b instanceof a.constructor || a instanceof b.constructor) { - // to catch short annotaion VS 'new' annotation of a - // declaration - // e.g. var i = 1; - // var j = new Number(1); - return a == b; - } else { - return a === b; - } - } - - return { - "string" : useStrictEquality, - "boolean" : useStrictEquality, - "number" : useStrictEquality, - "null" : useStrictEquality, - "undefined" : useStrictEquality, - - "nan" : function(b) { - return isNaN(b); - }, - - "date" : function(b, a) { - return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf(); - }, - - "regexp" : function(b, a) { - return QUnit.objectType(b) === "regexp" && - // the regex itself - a.source === b.source && - // and its modifers - a.global === b.global && - // (gmi) ... - a.ignoreCase === b.ignoreCase && - a.multiline === b.multiline; - }, - - // - skip when the property is a method of an instance (OOP) - // - abort otherwise, - // initial === would have catch identical references anyway - "function" : function() { - var caller = callers[callers.length - 1]; - return caller !== Object && typeof caller !== "undefined"; - }, - - "array" : function(b, a) { - var i, j, loop; - var len; - - // b could be an object literal here - if (QUnit.objectType(b) !== "array") { - return false; - } - - len = a.length; - if (len !== b.length) { // safe and faster - return false; - } - - // track reference to avoid circular references - parents.push(a); - for (i = 0; i < len; i++) { - loop = false; - for (j = 0; j < parents.length; j++) { - if (parents[j] === a[i]) { - loop = true;// dont rewalk array - } - } - if (!loop && !innerEquiv(a[i], b[i])) { - parents.pop(); - return false; - } - } - parents.pop(); - return true; - }, - - "object" : function(b, a) { - var i, j, loop; - var eq = true; // unless we can proove it - var aProperties = [], bProperties = []; // collection of - // strings - - // comparing constructors is more strict than using - // instanceof - if (a.constructor !== b.constructor) { - // Allow objects with no prototype to be equivalent to - // objects with Object as their constructor. - if (!((getProto(a) === null && getProto(b) === Object.prototype) || - (getProto(b) === null && getProto(a) === Object.prototype))) - { - return false; - } - } - - // stack constructor before traversing properties - callers.push(a.constructor); - // track reference to avoid circular references - parents.push(a); - - for (i in a) { // be strict: don't ensures hasOwnProperty - // and go deep - loop = false; - for (j = 0; j < parents.length; j++) { - if (parents[j] === a[i]) { - // don't go down the same path twice - loop = true; - } - } - aProperties.push(i); // collect a's properties - - if (!loop && !innerEquiv(a[i], b[i])) { - eq = false; - break; - } - } - - callers.pop(); // unstack, we are done - parents.pop(); - - for (i in b) { - bProperties.push(i); // collect b's properties - } - - // Ensures identical properties name - return eq && innerEquiv(aProperties.sort(), bProperties.sort()); - } - }; - }()); - - innerEquiv = function() { // can take multiple arguments - var args = Array.prototype.slice.apply(arguments); - if (args.length < 2) { - return true; // end transition - } - - return (function(a, b) { - if (a === b) { - return true; // catch the most you can - } else if (a === null || b === null || typeof a === "undefined" || - typeof b === "undefined" || - QUnit.objectType(a) !== QUnit.objectType(b)) { - return false; // don't lose time with error prone cases - } else { - return bindCallbacks(a, callbacks, [ b, a ]); - } - - // apply transition with (1..n) arguments - }(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length - 1))); - }; - - return innerEquiv; - -}()); - -/** - * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | - * http://flesler.blogspot.com Licensed under BSD - * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 - * - * @projectDescription Advanced and extensible data dumping for Javascript. - * @version 1.0.0 - * @author Ariel Flesler - * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} - */ -QUnit.jsDump = (function() { - function quote( str ) { - return '"' + str.toString().replace(/"/g, '\\"') + '"'; - } - function literal( o ) { - return o + ''; - } - function join( pre, arr, post ) { - var s = jsDump.separator(), - base = jsDump.indent(), - inner = jsDump.indent(1); - if ( arr.join ) { - arr = arr.join( ',' + s + inner ); - } - if ( !arr ) { - return pre + post; - } - return [ pre, inner + arr, base + post ].join(s); - } - function array( arr, stack ) { - var i = arr.length, ret = new Array(i); - this.up(); - while ( i-- ) { - ret[i] = this.parse( arr[i] , undefined , stack); - } - this.down(); - return join( '[', ret, ']' ); - } - - var reName = /^function (\w+)/; - - var jsDump = { - parse: function( obj, type, stack ) { //type is used mostly internally, you can fix a (custom)type in advance - stack = stack || [ ]; - var parser = this.parsers[ type || this.typeOf(obj) ]; - type = typeof parser; - var inStack = inArray(obj, stack); - if (inStack != -1) { - return 'recursion('+(inStack - stack.length)+')'; - } - //else - if (type == 'function') { - stack.push(obj); - var res = parser.call( this, obj, stack ); - stack.pop(); - return res; - } - // else - return (type == 'string') ? parser : this.parsers.error; - }, - typeOf: function( obj ) { - var type; - if ( obj === null ) { - type = "null"; - } else if (typeof obj === "undefined") { - type = "undefined"; - } else if (QUnit.is("RegExp", obj)) { - type = "regexp"; - } else if (QUnit.is("Date", obj)) { - type = "date"; - } else if (QUnit.is("Function", obj)) { - type = "function"; - } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") { - type = "window"; - } else if (obj.nodeType === 9) { - type = "document"; - } else if (obj.nodeType) { - type = "node"; - } else if ( - // native arrays - toString.call( obj ) === "[object Array]" || - // NodeList objects - ( typeof obj.length === "number" && typeof obj.item !== "undefined" && ( obj.length ? obj.item(0) === obj[0] : ( obj.item( 0 ) === null && typeof obj[0] === "undefined" ) ) ) - ) { - type = "array"; - } else { - type = typeof obj; - } - return type; - }, - separator: function() { - return this.multiline ? this.HTML ? '
          ' : '\n' : this.HTML ? ' ' : ' '; - }, - indent: function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing - if ( !this.multiline ) { - return ''; - } - var chr = this.indentChar; - if ( this.HTML ) { - chr = chr.replace(/\t/g,' ').replace(/ /g,' '); - } - return new Array( this._depth_ + (extra||0) ).join(chr); - }, - up: function( a ) { - this._depth_ += a || 1; - }, - down: function( a ) { - this._depth_ -= a || 1; - }, - setParser: function( name, parser ) { - this.parsers[name] = parser; - }, - // The next 3 are exposed so you can use them - quote: quote, - literal: literal, - join: join, - // - _depth_: 1, - // This is the list of parsers, to modify them, use jsDump.setParser - parsers: { - window: '[Window]', - document: '[Document]', - error: '[ERROR]', //when no parser is found, shouldn't happen - unknown: '[Unknown]', - 'null': 'null', - 'undefined': 'undefined', - 'function': function( fn ) { - var ret = 'function', - name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE - if ( name ) { - ret += ' ' + name; - } - ret += '('; - - ret = [ ret, QUnit.jsDump.parse( fn, 'functionArgs' ), '){'].join(''); - return join( ret, QUnit.jsDump.parse(fn,'functionCode'), '}' ); - }, - array: array, - nodelist: array, - 'arguments': array, - object: function( map, stack ) { - var ret = [ ], keys, key, val, i; - QUnit.jsDump.up(); - if (Object.keys) { - keys = Object.keys( map ); - } else { - keys = []; - for (key in map) { keys.push( key ); } - } - keys.sort(); - for (i = 0; i < keys.length; i++) { - key = keys[ i ]; - val = map[ key ]; - ret.push( QUnit.jsDump.parse( key, 'key' ) + ': ' + QUnit.jsDump.parse( val, undefined, stack ) ); - } - QUnit.jsDump.down(); - return join( '{', ret, '}' ); - }, - node: function( node ) { - var open = QUnit.jsDump.HTML ? '<' : '<', - close = QUnit.jsDump.HTML ? '>' : '>'; - - var tag = node.nodeName.toLowerCase(), - ret = open + tag; - - for ( var a in QUnit.jsDump.DOMAttrs ) { - var val = node[QUnit.jsDump.DOMAttrs[a]]; - if ( val ) { - ret += ' ' + a + '=' + QUnit.jsDump.parse( val, 'attribute' ); - } - } - return ret + close + open + '/' + tag + close; - }, - functionArgs: function( fn ) {//function calls it internally, it's the arguments part of the function - var l = fn.length; - if ( !l ) { - return ''; - } - - var args = new Array(l); - while ( l-- ) { - args[l] = String.fromCharCode(97+l);//97 is 'a' - } - return ' ' + args.join(', ') + ' '; - }, - key: quote, //object calls it internally, the key part of an item in a map - functionCode: '[code]', //function calls it internally, it's the content of the function - attribute: quote, //node calls it internally, it's an html attribute value - string: quote, - date: quote, - regexp: literal, //regex - number: literal, - 'boolean': literal - }, - DOMAttrs:{//attributes to dump from nodes, name=>realName - id:'id', - name:'name', - 'class':'className' - }, - HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) - indentChar:' ',//indentation unit - multiline:true //if true, items in a collection, are separated by a \n, else just a space. - }; - - return jsDump; -}()); - -// from Sizzle.js -function getText( elems ) { - var ret = "", elem; - - for ( var i = 0; elems[i]; i++ ) { - elem = elems[i]; - - // Get the text from text nodes and CDATA nodes - if ( elem.nodeType === 3 || elem.nodeType === 4 ) { - ret += elem.nodeValue; - - // Traverse everything else, except comment nodes - } else if ( elem.nodeType !== 8 ) { - ret += getText( elem.childNodes ); - } - } - - return ret; -} - -//from jquery.js -function inArray( elem, array ) { - if ( array.indexOf ) { - return array.indexOf( elem ); - } - - for ( var i = 0, length = array.length; i < length; i++ ) { - if ( array[ i ] === elem ) { - return i; - } - } - - return -1; -} - -/* - * Javascript Diff Algorithm - * By John Resig (http://ejohn.org/) - * Modified by Chu Alan "sprite" - * - * Released under the MIT license. - * - * More Info: - * http://ejohn.org/projects/javascript-diff-algorithm/ - * - * Usage: QUnit.diff(expected, actual) - * - * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick brown fox jumped jumps over" - */ -QUnit.diff = (function() { - function diff(o, n) { - var ns = {}; - var os = {}; - var i; - - for (i = 0; i < n.length; i++) { - if (ns[n[i]] == null) { - ns[n[i]] = { - rows: [], - o: null - }; - } - ns[n[i]].rows.push(i); - } - - for (i = 0; i < o.length; i++) { - if (os[o[i]] == null) { - os[o[i]] = { - rows: [], - n: null - }; - } - os[o[i]].rows.push(i); - } - - for (i in ns) { - if ( !hasOwn.call( ns, i ) ) { - continue; - } - if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) { - n[ns[i].rows[0]] = { - text: n[ns[i].rows[0]], - row: os[i].rows[0] - }; - o[os[i].rows[0]] = { - text: o[os[i].rows[0]], - row: ns[i].rows[0] - }; - } - } - - for (i = 0; i < n.length - 1; i++) { - if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && - n[i + 1] == o[n[i].row + 1]) { - n[i + 1] = { - text: n[i + 1], - row: n[i].row + 1 - }; - o[n[i].row + 1] = { - text: o[n[i].row + 1], - row: i + 1 - }; - } - } - - for (i = n.length - 1; i > 0; i--) { - if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && - n[i - 1] == o[n[i].row - 1]) { - n[i - 1] = { - text: n[i - 1], - row: n[i].row - 1 - }; - o[n[i].row - 1] = { - text: o[n[i].row - 1], - row: i - 1 - }; - } - } - - return { - o: o, - n: n - }; - } - - return function(o, n) { - o = o.replace(/\s+$/, ''); - n = n.replace(/\s+$/, ''); - var out = diff(o === "" ? [] : o.split(/\s+/), n === "" ? [] : n.split(/\s+/)); - - var str = ""; - var i; - - var oSpace = o.match(/\s+/g); - if (oSpace == null) { - oSpace = [" "]; - } - else { - oSpace.push(" "); - } - var nSpace = n.match(/\s+/g); - if (nSpace == null) { - nSpace = [" "]; - } - else { - nSpace.push(" "); - } - - if (out.n.length === 0) { - for (i = 0; i < out.o.length; i++) { - str += '' + out.o[i] + oSpace[i] + ""; - } - } - else { - if (out.n[0].text == null) { - for (n = 0; n < out.o.length && out.o[n].text == null; n++) { - str += '' + out.o[n] + oSpace[n] + ""; - } - } - - for (i = 0; i < out.n.length; i++) { - if (out.n[i].text == null) { - str += '' + out.n[i] + nSpace[i] + ""; - } - else { - var pre = ""; - - for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) { - pre += '' + out.o[n] + oSpace[n] + ""; - } - str += " " + out.n[i].text + nSpace[i] + pre; - } - } - } - - return str; - }; -}()); - -// for CommonJS enviroments, export everything -if ( typeof exports !== "undefined" || typeof require !== "undefined" ) { - extend(exports, QUnit); -} - -// get at whatever the global object is, like window in browsers -}( (function() {return this;}.call()) )); diff --git a/node/node_modules/grunt/tasks/init/jquery/root/src/name.js b/node/node_modules/grunt/tasks/init/jquery/root/src/name.js deleted file mode 100644 index 922c04146..000000000 --- a/node/node_modules/grunt/tasks/init/jquery/root/src/name.js +++ /dev/null @@ -1,28 +0,0 @@ -/* - * {%= name %} - * {%= homepage %} - * - * Copyright (c) {%= grunt.template.today('yyyy') %} {%= author_name %} - * Licensed under the {%= licenses.join(', ') %} license{%= licenses.length === 1 ? '' : 's' %}. - */ - -(function($) { - - // Collection method. - $.fn.awesome = function() { - return this.each(function() { - $(this).html('awesome'); - }); - }; - - // Static method. - $.awesome = function() { - return 'awesome'; - }; - - // Custom selector. - $.expr[':'].awesome = function(elem) { - return elem.textContent.indexOf('awesome') >= 0; - }; - -}(jQuery)); diff --git a/node/node_modules/grunt/tasks/init/jquery/root/test/name.html b/node/node_modules/grunt/tasks/init/jquery/root/test/name.html deleted file mode 100644 index 6f83f7da4..000000000 --- a/node/node_modules/grunt/tasks/init/jquery/root/test/name.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - {%= title || name %} Test Suite - - - - - - - - - - - - -

          {%= title || name %} Test Suite

          -

          -
          -

          -
            -
            - lame test markup - normal test markup - awesome test markup -
            - - diff --git a/node/node_modules/grunt/tasks/init/jquery/root/test/name_test.js b/node/node_modules/grunt/tasks/init/jquery/root/test/name_test.js deleted file mode 100644 index 129db8c36..000000000 --- a/node/node_modules/grunt/tasks/init/jquery/root/test/name_test.js +++ /dev/null @@ -1,57 +0,0 @@ -/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/ -/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/ -/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/ -(function($) { - - /* - ======== A Handy Little QUnit Reference ======== - http://docs.jquery.com/QUnit - - Test methods: - expect(numAssertions) - stop(increment) - start(decrement) - Test assertions: - ok(value, [message]) - equal(actual, expected, [message]) - notEqual(actual, expected, [message]) - deepEqual(actual, expected, [message]) - notDeepEqual(actual, expected, [message]) - strictEqual(actual, expected, [message]) - notStrictEqual(actual, expected, [message]) - raises(block, [expected], [message]) - */ - - module('jQuery#awesome', { - setup: function() { - this.elems = $('#qunit-fixture').children(); - } - }); - - test('is chainable', 1, function() { - // Not a bad test to run on collection methods. - strictEqual(this.elems.awesome(), this.elems, 'should be chaninable'); - }); - - test('is awesome', 1, function() { - strictEqual(this.elems.awesome().text(), 'awesomeawesomeawesome', 'should be thoroughly awesome'); - }); - - module('jQuery.awesome'); - - test('is awesome', 1, function() { - strictEqual($.awesome(), 'awesome', 'should be thoroughly awesome'); - }); - - module(':awesome selector', { - setup: function() { - this.elems = $('#qunit-fixture').children(); - } - }); - - test('is awesome', 1, function() { - // Use deepEqual & .get() when comparing jQuery objects. - deepEqual(this.elems.filter(':awesome').get(), this.elems.last().get(), 'knows awesome when it sees it'); - }); - -}(jQuery)); diff --git a/node/node_modules/grunt/tasks/init/licenses/LICENSE-GPL b/node/node_modules/grunt/tasks/init/licenses/LICENSE-GPL deleted file mode 100644 index 11dddd00e..000000000 --- a/node/node_modules/grunt/tasks/init/licenses/LICENSE-GPL +++ /dev/null @@ -1,278 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. diff --git a/node/node_modules/grunt/tasks/init/licenses/LICENSE-MIT b/node/node_modules/grunt/tasks/init/licenses/LICENSE-MIT deleted file mode 100644 index 1922cc28f..000000000 --- a/node/node_modules/grunt/tasks/init/licenses/LICENSE-MIT +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) {%= grunt.template.today('yyyy') %} {%= author_name %} - -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/node_modules/grunt/tasks/init/misc/placeholder b/node/node_modules/grunt/tasks/init/misc/placeholder deleted file mode 100644 index 4923c0736..000000000 --- a/node/node_modules/grunt/tasks/init/misc/placeholder +++ /dev/null @@ -1 +0,0 @@ -What is this I don’t even \ No newline at end of file diff --git a/node/node_modules/grunt/tasks/init/node.js b/node/node_modules/grunt/tasks/init/node.js deleted file mode 100644 index bee75b450..000000000 --- a/node/node_modules/grunt/tasks/init/node.js +++ /dev/null @@ -1,57 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -// Basic template description. -exports.description = 'Create a Node.js module, including Nodeunit unit tests.'; - -// Template-specific notes to be displayed before question prompts. -exports.notes = '_Project name_ shouldn\'t contain "node" or "js" and should ' + - 'be a unique ID not already in use at search.npmjs.org.'; - -// Any existing file or directory matching this wildcard will cause a warning. -exports.warnOn = '*'; - -// The actual init template. -exports.template = function(grunt, init, done) { - - grunt.helper('prompt', {type: 'node'}, [ - // Prompt for these values. - grunt.helper('prompt_for', 'name'), - grunt.helper('prompt_for', 'description'), - grunt.helper('prompt_for', 'version'), - grunt.helper('prompt_for', 'repository'), - grunt.helper('prompt_for', 'homepage'), - grunt.helper('prompt_for', 'bugs'), - grunt.helper('prompt_for', 'licenses'), - grunt.helper('prompt_for', 'author_name'), - grunt.helper('prompt_for', 'author_email'), - grunt.helper('prompt_for', 'author_url'), - grunt.helper('prompt_for', 'node_version'), - grunt.helper('prompt_for', 'main'), - grunt.helper('prompt_for', 'npm_test') - ], function(err, props) { - props.keywords = []; - - // Files to copy (and process). - var files = init.filesToCopy(props); - - // Add properly-named license files. - init.addLicenseFiles(files, props.licenses); - - // Actually copy (and process) files. - init.copyAndProcess(files, props); - - // Generate package.json file. - init.writePackageJSON('package.json', props); - - // All done! - done(); - }); - -}; diff --git a/node/node_modules/grunt/tasks/init/node/rename.json b/node/node_modules/grunt/tasks/init/node/rename.json deleted file mode 100644 index 69305eeef..000000000 --- a/node/node_modules/grunt/tasks/init/node/rename.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "lib/name.js": "lib/{%= name %}.js", - "test/name_test.js": "test/{%= name %}_test.js" -} diff --git a/node/node_modules/grunt/tasks/init/node/root/.npmignore b/node/node_modules/grunt/tasks/init/node/root/.npmignore deleted file mode 100644 index 2ccbe4656..000000000 --- a/node/node_modules/grunt/tasks/init/node/root/.npmignore +++ /dev/null @@ -1 +0,0 @@ -/node_modules/ diff --git a/node/node_modules/grunt/tasks/init/node/root/README.md b/node/node_modules/grunt/tasks/init/node/root/README.md deleted file mode 100644 index bb6766793..000000000 --- a/node/node_modules/grunt/tasks/init/node/root/README.md +++ /dev/null @@ -1,27 +0,0 @@ -# {%= name %} - -{%= description %} - -## Getting Started -Install the module with: `npm install {%= name %}` - -```javascript -var {%= js_safe_name %} = require('{%= name %}'); -{%= js_safe_name %}.awesome(); // "awesome" -``` - -## Documentation -_(Coming soon)_ - -## Examples -_(Coming soon)_ - -## Contributing -In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [grunt](https://github.com/gruntjs/grunt). - -## Release History -_(Nothing yet)_ - -## License -Copyright (c) {%= grunt.template.today('yyyy') %} {%= author_name %} -Licensed under the {%= licenses.join(', ') %} license{%= licenses.length === 1 ? '' : 's' %}. diff --git a/node/node_modules/grunt/tasks/init/node/root/grunt.js b/node/node_modules/grunt/tasks/init/node/root/grunt.js deleted file mode 100644 index e0c2cbbcb..000000000 --- a/node/node_modules/grunt/tasks/init/node/root/grunt.js +++ /dev/null @@ -1,39 +0,0 @@ -module.exports = function(grunt) { - - // Project configuration. - grunt.initConfig({ - pkg: '', - test: { - files: ['test/**/*.js'] - }, - lint: { - files: ['grunt.js', 'lib/**/*.js', 'test/**/*.js'] - }, - watch: { - files: '', - tasks: 'default' - }, - jshint: { - options: { - curly: true, - eqeqeq: true, - immed: true, - latedef: true, - newcap: true, - noarg: true, - sub: true, - undef: true, - boss: true, - eqnull: true, - node: true - }, - globals: { - exports: true - } - } - }); - - // Default task. - grunt.registerTask('default', 'lint test'); - -}; \ No newline at end of file diff --git a/node/node_modules/grunt/tasks/init/node/root/lib/name.js b/node/node_modules/grunt/tasks/init/node/root/lib/name.js deleted file mode 100644 index 021388353..000000000 --- a/node/node_modules/grunt/tasks/init/node/root/lib/name.js +++ /dev/null @@ -1,11 +0,0 @@ -/* - * {%= name %} - * {%= homepage %} - * - * Copyright (c) {%= grunt.template.today('yyyy') %} {%= author_name %} - * Licensed under the {%= licenses.join(', ') %} license{%= licenses.length === 1 ? '' : 's' %}. - */ - -exports.awesome = function() { - return 'awesome'; -}; diff --git a/node/node_modules/grunt/tasks/init/node/root/test/name_test.js b/node/node_modules/grunt/tasks/init/node/root/test/name_test.js deleted file mode 100644 index 252490f6f..000000000 --- a/node/node_modules/grunt/tasks/init/node/root/test/name_test.js +++ /dev/null @@ -1,34 +0,0 @@ -var {%= js_safe_name %} = require('../lib/{%= name %}.js'); - -/* - ======== A Handy Little Nodeunit Reference ======== - https://github.com/caolan/nodeunit - - Test methods: - test.expect(numAssertions) - test.done() - Test assertions: - test.ok(value, [message]) - test.equal(actual, expected, [message]) - test.notEqual(actual, expected, [message]) - test.deepEqual(actual, expected, [message]) - test.notDeepEqual(actual, expected, [message]) - test.strictEqual(actual, expected, [message]) - test.notStrictEqual(actual, expected, [message]) - test.throws(block, [error], [message]) - test.doesNotThrow(block, [error], [message]) - test.ifError(value) -*/ - -exports['awesome'] = { - setUp: function(done) { - // setup here - done(); - }, - 'no args': function(test) { - test.expect(1); - // tests here - test.equal({%= js_safe_name %}.awesome(), 'awesome', 'should be awesome.'); - test.done(); - } -}; diff --git a/node/node_modules/grunt/tasks/lint.js b/node/node_modules/grunt/tasks/lint.js deleted file mode 100644 index dfbfeb8ce..000000000 --- a/node/node_modules/grunt/tasks/lint.js +++ /dev/null @@ -1,151 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -module.exports = function(grunt) { - - // External libs. - var jshint = require('jshint').JSHINT; - - // ========================================================================== - // TASKS - // ========================================================================== - - grunt.registerMultiTask('lint', 'Validate files with JSHint.', function() { - // Get flags and globals, allowing target-specific options and globals to - // override the default options and globals. - var options, globals, tmp; - - tmp = grunt.config(['jshint', this.target, 'options']); - if (typeof tmp === 'object') { - grunt.verbose.writeln('Using "' + this.target + '" JSHint options.'); - options = tmp; - } else { - grunt.verbose.writeln('Using master JSHint options.'); - options = grunt.config('jshint.options'); - } - grunt.verbose.writeflags(options, 'Options'); - - tmp = grunt.config(['jshint', this.target, 'globals']); - if (typeof tmp === 'object') { - grunt.verbose.writeln('Using "' + this.target + '" JSHint globals.'); - globals = tmp; - } else { - grunt.verbose.writeln('Using master JSHint globals.'); - globals = grunt.config('jshint.globals'); - } - grunt.verbose.writeflags(globals, 'Globals'); - - // Lint specified files. - grunt.file.expandFiles(this.file.src).forEach(function(filepath) { - grunt.helper('lint', grunt.file.read(filepath), options, globals, filepath); - }); - - // Fail task if errors were logged. - if (this.errorCount) { return false; } - - // Otherwise, print a success message. - grunt.log.writeln('Lint free.'); - }); - - // ========================================================================== - // HELPERS - // ========================================================================== - - // No idea why JSHint treats tabs as options.indent # characters wide, but it - // does. See issue: https://github.com/jshint/jshint/issues/430 - function getTabStr(options) { - // Do something that's going to error. - jshint('\tx', options || {}); - // If an error occurred, figure out what character JSHint reported and - // subtract one. - var character = jshint.errors && jshint.errors[0] && jshint.errors[0].character - 1; - // If character is actually a number, use it. Otherwise use 1. - var tabsize = isNaN(character) ? 1 : character; - // If tabsize > 1, return something that should be safe to use as a - // placeholder. \uFFFF repeated 2+ times. - return tabsize > 1 && grunt.utils.repeat(tabsize, '\uFFFF'); - } - - var tabregex = /\t/g; - - // Lint source code with JSHint. - grunt.registerHelper('lint', function(src, options, globals, extraMsg) { - // JSHint sometimes modifies objects you pass in, so clone them. - options = grunt.utils._.clone(options); - globals = grunt.utils._.clone(globals); - // Enable/disable debugging if option explicitly set. - if (grunt.option('debug') !== undefined) { - options.devel = options.debug = grunt.option('debug'); - // Tweak a few things. - if (grunt.option('debug')) { - options.maxerr = Infinity; - } - } - var msg = 'Linting' + (extraMsg ? ' ' + extraMsg : '') + '...'; - grunt.verbose.write(msg); - // Tab size as reported by JSHint. - var tabstr = getTabStr(options); - var placeholderregex = new RegExp(tabstr, 'g'); - // Lint. - var result = jshint(src, options || {}, globals || {}); - // Attempt to work around JSHint erroneously reporting bugs. - // if (!result) { - // // Filter out errors that shouldn't be reported. - // jshint.errors = jshint.errors.filter(function(o) { - // return o && o.something === 'something'; - // }); - // // If no errors are left, JSHint actually succeeded. - // result = jshint.errors.length === 0; - // } - if (result) { - // Success! - grunt.verbose.ok(); - } else { - // Something went wrong. - grunt.verbose.or.write(msg); - grunt.log.error(); - // Iterate over all errors. - jshint.errors.forEach(function(e) { - // Sometimes there's no error object. - if (!e) { return; } - var pos; - var evidence = e.evidence; - var character = e.character; - if (evidence) { - // Manually increment errorcount since we're not using grunt.log.error(). - grunt.fail.errorcount++; - // Descriptive code error. - pos = '['.red + ('L' + e.line).yellow + ':'.red + ('C' + character).yellow + ']'.red; - grunt.log.writeln(pos + ' ' + e.reason.yellow); - // If necessary, eplace each tab char with something that can be - // swapped out later. - if (tabstr) { - evidence = evidence.replace(tabregex, tabstr); - } - if (character > evidence.length) { - // End of line. - evidence = evidence + ' '.inverse.red; - } else { - // Middle of line. - evidence = evidence.slice(0, character - 1) + evidence[character - 1].inverse.red + - evidence.slice(character); - } - // Replace tab placeholder (or tabs) but with a 2-space soft tab. - evidence = evidence.replace(tabstr ? placeholderregex : tabregex, ' '); - grunt.log.writeln(evidence); - } else { - // Generic "Whoops, too many errors" error. - grunt.log.error(e.reason); - } - }); - grunt.log.writeln(); - } - }); - -}; diff --git a/node/node_modules/grunt/tasks/min.js b/node/node_modules/grunt/tasks/min.js deleted file mode 100644 index 536e406be..000000000 --- a/node/node_modules/grunt/tasks/min.js +++ /dev/null @@ -1,92 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -module.exports = function(grunt) { - - // External libs. - var uglifyjs = require('uglify-js'); - var gzip = require('gzip-js'); - - // ========================================================================== - // TASKS - // ========================================================================== - - grunt.registerMultiTask('min', 'Minify files with UglifyJS.', function() { - var files = grunt.file.expandFiles(this.file.src); - // Get banner, if specified. It would be nice if UglifyJS supported ignoring - // all comments matching a certain pattern, like /*!...*/, but it doesn't. - var banner = grunt.task.directive(files[0], function() { return null; }); - if (banner === null) { - banner = ''; - } else { - files.shift(); - } - // Concat specified files. This should really be a single, pre-built (and - // linted) file, but it supports any number of files. - var max = grunt.helper('concat', files, {separator: this.data.separator}); - - // Concat banner + minified source. - var min = banner + grunt.helper('uglify', max, grunt.config('uglify')); - grunt.file.write(this.file.dest, min); - - // Fail task if errors were logged. - if (this.errorCount) { return false; } - - // Otherwise, print a success message.... - grunt.log.writeln('File "' + this.file.dest + '" created.'); - // ...and report some size information. - grunt.helper('min_max_info', min, max); - }); - - // ========================================================================== - // HELPERS - // ========================================================================== - - // Minify with UglifyJS. - // From https://github.com/mishoo/UglifyJS - grunt.registerHelper('uglify', function(src, options) { - if (!options) { options = {}; } - var jsp = uglifyjs.parser; - var pro = uglifyjs.uglify; - var ast, pos; - var msg = 'Minifying with UglifyJS...'; - grunt.verbose.write(msg); - try { - ast = jsp.parse(src); - ast = pro.ast_mangle(ast, options.mangle || {}); - ast = pro.ast_squeeze(ast, options.squeeze || {}); - src = pro.gen_code(ast, options.codegen || {}); - // Success! - grunt.verbose.ok(); - // UglifyJS adds a trailing semicolon only when run as a binary. - // So we manually add the trailing semicolon when using it as a module. - // https://github.com/mishoo/UglifyJS/issues/126 - return src + ';'; - } catch(e) { - // Something went wrong. - grunt.verbose.or.write(msg); - pos = '['.red + ('L' + e.line).yellow + ':'.red + ('C' + e.col).yellow + ']'.red; - grunt.log.error().writeln(pos + ' ' + (e.message + ' (position: ' + e.pos + ')').yellow); - grunt.warn('UglifyJS found errors.', 10); - } - }); - - // Return gzipped source. - grunt.registerHelper('gzip', function(src) { - return src ? gzip.zip(src, {}) : ''; - }); - - // Output some size info about a file. - grunt.registerHelper('min_max_info', function(min, max) { - var gzipSize = String(grunt.helper('gzip', min).length); - grunt.log.writeln('Uncompressed size: ' + String(max.length).green + ' bytes.'); - grunt.log.writeln('Compressed size: ' + gzipSize.green + ' bytes gzipped (' + String(min.length).green + ' bytes minified).'); - }); - -}; diff --git a/node/node_modules/grunt/tasks/misc.js b/node/node_modules/grunt/tasks/misc.js deleted file mode 100644 index e6265cddf..000000000 --- a/node/node_modules/grunt/tasks/misc.js +++ /dev/null @@ -1,85 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -module.exports = function(grunt) { - - // ========================================================================== - // HELPERS - // ========================================================================== - - // Get a config property. Most useful as a directive like . - grunt.registerHelper('config', grunt.config); - - // Read a JSON file. Most useful as a directive like . - var jsons = {}; - grunt.registerHelper('json', function(filepath) { - // Don't re-fetch if being called as a directive and JSON is already cached. - if (!this.directive || !(filepath in jsons)) { - jsons[filepath] = grunt.file.readJSON(filepath); - } - return jsons[filepath]; - }); - - // Return the given source coude with any leading banner comment stripped. - grunt.registerHelper('strip_banner', function(src, options) { - if (!options) { options = {}; } - var m = []; - if (options.line) { - // Strip // ... leading banners. - m.push('(?:.*\\/\\/.*\\n)*\\s*'); - } - if (options.block) { - // Strips all /* ... */ block comment banners. - m.push('\\/\\*[\\s\\S]*?\\*\\/'); - } else { - // Strips only /* ... */ block comment banners, excluding /*! ... */. - m.push('\\/\\*[^!][\\s\\S]*?\\*\\/'); - } - var re = new RegExp('^\\s*(?:' + m.join('|') + ')\\s*', ''); - return src.replace(re, ''); - }); - - // Get a source file's contents with any leading banner comment stripped. If - // used as a directive, get options from the flags object. - grunt.registerHelper('file_strip_banner', function(filepath, opts) { - var src = grunt.file.read(filepath); - return grunt.helper('strip_banner', src, this.directive ? this.flags : opts); - }); - - // Process a file as a template. - grunt.registerHelper('file_template', function(filepath) { - var src = grunt.file.read(filepath); - return grunt.template.process(src); - }); - - // Generate banner from template. - grunt.registerHelper('banner', function(prop) { - if (!prop) { prop = 'meta.banner'; } - var banner; - var tmpl = grunt.config(prop); - if (tmpl) { - // Now, log. - grunt.verbose.write('Generating banner...'); - try { - // Compile and run template, using config object as the data source. - banner = grunt.template.process(tmpl) + grunt.utils.linefeed; - grunt.verbose.ok(); - } catch(e) { - banner = ''; - grunt.verbose.error(); - grunt.warn(e, 11); - } - } else { - grunt.warn('No "' + prop + '" banner template defined.', 11); - banner = ''; - } - return banner; - }); - -}; diff --git a/node/node_modules/grunt/tasks/qunit.js b/node/node_modules/grunt/tasks/qunit.js deleted file mode 100644 index 851afd818..000000000 --- a/node/node_modules/grunt/tasks/qunit.js +++ /dev/null @@ -1,258 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -module.exports = function(grunt) { - - // Nodejs libs. - var fs = require('fs'); - var path = require('path'); - - // External libs. - var Tempfile = require('temporary/lib/file'); - - // Keep track of the last-started module, test and status. - var currentModule, currentTest, status; - // Keep track of the last-started test(s). - var unfinished = {}; - - // Allow an error message to retain its color when split across multiple lines. - function formatMessage(str) { - return String(str).split('\n').map(function(s) { return s.magenta; }).join('\n'); - } - - // Keep track of failed assertions for pretty-printing. - var failedAssertions = []; - function logFailedAssertions() { - var assertion; - // Print each assertion error. - while (assertion = failedAssertions.shift()) { - grunt.verbose.or.error(assertion.testName); - grunt.log.error('Message: ' + formatMessage(assertion.message)); - if (assertion.actual !== assertion.expected) { - grunt.log.error('Actual: ' + formatMessage(assertion.actual)); - grunt.log.error('Expected: ' + formatMessage(assertion.expected)); - } - if (assertion.source) { - grunt.log.error(assertion.source.replace(/ {4}(at)/g, ' $1')); - } - grunt.log.writeln(); - } - } - - // Handle methods passed from PhantomJS, including QUnit hooks. - var phantomHandlers = { - // QUnit hooks. - moduleStart: function(name) { - unfinished[name] = true; - currentModule = name; - }, - moduleDone: function(name, failed, passed, total) { - delete unfinished[name]; - }, - log: function(result, actual, expected, message, source) { - if (!result) { - failedAssertions.push({ - actual: actual, expected: expected, message: message, source: source, - testName: currentTest - }); - } - }, - testStart: function(name) { - currentTest = (currentModule ? currentModule + ' - ' : '') + name; - grunt.verbose.write(currentTest + '...'); - }, - testDone: function(name, failed, passed, total) { - // Log errors if necessary, otherwise success. - if (failed > 0) { - // list assertions - if (grunt.option('verbose')) { - grunt.log.error(); - logFailedAssertions(); - } else { - grunt.log.write('F'.red); - } - } else { - grunt.verbose.ok().or.write('.'); - } - }, - done: function(failed, passed, total, duration) { - status.failed += failed; - status.passed += passed; - status.total += total; - status.duration += duration; - // Print assertion errors here, if verbose mode is disabled. - if (!grunt.option('verbose')) { - if (failed > 0) { - grunt.log.writeln(); - logFailedAssertions(); - } else { - grunt.log.ok(); - } - } - }, - // Error handlers. - done_fail: function(url) { - grunt.verbose.write('Running PhantomJS...').or.write('...'); - grunt.log.error(); - grunt.warn('PhantomJS unable to load "' + url + '" URI.', 90); - }, - done_timeout: function() { - grunt.log.writeln(); - grunt.warn('PhantomJS timed out, possibly due to a missing QUnit start() call.', 90); - }, - // console.log pass-through. - console: console.log.bind(console), - // Debugging messages. - debug: grunt.log.debug.bind(grunt.log, 'phantomjs') - }; - - // ========================================================================== - // TASKS - // ========================================================================== - - grunt.registerMultiTask('qunit', 'Run QUnit unit tests in a headless PhantomJS instance.', function() { - // Get files as URLs. - var urls = grunt.file.expandFileURLs(this.file.src); - - // This task is asynchronous. - var done = this.async(); - - // Reset status. - status = {failed: 0, passed: 0, total: 0, duration: 0}; - - // Process each filepath in-order. - grunt.utils.async.forEachSeries(urls, function(url, next) { - var basename = path.basename(url); - grunt.verbose.subhead('Testing ' + basename).or.write('Testing ' + basename); - - // Create temporary file to be used for grunt-phantom communication. - var tempfile = new Tempfile(); - // Timeout ID. - var id; - // The number of tempfile lines already read. - var n = 0; - - // Reset current module. - currentModule = null; - - // Clean up. - function cleanup() { - clearTimeout(id); - tempfile.unlink(); - } - - // It's simple. As QUnit tests, assertions and modules begin and complete, - // the results are written as JSON to a temporary file. This polling loop - // checks that file for new lines, and for each one parses its JSON and - // executes the corresponding method with the specified arguments. - (function loopy() { - // Disable logging temporarily. - grunt.log.muted = true; - // Read the file, splitting lines on \n, and removing a trailing line. - var lines = grunt.file.read(tempfile.path).split('\n').slice(0, -1); - // Re-enable logging. - grunt.log.muted = false; - // Iterate over all lines that haven't already been processed. - var done = lines.slice(n).some(function(line) { - // Get args and method. - var args = JSON.parse(line); - var method = args.shift(); - // Execute method if it exists. - if (phantomHandlers[method]) { - phantomHandlers[method].apply(null, args); - } - // If the method name started with test, return true. Because the - // Array#some method was used, this not only sets "done" to true, - // but stops further iteration from occurring. - return (/^done/).test(method); - }); - - if (done) { - // All done. - cleanup(); - next(); - } else { - // Update n so previously processed lines are ignored. - n = lines.length; - // Check back in a little bit. - id = setTimeout(loopy, 100); - } - }()); - - // Launch PhantomJS. - grunt.helper('phantomjs', { - code: 90, - args: [ - // PhantomJS options. - '--config=' + grunt.task.getFile('qunit/phantom.json'), - // The main script file. - grunt.task.getFile('qunit/phantom.js'), - // The temporary file used for communications. - tempfile.path, - // The QUnit helper file to be injected. - grunt.task.getFile('qunit/qunit.js'), - // URL to the QUnit .html test file to run. - url - ], - done: function(err) { - if (err) { - cleanup(); - done(); - } - }, - }); - }, function(err) { - // All tests have been run. - - // Log results. - if (status.failed > 0) { - grunt.warn(status.failed + '/' + status.total + ' assertions failed (' + - status.duration + 'ms)', Math.min(99, 90 + status.failed)); - } else { - grunt.verbose.writeln(); - grunt.log.ok(status.total + ' assertions passed (' + status.duration + 'ms)'); - } - - // All done! - done(); - }); - }); - - // ========================================================================== - // HELPERS - // ========================================================================== - - grunt.registerHelper('phantomjs', function(options) { - return grunt.utils.spawn({ - cmd: 'phantomjs', - args: options.args - }, function(err, result, code) { - if (!err) { return options.done(null); } - // Something went horribly wrong. - grunt.verbose.or.writeln(); - grunt.log.write('Running PhantomJS...').error(); - if (code === 127) { - grunt.log.errorlns( - 'In order for this task to work properly, PhantomJS must be ' + - 'installed and in the system PATH (if you can run "phantomjs" at' + - ' the command line, this task should work). Unfortunately, ' + - 'PhantomJS cannot be installed automatically via npm or grunt. ' + - 'See the grunt FAQ for PhantomJS installation instructions: ' + - 'https://github.com/gruntjs/grunt/blob/master/docs/faq.md' - ); - grunt.warn('PhantomJS not found.', options.code); - } else { - result.split('\n').forEach(grunt.log.error, grunt.log); - grunt.warn('PhantomJS exited unexpectedly with exit code ' + code + '.', options.code); - } - options.done(code); - }); - }); - -}; diff --git a/node/node_modules/grunt/tasks/qunit/phantom.js b/node/node_modules/grunt/tasks/qunit/phantom.js deleted file mode 100644 index ab4cdc877..000000000 --- a/node/node_modules/grunt/tasks/qunit/phantom.js +++ /dev/null @@ -1,91 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -/*global phantom:true*/ - -var fs = require('fs'); - -// The temporary file used for communications. -var tmpfile = phantom.args[0]; -// The QUnit helper file to be injected. -var qunit = phantom.args[1]; -// The QUnit .html test file to run. -var url = phantom.args[2]; - -// Keep track of the last time a QUnit message was sent. -var last = new Date(); - -// Messages are sent to the parent by appending them to the tempfile. -function sendMessage(args) { - last = new Date(); - fs.write(tmpfile, JSON.stringify(args) + '\n', 'a'); - // Exit when all done. - if (/^done/.test(args[0])) { - phantom.exit(); - } -} - -// Send a debugging message. -function sendDebugMessage() { - sendMessage(['debug'].concat([].slice.call(arguments))); -} - -// Abort if QUnit doesn't do anything for a while. -setInterval(function() { - if (new Date() - last > 5000) { - sendMessage(['done_timeout']); - } -}, 1000); - -// Create a new page. -var page = require('webpage').create(); - -// QUnit sends its messages via alert(jsonstring); -page.onAlert = function(args) { - sendMessage(JSON.parse(args)); -}; - -// Keep track if QUnit has been injected already. -var injected; - -// Additional message sending -page.onConsoleMessage = function(message) { - sendMessage(['console', message]); -}; -page.onResourceRequested = function(request) { - if (/\/qunit\.js$/.test(request.url)) { - // Reset injected to false, if for some reason a redirect occurred and - // the test page (including qunit.js) had to be re-requested. - injected = false; - } - sendDebugMessage('onResourceRequested', request.url); -}; -page.onResourceReceived = function(request) { - if (request.stage === 'end') { - sendDebugMessage('onResourceReceived', request.url); - } -}; - -page.open(url, function(status) { - // Only execute this code if QUnit has not yet been injected. - if (injected) { return; } - injected = true; - // The window has loaded. - if (status !== 'success') { - // File loading failure. - sendMessage(['done_fail', url]); - } else { - // Inject QUnit helper file. - sendDebugMessage('inject', qunit); - page.injectJs(qunit); - // Because injection happens after window load, "begin" must be sent - // manually. - sendMessage(['begin']); - } -}); diff --git a/node/node_modules/grunt/tasks/qunit/phantom.json b/node/node_modules/grunt/tasks/qunit/phantom.json deleted file mode 100644 index 9e26dfeeb..000000000 --- a/node/node_modules/grunt/tasks/qunit/phantom.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/node/node_modules/grunt/tasks/qunit/qunit.js b/node/node_modules/grunt/tasks/qunit/qunit.js deleted file mode 100644 index f7754265b..000000000 --- a/node/node_modules/grunt/tasks/qunit/qunit.js +++ /dev/null @@ -1,55 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -/*global QUnit:true, alert:true*/ - -// Don't re-order tests. -QUnit.config.reorder = false; -// Run tests serially, not in parallel. -QUnit.config.autorun = false; - -// Send messages to the parent zombie.js process via alert! Good times!! -function sendMessage() { - var args = [].slice.call(arguments); - alert(JSON.stringify(args)); -} - -QUnit.log(function(obj) { - // What is this I don’t even - if (obj.message === '[object Object], undefined:undefined') { return; } - // Parse some stuff before sending it. - var actual = QUnit.jsDump.parse(obj.actual); - var expected = QUnit.jsDump.parse(obj.expected); - // Send it. - sendMessage('log', obj.result, actual, expected, obj.message, obj.source); -}); - -QUnit.testStart(function(obj) { - sendMessage('testStart', obj.name); -}); - -QUnit.testDone(function(obj) { - sendMessage('testDone', obj.name, obj.failed, obj.passed, obj.total); -}); - -QUnit.moduleStart(function(obj) { - sendMessage('moduleStart', obj.name); -}); - -QUnit.moduleDone(function(obj) { - sendMessage('moduleDone', obj.name, obj.failed, obj.passed, obj.total); -}); - -QUnit.begin(function() { - sendMessage('begin'); -}); - -QUnit.done(function(obj) { - sendMessage('done', obj.failed, obj.passed, obj.total, obj.runtime); -}); diff --git a/node/node_modules/grunt/tasks/server.js b/node/node_modules/grunt/tasks/server.js deleted file mode 100644 index 450e8de14..000000000 --- a/node/node_modules/grunt/tasks/server.js +++ /dev/null @@ -1,46 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -module.exports = function(grunt) { - - // Nodejs libs. - var path = require('path'); - - // External libs. - var connect = require('connect'); - - // ========================================================================== - // TASKS - // ========================================================================== - - grunt.registerTask('server', 'Start a static web server.', function() { - // Get values from config, or use defaults. - var port = grunt.config('server.port') || 8000; - var base = path.resolve(grunt.config('server.base') || '.'); - - var middleware = [ - // Serve static files. - connect.static(base), - // Make empty directories browsable. (overkill?) - connect.directory(base) - ]; - - // If --debug was specified, enable logging. - if (grunt.option('debug')) { - connect.logger.format('grunt', ('[D] server :method :url :status ' + - ':res[content-length] - :response-time ms').magenta); - middleware.unshift(connect.logger('grunt')); - } - - // Start server. - grunt.log.writeln('Starting static web server on port ' + port + '.'); - connect.apply(null, middleware).listen(port); - }); - -}; diff --git a/node/node_modules/grunt/tasks/test.js b/node/node_modules/grunt/tasks/test.js deleted file mode 100644 index 048665a28..000000000 --- a/node/node_modules/grunt/tasks/test.js +++ /dev/null @@ -1,160 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -module.exports = function(grunt) { - - // Nodejs libs. - var path = require('path'); - - // External libs. - var nodeunit = require('nodeunit'); - var nodeunitUtils = require('nodeunit/lib/utils'); - - // ========================================================================== - // CUSTOM NODEUNIT REPORTER - // ========================================================================== - - // Keep track of the last-started module. - var currentModule; - // Keep track of the last-started test(s). - var unfinished = {}; - - // If Nodeunit explodes because a test was missing test.done(), handle it. - process.on('exit', function() { - var len = Object.keys(unfinished).length; - // If there are unfinished tests, tell the user why Nodeunit killed grunt. - if (len > 0) { - grunt.log.muted = false; - grunt.verbose.error().or.writeln('F'.red); - grunt.log.error('Incomplete tests/setups/teardowns:'); - Object.keys(unfinished).forEach(grunt.log.error, grunt.log); - grunt.fatal('A test was missing test.done(), so nodeunit exploded. Sorry!', - Math.min(99, 90 + len)); - } - }); - - // Keep track of failed assertions for pretty-printing. - var failedAssertions = []; - function logFailedAssertions() { - var assertion, stack; - // Print each assertion error + stack. - while (assertion = failedAssertions.shift()) { - nodeunitUtils.betterErrors(assertion); - grunt.verbose.or.error(assertion.testName); - if (assertion.error.name === 'AssertionError' && assertion.message) { - grunt.log.error('AssertionMessage: ' + assertion.message.magenta); - } - stack = assertion.error.stack.replace(/ {4}(at)/g, ' $1'); - stack = stack.replace(/:(.*?\n)/, '$1'.magenta); - grunt.log.error(stack + '\n').writeln(); - } - } - - // Define our own Nodeunit reporter. - nodeunit.reporters.grunt = { - info: 'Grunt reporter', - run: function(files, options, callback) { - var opts = { - // No idea. - testspec: undefined, - // Executed when the first test in a file is run. If no tests exist in - // the file, this doesn't execute. - moduleStart: function(name) { - // Keep track of this so that moduleDone output can be suppressed in - // cases where a test file contains no tests. - currentModule = name; - grunt.verbose.subhead('Testing ' + name).or.write('Testing ' + name); - }, - // Executed after a file is done being processed. This executes whether - // tests exist in the file or not. - moduleDone: function(name) { - // Abort if no tests actually ran. - if (name !== currentModule) { return; } - // Print assertion errors here, if verbose mode is disabled. - if (!grunt.option('verbose')) { - if (failedAssertions.length > 0) { - grunt.log.writeln(); - logFailedAssertions(); - } else { - grunt.log.ok(); - } - } - }, - // Executed before each test is run. - testStart: function(name) { - // Keep track of the current test, in case test.done() was omitted - // and Nodeunit explodes. - unfinished[name] = name; - grunt.verbose.write(name + '...'); - // Mute output, in cases where a function being tested logs through - // grunt (for testing grunt internals). - grunt.log.muted = true; - }, - // Executed after each test and all its assertions are run. - testDone: function(name, assertions) { - delete unfinished[name]; - // Un-mute output. - grunt.log.muted = false; - // Log errors if necessary, otherwise success. - if (assertions.failures()) { - assertions.forEach(function(ass) { - if (ass.failed()) { - ass.testName = name; - failedAssertions.push(ass); - } - }); - if (grunt.option('verbose')) { - grunt.log.error(); - logFailedAssertions(); - } else { - grunt.log.write('F'.red); - } - } else { - grunt.verbose.ok().or.write('.'); - } - }, - // Executed when everything is all done. - done: function (assertions) { - if (assertions.failures()) { - grunt.warn(assertions.failures() + '/' + assertions.length + - ' assertions failed (' + assertions.duration + 'ms)', - Math.min(99, 90 + assertions.failures())); - } else { - grunt.verbose.writeln(); - grunt.log.ok(assertions.length + ' assertions passed (' + - assertions.duration + 'ms)'); - } - // Tell the task manager we're all done. - callback(); // callback(assertions.failures() === 0); - } - }; - - // Nodeunit needs absolute paths. - var paths = files.map(function(filepath) { - return path.resolve(filepath); - }); - nodeunit.runFiles(paths, opts); - } - }; - - // ========================================================================== - // TASKS - // ========================================================================== - - grunt.registerMultiTask('test', 'Run unit tests with nodeunit.', function() { - // File paths. - var filepaths = grunt.file.expandFiles(this.file.src); - // Clear all tests' cached require data, in case this task is run inside a - // "watch" task loop. - grunt.file.clearRequireCache(filepaths); - // Run test(s)... asynchronously! - nodeunit.reporters.grunt.run(filepaths, {}, this.async()); - }); - -}; diff --git a/node/node_modules/grunt/tasks/watch.js b/node/node_modules/grunt/tasks/watch.js deleted file mode 100644 index 98e61b1ff..000000000 --- a/node/node_modules/grunt/tasks/watch.js +++ /dev/null @@ -1,168 +0,0 @@ -/* - * grunt - * http://gruntjs.com/ - * - * Copyright (c) 2012 "Cowboy" Ben Alman - * Licensed under the MIT license. - * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT - */ - -module.exports = function(grunt) { - - // Nodejs libs. - var fs = require('fs'); - var path = require('path'); - // In Nodejs 0.8.0, existsSync moved from path -> fs. - var existsSync = fs.existsSync || path.existsSync; - - // ========================================================================== - // TASKS - // ========================================================================== - - // Keep track of last modified times of files, in case files are reported to - // have changed incorrectly. - var mtimes = {}; - - grunt.registerTask('watch', 'Run predefined tasks whenever watched files change.', function(target) { - this.requiresConfig('watch'); - // Build an array of files/tasks objects. - var watch = grunt.config('watch'); - var targets = target ? [target] : Object.keys(watch).filter(function(key) { - return typeof watch[key] !== 'string' && !Array.isArray(watch[key]); - }); - targets = targets.map(function(target) { - // Fail if any required config properties have been omitted. - target = ['watch', target]; - this.requiresConfig(target.concat('files'), target.concat('tasks')); - return grunt.config(target); - }, this); - - // Allow "basic" non-target format. - if (typeof watch.files === 'string' || Array.isArray(watch.files)) { - targets.push({files: watch.files, tasks: watch.tasks}); - } - - grunt.log.write('Waiting...'); - - // This task is asynchronous. - var taskDone = this.async(); - // Get a list of files to be watched. - var patterns = grunt.utils._.chain(targets).pluck('files').flatten().uniq().value(); - var getFiles = grunt.file.expandFiles.bind(grunt.file, patterns); - // The tasks to be run. - var tasks = []; //grunt.config(tasksProp); - // This task's name + optional args, in string format. - var nameArgs = this.nameArgs; - // An ID by which the setInterval can be canceled. - var intervalId; - // Files that are being watched. - var watchedFiles = {}; - // File changes to be logged. - var changedFiles = {}; - - // Define an alternate fail "warn" behavior. - grunt.fail.warnAlternate = function() { - grunt.task.clearQueue({untilMarker: true}).run(nameArgs); - }; - - // Cleanup when files have changed. This is debounced to handle situations - // where editors save multiple files "simultaneously" and should wait until - // all the files are saved. - var done = grunt.utils._.debounce(function() { - // Clear the files-added setInterval. - clearInterval(intervalId); - // Ok! - grunt.log.ok(); - var fileArray = Object.keys(changedFiles); - fileArray.forEach(function(filepath) { - // Log which file has changed, and how. - grunt.log.ok('File "' + filepath + '" ' + changedFiles[filepath] + '.'); - // Clear the modified file's cached require data. - grunt.file.clearRequireCache(filepath); - }); - // Unwatch all watched files. - Object.keys(watchedFiles).forEach(unWatchFile); - // For each specified target, test to see if any files matching that - // target's file patterns were modified. - targets.forEach(function(target) { - var files = grunt.file.expandFiles(target.files); - var intersection = grunt.utils._.intersection(fileArray, files); - // Enqueue specified tasks if a matching file was found. - if (intersection.length > 0 && target.tasks) { - grunt.task.run(target.tasks).mark(); - } - }); - // Enqueue the watch task, so that it loops. - grunt.task.run(nameArgs); - // Continue task queue. - taskDone(); - }, 250); - - // Handle file changes. - function fileChanged(status, filepath) { - // If file was deleted and then re-added, consider it changed. - if (changedFiles[filepath] === 'deleted' && status === 'added') { - status = 'changed'; - } - // Keep track of changed status for later. - changedFiles[filepath] = status; - // Execute debounced done function. - done(); - } - - // Watch a file. - function watchFile(filepath) { - if (!watchedFiles[filepath]) { - // Watch this file for changes. This probably won't scale to hundreds of - // files.. but I bet someone will try it! - watchedFiles[filepath] = fs.watch(filepath, function(event) { - var mtime; - // Has the file been deleted? - var deleted = !existsSync(filepath); - if (deleted) { - // If file was deleted, stop watching file. - unWatchFile(filepath); - // Remove from mtimes. - delete mtimes[filepath]; - } else { - // Get last modified time of file. - mtime = +fs.statSync(filepath).mtime; - // If same as stored mtime, the file hasn't changed. - if (mtime === mtimes[filepath]) { return; } - // Otherwise it has, store mtime for later use. - mtimes[filepath] = mtime; - } - // Call "change" for this file, setting status appropriately (rename -> - // renamed, change -> changed). - fileChanged(deleted ? 'deleted' : event + 'd', filepath); - }); - } - } - - // Unwatch a file. - function unWatchFile(filepath) { - if (watchedFiles[filepath]) { - // Close watcher. - watchedFiles[filepath].close(); - // Remove from watched files. - delete watchedFiles[filepath]; - } - } - - // Watch all currently existing files for changes. - getFiles().forEach(watchFile); - - // Watch for files to be added. - intervalId = setInterval(function() { - // Files that have been added since last interval execution. - var added = grunt.utils._.difference(getFiles(), Object.keys(watchedFiles)); - added.forEach(function(filepath) { - // This file has been added. - fileChanged('added', filepath); - // Watch this file. - watchFile(filepath); - }); - }, 200); - }); - -}; diff --git a/node/node_modules/grunt/test/fixtures/BOM.txt b/node/node_modules/grunt/test/fixtures/BOM.txt new file mode 100644 index 000000000..e1fde7839 --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/BOM.txt @@ -0,0 +1 @@ +foo \ No newline at end of file diff --git a/node/node_modules/grunt/test/fixtures/Gruntfile-print-text.js b/node/node_modules/grunt/test/fixtures/Gruntfile-print-text.js new file mode 100644 index 000000000..910197dd9 --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/Gruntfile-print-text.js @@ -0,0 +1,8 @@ +module.exports = function(grunt) { + + grunt.registerTask('print', 'Print the specified text.', function(text) { + console.log('OUTPUT: ' + text); + // console.log(process.cwd()); + }); + +}; diff --git a/node/node_modules/grunt/test/fixtures/exec.cmd b/node/node_modules/grunt/test/fixtures/exec.cmd new file mode 100755 index 000000000..6e4a52bb2 --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/exec.cmd @@ -0,0 +1 @@ +@echo done diff --git a/node/node_modules/grunt/test/fixtures/exec.sh b/node/node_modules/grunt/test/fixtures/exec.sh new file mode 100755 index 000000000..889079978 --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/exec.sh @@ -0,0 +1,2 @@ +#!/bin/bash +echo "done" diff --git a/node/node_modules/grunt/test/fixtures/expand-mapping-ext/dir.ectory/file-no-extension b/node/node_modules/grunt/test/fixtures/expand-mapping-ext/dir.ectory/file-no-extension new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/expand-mapping-ext/dir.ectory/sub.dir.ectory/file.ext.ension b/node/node_modules/grunt/test/fixtures/expand-mapping-ext/dir.ectory/sub.dir.ectory/file.ext.ension new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/expand-mapping-ext/file.ext.ension b/node/node_modules/grunt/test/fixtures/expand-mapping-ext/file.ext.ension new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/expand/README.md b/node/node_modules/grunt/test/fixtures/expand/README.md new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/expand/css/baz.css b/node/node_modules/grunt/test/fixtures/expand/css/baz.css new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/expand/css/qux.css b/node/node_modules/grunt/test/fixtures/expand/css/qux.css new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/expand/deep/deep.txt b/node/node_modules/grunt/test/fixtures/expand/deep/deep.txt new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/expand/deep/deeper/deeper.txt b/node/node_modules/grunt/test/fixtures/expand/deep/deeper/deeper.txt new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/expand/deep/deeper/deepest/deepest.txt b/node/node_modules/grunt/test/fixtures/expand/deep/deeper/deepest/deepest.txt new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/expand/js/bar.js b/node/node_modules/grunt/test/fixtures/expand/js/bar.js new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/expand/js/foo.js b/node/node_modules/grunt/test/fixtures/expand/js/foo.js new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/files/dist/built-123-a.js b/node/node_modules/grunt/test/fixtures/files/dist/built-123-a.js new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/files/dist/built-123-b.js b/node/node_modules/grunt/test/fixtures/files/dist/built-123-b.js new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/files/dist/built-a.js b/node/node_modules/grunt/test/fixtures/files/dist/built-a.js new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/files/dist/built-b.js b/node/node_modules/grunt/test/fixtures/files/dist/built-b.js new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/files/dist/built.js b/node/node_modules/grunt/test/fixtures/files/dist/built.js new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/files/src/file1-123.js b/node/node_modules/grunt/test/fixtures/files/src/file1-123.js new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/files/src/file1.js b/node/node_modules/grunt/test/fixtures/files/src/file1.js new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/files/src/file2-123.js b/node/node_modules/grunt/test/fixtures/files/src/file2-123.js new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/files/src/file2.js b/node/node_modules/grunt/test/fixtures/files/src/file2.js new file mode 100644 index 000000000..e69de29bb diff --git a/node/node_modules/grunt/test/fixtures/iso-8859-1.json b/node/node_modules/grunt/test/fixtures/iso-8859-1.json new file mode 100644 index 000000000..31e1dc348 --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/iso-8859-1.json @@ -0,0 +1,4 @@ +{ + "foo": "Ao isso a", + "bar": ["mg", "pnies"] +} diff --git a/node/node_modules/grunt/test/fixtures/iso-8859-1.txt b/node/node_modules/grunt/test/fixtures/iso-8859-1.txt new file mode 100644 index 000000000..c4a168446 --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/iso-8859-1.txt @@ -0,0 +1 @@ +Ao isso a diff --git a/node/node_modules/grunt/test/fixtures/iso-8859-1.yaml b/node/node_modules/grunt/test/fixtures/iso-8859-1.yaml new file mode 100644 index 000000000..b869cc121 --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/iso-8859-1.yaml @@ -0,0 +1,4 @@ +foo: Ao isso a +bar: + - mg + - pnies diff --git a/node/node_modules/grunt/test/fixtures/lint.txt b/node/node_modules/grunt/test/fixtures/lint.txt new file mode 100644 index 000000000..62b115667 Binary files /dev/null and b/node/node_modules/grunt/test/fixtures/lint.txt differ diff --git a/node/node_modules/grunt/test/fixtures/lintTest.js b/node/node_modules/grunt/test/fixtures/lintTest.js deleted file mode 100644 index 3b27fb940..000000000 --- a/node/node_modules/grunt/test/fixtures/lintTest.js +++ /dev/null @@ -1,10 +0,0 @@ -var a = 0 - , b = 1 - , c = 2 - , d = 3 - -var foo = function(varA, varB, varC, varD) { - return varA + varB + varC + varD -} - -foo(a, b, c, d) diff --git a/node/node_modules/grunt/test/fixtures/no_BOM.txt b/node/node_modules/grunt/test/fixtures/no_BOM.txt new file mode 100644 index 000000000..191028156 --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/no_BOM.txt @@ -0,0 +1 @@ +foo \ No newline at end of file diff --git a/node/node_modules/grunt/test/fixtures/spawn-multibyte.js b/node/node_modules/grunt/test/fixtures/spawn-multibyte.js new file mode 100644 index 000000000..8277711f6 --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/spawn-multibyte.js @@ -0,0 +1,17 @@ +// This is a test fixture for a case where spawn receives incomplete +// multibyte strings in separate data events. + +// A multibyte buffer containing all our output. We will slice it later. +// In this case we are using a Japanese word for hello / good day, where each +// character takes three bytes. +var fullOutput = new Buffer('こんにちは'); + +// Output one full character and one third of a character +process.stdout.write(fullOutput.slice(0, 4)); + +// Output the rest of the string +process.stdout.write(fullOutput.slice(4)); + +// Do the same for stderr +process.stderr.write(fullOutput.slice(0, 4)); +process.stderr.write(fullOutput.slice(4)); diff --git a/node/node_modules/grunt/test/fixtures/spawn.js b/node/node_modules/grunt/test/fixtures/spawn.js new file mode 100644 index 000000000..eb656579f --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/spawn.js @@ -0,0 +1,9 @@ + +var code = Number(process.argv[2]); + +process.stdout.write('stdout\n'); +process.stderr.write('stderr\n'); + +// Use instead of process.exit to ensure stdout/stderr are flushed +// before exiting in Windows (Tested in Node.js v0.8.7) +require('../../lib/util/exit').exit(code); diff --git a/node/node_modules/grunt/test/fixtures/utf8.json b/node/node_modules/grunt/test/fixtures/utf8.json new file mode 100644 index 000000000..d10e97537 --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/utf8.json @@ -0,0 +1,4 @@ +{ + "foo": "Ação é isso aí", + "bar": ["ømg", "pønies"] +} diff --git a/node/node_modules/grunt/test/fixtures/utf8.txt b/node/node_modules/grunt/test/fixtures/utf8.txt new file mode 100644 index 000000000..eadbdb40b --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/utf8.txt @@ -0,0 +1 @@ +Ação é isso aí diff --git a/node/node_modules/grunt/test/fixtures/utf8.yaml b/node/node_modules/grunt/test/fixtures/utf8.yaml new file mode 100644 index 000000000..7eb7321c6 --- /dev/null +++ b/node/node_modules/grunt/test/fixtures/utf8.yaml @@ -0,0 +1,4 @@ +foo: Ação é isso aí +bar: + - ømg + - pønies diff --git a/node/node_modules/grunt/test/grunt/config_test.js b/node/node_modules/grunt/test/grunt/config_test.js new file mode 100644 index 000000000..8b731d767 --- /dev/null +++ b/node/node_modules/grunt/test/grunt/config_test.js @@ -0,0 +1,110 @@ +'use strict'; + +var grunt = require('../../lib/grunt'); + +exports['config'] = { + setUp: function(done) { + this.origData = grunt.config.data; + grunt.config.init({ + meta: grunt.file.readJSON('test/fixtures/test.json'), + foo: '<%= meta.foo %>', + foo2: '<%= foo %>', + obj: { + foo: '<%= meta.foo %>', + foo2: '<%= obj.foo %>', + Arr: ['foo', '<%= obj.foo2 %>'], + arr2: ['<%= arr %>', '<%= obj.Arr %>'], + }, + bar: 'bar', + arr: ['foo', '<%= obj.foo2 %>'], + arr2: ['<%= arr %>', '<%= obj.Arr %>'], + }); + done(); + }, + tearDown: function(done) { + grunt.config.data = this.origData; + done(); + }, + 'config.escape': function(test) { + test.expect(2); + test.equal(grunt.config.escape('foo'), 'foo', 'Should do nothing if no . chars.'); + test.equal(grunt.config.escape('foo.bar.baz'), 'foo\\.bar\\.baz', 'Should escape all . chars.'); + test.done(); + }, + 'config.getPropString': function(test) { + test.expect(4); + test.equal(grunt.config.getPropString('foo'), 'foo', 'Should do nothing if already a string.'); + test.equal(grunt.config.getPropString('foo.bar.baz'), 'foo.bar.baz', 'Should do nothing if already a string.'); + test.equal(grunt.config.getPropString(['foo', 'bar']), 'foo.bar', 'Should join parts into a dot-delimited string.'); + test.equal(grunt.config.getPropString(['foo.bar', 'baz.qux.zip']), 'foo\\.bar.baz\\.qux\\.zip', 'Should join parts into a dot-delimited string, escaping . chars in parts.'); + test.done(); + }, + 'config.getRaw': function(test) { + test.expect(4); + test.equal(grunt.config.getRaw('foo'), '<%= meta.foo %>', 'Should not process templates.'); + test.equal(grunt.config.getRaw('obj.foo2'), '<%= obj.foo %>', 'Should not process templates.'); + test.equal(grunt.config.getRaw(['obj', 'foo2']), '<%= obj.foo %>', 'Should not process templates.'); + test.deepEqual(grunt.config.getRaw('arr'), ['foo', '<%= obj.foo2 %>'], 'Should not process templates.'); + test.done(); + }, + 'config.process': function(test) { + test.expect(5); + test.equal(grunt.config.process('<%= meta.foo %>'), 'bar', 'Should process templates.'); + test.equal(grunt.config.process('<%= foo %>'), 'bar', 'Should process templates recursively.'); + test.equal(grunt.config.process('<%= obj.foo %>'), 'bar', 'Should process deeply nested templates recursively.'); + test.deepEqual(grunt.config.process(['foo', '<%= obj.foo2 %>']), ['foo', 'bar'], 'Should process templates in arrays.'); + test.deepEqual(grunt.config.process(['<%= arr %>', '<%= obj.Arr %>']), [['foo', 'bar'], ['foo', 'bar']], 'Should expand <%= arr %> and <%= obj.Arr %> values as objects if possible.'); + test.done(); + }, + 'config.get': function(test) { + test.expect(8); + test.equal(grunt.config.get('foo'), 'bar', 'Should process templates.'); + test.equal(grunt.config.get('foo2'), 'bar', 'Should process templates recursively.'); + test.equal(grunt.config.get('obj.foo2'), 'bar', 'Should process deeply nested templates recursively.'); + test.equal(grunt.config.get(['obj', 'foo2']), 'bar', 'Should process deeply nested templates recursively.'); + test.deepEqual(grunt.config.get('arr'), ['foo', 'bar'], 'Should process templates in arrays.'); + test.deepEqual(grunt.config.get('obj.Arr'), ['foo', 'bar'], 'Should process templates in arrays.'); + test.deepEqual(grunt.config.get('arr2'), [['foo', 'bar'], ['foo', 'bar']], 'Should expand <%= arr %> and <%= obj.Arr %> values as objects if possible.'); + test.deepEqual(grunt.config.get(['obj', 'arr2']), [['foo', 'bar'], ['foo', 'bar']], 'Should expand <%= arr %> and <%= obj.Arr %> values as objects if possible.'); + test.done(); + }, + 'config.set': function(test) { + test.expect(6); + test.equal(grunt.config.set('foo3', '<%= foo2 %>'), '<%= foo2 %>', 'Should set values.'); + test.equal(grunt.config.getRaw('foo3'), '<%= foo2 %>', 'Should have set the value.'); + test.equal(grunt.config.data.foo3, '<%= foo2 %>', 'Should have set the value.'); + test.equal(grunt.config.set('a.b.c', '<%= foo2 %>'), '<%= foo2 %>', 'Should create interim objects.'); + test.equal(grunt.config.getRaw('a.b.c'), '<%= foo2 %>', 'Should have set the value.'); + test.equal(grunt.config.data.a.b.c, '<%= foo2 %>', 'Should have set the value.'); + test.done(); + }, + 'config': function(test) { + test.expect(10); + test.equal(grunt.config('foo'), 'bar', 'Should retrieve processed data.'); + test.equal(grunt.config('obj.foo2'), 'bar', 'Should retrieve processed data.'); + test.equal(grunt.config(['obj', 'foo2']), 'bar', 'Should retrieve processed data.'); + test.deepEqual(grunt.config('arr'), ['foo', 'bar'], 'Should process templates in arrays.'); + + test.equal(grunt.config('foo3', '<%= foo2 %>'), '<%= foo2 %>', 'Should set values.'); + test.equal(grunt.config.getRaw('foo3'), '<%= foo2 %>', 'Should have set the value.'); + test.equal(grunt.config.data.foo3, '<%= foo2 %>', 'Should have set the value.'); + test.equal(grunt.config('a.b.c', '<%= foo2 %>'), '<%= foo2 %>', 'Should create interim objects.'); + test.equal(grunt.config.getRaw('a.b.c'), '<%= foo2 %>', 'Should have set the value.'); + test.equal(grunt.config.data.a.b.c, '<%= foo2 %>', 'Should have set the value.'); + test.done(); + }, + 'config.requires': function(test) { + test.expect(8); + grunt.log.muted = true; + test.doesNotThrow(function() { grunt.config.requires('foo'); }, 'This property exists.'); + test.doesNotThrow(function() { grunt.config.requires('obj.foo'); }, 'This property exists.'); + test.doesNotThrow(function() { grunt.config.requires('foo', 'obj.foo', 'obj.foo2'); }, 'These properties exist.'); + test.doesNotThrow(function() { grunt.config.requires('foo', ['obj', 'foo'], ['obj', 'foo2']); }, 'These properties exist.'); + test.throws(function() { grunt.config.requires('xyz'); }, 'This property does not exist.'); + test.throws(function() { grunt.config.requires('obj.xyz'); }, 'This property does not exist.'); + test.throws(function() { grunt.config.requires('foo', 'obj.foo', 'obj.xyz'); }, 'One property does not exist.'); + test.throws(function() { grunt.config.requires('foo', ['obj', 'foo'], ['obj', 'xyz']); }, 'One property does not exist.'); + grunt.log.muted = false; + test.done(); + }, +}; diff --git a/node/node_modules/grunt/test/grunt/event_test.js b/node/node_modules/grunt/test/grunt/event_test.js new file mode 100644 index 000000000..0d7235316 --- /dev/null +++ b/node/node_modules/grunt/test/grunt/event_test.js @@ -0,0 +1,18 @@ +'use strict'; + +var grunt = require('../../lib/grunt'); + +exports['event'] = function(test) { + test.expect(3); + grunt.event.on('test.foo', function(a, b, c) { + // This should get executed once (emit test.foo). + test.equals(a + b + c, '123', 'Should have received the correct arguments.'); + }); + grunt.event.on('test.*', function(a, b, c) { + // This should get executed twice (emit test.foo and test.bar). + test.equals(a + b + c, '123', 'Should have received the correct arguments.'); + }); + grunt.event.emit('test.foo', '1', '2', '3'); + grunt.event.emit('test.bar', '1', '2', '3'); + test.done(); +}; diff --git a/node/node_modules/grunt/test/grunt/file_test.js b/node/node_modules/grunt/test/grunt/file_test.js index 2d8a608f5..e996cf97d 100644 --- a/node/node_modules/grunt/test/grunt/file_test.js +++ b/node/node_modules/grunt/test/grunt/file_test.js @@ -1,67 +1,764 @@ +'use strict'; + var grunt = require('../../lib/grunt'); var fs = require('fs'); var path = require('path'); -// test helper -// -// compare - to effectively compare Buffers, we would need something like -// bnoordhuis/buffertools, but I'd rather not add a new dependency for the sake -// of testing. -// -// So we're relying on comparisons between the `hex` of buffers to do that, -// seems to be reliant enough to cover our test needs with file copy. -function compare(actual, expected, encoding) { - encoding = encoding || 'hex'; - return fs.readFileSync(actual, encoding) === fs.readFileSync(expected, encoding); -} +var Tempfile = require('temporary/lib/file'); +var Tempdir = require('temporary/lib/dir'); -exports['file'] = { - 'isPathAbsolute': function(test) { +var tmpdir = new Tempdir(); +fs.symlinkSync(path.resolve('test/fixtures/octocat.png'), path.join(tmpdir.path, 'octocat.png'), 'file'); +fs.symlinkSync(path.resolve('test/fixtures/expand'), path.join(tmpdir.path, 'expand'), 'dir'); + +exports['file.match'] = { + 'empty set': function(test) { + test.expect(12); + // Should return empty set if a required argument is missing or an empty set. + test.deepEqual(grunt.file.match(null, null), [], 'should return empty set.'); + test.deepEqual(grunt.file.match({}, null, null), [], 'should return empty set.'); + test.deepEqual(grunt.file.match(null, 'foo.js'), [], 'should return empty set.'); + test.deepEqual(grunt.file.match('*.js', null), [], 'should return empty set.'); + test.deepEqual(grunt.file.match({}, null, 'foo.js'), [], 'should return empty set.'); + test.deepEqual(grunt.file.match({}, '*.js', null), [], 'should return empty set.'); + test.deepEqual(grunt.file.match({}, [], 'foo.js'), [], 'should return empty set.'); + test.deepEqual(grunt.file.match({}, '*.js', []), [], 'should return empty set.'); + test.deepEqual(grunt.file.match(null, ['foo.js']), [], 'should return empty set.'); + test.deepEqual(grunt.file.match(['*.js'], null), [], 'should return empty set.'); + test.deepEqual(grunt.file.match({}, null, ['foo.js']), [], 'should return empty set.'); + test.deepEqual(grunt.file.match({}, ['*.js'], null), [], 'should return empty set.'); + test.done(); + }, + 'basic matching': function(test) { + test.expect(6); + test.deepEqual(grunt.file.match('*.js', 'foo.js'), ['foo.js'], 'should match correctly.'); + test.deepEqual(grunt.file.match('*.js', ['foo.js']), ['foo.js'], 'should match correctly.'); + test.deepEqual(grunt.file.match('*.js', ['foo.js', 'bar.css']), ['foo.js'], 'should match correctly.'); + test.deepEqual(grunt.file.match(['*.js', '*.css'], 'foo.js'), ['foo.js'], 'should match correctly.'); + test.deepEqual(grunt.file.match(['*.js', '*.css'], ['foo.js']), ['foo.js'], 'should match correctly.'); + test.deepEqual(grunt.file.match(['*.js', '*.css'], ['foo.js', 'bar.css']), ['foo.js', 'bar.css'], 'should match correctly.'); + test.done(); + }, + 'no matches': function(test) { test.expect(2); - test.ok(grunt.file.isPathAbsolute(path.resolve('test/fixtures/a.js')), 'should return true'); - test.equal(grunt.file.isPathAbsolute('test/fixtures/a.js'), false, 'should return false'); + test.deepEqual(grunt.file.match('*.js', 'foo.css'), [], 'should fail to match.'); + test.deepEqual(grunt.file.match('*.js', ['foo.css', 'bar.css']), [], 'should fail to match.'); test.done(); }, - 'read': function(test) { + 'unique': function(test) { test.expect(2); - test.strictEqual(grunt.file.read('test/fixtures/a.js'), fs.readFileSync('test/fixtures/a.js', 'utf8')); - test.strictEqual(grunt.file.read('test/fixtures/octocat.png'), fs.readFileSync('test/fixtures/octocat.png', 'utf8')); + test.deepEqual(grunt.file.match('*.js', ['foo.js', 'foo.js']), ['foo.js'], 'should return a uniqued set.'); + test.deepEqual(grunt.file.match(['*.js', '*.*'], ['foo.js', 'foo.js']), ['foo.js'], 'should return a uniqued set.'); test.done(); }, - 'write': function(test) { + 'flatten': function(test) { + test.expect(1); + test.deepEqual(grunt.file.match([['*.js', '*.css'], ['*.*', '*.js']], ['foo.js', 'bar.css']), ['foo.js', 'bar.css'], 'should process nested pattern arrays correctly.'); + test.done(); + }, + 'exclusion': function(test) { + test.expect(5); + test.deepEqual(grunt.file.match(['!*.js'], ['foo.js', 'bar.js']), [], 'solitary exclusion should match nothing'); + test.deepEqual(grunt.file.match(['*.js', '!*.js'], ['foo.js', 'bar.js']), [], 'exclusion should cancel match'); + test.deepEqual(grunt.file.match(['*.js', '!f*.js'], ['foo.js', 'bar.js', 'baz.js']), ['bar.js', 'baz.js'], 'partial exclusion should partially cancel match'); + test.deepEqual(grunt.file.match(['*.js', '!*.js', 'b*.js'], ['foo.js', 'bar.js', 'baz.js']), ['bar.js', 'baz.js'], 'inclusion / exclusion order matters'); + test.deepEqual(grunt.file.match(['*.js', '!f*.js', '*.js'], ['foo.js', 'bar.js', 'baz.js']), ['bar.js', 'baz.js', 'foo.js'], 'inclusion / exclusion order matters'); + test.done(); + }, + 'options.matchBase': function(test) { + test.expect(2); + test.deepEqual(grunt.file.match({matchBase: true}, '*.js', ['foo.js', 'bar', 'baz/xyz.js']), ['foo.js', 'baz/xyz.js'], 'should matchBase (minimatch) when specified.'); + test.deepEqual(grunt.file.match('*.js', ['foo.js', 'bar', 'baz/xyz.js']), ['foo.js'], 'should not matchBase (minimatch) by default.'); + test.done(); + } +}; + +exports['file.isMatch'] = { + 'basic matching': function(test) { + test.expect(6); + test.ok(grunt.file.isMatch('*.js', 'foo.js'), 'should match correctly.'); + test.ok(grunt.file.isMatch('*.js', ['foo.js']), 'should match correctly.'); + test.ok(grunt.file.isMatch('*.js', ['foo.js', 'bar.css']), 'should match correctly.'); + test.ok(grunt.file.isMatch(['*.js', '*.css'], 'foo.js'), 'should match correctly.'); + test.ok(grunt.file.isMatch(['*.js', '*.css'], ['foo.js']), 'should match correctly.'); + test.ok(grunt.file.isMatch(['*.js', '*.css'], ['foo.js', 'bar.css']), 'should match correctly.'); + test.done(); + }, + 'no matches': function(test) { + test.expect(6); + test.equal(grunt.file.isMatch('*.js', 'foo.css'), false, 'should fail to match.'); + test.equal(grunt.file.isMatch('*.js', ['foo.css', 'bar.css']), false, 'should fail to match.'); + test.equal(grunt.file.isMatch(null, 'foo.css'), false, 'should fail to match.'); + test.equal(grunt.file.isMatch('*.js', null), false, 'should fail to match.'); + test.equal(grunt.file.isMatch([], 'foo.css'), false, 'should fail to match.'); + test.equal(grunt.file.isMatch('*.js', []), false, 'should fail to match.'); + test.done(); + }, + 'options.matchBase': function(test) { + test.expect(2); + test.ok(grunt.file.isMatch({matchBase: true}, '*.js', ['baz/xyz.js']), 'should matchBase (minimatch) when specified.'); + test.equal(grunt.file.isMatch('*.js', ['baz/xyz.js']), false, 'should not matchBase (minimatch) by default.'); + test.done(); + } +}; + +exports['file.expand*'] = { + setUp: function(done) { + this.cwd = process.cwd(); + process.chdir('test/fixtures/expand'); + done(); + }, + tearDown: function(done) { + process.chdir(this.cwd); + done(); + }, + 'basic matching': function(test) { + test.expect(8); + test.deepEqual(grunt.file.expand('**/*.js'), ['js/bar.js', 'js/foo.js'], 'should match.'); + test.deepEqual(grunt.file.expand('**/*.js', '**/*.css'), ['js/bar.js', 'js/foo.js', 'css/baz.css', 'css/qux.css'], 'should match.'); + test.deepEqual(grunt.file.expand(['**/*.js', '**/*.css']), ['js/bar.js', 'js/foo.js', 'css/baz.css', 'css/qux.css'], 'should match.'); + test.deepEqual(grunt.file.expand('**d*/**'), [ + 'deep', + 'deep/deep.txt', + 'deep/deeper', + 'deep/deeper/deeper.txt', + 'deep/deeper/deepest', + 'deep/deeper/deepest/deepest.txt'], 'should match files and directories.'); + test.deepEqual(grunt.file.expand({mark: true}, '**d*/**'), [ + 'deep/', + 'deep/deep.txt', + 'deep/deeper/', + 'deep/deeper/deeper.txt', + 'deep/deeper/deepest/', + 'deep/deeper/deepest/deepest.txt'], 'the minimatch "mark" option ensures directories end in /.'); + test.deepEqual(grunt.file.expand('**d*/**/'), [ + 'deep/', + 'deep/deeper/', + 'deep/deeper/deepest/'], 'should match directories, arbitrary / at the end appears in matches.'); + test.deepEqual(grunt.file.expand({mark: true}, '**d*/**/'), [ + 'deep/', + 'deep/deeper/', + 'deep/deeper/deepest/'], 'should match directories, arbitrary / at the end appears in matches.'); + test.deepEqual(grunt.file.expand('*.xyz'), [], 'should fail to match.'); + test.done(); + }, + 'filter': function(test) { + test.expect(5); + test.deepEqual(grunt.file.expand({filter: 'isFile'}, '**d*/**'), [ + 'deep/deep.txt', + 'deep/deeper/deeper.txt', + 'deep/deeper/deepest/deepest.txt' + ], 'should match files only.'); + test.deepEqual(grunt.file.expand({filter: 'isDirectory'}, '**d*/**'), [ + 'deep', + 'deep/deeper', + 'deep/deeper/deepest' + ], 'should match directories only.'); + test.deepEqual(grunt.file.expand({filter: function(filepath) { return (/deepest/).test(filepath); }}, '**'), [ + 'deep/deeper/deepest', + 'deep/deeper/deepest/deepest.txt', + ], 'should filter arbitrarily.'); + test.deepEqual(grunt.file.expand({filter: 'isFile'}, 'js', 'css'), [], 'should fail to match.'); + test.deepEqual(grunt.file.expand({filter: 'isDirectory'}, '**/*.js'), [], 'should fail to match.'); + test.done(); + }, + 'unique': function(test) { test.expect(4); - var content = 'var a = "foobar";'; - grunt.file.write('test/fixtures/test_write.js', content); - test.strictEqual(fs.readFileSync('test/fixtures/test_write.js', 'utf8'), content); - test.strictEqual(grunt.file.read('test/fixtures/test_write.js'), content); + test.deepEqual(grunt.file.expand('**/*.js', 'js/*.js'), ['js/bar.js', 'js/foo.js'], 'file list should be uniqed.'); + test.deepEqual(grunt.file.expand('**/*.js', '**/*.css', 'js/*.js'), ['js/bar.js', 'js/foo.js', 'css/baz.css', 'css/qux.css'], 'file list should be uniqed.'); + test.deepEqual(grunt.file.expand('js', 'js/'), ['js', 'js/'], 'mixed non-ending-/ and ending-/ dirs will not be uniqed by default.'); + test.deepEqual(grunt.file.expand({mark: true}, 'js', 'js/'), ['js/'], 'mixed non-ending-/ and ending-/ dirs will be uniqed when "mark" is specified.'); + test.done(); + }, + 'file order': function(test) { + test.expect(4); + var actual = grunt.file.expand('**/*.{js,css}'); + var expected = ['css/baz.css', 'css/qux.css', 'js/bar.js', 'js/foo.js']; + test.deepEqual(actual, expected, 'should select 4 files in this order, by default.'); + + actual = grunt.file.expand('js/foo.js', 'js/bar.js', '**/*.{js,css}'); + expected = ['js/foo.js', 'js/bar.js', 'css/baz.css', 'css/qux.css']; + test.deepEqual(actual, expected, 'specifically-specified-up-front file order should be maintained.'); + + actual = grunt.file.expand('js/bar.js', 'js/foo.js', '**/*.{js,css}'); + expected = ['js/bar.js', 'js/foo.js', 'css/baz.css', 'css/qux.css']; + test.deepEqual(actual, expected, 'specifically-specified-up-front file order should be maintained.'); + actual = grunt.file.expand('js/foo.js', '**/*.{js,css}', '!js/bar.js', 'js/bar.js'); + expected = ['js/foo.js', 'css/baz.css', 'css/qux.css', 'js/bar.js']; + test.deepEqual(actual, expected, 'if a file is excluded and then re-added, it should be added at the end.'); + test.done(); + }, + 'flatten': function(test) { + test.expect(1); + test.deepEqual(grunt.file.expand([['**/*.js'], ['**/*.css', 'js/*.js']]), ['js/bar.js', 'js/foo.js', 'css/baz.css', 'css/qux.css'], 'should match.'); + test.done(); + }, + 'exclusion': function(test) { + test.expect(8); + test.deepEqual(grunt.file.expand(['!js/*.js']), [], 'solitary exclusion should match nothing'); + test.deepEqual(grunt.file.expand(['js/bar.js','!js/bar.js']), [], 'exclusion should cancel match'); + test.deepEqual(grunt.file.expand(['**/*.js', '!js/foo.js']), ['js/bar.js'], 'should omit single file from matched set'); + test.deepEqual(grunt.file.expand(['!js/foo.js', '**/*.js']), ['js/bar.js', 'js/foo.js'], 'inclusion / exclusion order matters'); + test.deepEqual(grunt.file.expand(['**/*.js', '**/*.css', '!js/bar.js', '!css/baz.css']), ['js/foo.js','css/qux.css'], 'multiple exclusions should be removed from the set'); + test.deepEqual(grunt.file.expand(['**/*.js', '**/*.css', '!**/*.css']), ['js/bar.js', 'js/foo.js'], 'excluded wildcards should be removed from the matched set'); + test.deepEqual(grunt.file.expand(['js/bar.js', 'js/foo.js', 'css/baz.css', 'css/qux.css', '!**/b*.*']), ['js/foo.js', 'css/qux.css'], 'different pattern for exclusion should still work'); + test.deepEqual(grunt.file.expand(['js/bar.js', '!**/b*.*', 'js/foo.js', 'css/baz.css', 'css/qux.css']), ['js/foo.js', 'css/baz.css', 'css/qux.css'], 'inclusion / exclusion order matters'); + test.done(); + }, + 'options.matchBase': function(test) { + test.expect(4); + var opts = {matchBase: true}; + test.deepEqual(grunt.file.expand('*.js'), [], 'should not matchBase (minimatch) by default.'); + test.deepEqual(grunt.file.expand(opts, '*.js'), ['js/bar.js', 'js/foo.js'], 'options should be passed through to minimatch.'); + test.deepEqual(grunt.file.expand(opts, '*.js', '*.css'), ['js/bar.js', 'js/foo.js', 'css/baz.css', 'css/qux.css'], 'should match.'); + test.deepEqual(grunt.file.expand(opts, ['*.js', '*.css']), ['js/bar.js', 'js/foo.js', 'css/baz.css', 'css/qux.css'], 'should match.'); + test.done(); + }, + 'options.cwd': function(test) { + test.expect(4); + var cwd = path.resolve(process.cwd(), '..'); + test.deepEqual(grunt.file.expand({cwd: cwd}, ['expand/js', 'expand/js/*']), ['expand/js', 'expand/js/bar.js', 'expand/js/foo.js'], 'should match.'); + test.deepEqual(grunt.file.expand({cwd: cwd, filter: 'isFile'}, ['expand/js', 'expand/js/*']), ['expand/js/bar.js', 'expand/js/foo.js'], 'should match.'); + test.deepEqual(grunt.file.expand({cwd: cwd, filter: 'isDirectory'}, ['expand/js', 'expand/js/*']), ['expand/js'], 'should match.'); + test.deepEqual(grunt.file.expand({cwd: cwd, filter: 'isFile'}, ['expand/js', 'expand/js/*', '!**/b*.js']), ['expand/js/foo.js'], 'should negate properly.'); + test.done(); + }, + 'options.nonull': function(test) { + test.expect(2); + var opts = {nonull: true}; + test.deepEqual(grunt.file.expand(opts, ['js/a*', 'js/b*', 'js/c*']), ['js/a*', 'js/bar.js', 'js/c*'], 'non-matching patterns should be returned in result set.'); + test.deepEqual(grunt.file.expand(opts, ['js/foo.js', 'js/bar.js', 'js/baz.js']), ['js/foo.js', 'js/bar.js', 'js/baz.js'], 'non-matching filenames should be returned in result set.'); + test.done(); + }, +}; + +exports['file.expandMapping'] = { + setUp: function(done) { + this.cwd = process.cwd(); + process.chdir('test/fixtures'); + done(); + }, + tearDown: function(done) { + process.chdir(this.cwd); + done(); + }, + 'basic matching': function(test) { + test.expect(2); + + var actual = grunt.file.expandMapping(['expand/**/*.txt'], 'dest'); + var expected = [ + {dest: 'dest/expand/deep/deep.txt', src: ['expand/deep/deep.txt']}, + {dest: 'dest/expand/deep/deeper/deeper.txt', src: ['expand/deep/deeper/deeper.txt']}, + {dest: 'dest/expand/deep/deeper/deepest/deepest.txt', src: ['expand/deep/deeper/deepest/deepest.txt']}, + ]; + test.deepEqual(actual, expected, 'basic src-dest options'); + + actual = grunt.file.expandMapping(['expand/**/*.txt'], 'dest/'); + test.deepEqual(actual, expected, 'destBase should behave the same both with or without trailing slash'); + + test.done(); + }, + 'flatten': function(test) { + test.expect(1); + var actual = grunt.file.expandMapping(['expand/**/*.txt'], 'dest', {flatten: true}); + var expected = [ + {dest: 'dest/deep.txt', src: ['expand/deep/deep.txt']}, + {dest: 'dest/deeper.txt', src: ['expand/deep/deeper/deeper.txt']}, + {dest: 'dest/deepest.txt', src: ['expand/deep/deeper/deepest/deepest.txt']}, + ]; + test.deepEqual(actual, expected, 'dest paths should be flattened pre-destBase+destPath join'); + test.done(); + }, + 'ext': function(test) { + test.expect(2); + var actual, expected; + actual = grunt.file.expandMapping(['expand/**/*.txt'], 'dest', {ext: '.foo'}); + expected = [ + {dest: 'dest/expand/deep/deep.foo', src: ['expand/deep/deep.txt']}, + {dest: 'dest/expand/deep/deeper/deeper.foo', src: ['expand/deep/deeper/deeper.txt']}, + {dest: 'dest/expand/deep/deeper/deepest/deepest.foo', src: ['expand/deep/deeper/deepest/deepest.txt']}, + ]; + test.deepEqual(actual, expected, 'specified extension should be added'); + actual = grunt.file.expandMapping(['expand-mapping-ext/**/file*'], 'dest', {ext: '.foo'}); + expected = [ + {dest: 'dest/expand-mapping-ext/dir.ectory/file-no-extension.foo', src: ['expand-mapping-ext/dir.ectory/file-no-extension']}, + {dest: 'dest/expand-mapping-ext/dir.ectory/sub.dir.ectory/file.foo', src: ['expand-mapping-ext/dir.ectory/sub.dir.ectory/file.ext.ension']}, + {dest: 'dest/expand-mapping-ext/file.foo', src: ['expand-mapping-ext/file.ext.ension']}, + ]; + test.deepEqual(actual, expected, 'specified extension should be added'); + test.done(); + }, + 'cwd': function(test) { + test.expect(1); + var actual = grunt.file.expandMapping(['**/*.txt'], 'dest', {cwd: 'expand'}); + var expected = [ + {dest: 'dest/deep/deep.txt', src: ['expand/deep/deep.txt']}, + {dest: 'dest/deep/deeper/deeper.txt', src: ['expand/deep/deeper/deeper.txt']}, + {dest: 'dest/deep/deeper/deepest/deepest.txt', src: ['expand/deep/deeper/deepest/deepest.txt']}, + ]; + test.deepEqual(actual, expected, 'cwd should be stripped from front of destPath, pre-destBase+destPath join'); + test.done(); + }, + 'rename': function(test) { + test.expect(1); + var actual = grunt.file.expandMapping(['**/*.txt'], 'dest', { + cwd: 'expand', + flatten: true, + rename: function(destBase, destPath, options) { + return path.join(destBase, options.cwd, 'o-m-g', destPath); + } + }); + var expected = [ + {dest: 'dest/expand/o-m-g/deep.txt', src: ['expand/deep/deep.txt']}, + {dest: 'dest/expand/o-m-g/deeper.txt', src: ['expand/deep/deeper/deeper.txt']}, + {dest: 'dest/expand/o-m-g/deepest.txt', src: ['expand/deep/deeper/deepest/deepest.txt']}, + ]; + test.deepEqual(actual, expected, 'custom rename function should be used to build dest, post-flatten'); + test.done(); + }, + 'rename to same dest': function(test) { + test.expect(1); + var actual = grunt.file.expandMapping(['**/*'], 'dest', { + filter: 'isFile', + cwd: 'expand', + flatten: true, + rename: function(destBase, destPath) { + return path.join(destBase, 'all' + path.extname(destPath)); + } + }); + var expected = [ + {dest: 'dest/all.md', src: ['expand/README.md']}, + {dest: 'dest/all.css', src: ['expand/css/baz.css', 'expand/css/qux.css']}, + {dest: 'dest/all.txt', src: ['expand/deep/deep.txt', 'expand/deep/deeper/deeper.txt', 'expand/deep/deeper/deepest/deepest.txt']}, + {dest: 'dest/all.js', src: ['expand/js/bar.js', 'expand/js/foo.js']}, + ]; + test.deepEqual(actual, expected, 'if dest is same for multiple src, create an array of src'); + test.done(); + }, +}; + + +// Compare two buffers. Returns true if they are equivalent. +var compareBuffers = function(buf1, buf2) { + if (!Buffer.isBuffer(buf1) || !Buffer.isBuffer(buf2)) { return false; } + if (buf1.length !== buf2.length) { return false; } + for (var i = 0; i < buf2.length; i++) { + if (buf1[i] !== buf2[i]) { return false; } + } + return true; +}; + +// Compare two files. Returns true if they are equivalent. +var compareFiles = function(filepath1, filepath2) { + return compareBuffers(fs.readFileSync(filepath1), fs.readFileSync(filepath2)); +}; + +exports['file'] = { + setUp: function(done) { + this.defaultEncoding = grunt.file.defaultEncoding; + grunt.file.defaultEncoding = 'utf8'; + this.string = 'Ação é isso aí\n'; + this.object = {foo: 'Ação é isso aí', bar: ['ømg', 'pønies']}; + this.writeOption = grunt.option('write'); + done(); + }, + tearDown: function(done) { + grunt.file.defaultEncoding = this.defaultEncoding; + grunt.option('write', this.writeOption); + done(); + }, + 'read': function(test) { + test.expect(5); + test.strictEqual(grunt.file.read('test/fixtures/utf8.txt'), this.string, 'file should be read as utf8 by default.'); + test.strictEqual(grunt.file.read('test/fixtures/iso-8859-1.txt', {encoding: 'iso-8859-1'}), this.string, 'file should be read using the specified encoding.'); + test.ok(compareBuffers(grunt.file.read('test/fixtures/octocat.png', {encoding: null}), fs.readFileSync('test/fixtures/octocat.png')), 'file should be read as a buffer if encoding is specified as null.'); + test.strictEqual(grunt.file.read('test/fixtures/BOM.txt'), 'foo', 'file should have BOM stripped.'); + + grunt.file.defaultEncoding = 'iso-8859-1'; + test.strictEqual(grunt.file.read('test/fixtures/iso-8859-1.txt'), this.string, 'changing the default encoding should work.'); + test.done(); + }, + 'readJSON': function(test) { + test.expect(3); + var obj; + obj = grunt.file.readJSON('test/fixtures/utf8.json'); + test.deepEqual(obj, this.object, 'file should be read as utf8 by default and parsed correctly.'); + + obj = grunt.file.readJSON('test/fixtures/iso-8859-1.json', {encoding: 'iso-8859-1'}); + test.deepEqual(obj, this.object, 'file should be read using the specified encoding.'); + + grunt.file.defaultEncoding = 'iso-8859-1'; + obj = grunt.file.readJSON('test/fixtures/iso-8859-1.json'); + test.deepEqual(obj, this.object, 'changing the default encoding should work.'); + test.done(); + }, + 'readYAML': function(test) { + test.expect(3); + var obj; + obj = grunt.file.readYAML('test/fixtures/utf8.yaml'); + test.deepEqual(obj, this.object, 'file should be read as utf8 by default and parsed correctly.'); + + obj = grunt.file.readYAML('test/fixtures/iso-8859-1.yaml', {encoding: 'iso-8859-1'}); + test.deepEqual(obj, this.object, 'file should be read using the specified encoding.'); + + grunt.file.defaultEncoding = 'iso-8859-1'; + obj = grunt.file.readYAML('test/fixtures/iso-8859-1.yaml'); + test.deepEqual(obj, this.object, 'changing the default encoding should work.'); + test.done(); + }, + 'write': function(test) { + test.expect(5); + var tmpfile; + tmpfile = new Tempfile(); + grunt.file.write(tmpfile.path, this.string); + test.strictEqual(fs.readFileSync(tmpfile.path, 'utf8'), this.string, 'file should be written as utf8 by default.'); + tmpfile.unlinkSync(); + + tmpfile = new Tempfile(); + grunt.file.write(tmpfile.path, this.string, {encoding: 'iso-8859-1'}); + test.strictEqual(grunt.file.read(tmpfile.path, {encoding: 'iso-8859-1'}), this.string, 'file should be written using the specified encoding.'); + tmpfile.unlinkSync(); + + grunt.file.defaultEncoding = 'iso-8859-1'; + tmpfile = new Tempfile(); + grunt.file.write(tmpfile.path, this.string); + grunt.file.defaultEncoding = 'utf8'; + test.strictEqual(grunt.file.read(tmpfile.path, {encoding: 'iso-8859-1'}), this.string, 'changing the default encoding should work.'); + tmpfile.unlinkSync(); + + tmpfile = new Tempfile(); var octocat = fs.readFileSync('test/fixtures/octocat.png'); - grunt.file.write('test/fixtures/test_write.png', octocat); - test.strictEqual(fs.readFileSync('test/fixtures/test_write.png', 'utf8'), fs.readFileSync('test/fixtures/octocat.png', 'utf8')); - test.ok(compare('test/fixtures/test_write.png', 'test/fixtures/octocat.png'), 'both buffers should match'); + grunt.file.write(tmpfile.path, octocat); + test.ok(compareBuffers(fs.readFileSync(tmpfile.path), octocat), 'buffers should always be written as-specified, with no attempt at re-encoding.'); + tmpfile.unlinkSync(); - ['test/fixtures/test_write.js', 'test/fixtures/test_write.png'].forEach(fs.unlinkSync); + grunt.option('write', false); + var filepath = path.join(tmpdir.path, 'should-not-exist.txt'); + grunt.file.write(filepath, 'test'); + test.equal(grunt.file.exists(filepath), false, 'file should NOT be created if --no-write was specified.'); test.done(); }, 'copy': function(test) { - test.expect(6); - grunt.file.copy('test/fixtures/a.js', 'test/fixtures/test_copy.js'); - test.strictEqual(fs.readFileSync('test/fixtures/test_copy.js', 'utf8'), fs.readFileSync('test/fixtures/a.js', 'utf8')); + test.expect(4); + var tmpfile; + tmpfile = new Tempfile(); + grunt.file.copy('test/fixtures/utf8.txt', tmpfile.path); + test.ok(compareFiles(tmpfile.path, 'test/fixtures/utf8.txt'), 'files should just be copied as encoding-agnostic by default.'); + tmpfile.unlinkSync(); - var tmpltest = '// should src be a string and template process be all good.'; - grunt.file.copy('test/fixtures/a.js', 'test/fixtures/test_copy.js', {process: function(src) { - test.equal(Buffer.isBuffer(src), false); - test.equal(typeof src, 'string'); - return grunt.template.process(src + '<%= tmpltest %>', {tmpltest: tmpltest}); - }}); - test.strictEqual(fs.readFileSync('test/fixtures/test_copy.js', 'utf8'), grunt.utils.normalizelf(fs.readFileSync('test/fixtures/a.js', 'utf8')) + tmpltest); + tmpfile = new Tempfile(); + grunt.file.copy('test/fixtures/iso-8859-1.txt', tmpfile.path); + test.ok(compareFiles(tmpfile.path, 'test/fixtures/iso-8859-1.txt'), 'files should just be copied as encoding-agnostic by default.'); + tmpfile.unlinkSync(); - grunt.file.copy('test/fixtures/octocat.png', 'test/fixtures/test_copy.png'); - test.strictEqual(fs.readFileSync('test/fixtures/test_copy.png', 'utf8'), fs.readFileSync('test/fixtures/octocat.png', 'utf8')); - test.ok(compare('test/fixtures/test_copy.png', 'test/fixtures/octocat.png'), 'both buffers should match'); + tmpfile = new Tempfile(); + grunt.file.copy('test/fixtures/octocat.png', tmpfile.path); + test.ok(compareFiles(tmpfile.path, 'test/fixtures/octocat.png'), 'files should just be copied as encoding-agnostic by default.'); + tmpfile.unlinkSync(); - ['test/fixtures/test_copy.js', 'test/fixtures/test_copy.png'].forEach(fs.unlinkSync); + grunt.option('write', false); + var filepath = path.join(tmpdir.path, 'should-not-exist.txt'); + grunt.file.copy('test/fixtures/utf8.txt', filepath); + test.equal(grunt.file.exists(filepath), false, 'file should NOT be created if --no-write was specified.'); test.done(); - } + }, + 'copy and process': function(test) { + test.expect(13); + var tmpfile; + tmpfile = new Tempfile(); + grunt.file.copy('test/fixtures/utf8.txt', tmpfile.path, { + process: function(src, filepath) { + test.equal(filepath, 'test/fixtures/utf8.txt', 'filepath should be passed in, as-specified.'); + test.equal(Buffer.isBuffer(src), false, 'when no encoding is specified, use default encoding and process src as a string'); + test.equal(typeof src, 'string', 'when no encoding is specified, use default encoding and process src as a string'); + return 'føø' + src + 'bår'; + } + }); + test.equal(grunt.file.read(tmpfile.path), 'føø' + this.string + 'bår', 'file should be saved as properly encoded processed string.'); + tmpfile.unlinkSync(); + + tmpfile = new Tempfile(); + grunt.file.copy('test/fixtures/iso-8859-1.txt', tmpfile.path, { + encoding: 'iso-8859-1', + process: function(src) { + test.equal(Buffer.isBuffer(src), false, 'use specified encoding and process src as a string'); + test.equal(typeof src, 'string', 'use specified encoding and process src as a string'); + return 'føø' + src + 'bår'; + } + }); + test.equal(grunt.file.read(tmpfile.path, {encoding: 'iso-8859-1'}), 'føø' + this.string + 'bår', 'file should be saved as properly encoded processed string.'); + tmpfile.unlinkSync(); + + tmpfile = new Tempfile(); + grunt.file.copy('test/fixtures/utf8.txt', tmpfile.path, { + encoding: null, + process: function(src) { + test.ok(Buffer.isBuffer(src), 'when encoding is specified as null, process src as a buffer'); + return new Buffer('føø' + src.toString() + 'bår'); + } + }); + test.equal(grunt.file.read(tmpfile.path), 'føø' + this.string + 'bår', 'file should be saved as the buffer returned by process.'); + tmpfile.unlinkSync(); + + grunt.file.defaultEncoding = 'iso-8859-1'; + tmpfile = new Tempfile(); + grunt.file.copy('test/fixtures/iso-8859-1.txt', tmpfile.path, { + process: function(src) { + test.equal(Buffer.isBuffer(src), false, 'use non-utf8 default encoding and process src as a string'); + test.equal(typeof src, 'string', 'use non-utf8 default encoding and process src as a string'); + return 'føø' + src + 'bår'; + } + }); + test.equal(grunt.file.read(tmpfile.path), 'føø' + this.string + 'bår', 'file should be saved as properly encoded processed string.'); + tmpfile.unlinkSync(); + + var filepath = path.join(tmpdir.path, 'should-not-exist.txt'); + grunt.file.copy('test/fixtures/iso-8859-1.txt', filepath, { + process: function() { + return false; + } + }); + test.equal(grunt.file.exists(filepath), false, 'file should NOT be created if process returns false.'); + test.done(); + }, + 'copy and process, noprocess': function(test) { + test.expect(4); + var tmpfile; + tmpfile = new Tempfile(); + grunt.file.copy('test/fixtures/utf8.txt', tmpfile.path, { + noProcess: true, + process: function(src) { + return 'føø' + src + 'bår'; + } + }); + test.equal(grunt.file.read(tmpfile.path), this.string, 'file should not have been processed.'); + tmpfile.unlinkSync(); + + ['process', 'noprocess', 'othernoprocess'].forEach(function(filename) { + var filepath = path.join(tmpdir.path, filename); + grunt.file.copy('test/fixtures/utf8.txt', filepath); + var tmpfile = new Tempfile(); + grunt.file.copy(filepath, tmpfile.path, { + noProcess: ['**/*no*'], + process: function(src) { + return 'føø' + src + 'bår'; + } + }); + if (filename === 'process') { + test.equal(grunt.file.read(tmpfile.path), 'føø' + this.string + 'bår', 'file should have been processed.'); + } else { + test.equal(grunt.file.read(tmpfile.path), this.string, 'file should not have been processed.'); + } + tmpfile.unlinkSync(); + }, this); + + test.done(); + }, + 'delete': function(test) { + test.expect(2); + var oldBase = process.cwd(); + var cwd = path.resolve(tmpdir.path, 'delete', 'folder'); + grunt.file.mkdir(cwd); + grunt.file.setBase(tmpdir.path); + + grunt.file.write(path.join(cwd, 'test.js'), 'var test;'); + test.ok(grunt.file.delete(cwd), 'should return true after deleting file.'); + test.equal(grunt.file.exists(cwd), false, 'file should have been deleted.'); + grunt.file.setBase(oldBase); + test.done(); + }, + 'delete nonexistent file': function(test) { + test.expect(1); + test.ok(!grunt.file.delete('nonexistent'), 'should return false if file does not exist.'); + test.done(); + }, + 'delete outside working directory': function(test) { + test.expect(3); + var oldBase = process.cwd(); + var oldWarn = grunt.fail.warn; + grunt.fail.warn = function() {}; + + var cwd = path.resolve(tmpdir.path, 'delete', 'folder'); + var outsidecwd = path.resolve(tmpdir.path, 'delete', 'outsidecwd'); + grunt.file.mkdir(cwd); + grunt.file.mkdir(outsidecwd); + grunt.file.setBase(cwd); + + grunt.file.write(path.join(outsidecwd, 'test.js'), 'var test;'); + test.equal(grunt.file.delete(path.join(outsidecwd, 'test.js')), false, 'should not delete anything outside the cwd.'); + + test.ok(grunt.file.delete(path.join(outsidecwd), {force:true}), 'should delete outside cwd when using the --force.'); + test.equal(grunt.file.exists(outsidecwd), false, 'file outside cwd should have been deleted when using the --force.'); + + grunt.file.setBase(oldBase); + grunt.fail.warn = oldWarn; + test.done(); + }, + 'dont delete current working directory': function(test) { + test.expect(2); + var oldBase = process.cwd(); + var oldWarn = grunt.fail.warn; + grunt.fail.warn = function() {}; + + var cwd = path.resolve(tmpdir.path, 'dontdelete', 'folder'); + grunt.file.mkdir(cwd); + grunt.file.setBase(cwd); + + test.equal(grunt.file.delete(cwd), false, 'should not delete the cwd.'); + test.ok(grunt.file.exists(cwd), 'the cwd should exist.'); + + grunt.file.setBase(oldBase); + grunt.fail.warn = oldWarn; + test.done(); + }, + 'dont actually delete with no-write option on': function(test) { + test.expect(2); + grunt.option('write', false); + + var oldBase = process.cwd(); + var cwd = path.resolve(tmpdir.path, 'dontdelete', 'folder'); + grunt.file.mkdir(cwd); + grunt.file.setBase(tmpdir.path); + + grunt.file.write(path.join(cwd, 'test.js'), 'var test;'); + test.ok(grunt.file.delete(cwd), 'should return true after not actually deleting file.'); + test.equal(grunt.file.exists(cwd), true, 'file should NOT be deleted if --no-write was specified.'); + grunt.file.setBase(oldBase); + + test.done(); + }, + 'mkdir': function(test) { + test.expect(5); + test.doesNotThrow(function() { + grunt.file.mkdir(tmpdir.path); + }, 'Should not explode if the directory already exists.'); + test.ok(fs.existsSync(tmpdir.path), 'path should still exist.'); + + test.doesNotThrow(function() { + grunt.file.mkdir(path.join(tmpdir.path, 'aa/bb/cc')); + }, 'Should also not explode, otherwise.'); + test.ok(path.join(tmpdir.path, 'aa/bb/cc'), 'path should have been created.'); + + fs.writeFileSync(path.join(tmpdir.path, 'aa/bb/xx'), 'test'); + test.throws(function() { + grunt.file.mkdir(path.join(tmpdir.path, 'aa/bb/xx/yy')); + }, 'Should throw if a path cannot be created (ENOTDIR).'); + + test.done(); + }, + 'recurse': function(test) { + test.expect(1); + var rootdir = 'test/fixtures/expand'; + var expected = {}; + expected[rootdir + '/css/baz.css'] = [rootdir, 'css', 'baz.css']; + expected[rootdir + '/css/qux.css'] = [rootdir, 'css', 'qux.css']; + expected[rootdir + '/deep/deep.txt'] = [rootdir, 'deep', 'deep.txt']; + expected[rootdir + '/deep/deeper/deeper.txt'] = [rootdir, 'deep/deeper', 'deeper.txt']; + expected[rootdir + '/deep/deeper/deepest/deepest.txt'] = [rootdir, 'deep/deeper/deepest', 'deepest.txt']; + expected[rootdir + '/js/bar.js'] = [rootdir, 'js', 'bar.js']; + expected[rootdir + '/js/foo.js'] = [rootdir, 'js', 'foo.js']; + expected[rootdir + '/README.md'] = [rootdir, undefined, 'README.md']; + + var actual = {}; + grunt.file.recurse(rootdir, function(abspath, rootdir, subdir, filename) { + actual[abspath] = [rootdir, subdir, filename]; + }); + + test.deepEqual(actual, expected, 'paths and arguments should match.'); + test.done(); + }, + 'exists': function(test) { + test.expect(6); + test.ok(grunt.file.exists('test/fixtures/octocat.png'), 'files exist.'); + test.ok(grunt.file.exists('test', 'fixtures', 'octocat.png'), 'should work for paths in parts.'); + test.ok(grunt.file.exists('test/fixtures'), 'directories exist.'); + test.ok(grunt.file.exists(path.join(tmpdir.path, 'octocat.png')), 'file links exist.'); + test.ok(grunt.file.exists(path.join(tmpdir.path, 'expand')), 'directory links exist.'); + test.equal(grunt.file.exists('test/fixtures/does/not/exist'), false, 'nonexistent files do not exist.'); + test.done(); + }, + 'isLink': function(test) { + test.expect(6); + test.equals(grunt.file.isLink('test/fixtures/octocat.png'), false, 'files are not links.'); + test.equals(grunt.file.isLink('test/fixtures'), false, 'directories are not links.'); + test.ok(grunt.file.isLink(path.join(tmpdir.path, 'octocat.png')), 'file links are links.'); + test.ok(grunt.file.isLink(path.join(tmpdir.path, 'expand')), 'directory links are links.'); + test.ok(grunt.file.isLink(tmpdir.path, 'octocat.png'), 'should work for paths in parts.'); + test.equals(grunt.file.isLink('test/fixtures/does/not/exist'), false, 'nonexistent files are not links.'); + test.done(); + }, + 'isDir': function(test) { + test.expect(6); + test.equals(grunt.file.isDir('test/fixtures/octocat.png'), false, 'files are not directories.'); + test.ok(grunt.file.isDir('test/fixtures'), 'directories are directories.'); + test.ok(grunt.file.isDir('test', 'fixtures'), 'should work for paths in parts.'); + test.equals(grunt.file.isDir(path.join(tmpdir.path, 'octocat.png')), false, 'file links are not directories.'); + test.ok(grunt.file.isDir(path.join(tmpdir.path, 'expand')), 'directory links are directories.'); + test.equals(grunt.file.isDir('test/fixtures/does/not/exist'), false, 'nonexistent files are not directories.'); + test.done(); + }, + 'isFile': function(test) { + test.expect(6); + test.ok(grunt.file.isFile('test/fixtures/octocat.png'), 'files are files.'); + test.ok(grunt.file.isFile('test', 'fixtures', 'octocat.png'), 'should work for paths in parts.'); + test.equals(grunt.file.isFile('test/fixtures'), false, 'directories are not files.'); + test.ok(grunt.file.isFile(path.join(tmpdir.path, 'octocat.png')), 'file links are files.'); + test.equals(grunt.file.isFile(path.join(tmpdir.path, 'expand')), false, 'directory links are not files.'); + test.equals(grunt.file.isFile('test/fixtures/does/not/exist'), false, 'nonexistent files are not files.'); + test.done(); + }, + 'isPathAbsolute': function(test) { + test.expect(5); + test.ok(grunt.file.isPathAbsolute(path.resolve('/foo')), 'should return true'); + test.ok(grunt.file.isPathAbsolute(path.resolve('/foo') + path.sep), 'should return true'); + test.equal(grunt.file.isPathAbsolute('foo'), false, 'should return false'); + test.ok(grunt.file.isPathAbsolute(path.resolve('test/fixtures/a.js')), 'should return true'); + test.equal(grunt.file.isPathAbsolute('test/fixtures/a.js'), false, 'should return false'); + test.done(); + }, + 'arePathsEquivalent': function(test) { + test.expect(5); + test.ok(grunt.file.arePathsEquivalent('/foo'), 'should return true'); + test.ok(grunt.file.arePathsEquivalent('/foo', '/foo/', '/foo/../foo/'), 'should return true'); + test.ok(grunt.file.arePathsEquivalent(process.cwd(), '.', './', 'test/..'), 'should return true'); + test.equal(grunt.file.arePathsEquivalent(process.cwd(), '..'), false, 'should return false'); + test.equal(grunt.file.arePathsEquivalent('.', '..'), false, 'should return false'); + test.done(); + }, + 'doesPathContain': function(test) { + test.expect(6); + test.ok(grunt.file.doesPathContain('/foo', '/foo/bar'), 'should return true'); + test.ok(grunt.file.doesPathContain('/foo/', '/foo/bar/baz', '/foo/bar', '/foo/whatever'), 'should return true'); + test.equal(grunt.file.doesPathContain('/foo', '/foo'), false, 'should return false'); + test.equal(grunt.file.doesPathContain('/foo/xyz', '/foo/xyz/123', '/foo/bar/baz'), false, 'should return false'); + test.equal(grunt.file.doesPathContain('/foo/xyz', '/foo'), false, 'should return false'); + test.ok(grunt.file.doesPathContain(process.cwd(), 'test', 'test/fixtures', 'lib'), 'should return true'); + test.done(); + }, + 'isPathCwd': function(test) { + test.expect(8); + test.ok(grunt.file.isPathCwd(process.cwd()), 'cwd is cwd'); + test.ok(grunt.file.isPathCwd('.'), 'cwd is cwd'); + test.equal(grunt.file.isPathCwd('test'), false, 'subdirectory is not cwd'); + test.equal(grunt.file.isPathCwd(path.resolve('test')), false, 'subdirectory is not cwd'); + test.equal(grunt.file.isPathCwd('..'), false, 'parent is not cwd'); + test.equal(grunt.file.isPathCwd(path.resolve('..')), false, 'parent is not cwd'); + test.equal(grunt.file.isPathCwd('/'), false, 'root is not cwd (I hope)'); + test.equal(grunt.file.isPathCwd('nonexistent'), false, 'nonexistent path is not cwd'); + test.done(); + }, + 'isPathInCwd': function(test) { + test.expect(8); + test.equal(grunt.file.isPathInCwd(process.cwd()), false, 'cwd is not IN cwd'); + test.equal(grunt.file.isPathInCwd('.'), false, 'cwd is not IN cwd'); + test.ok(grunt.file.isPathInCwd('test'), 'subdirectory is in cwd'); + test.ok(grunt.file.isPathInCwd(path.resolve('test')), 'subdirectory is in cwd'); + test.equal(grunt.file.isPathInCwd('..'), false, 'parent is not in cwd'); + test.equal(grunt.file.isPathInCwd(path.resolve('..')), false, 'parent is not in cwd'); + test.equal(grunt.file.isPathInCwd('/'), false, 'root is not in cwd (I hope)'); + test.equal(grunt.file.isPathInCwd('nonexistent'), false, 'nonexistent path is not in cwd'); + test.done(); + }, }; diff --git a/node/node_modules/grunt/test/grunt/log_test.js b/node/node_modules/grunt/test/grunt/log_test.js new file mode 100644 index 000000000..27b982cdd --- /dev/null +++ b/node/node_modules/grunt/test/grunt/log_test.js @@ -0,0 +1,224 @@ +'use strict'; + +var grunt = require('../../lib/grunt'); +var log = grunt.log; + +var fooBuffer = new Buffer('foo'); + +// Helper for testing stdout +var hooker = grunt.util.hooker; +var stdoutEqual = function(test, callback, expected) { + var actual = ''; + // Hook process.stdout.write + hooker.hook(process.stdout, 'write', { + // This gets executed before the original process.stdout.write. + pre: function(result) { + // Concatenate uncolored result onto actual. + actual += log.uncolor(result); + // Prevent the original process.stdout.write from executing. + return hooker.preempt(); + } + }); + // Execute the logging code to be tested. + callback(); + // Restore process.stdout.write to its original value. + hooker.unhook(process.stdout, 'write'); + // Actually test the actually-logged stdout string to the expected value. + test.equal(actual, expected); +}; + +exports['log'] = { + 'setUp': function(done) { + log.muted = false; + grunt.fail.errorcount = 0; + done(); + }, + 'write': function(test) { + test.expect(4); + + stdoutEqual(test, function() { log.write(''); }, ''); + stdoutEqual(test, function() { log.write('foo'); }, 'foo'); + stdoutEqual(test, function() { log.write('%s', 'foo'); }, 'foo'); + stdoutEqual(test, function() { log.write(fooBuffer); }, 'foo'); + + test.done(); + }, + 'writeln': function(test) { + test.expect(4); + + stdoutEqual(test, function() { log.writeln(); }, '\n'); + stdoutEqual(test, function() { log.writeln('foo'); }, 'foo\n'); + stdoutEqual(test, function() { log.writeln('%s', 'foo'); }, 'foo\n'); + stdoutEqual(test, function() { log.writeln(fooBuffer); }, 'foo\n'); + + test.done(); + }, + 'warn': function(test) { + test.expect(5); + + stdoutEqual(test, function() { log.warn(); }, 'ERROR\n'); + stdoutEqual(test, function() { log.warn('foo'); }, '>> foo\n'); + stdoutEqual(test, function() { log.warn('%s', 'foo'); }, '>> foo\n'); + stdoutEqual(test, function() { log.warn(fooBuffer); }, '>> foo\n'); + test.equal(grunt.fail.errorcount, 0); + + test.done(); + }, + 'error': function(test) { + test.expect(5); + + stdoutEqual(test, function() { log.error(); }, 'ERROR\n'); + stdoutEqual(test, function() { log.error('foo'); }, '>> foo\n'); + stdoutEqual(test, function() { log.error('%s', 'foo'); }, '>> foo\n'); + stdoutEqual(test, function() { log.error(fooBuffer); }, '>> foo\n'); + test.equal(grunt.fail.errorcount, 4); + + test.done(); + }, + 'ok': function(test) { + test.expect(4); + + stdoutEqual(test, function() { log.ok(); }, 'OK\n'); + stdoutEqual(test, function() { log.ok('foo'); }, '>> foo\n'); + stdoutEqual(test, function() { log.ok('%s', 'foo'); }, '>> foo\n'); + stdoutEqual(test, function() { log.ok(fooBuffer); }, '>> foo\n'); + + test.done(); + }, + 'errorlns': function(test) { + test.expect(2); + + stdoutEqual(test, function() { + log.errorlns(grunt.util._.repeat('foo', 30, ' ')); + }, '>> ' + grunt.util._.repeat('foo', 19, ' ') + '\n' + + '>> ' + grunt.util._.repeat('foo', 11, ' ') + '\n'); + test.equal(grunt.fail.errorcount, 1); + + test.done(); + }, + 'oklns': function(test) { + test.expect(1); + + stdoutEqual(test, function() { + log.oklns(grunt.util._.repeat('foo', 30, ' ')); + }, '>> ' + grunt.util._.repeat('foo', 19, ' ') + '\n' + + '>> ' + grunt.util._.repeat('foo', 11, ' ') + '\n'); + + test.done(); + }, + 'success': function(test) { + test.expect(4); + + stdoutEqual(test, function() { log.success(); }, '\n'); + stdoutEqual(test, function() { log.success('foo'); }, 'foo\n'); + stdoutEqual(test, function() { log.success('%s', 'foo'); }, 'foo\n'); + stdoutEqual(test, function() { log.success(fooBuffer); }, 'foo\n'); + + test.done(); + }, + 'fail': function(test) { + test.expect(4); + + stdoutEqual(test, function() { log.fail(); }, '\n'); + stdoutEqual(test, function() { log.fail('foo'); }, 'foo\n'); + stdoutEqual(test, function() { log.fail('%s', 'foo'); }, 'foo\n'); + stdoutEqual(test, function() { log.fail(fooBuffer); }, 'foo\n'); + + test.done(); + }, + 'header': function(test) { + test.expect(4); + + stdoutEqual(test, function() { log.header(); }, '\n\n'); + stdoutEqual(test, function() { log.header('foo'); }, '\nfoo\n'); + stdoutEqual(test, function() { log.header('%s', 'foo'); }, '\nfoo\n'); + stdoutEqual(test, function() { log.header(fooBuffer); }, '\nfoo\n'); + + test.done(); + }, + 'subhead': function(test) { + test.expect(4); + + stdoutEqual(test, function() { log.subhead(); }, '\n\n'); + stdoutEqual(test, function() { log.subhead('foo'); }, '\nfoo\n'); + stdoutEqual(test, function() { log.subhead('%s', 'foo'); }, '\nfoo\n'); + stdoutEqual(test, function() { log.subhead(fooBuffer); }, '\nfoo\n'); + + test.done(); + }, + 'debug': function(test) { + test.expect(5); + var debug = grunt.option('debug'); + + grunt.option('debug', true); + stdoutEqual(test, function() { log.debug(); }, '[D] \n'); + stdoutEqual(test, function() { log.debug('foo'); }, '[D] foo\n'); + stdoutEqual(test, function() { log.debug('%s', 'foo'); }, '[D] foo\n'); + stdoutEqual(test, function() { log.debug(fooBuffer); }, '[D] foo\n'); + + grunt.option('debug', false); + stdoutEqual(test, function() { log.debug('foo'); }, ''); + + grunt.option('debug', debug); + test.done(); + }, + 'writetableln': function(test) { + test.expect(1); + + stdoutEqual(test, function() { + log.writetableln([10], [grunt.util._.repeat('foo', 10)]); + }, 'foofoofoof\noofoofoofo\nofoofoofoo\n'); + + test.done(); + }, + 'writelns': function(test) { + test.expect(1); + + stdoutEqual(test, function() { + log.writelns(grunt.util._.repeat('foo', 30, ' ')); + }, grunt.util._.repeat('foo', 20, ' ') + '\n' + + grunt.util._.repeat('foo', 10, ' ') + '\n'); + + test.done(); + }, + 'writeflags': function(test) { + test.expect(1); + + stdoutEqual(test, function() { + log.writeflags(['foo', 'bar'], 'test'); + }, 'test: foo, bar\n'); + + test.done(); + }, + 'verbose': function(test) { + test.expect(1); + log.muted = true; + + // Test a chain to make sure it's always returning the verbose object. + var obj; + ['write','writeln','warn','error','ok'].forEach(function(key) { + obj = obj ? obj[key]('foo') : log.verbose[key]('foo'); + }); + + test.strictEqual(obj, log.verbose); + + test.done(); + }, + 'notverbose': function(test) { + test.expect(1); + hooker.hook(process.stdout, 'write', { + pre: function() { return hooker.preempt(); } + }); + + // Test a chain to make sure it's always returning the notverbose object. + var obj; + ['write','writeln','warn','error','ok'].forEach(function(key) { + obj = obj ? obj[key]('foo') : log.notverbose[key]('foo'); + }); + + test.strictEqual(obj, log.notverbose); + + hooker.unhook(process.stdout, 'write'); + test.done(); + } +}; diff --git a/node/node_modules/grunt/test/grunt/option_test.js b/node/node_modules/grunt/test/grunt/option_test.js new file mode 100644 index 000000000..8917a57fe --- /dev/null +++ b/node/node_modules/grunt/test/grunt/option_test.js @@ -0,0 +1,41 @@ +'use strict'; + +var grunt = require('../../lib/grunt'); + +exports['option'] = { + setUp: function(done) { + grunt.option.init(); + done(); + }, + tearDown: function(done) { + grunt.option.init(); + done(); + }, + 'option.init': function(test) { + test.expect(1); + var expected = {foo:'bar',bool:true,'bar':{foo:'bar'}}; + test.deepEqual(grunt.option.init(expected), expected); + test.done(); + }, + 'option': function(test) { + test.expect(4); + test.equal(grunt.option('foo', 'bar'), grunt.option('foo')); + grunt.option('foo', {foo:'bar'}); + test.deepEqual(grunt.option('foo'), {foo:'bar'}); + test.equal(grunt.option('no-there'), false); + grunt.option('there', false); + test.equal(grunt.option('no-there'), true); + test.done(); + }, + 'option.flags': function(test) { + test.expect(1); + grunt.option.init({ + foo: 'bar', + there: true, + obj: {foo: 'bar'}, + arr: [] + }); + test.deepEqual(grunt.option.flags(), ['--foo=bar', '--there', '--obj=[object Object]']); + test.done(); + }, +}; diff --git a/node/node_modules/grunt/test/grunt/task_test.js b/node/node_modules/grunt/test/grunt/task_test.js new file mode 100644 index 000000000..fe6ab8b06 --- /dev/null +++ b/node/node_modules/grunt/test/grunt/task_test.js @@ -0,0 +1,259 @@ +'use strict'; + +var grunt = require('../../lib/grunt'); + +exports['task.normalizeMultiTaskFiles'] = { + setUp: function(done) { + this.cwd = process.cwd(); + process.chdir('test/fixtures/files'); + done(); + }, + tearDown: function(done) { + process.chdir(this.cwd); + done(); + }, + 'normalize': function(test) { + test.expect(7); + var actual, expected, key, value; + var flatten = grunt.util._.flatten; + + key = 'dist/built.js'; + value = 'src/*1.js'; + actual = grunt.task.normalizeMultiTaskFiles(value, key); + expected = [ + { + dest: 'dist/built.js', + src: ['src/file1.js'], + orig: {dest: key, src: [value]}, + }, + ]; + test.deepEqual(actual, expected, 'should normalize destTarget: srcString.'); + + key = 'dist/built.js'; + value = [['src/*1.js'], ['src/*2.js']]; + actual = grunt.task.normalizeMultiTaskFiles(value, key); + expected = [ + { + dest: 'dist/built.js', + src: ['src/file1.js', 'src/file2.js'], + orig: {dest: key, src: flatten(value)}, + }, + ]; + test.deepEqual(actual, expected, 'should normalize destTarget: srcArray.'); + + value = { + src: ['src/*1.js', 'src/*2.js'], + dest: 'dist/built.js' + }; + actual = grunt.task.normalizeMultiTaskFiles(value, 'ignored'); + expected = [ + { + dest: 'dist/built.js', + src: ['src/file1.js', 'src/file2.js'], + orig: value, + }, + ]; + test.deepEqual(actual, expected, 'should normalize target: {src: srcStuff, dest: destStuff}.'); + + value = { + files: { + 'dist/built-a.js': 'src/*1.js', + 'dist/built-b.js': ['src/*1.js', [['src/*2.js']]] + } + }; + actual = grunt.task.normalizeMultiTaskFiles(value, 'ignored'); + expected = [ + { + dest: 'dist/built-a.js', + src: ['src/file1.js'], + orig: {dest: 'dist/built-a.js', src: [value.files['dist/built-a.js']]}, + }, + { + dest: 'dist/built-b.js', + src: ['src/file1.js', 'src/file2.js'], + orig: {dest: 'dist/built-b.js', src: flatten(value.files['dist/built-b.js'])}, + }, + ]; + test.deepEqual(actual, expected, 'should normalize target: {files: {destTarget: srcStuff, ...}}.'); + + value = { + files: [ + {'dist/built-a.js': 'src/*.whoops'}, + {'dist/built-b.js': [[['src/*1.js'], 'src/*2.js']]} + ] + }; + actual = grunt.task.normalizeMultiTaskFiles(value, 'ignored'); + expected = [ + { + dest: 'dist/built-a.js', + src: [], + orig: {dest: Object.keys(value.files[0])[0], src: [value.files[0]['dist/built-a.js']]}, + }, + { + dest: 'dist/built-b.js', + src: ['src/file1.js', 'src/file2.js'], + orig: {dest: Object.keys(value.files[1])[0], src: flatten(value.files[1]['dist/built-b.js'])}, + }, + ]; + test.deepEqual(actual, expected, 'should normalize target: {files: [{destTarget: srcStuff}, ...]}.'); + + value = { + files: [ + {dest: 'dist/built-a.js', src: ['src/*2.js']}, + {dest: 'dist/built-b.js', src: ['src/*1.js', 'src/*2.js']} + ] + }; + actual = grunt.task.normalizeMultiTaskFiles(value, 'ignored'); + expected = [ + { + dest: 'dist/built-a.js', + src: ['src/file2.js'], + orig: value.files[0], + }, + { + dest: 'dist/built-b.js', + src: ['src/file1.js', 'src/file2.js'], + orig: value.files[1], + }, + ]; + test.deepEqual(actual, expected, 'should normalize target: {files: [{src: srcStuff, dest: destStuff}, ...]}.'); + + value = { + files: [ + {dest: 'dist/built-a.js', src: ['src/*2.js'], foo: 123, bar: true}, + {dest: 'dist/built-b.js', src: ['src/*1.js', 'src/*2.js'], foo: 456, bar: null} + ] + }; + actual = grunt.task.normalizeMultiTaskFiles(value, 'ignored'); + expected = [ + { + dest: 'dist/built-a.js', + src: ['src/file2.js'], + foo: 123, + bar: true, + orig: value.files[0], + }, + { + dest: 'dist/built-b.js', + src: ['src/file1.js', 'src/file2.js'], + foo: 456, + bar: null, + orig: value.files[1], + }, + ]; + test.deepEqual(actual, expected, 'should propagate extra properties.'); + + test.done(); + }, + 'nonull': function(test) { + test.expect(2); + var actual, expected, value; + + value = { + src: ['src/xxx*.js', 'src/yyy*.js'], + dest: 'dist/built.js', + }; + actual = grunt.task.normalizeMultiTaskFiles(value, 'ignored'); + expected = [ + { + dest: value.dest, + src: [], + orig: value, + }, + ]; + test.deepEqual(actual, expected, 'if nonull is not set, should not include non-matching patterns.'); + + value = { + src: ['src/xxx*.js', 'src/yyy*.js'], + dest: 'dist/built.js', + nonull: true, + }; + actual = grunt.task.normalizeMultiTaskFiles(value, 'ignored'); + expected = [ + { + dest: value.dest, + src: value.src, + nonull: true, + orig: value, + }, + ]; + test.deepEqual(actual, expected, 'if nonull is set, should include non-matching patterns.'); + test.done(); + }, + 'expandMapping': function(test) { + test.expect(3); + var actual, expected, value; + + value = { + files: [ + {dest: 'dist/', src: ['src/file?.js'], expand: true}, + {dest: 'dist/', src: ['file?.js'], expand: true, cwd: 'src'}, + ] + }; + actual = grunt.task.normalizeMultiTaskFiles(value, 'ignored'); + expected = [ + { + dest: 'dist/src/file1.js', src: ['src/file1.js'], + orig: value.files[0], + }, + { + dest: 'dist/src/file2.js', src: ['src/file2.js'], + orig: value.files[0], + }, + { + dest: 'dist/file1.js', src: ['src/file1.js'], + orig: value.files[1], + }, + { + dest: 'dist/file2.js', src: ['src/file2.js'], + orig: value.files[1], + }, + ]; + test.deepEqual(actual, expected, 'expand to file mapping, removing cwd from destination paths.'); + + value = { + files: [ + {dest: 'dist/', src: ['src/file?.js'], expand: true, flatten: true}, + ] + }; + actual = grunt.task.normalizeMultiTaskFiles(value, 'ignored'); + expected = [ + { + dest: 'dist/file1.js', src: ['src/file1.js'], + orig: value.files[0], + }, + { + dest: 'dist/file2.js', src: ['src/file2.js'], + orig: value.files[0], + }, + ]; + test.deepEqual(actual, expected, 'expand to file mapping, flattening destination paths.'); + + value = { + files: [ + { + dest: 'dist/', + src: ['src/file?.js'], + expand: true, + rename: function(destBase, destPath) { + return destBase + 'min/' + destPath.replace(/(\.js)$/, '.min$1'); + }, + }, + ] + }; + actual = grunt.task.normalizeMultiTaskFiles(value, 'ignored'); + expected = [ + { + dest: 'dist/min/src/file1.min.js', src: ['src/file1.js'], + orig: value.files[0], + }, + { + dest: 'dist/min/src/file2.min.js', src: ['src/file2.js'], + orig: value.files[0], + }, + ]; + test.deepEqual(actual, expected, 'expand to file mapping, renaming files.'); + + test.done(); + }, +}; diff --git a/node/node_modules/grunt/test/grunt/template_test.js b/node/node_modules/grunt/test/grunt/template_test.js index f119a66d9..b7903ac3d 100644 --- a/node/node_modules/grunt/test/grunt/template_test.js +++ b/node/node_modules/grunt/test/grunt/template_test.js @@ -1,3 +1,5 @@ +'use strict'; + var grunt = require('../../lib/grunt'); exports['template'] = { @@ -9,12 +11,37 @@ exports['template'] = { baz: 'a<%= bar %>e' }; - test.equal(grunt.template.process('<%= foo %>', obj), 'c', 'should retrieve value.'); - test.equal(grunt.template.process('<%= bar %>', obj), 'bcd', 'should recurse.'); - test.equal(grunt.template.process('<%= baz %>', obj), 'abcde', 'should recurse.'); + test.equal(grunt.template.process('<%= foo %>', {data: obj}), 'c', 'should retrieve value.'); + test.equal(grunt.template.process('<%= bar %>', {data: obj}), 'bcd', 'should recurse.'); + test.equal(grunt.template.process('<%= baz %>', {data: obj}), 'abcde', 'should recurse.'); obj.foo = '<% oops %'; - test.equal(grunt.template.process('<%= baz %>', obj), 'ab<% oops %de', 'should not explode.'); + test.equal(grunt.template.process('<%= baz %>', {data: obj}), 'ab<% oops %de', 'should not explode.'); + test.done(); + }, + + 'custom delimiters': function(test) { + test.expect(6); + var obj = { + foo: 'c', + bar: 'b{%= foo %}d', + baz: 'a{%= bar %}e' + }; + + test.equal(grunt.template.process('{%= foo %}', {data: obj, delimiters: 'custom'}), '{%= foo %}', 'custom delimiters have yet to be defined.'); + + // Define custom delimiters. + grunt.template.addDelimiters('custom', '{%', '%}'); + + test.equal(grunt.template.process('{%= foo %}', {data: obj, delimiters: 'custom'}), 'c', 'should retrieve value.'); + test.equal(grunt.template.process('{%= bar %}', {data: obj, delimiters: 'custom'}), 'bcd', 'should recurse.'); + test.equal(grunt.template.process('{%= baz %}', {data: obj, delimiters: 'custom'}), 'abcde', 'should recurse.'); + + test.equal(grunt.template.process('{%= foo %}<%= foo %>', {data: obj, delimiters: 'custom'}), 'c<%= foo %>', 'should ignore default delimiters'); + + obj.foo = '{% oops %'; + test.equal(grunt.template.process('{%= baz %}', {data: obj, delimiters: 'custom'}), 'ab{% oops %de', 'should not explode.'); + test.done(); - } + }, }; diff --git a/node/node_modules/grunt/test/grunt/util_test.js b/node/node_modules/grunt/test/grunt/util_test.js new file mode 100644 index 000000000..01e8b1c1e --- /dev/null +++ b/node/node_modules/grunt/test/grunt/util_test.js @@ -0,0 +1,301 @@ +'use strict'; + +var grunt = require('../../lib/grunt'); + +var fs = require('fs'); +var path = require('path'); + +var Tempfile = require('temporary/lib/file'); + +exports['util.callbackify'] = { + 'return': function(test) { + test.expect(1); + // This function returns a value. + function add(a, b) { + return a + b; + } + grunt.util.callbackify(add)(1, 2, function(result) { + test.equal(result, 3, 'should be the correct result.'); + test.done(); + }); + }, + 'callback (sync)': function(test) { + test.expect(1); + // This function accepts a callback which it calls synchronously. + function add(a, b, done) { + done(a + b); + } + grunt.util.callbackify(add)(1, 2, function(result) { + test.equal(result, 3, 'should be the correct result.'); + test.done(); + }); + }, + 'callback (async)': function(test) { + test.expect(1); + // This function accepts a callback which it calls asynchronously. + function add(a, b, done) { + setTimeout(done.bind(null, a + b), 0); + } + grunt.util.callbackify(add)(1, 2, function(result) { + test.equal(result, 3, 'should be the correct result.'); + test.done(); + }); + } +}; + +exports['util'] = { + 'error': function(test) { + test.expect(9); + var origError = new Error('Original error.'); + + var err = grunt.util.error('Test message.'); + test.ok(err instanceof Error, 'Should be an Error.'); + test.equal(err.name, 'Error', 'Should be an Error.'); + test.equal(err.message, 'Test message.', 'Should have the correct message.'); + + err = grunt.util.error('Test message.', origError); + test.ok(err instanceof Error, 'Should be an Error.'); + test.equal(err.name, 'Error', 'Should be an Error.'); + test.equal(err.message, 'Test message.', 'Should have the correct message.'); + test.equal(err.origError, origError, 'Should reflect the original error.'); + + var newError = new Error('Test message.'); + err = grunt.util.error(newError, origError); + test.equal(err, newError, 'Should be the passed-in Error.'); + test.equal(err.origError, origError, 'Should reflect the original error.'); + test.done(); + }, + 'linefeed': function(test) { + test.expect(1); + if (process.platform === 'win32') { + test.equal(grunt.util.linefeed, '\r\n', 'linefeed should be operating-system appropriate.'); + } else { + test.equal(grunt.util.linefeed, '\n', 'linefeed should be operating-system appropriate.'); + } + test.done(); + }, + 'normalizelf': function(test) { + test.expect(1); + if (process.platform === 'win32') { + test.equal(grunt.util.normalizelf('foo\nbar\r\nbaz\r\n\r\nqux\n\nquux'), 'foo\r\nbar\r\nbaz\r\n\r\nqux\r\n\r\nquux', 'linefeeds should be normalized'); + } else { + test.equal(grunt.util.normalizelf('foo\nbar\r\nbaz\r\n\r\nqux\n\nquux'), 'foo\nbar\nbaz\n\nqux\n\nquux', 'linefeeds should be normalized'); + } + test.done(); + } +}; + +exports['util.spawn'] = { + setUp: function(done) { + this.script = path.resolve('test/fixtures/spawn.js'); + done(); + }, + 'exit code 0': function(test) { + test.expect(6); + grunt.util.spawn({ + cmd: process.execPath, + args: [ this.script, 0 ], + }, function(err, result, code) { + test.equals(err, null); + test.equals(code, 0); + test.equals(result.stdout, 'stdout'); + test.equals(result.stderr, 'stderr'); + test.equals(result.code, 0); + test.equals(String(result), 'stdout'); + test.done(); + }); + }, + 'exit code 0, fallback': function(test) { + test.expect(6); + grunt.util.spawn({ + cmd: process.execPath, + args: [ this.script, 0 ], + fallback: 'ignored if exit code is 0' + }, function(err, result, code) { + test.equals(err, null); + test.equals(code, 0); + test.equals(result.stdout, 'stdout'); + test.equals(result.stderr, 'stderr'); + test.equals(result.code, 0); + test.equals(String(result), 'stdout'); + test.done(); + }); + }, + 'non-zero exit code': function(test) { + test.expect(7); + grunt.util.spawn({ + cmd: process.execPath, + args: [ this.script, 123 ], + }, function(err, result, code) { + test.ok(err instanceof Error); + test.equals(err.message, 'stderr'); + test.equals(code, 123); + test.equals(result.stdout, 'stdout'); + test.equals(result.stderr, 'stderr'); + test.equals(result.code, 123); + test.equals(String(result), 'stderr'); + test.done(); + }); + }, + 'non-zero exit code, fallback': function(test) { + test.expect(6); + grunt.util.spawn({ + cmd: process.execPath, + args: [ this.script, 123 ], + fallback: 'custom fallback' + }, function(err, result, code) { + test.equals(err, null); + test.equals(code, 123); + test.equals(result.stdout, 'stdout'); + test.equals(result.stderr, 'stderr'); + test.equals(result.code, 123); + test.equals(String(result), 'custom fallback'); + test.done(); + }); + }, + 'cmd not found': function(test) { + test.expect(3); + grunt.util.spawn({ + cmd: 'nodewtfmisspelled', + }, function(err, result, code) { + test.ok(err instanceof Error); + test.equals(code, 127); + test.equals(result.code, 127); + test.done(); + }); + }, + 'cmd not found, fallback': function(test) { + test.expect(4); + grunt.util.spawn({ + cmd: 'nodewtfmisspelled', + fallback: 'use a fallback or good luck' + }, function(err, result, code) { + test.equals(err, null); + test.equals(code, 127); + test.equals(result.code, 127); + test.equals(String(result), 'use a fallback or good luck'); + test.done(); + }); + }, + 'cmd not in path': function(test) { + test.expect(6); + var win32 = process.platform === 'win32'; + grunt.util.spawn({ + cmd: 'test\\fixtures\\exec' + (win32 ? '.cmd' : '.sh'), + }, function(err, result, code) { + test.equals(err, null); + test.equals(code, 0); + test.equals(result.stdout, 'done'); + test.equals(result.stderr, ''); + test.equals(result.code, 0); + test.equals(String(result), 'done'); + test.done(); + }); + }, + 'cmd not in path (with cwd)': function(test) { + test.expect(6); + var win32 = process.platform === 'win32'; + grunt.util.spawn({ + cmd: './exec' + (win32 ? '.cmd' : '.sh'), + opts: {cwd: 'test/fixtures'}, + }, function(err, result, code) { + test.equals(err, null); + test.equals(code, 0); + test.equals(result.stdout, 'done'); + test.equals(result.stderr, ''); + test.equals(result.code, 0); + test.equals(String(result), 'done'); + test.done(); + }); + }, + 'grunt': function(test) { + test.expect(3); + grunt.util.spawn({ + grunt: true, + args: [ '--gruntfile', 'test/fixtures/Gruntfile-print-text.js', 'print:foo' ], + }, function(err, result, code) { + test.equals(err, null); + test.equals(code, 0); + test.ok(/^OUTPUT: foo/m.test(result.stdout), 'stdout should contain output indicating the grunt task was run.'); + test.done(); + }); + }, + 'grunt (with cwd)': function(test) { + test.expect(3); + grunt.util.spawn({ + grunt: true, + args: [ '--gruntfile', 'Gruntfile-print-text.js', 'print:foo' ], + opts: {cwd: 'test/fixtures'}, + }, function(err, result, code) { + test.equals(err, null); + test.equals(code, 0); + test.ok(/^OUTPUT: foo/m.test(result.stdout), 'stdout should contain output indicating the grunt task was run.'); + test.done(); + }); + }, + 'grunt result.toString() with error': function(test) { + // grunt.log.error uses standard out, to be fixed in 0.5. + test.expect(4); + grunt.util.spawn({ + grunt: true, + args: [ 'nonexistentTask' ] + }, function(err, result, code) { + test.ok(err instanceof Error, 'Should be an Error.'); + test.equal(err.name, 'Error', 'Should be an Error.'); + test.equals(code, 3); + test.ok(/Warning: Task "nonexistentTask" not found./m.test(result.toString()), 'stdout should contain output indicating the grunt task was (attempted to be) run.'); + test.done(); + }); + }, + 'custom stdio stream(s)': function(test) { + test.expect(6); + var stdoutFile = new Tempfile(); + var stderrFile = new Tempfile(); + var stdout = fs.openSync(stdoutFile.path, 'a'); + var stderr = fs.openSync(stderrFile.path, 'a'); + var child = grunt.util.spawn({ + cmd: process.execPath, + args: [ this.script, 0 ], + opts: {stdio: [null, stdout, stderr]}, + }, function(err, result, code) { + test.equals(code, 0); + test.equals(String(fs.readFileSync(stdoutFile.path)), 'stdout\n', 'Child process stdout should have been captured via custom stream.'); + test.equals(String(fs.readFileSync(stderrFile.path)), 'stderr\n', 'Child process stderr should have been captured via custom stream.'); + stdoutFile.unlinkSync(); + stderrFile.unlinkSync(); + test.equals(result.stdout, '', 'Nothing will be passed to the stdout string when spawn stdio is a custom stream.'); + test.done(); + }); + test.ok(!child.stdout, 'child should not have a stdout property.'); + test.ok(!child.stderr, 'child should not have a stderr property.'); + }, +}; + +exports['util.spawn.multibyte'] = { + setUp: function(done) { + this.script = path.resolve('test/fixtures/spawn-multibyte.js'); + done(); + }, + 'partial stdout': function(test) { + test.expect(4); + grunt.util.spawn({ + cmd: process.execPath, + args: [ this.script ], + }, function(err, result, code) { + test.equals(err, null); + test.equals(code, 0); + test.equals(result.stdout, 'こんにちは'); + test.equals(result.stderr, 'こんにちは'); + test.done(); + }); + } +}; + +exports['util.underscore.string'] = function(test) { + test.expect(4); + test.equals(grunt.util._.trim(' foo '), 'foo', 'Should have trimmed the string.'); + test.equals(grunt.util._.capitalize('foo'), 'Foo', 'Should have capitalized the first letter.'); + test.equals(grunt.util._.words('one two three').length, 3, 'Should have counted three words.'); + test.ok(grunt.util._.isBlank(' '), 'Should be blank.'); + test.done(); +}; diff --git a/node/node_modules/grunt/test/grunt/utils_test.js b/node/node_modules/grunt/test/grunt/utils_test.js deleted file mode 100644 index 52b6f66f4..000000000 --- a/node/node_modules/grunt/test/grunt/utils_test.js +++ /dev/null @@ -1,22 +0,0 @@ -var grunt = require('../../lib/grunt'); - -exports['utils'] = { - 'linefeed': function(test) { - test.expect(1); - if (process.platform === 'win32') { - test.equal(grunt.utils.linefeed, '\r\n', 'linefeed should be operating-system appropriate.'); - } else { - test.equal(grunt.utils.linefeed, '\n', 'linefeed should be operating-system appropriate.'); - } - test.done(); - }, - 'normalizelf': function(test) { - test.expect(1); - if (process.platform === 'win32') { - test.equal(grunt.utils.normalizelf('foo\nbar\r\nbaz\r\n\r\nqux\n\nquux'), 'foo\r\nbar\r\nbaz\r\n\r\nqux\r\n\r\nquux', 'linefeeds should be normalized'); - } else { - test.equal(grunt.utils.normalizelf('foo\nbar\r\nbaz\r\n\r\nqux\n\nquux'), 'foo\nbar\nbaz\n\nqux\n\nquux', 'linefeeds should be normalized'); - } - test.done(); - } -}; diff --git a/node/node_modules/grunt/test/gruntfile/multi-task-files.js b/node/node_modules/grunt/test/gruntfile/multi-task-files.js new file mode 100644 index 000000000..3fda2e400 --- /dev/null +++ b/node/node_modules/grunt/test/gruntfile/multi-task-files.js @@ -0,0 +1,361 @@ +/* + * grunt + * http://gruntjs.com/ + * + * Copyright (c) 2013 "Cowboy" Ben Alman + * Licensed under the MIT license. + * https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT + */ + +// For now, run this "test suite" with: +// grunt --gruntfile ./test/gruntfile/multi-task-files.js + +'use strict'; + +module.exports = function(grunt) { + grunt.file.setBase('../fixtures/files'); + + grunt.initConfig({ + build: '123', + mappings: { + cwd: 'src/', + dest: 'foo/', + ext: '.bar', + rename: function(destBase, destPath) { + return destBase + 'baz/' + destPath.replace(/\.js$/, '<%= mappings.ext %>'); + }, + }, + run: { + options: {a: 1, b: 11}, + // This is the "compact" format, where the target name is actually the + // dest filename. Doesn't support per-target options, templated dest, or + // >1 srcs-dest grouping. + 'dist/built.js': 'src/*1.js', + 'dist/built1.js': ['src/*1.js', 'src/*2.js'], + // This is the "medium" format. The target name is arbitrary and can be + // used like "grunt run:built". Supports per-target options, templated + // dest, and arbitrary "extra" paramters. Doesn't support >1 srcs-dest + // grouping. + built: { + options: {a: 2, c: 22}, + src: ['src/*1.js', 'src/*2.js'], + dest: 'dist/built-<%= build %>.js', + extra: 123, + }, + // This is the "full" format. The target name is arbitrary and can be + // used like "grunt run:long1". Supports per-target options, templated + // dest and >1 srcs-dest grouping. + long1: { + options: {a: 3, c: 33}, + files: { + 'dist/built-<%= build %>-a.js': ['src/*1.js'], + 'dist/built-<%= build %>-b.js': ['src/*1.js', 'src/*2.js'], + } + }, + long2: { + options: {a: 4, c: 44}, + files: [ + {'dist/built-<%= build %>-a.js': ['src/*.whoops']}, + {'dist/built-<%= build %>-b.js': ['src/*1.js', 'src/*2.js']}, + ] + }, + // This "full" variant supports per srcs-dest arbitrary "extra" paramters. + long3: { + options: {a: 5, c: 55}, + files: [ + {dest: 'dist/built-<%= build %>-a.js', src: ['src/*2.js'], extra: 456}, + {dest: 'dist/built-<%= build %>-b.js', src: ['src/*1.js', 'src/*2.js'], extra: 789}, + ] + }, + // File mapping options can be specified in these 2 formats. + built_mapping: { + options: {a: 6, c: 66}, + expand: true, + cwd: '<%= mappings.cwd %>', + src: ['*1.js', '*2.js'], + dest: '<%= mappings.dest %>', + rename: '<%= mappings.rename %>', + extra: 123 + }, + long3_mapping: { + options: {a: 7, c: 77}, + files: [ + { + expand: true, + cwd: '<%= mappings.cwd %>', + src: ['*1.js', '*2.js'], + dest: '<%= mappings.dest %>', + rename: '<%= mappings.rename %>', + extra: 123 + } + ] + }, + // Need to ensure the task function is run if no files or options were + // specified! + no_files_or_options: {}, + }, + }); + + var results = {}; + + var counters = []; + var counter = -1; + grunt.registerMultiTask('run', 'Store stuff for later testing.', function() { + var key = this.nameArgs; + results[key] = { + options: this.options({d: 9}), + files: this.files, + }; + // Test asynchronous-ness. + var done; + if (counter++ % 2 === 0) { + done = this.async(); + setTimeout(function() { + counters.push(counter); + done(); + }, 10); + } else { + counters.push(counter); + } + }); + + var expecteds = { + 'run:no_files_or_options': { + options: {a: 1, b: 11, d: 9}, + files: [], + }, + 'run:dist/built.js': { + options: {a: 1, b: 11, d: 9}, + files: [ + { + dest: 'dist/built.js', + src: ['src/file1.js'], + orig: { + dest: 'dist/built.js', + src: ['src/*1.js'], + }, + }, + ] + }, + 'run:dist/built1.js': { + options: {a: 1, b: 11, d: 9}, + files: [ + { + dest: 'dist/built1.js', + src: ['src/file1.js', 'src/file2.js'], + orig: { + dest: 'dist/built1.js', + src: ['src/*1.js', 'src/*2.js'], + }, + }, + ] + }, + 'run:built': { + options: {a: 2, b: 11, c: 22, d: 9}, + files: [ + { + dest: 'dist/built-123.js', + src: ['src/file1.js', 'src/file2.js'], + extra: 123, + orig: { + dest: 'dist/built-123.js', + src: ['src/*1.js', 'src/*2.js'], + extra: 123, + }, + }, + ], + }, + 'run:long1': { + options: {a: 3, b: 11, c: 33, d: 9}, + files: [ + { + dest: 'dist/built-123-a.js', + src: ['src/file1.js'], + orig: { + dest: 'dist/built-123-a.js', + src: ['src/*1.js'], + }, + }, + { + dest: 'dist/built-123-b.js', + src: ['src/file1.js', 'src/file2.js'], + orig: { + dest: 'dist/built-123-b.js', + src: ['src/*1.js', 'src/*2.js'], + }, + }, + ], + }, + 'run:long2': { + options: {a: 4, b: 11, c: 44, d: 9}, + files: [ + { + dest: 'dist/built-123-a.js', + src: [], + orig: { + dest: 'dist/built-123-a.js', + src: ['src/*.whoops'], + }, + }, + { + dest: 'dist/built-123-b.js', + src: ['src/file1.js', 'src/file2.js'], + orig: { + dest: 'dist/built-123-b.js', + src: ['src/*1.js', 'src/*2.js'], + }, + }, + ], + }, + 'run:long3': { + options: {a: 5, b: 11, c: 55, d: 9}, + files: [ + { + dest: 'dist/built-123-a.js', + src: ['src/file2.js'], + extra: 456, + orig: { + dest: 'dist/built-123-a.js', + src: ['src/*2.js'], + extra: 456, + }, + }, + { + dest: 'dist/built-123-b.js', + src: ['src/file1.js', 'src/file2.js'], + extra: 789, + orig: { + src: ['src/*1.js', 'src/*2.js'], + dest: 'dist/built-123-b.js', + extra: 789, + }, + }, + ], + }, + 'run:built_mapping': { + options: {a: 6, b: 11, c: 66, d: 9}, + files: [ + { + dest: 'foo/baz/file1.bar', + src: ['src/file1.js'], + extra: 123, + orig: { + expand: true, + cwd: grunt.config.get('mappings.cwd'), + src: ['*1.js', '*2.js'], + dest: grunt.config.get('mappings.dest'), + rename: grunt.config.get('run.built_mapping.rename'), + extra: 123, + }, + }, + { + dest: 'foo/baz/file2.bar', + src: ['src/file2.js'], + extra: 123, + orig: { + expand: true, + cwd: grunt.config.get('run.built_mapping.cwd'), + src: ['*1.js', '*2.js'], + dest: grunt.config.get('run.built_mapping.dest'), + rename: grunt.config.get('run.built_mapping.rename'), + extra: 123, + }, + }, + ], + }, + 'run:long3_mapping': { + options: {a: 7, b: 11, c: 77, d: 9}, + files: [ + { + dest: 'foo/baz/file1.bar', + src: ['src/file1.js'], + extra: 123, + orig: { + expand: true, + cwd: grunt.config.get('mappings.cwd'), + src: ['*1.js', '*2.js'], + dest: grunt.config.get('mappings.dest'), + rename: grunt.config.get('mappings.rename'), + extra: 123, + }, + }, + { + dest: 'foo/baz/file2.bar', + src: ['src/file2.js'], + extra: 123, + orig: { + expand: true, + cwd: grunt.config.get('mappings.cwd'), + src: ['*1.js', '*2.js'], + dest: grunt.config.get('mappings.dest'), + rename: grunt.config.get('run.built_mapping.rename'), + extra: 123, + }, + }, + ], + }, + }; + + var assert = require('assert'); + var difflet = require('difflet')({indent: 2, comment: true}); + var test = function(name, fn) { + try { + fn(); + } catch (err) { + grunt.log.subhead('Assertion Failure in ' + name); + console.log(difflet.compare(err.expected, err.actual)); + throw new Error(err.message); + } + }; + + grunt.registerTask('test', 'Test file and option objects.', function() { + var key = 'run:' + this.nameArgs.replace(/^.*?:/, ''); + var all = key === 'run:all'; + var actual = all ? results : results[key]; + var expected = all ? expecteds : expecteds[key]; + + test(this.name, function() { + assert.deepEqual(actual, expected, 'Actual should match expected.'); + }); + + if (all) { + results = {}; + } else { + delete results[key]; + } + }); + + grunt.registerTask('test:counters', 'Test function execution order.', function() { + test(this.name, function() { + assert.equal(counters.length, counter + 1, 'Task functions should have run the correct number of times.'); + var expected = []; + for (var i = 0; i < counters.length; i++) { expected.push(i); } + assert.deepEqual(counters, expected, 'Task functions should have actually executed in-order.'); + }); + }); + + grunt.registerTask('default', [ + 'run:no_files_or_options', + 'test:no_files_or_options', + 'run:dist/built.js', + 'test:dist/built.js', + 'run:dist/built1.js', + 'test:dist/built1.js', + 'run:built', + 'test:built', + 'run:long1', + 'test:long1', + 'run:long2', + 'test:long2', + 'run:long3', + 'test:long3', + 'run:built_mapping', + 'test:built_mapping', + 'run:long3_mapping', + 'test:long3_mapping', + 'run', + 'test:all', + 'test:counters', + ]); + +}; diff --git a/node/node_modules/grunt/test/tasks/concat_test.js b/node/node_modules/grunt/test/tasks/concat_test.js deleted file mode 100644 index afba24ade..000000000 --- a/node/node_modules/grunt/test/tasks/concat_test.js +++ /dev/null @@ -1,21 +0,0 @@ -var grunt = require('../../lib/grunt'); - -// In case the grunt being used to test is different than the grunt being -// tested, initialize the task and config subsystems. -if (grunt.task.searchDirs.length === 0) { - grunt.task.init([]); - grunt.config.init({}); -} - -exports['concat'] = function(test) { - test.expect(1); - grunt.registerHelper('test_helper', function(a, b) { return a + b; }); - var files = [ - 'test/fixtures/a.js', - '', - 'test/fixtures/b.js' - ]; - var lf = grunt.utils.linefeed; - test.equal(grunt.helper('concat', files), 'var a = 1;\n' + lf + 'xy' + lf + 'var b = 2;\n', 'It should concatenate files and directives.'); - test.done(); -}; diff --git a/node/node_modules/grunt/test/tasks/init_test.js b/node/node_modules/grunt/test/tasks/init_test.js deleted file mode 100644 index 891c9e05e..000000000 --- a/node/node_modules/grunt/test/tasks/init_test.js +++ /dev/null @@ -1,44 +0,0 @@ -var grunt = require('../../lib/grunt'); - -// In case the grunt being used to test is different than the grunt being -// tested, initialize the task and config subsystems. -if (grunt.task.searchDirs.length === 0) { - grunt.task.init([]); - grunt.config.init({}); -} - -exports['github_web_url'] = { - 'no args': function(test) { - test.expect(1); - test.equal(grunt.helper('github_web_url'), null, 'It should return null.'); - test.done(); - }, - 'nonsensical args': function(test) { - test.expect(3); - test.equal(grunt.helper('github_web_url', ''), null, 'It should return null.'); - test.equal(grunt.helper('github_web_url', 'omgfoo'), null, 'It should return null.'); - test.equal(grunt.helper('github_web_url', 'http://benalman.com/'), null, 'It should return null.'); - test.done(); - }, - 'no suffix': function(test) { - test.expect(5); - test.equal(grunt.helper('github_web_url', 'git@github.com:cowboy/grunt.git'), 'https://github.com/cowboy/grunt', 'It should convert the URI.'); - test.equal(grunt.helper('github_web_url', 'https://cowboy@github.com/cowboy/grunt.git'), 'https://github.com/cowboy/grunt', 'It should convert the URI.'); - test.equal(grunt.helper('github_web_url', 'git://github.com/cowboy/grunt.git'), 'https://github.com/cowboy/grunt', 'It should convert the URI.'); - test.equal(grunt.helper('github_web_url', 'http://github.com/paulirish/newsite'), 'https://github.com/paulirish/newsite', 'It should convert the URI.'); - test.equal(grunt.helper('github_web_url', 'http://github.com/paulirish/newsite/'), 'https://github.com/paulirish/newsite', 'It should convert the URI.'); - test.done(); - }, - 'suffix': function(test) { - test.expect(7); - test.equal(grunt.helper('github_web_url', 'git@github.com:cowboy/grunt.git', 'issues'), 'https://github.com/cowboy/grunt/issues', 'It should convert the URI.'); - test.equal(grunt.helper('github_web_url', 'https://cowboy@github.com/cowboy/grunt.git', 'issues'), 'https://github.com/cowboy/grunt/issues', 'It should convert the URI.'); - test.equal(grunt.helper('github_web_url', 'git://github.com/cowboy/grunt.git', 'issues'), 'https://github.com/cowboy/grunt/issues', 'It should convert the URI.'); - test.equal(grunt.helper('github_web_url', 'http://github.com/paulirish/newsite', 'issues'), 'https://github.com/paulirish/newsite/issues', 'It should convert the URI.'); - test.equal(grunt.helper('github_web_url', 'http://github.com/paulirish/newsite/', 'issues'), 'https://github.com/paulirish/newsite/issues', 'It should convert the URI.'); - test.equal(grunt.helper('github_web_url', 'http://github.com/paulirish/newsite', '/issues'), 'https://github.com/paulirish/newsite/issues', 'It should convert the URI.'); - test.equal(grunt.helper('github_web_url', 'http://github.com/paulirish/newsite/', '/issues'), 'https://github.com/paulirish/newsite/issues', 'It should convert the URI.'); - test.done(); - } -}; - diff --git a/node/node_modules/grunt/test/tasks/lint_test.js b/node/node_modules/grunt/test/tasks/lint_test.js deleted file mode 100644 index 66e16cc49..000000000 --- a/node/node_modules/grunt/test/tasks/lint_test.js +++ /dev/null @@ -1,28 +0,0 @@ -var grunt = require('../../lib/grunt'); - -// In case the grunt being used to test is different than the grunt being -// tested, initialize the task and config subsystems. -if (grunt.task.searchDirs.length === 0) { - grunt.task.init([]); - grunt.config.init({}); -} - -// Just tests whether options are correctly set -exports['jshint'] = function(test) { - test.expect(1); - - var options = { - asi: true, - laxcomma: true, - maxparams: 3 - }; - var globals = { - node: true - }; - - var errorcount = grunt.fail.errorcount; - grunt.helper('lint', grunt.file.read('test/fixtures/lintTest.js'), options, globals); - test.equal(grunt.fail.errorcount - errorcount, 1, 'One error should have been logged.'); - - test.done(); -}; diff --git a/node/node_modules/grunt/test/tasks/misc_test.js b/node/node_modules/grunt/test/tasks/misc_test.js deleted file mode 100644 index e14e1ca50..000000000 --- a/node/node_modules/grunt/test/tasks/misc_test.js +++ /dev/null @@ -1,91 +0,0 @@ -var grunt = require('../../lib/grunt'); - -// In case the grunt being used to test is different than the grunt being -// tested, initialize the task and config subsystems. -if (grunt.task.searchDirs.length === 0) { - grunt.task.init([]); - grunt.config.init({}); -} - -exports['config'] = function(test) { - test.expect(2); - test.deepEqual(grunt.helper('config'), grunt.config(), 'It should just pass through to config.'); - test.deepEqual(grunt.helper('config', 'meta'), grunt.config('meta'), 'It should just pass through to config.'); - test.done(); -}; - -exports['json'] = function(test) { - test.expect(2); - var obj = grunt.helper('json', 'test/fixtures/test.json'); - test.equal(obj.foo, 'bar', 'JSON properties should be available as-defined.'); - test.deepEqual(obj.baz, [1, 2, 3], 'JSON properties should be available as-defined.'); - test.done(); -}; - -exports['strip_banner'] = function(test) { - test.expect(7); - var src = grunt.file.read('test/fixtures/banner.js'); - test.equal(grunt.helper('strip_banner', src), '// Comment\n\n/* Comment */\n', 'It should strip the top banner.'); - test.equal(grunt.helper('strip_banner', src, {block: true}), '// Comment\n\n/* Comment */\n', 'It should strip the top banner.'); - src = grunt.file.read('test/fixtures/banner2.js'); - test.equal(grunt.helper('strip_banner', src), '\n/*! SAMPLE\n * BANNER */\n\n// Comment\n\n/* Comment */\n', 'It should not strip the top banner.'); - test.equal(grunt.helper('strip_banner', src, {block: true}), '// Comment\n\n/* Comment */\n', 'It should strip the top banner.'); - src = grunt.file.read('test/fixtures/banner3.js'); - test.equal(grunt.helper('strip_banner', src), '\n// This is\n// A sample\n// Banner\n\n// But this is not\n\n/* And neither\n * is this\n */\n', 'It should not strip the top banner.'); - test.equal(grunt.helper('strip_banner', src, {block: true}), '\n// This is\n// A sample\n// Banner\n\n// But this is not\n\n/* And neither\n * is this\n */\n', 'It should not strip the top banner.'); - test.equal(grunt.helper('strip_banner', src, {line: true}), '// But this is not\n\n/* And neither\n * is this\n */\n', 'It should strip the top banner.'); - test.done(); -}; - -exports['file_strip_banner'] = function(test) { - test.expect(14); - var filepath = 'test/fixtures/banner.js'; - test.equal(grunt.helper('file_strip_banner', filepath), '// Comment\n\n/* Comment */\n', 'It should strip the top banner.'); - test.equal(grunt.helper('file_strip_banner', filepath, {block: true}), '// Comment\n\n/* Comment */\n', 'It should strip the top banner.'); - filepath = 'test/fixtures/banner2.js'; - test.equal(grunt.helper('file_strip_banner', filepath), '\n/*! SAMPLE\n * BANNER */\n\n// Comment\n\n/* Comment */\n', 'It should not strip the top banner.'); - test.equal(grunt.helper('file_strip_banner', filepath, {block: true}), '// Comment\n\n/* Comment */\n', 'It should strip the top banner.'); - filepath = 'test/fixtures/banner3.js'; - test.equal(grunt.helper('file_strip_banner', filepath), '\n// This is\n// A sample\n// Banner\n\n// But this is not\n\n/* And neither\n * is this\n */\n', 'It should not strip the top banner.'); - test.equal(grunt.helper('file_strip_banner', filepath, {block: true}), '\n// This is\n// A sample\n// Banner\n\n// But this is not\n\n/* And neither\n * is this\n */\n', 'It should not strip the top banner.'); - test.equal(grunt.helper('file_strip_banner', filepath, {line: true}), '// But this is not\n\n/* And neither\n * is this\n */\n', 'It should strip the top banner.'); - - test.equal(grunt.task.directive(''), '// Comment\n\n/* Comment */\n', 'It should strip the top banner.'); - test.equal(grunt.task.directive(''), '// Comment\n\n/* Comment */\n', 'It should strip the top banner.'); - test.equal(grunt.task.directive(''), '\n/*! SAMPLE\n * BANNER */\n\n// Comment\n\n/* Comment */\n', 'It should not strip the top banner.'); - test.equal(grunt.task.directive(''), '// Comment\n\n/* Comment */\n', 'It should strip the top banner.'); - test.equal(grunt.task.directive(''), '\n// This is\n// A sample\n// Banner\n\n// But this is not\n\n/* And neither\n * is this\n */\n', 'It should not strip the top banner.'); - test.equal(grunt.task.directive(''), '\n// This is\n// A sample\n// Banner\n\n// But this is not\n\n/* And neither\n * is this\n */\n', 'It should not strip the top banner.'); - test.equal(grunt.task.directive(''), '// But this is not\n\n/* And neither\n * is this\n */\n', 'It should strip the top banner.'); - test.done(); -}; - -exports['file_template'] = function(test) { - test.expect(2); - var expected = 'Version: ' + grunt.version + ', today: ' + grunt.template.today('yyyy-mm-dd') + '.'; - test.equal(grunt.helper('file_template', 'test/fixtures/template.txt'), expected, 'It should return the parsed template.'); - test.equal(grunt.task.directive(''), expected, 'It should return the parsed template.'); - test.done(); -}; - -exports['banner'] = function(test) { - test.expect(5); - grunt.config('test_config', {a: 'aaaaa', b: 'bbbbb', c: [1, 2, 3], d: [{a: 1}, {a: 2}, {a: 3}]}); - - grunt.config('meta.banner', 'foo\n<%= test_config.a %>\nbar'); - test.equal(grunt.helper('banner'), grunt.utils.normalizelf('foo\naaaaa\nbar\n'), 'It should use the default banner.'); - - grunt.config('test_config.banner', '<%= test_config.b %>'); - test.equal(grunt.helper('banner', 'test_config.banner'), grunt.utils.normalizelf('bbbbb\n'), 'It should use the requested banner.'); - - grunt.config('test_config.banner', '<%= test_config.c.join(", ") %>'); - test.equal(grunt.helper('banner', 'test_config.banner'), grunt.utils.normalizelf('1, 2, 3\n'), 'It should join arrays.'); - - grunt.config('test_config.banner', '<%= _.pluck(test_config.d, "a").join(", ") %>'); - test.equal(grunt.helper('banner', 'test_config.banner'), grunt.utils.normalizelf('1, 2, 3\n'), 'It should join arrays.'); - - grunt.config('test_config.banner', '<%= grunt.template.today("yyyy-mm-dd") %>'); - test.equal(grunt.helper('banner', 'test_config.banner'), grunt.utils.normalizelf(grunt.template.today('yyyy-mm-dd') + '\n'), 'It should parse the current date correctly.'); - - test.done(); -}; diff --git a/node/node_modules/grunt/test/util/namespace_test.js b/node/node_modules/grunt/test/util/namespace_test.js index dc04594be..9a236161a 100644 --- a/node/node_modules/grunt/test/util/namespace_test.js +++ b/node/node_modules/grunt/test/util/namespace_test.js @@ -1,3 +1,5 @@ +'use strict'; + var namespace = require('../../lib/util/namespace.js'); exports.get = { diff --git a/node/node_modules/grunt/test/util/task_test.js b/node/node_modules/grunt/test/util/task_test.js index afe9e16c7..fc893ac73 100644 --- a/node/node_modules/grunt/test/util/task_test.js +++ b/node/node_modules/grunt/test/util/task_test.js @@ -1,3 +1,5 @@ +'use strict'; + // Test helpers. function delay(fn) { setTimeout(fn, 10); } @@ -13,7 +15,7 @@ var result = (function() { }; }()); -var requireTask = require.bind(this, '../../lib/util/task.js'); +var requireTask = require.bind(exports, '../../lib/util/task.js'); exports['new Task'] = { 'create': function(test) { @@ -24,92 +26,6 @@ exports['new Task'] = { } }; -exports['Helpers'] = { - setUp: function(done) { - this.task = requireTask().create(); - this.fn = function(a, b) { return a + b; }; - this.task.registerHelper('add', this.fn); - done(); - }, - 'Task#registerHelper': function(test) { - test.expect(1); - var task = this.task; - test.ok('add' in task._helpers, 'It should register the passed helper.'); - test.done(); - }, - 'Task#helper': function(test) { - test.expect(4); - var task = this.task; - test.strictEqual(task.helper('add', 1, 2), 3, 'It should receive arguments and return a value.'); - test.throws(function() { task.helper('nonexistent'); }, 'Attempting to execute unregistered handlers should throw an exception.'); - task.options({ - error: result.pushTaskname - }); - result.reset(); - test.doesNotThrow(function() { task.helper('nonexistent'); }, 'It should not throw an exception because an error handler is defined.'); - test.deepEqual(result.get(), [null], 'Non-nested tasks have a null name.'); - test.done(); - }, - 'Task#renameHelper': function(test) { - test.expect(4); - var task = this.task; - task.renameHelper('add', 'newadd'); - test.ok('newadd' in task._helpers, 'It should rename the specified helper.'); - test.equal('add' in task._helpers, false, 'It should remove the previous helper.'); - test.doesNotThrow(function() { task.helper('newadd'); }, 'It should be accessible by its new name.'); - test.throws(function() { task.helper('add'); }, 'It should not be accessible by its previous name.'); - test.done(); - } -}; - -exports['Directives'] = { - setUp: function(done) { - this.task = requireTask().create(); - this.task.registerHelper('add', function(a, b) { return Number(a) + Number(b); }); - done(); - }, - 'Task#getDirectiveParts': function(test) { - test.expect(8); - var task = this.task; - test.deepEqual(task.getDirectiveParts(''), ['add'], 'It should split a directive into parts.'); - test.deepEqual(task.getDirectiveParts(''), ['add', '1'], 'It should split a directive into parts.'); - test.deepEqual(task.getDirectiveParts(''), ['add', '1', '2'], 'It should split a directive into parts.'); - test.deepEqual(task.getDirectiveParts(''), null, 'It should return null if the directive does not match an existing helper.'); - test.deepEqual(task.getDirectiveParts(''), null, 'It should return null if the directive does not match an existing helper.'); - test.deepEqual(task.getDirectiveParts('x'), null, 'It should return null otherwise.'); - test.deepEqual(task.getDirectiveParts('x'), null, 'It should return null otherwise.'); - test.deepEqual(task.getDirectiveParts('<--arrow!'), null, 'It should return null otherwise.'); - test.done(); - }, - 'Task#directive': function(test) { - test.expect(13); - var task = this.task; - var fn = function(val) { return '_' + val + '_'; }; - test.equal(task.directive('foo'), 'foo', 'If a directive is not passed, it should return the passed value.'); - test.equal(task.directive('foo', fn), '_foo_', 'If a directive is not passed, the value should be passed through the specified callback.'); - test.equal(task.directive(''), '', 'If a directive is passed but not found, it should return the passed value.'); - test.equal(task.directive('', fn), '__', 'If a directive is passed but not found, the value should be passed through the specified callback.'); - test.equal(task.directive(''), 3, 'If a directive is passed and found, it should call the directive with arguments.'); - - task.registerHelper('call_as_helper', function(a, b) { - test.ok(!this.directive, 'should not indicate the helper was called as a directive'); - test.deepEqual(this.args, [1, 2], 'Should be an array of args.'); - test.deepEqual(this.flags, {'1': true, '2': true}, 'Should be a map of flags.'); - return a + b; - }); - test.equal(task.helper('call_as_helper', 1, 2), 3, 'Should receive the proper arguments (and return the proper result).'); - - task.registerHelper('call_as_directive', function(a, b) { - test.ok(this.directive, 'should indicate the helper was called as a directive'); - test.deepEqual(this.args, ['1', '2'], 'Should be an array of args.'); - test.deepEqual(this.flags, {'1': true, '2': true}, 'Should be a map of flags.'); - return Number(a) + Number(b); - }); - test.equal(task.directive(''), 3, 'Should receive the proper arguments (and return the proper result).'); - test.done(); - } -}; - exports['Tasks'] = { setUp: function(done) { result.reset(); @@ -129,29 +45,27 @@ exports['Tasks'] = { var task = this.task; task.registerTask('a', 'Push task name onto result.', result.pushTaskname); task.registerTask('b', 'Push task name onto result.', result.pushTaskname); - task.registerTask('c', 'Push task name onto result.', result.pushTaskname); - task.registerTask('x', 'a b c'); - task.registerTask('y', ['a', 'b', 'c']); - task.registerTask('z', 'a b nonexistent c'); + task.registerTask('c d', 'Push task name onto result.', result.pushTaskname); + task.registerTask('y', ['a', 'b', 'c d']); + task.registerTask('z', ['a', 'b', 'nonexistent', 'c d']); task.options({ - error: function(e) { + error: function() { result.push('!' + this.name); }, done: function() { - test.strictEqual(result.getJoined(), 'abcabc!z', 'The specified tasks should have run, in-order.'); + test.strictEqual(result.getJoined(), 'abc d!z', 'The specified tasks should have run, in-order.'); test.done(); } }); - task.run('x y z').start(); + task.run('y', 'z').start(); }, 'Task#isTaskAlias': function(test) { test.expect(2); var task = this.task; task.registerTask('a', 'nothing', function() {}); - task.registerTask('b', 'nothing', function() {}); - task.registerTask('c', 'a b'); + task.registerTask('b', ['a']); test.strictEqual(task.isTaskAlias('a'), false, 'It should not be an alias.'); - test.strictEqual(task.isTaskAlias('c'), true, 'It should be an alias.'); + test.strictEqual(task.isTaskAlias('b'), true, 'It should be an alias.'); test.done(); }, 'Task#renameTask': function(test) { @@ -176,6 +90,85 @@ exports['Tasks'] = { test.deepEqual(result.get(), [null], 'Non-nested tasks have a null name.'); test.done(); }, + 'Task#run (async failing)': function(test) { + test.expect(1); + var task = this.task; + var results = []; + + task.registerTask('sync1', 'sync, gonna succeed', function() {}); + + task.registerTask('sync2', 'sync, gonna fail', function() { + return false; + }); + + task.registerTask('sync3', 'sync, gonna fail', function() { + return new Error('sync3: Error'); + }); + + task.registerTask('sync4', 'sync, gonna fail', function() { + return new TypeError('sync4: TypeError'); + }); + + task.registerTask('sync5', 'sync, gonna fail', function() { + throw new Error('sync5: Error'); + }); + + task.registerTask('sync6', 'sync, gonna fail', function() { + throw new TypeError('sync6: TypeError'); + }); + + task.registerTask('syncs', ['sync1', 'sync2', 'sync3', 'sync4', 'sync5', 'sync6']); + + task.registerTask('async1', 'async, gonna succeed', function() { + var done = this.async(); + setTimeout(function() { + done(); + }, 1); + }); + + task.registerTask('async2', 'async, gonna fail', function() { + var done = this.async(); + setTimeout(function() { + done(false); + }, 1); + }); + + task.registerTask('async3', 'async, gonna fail', function() { + var done = this.async(); + setTimeout(function() { + done(new Error('async3: Error')); + }, 1); + }); + + task.registerTask('async4', 'async, gonna fail', function() { + var done = this.async(); + setTimeout(function() { + done(new TypeError('async4: TypeError')); + }, 1); + }); + + task.registerTask('asyncs', ['async1', 'async2', 'async3', 'async4']); + + task.options({ + error: function(e) { + results.push({name: e.name, message: e.message}); + }, + done: function() { + test.deepEqual(results, [ + {name: 'Error', message: 'Task "sync2" failed.'}, + {name: 'Error', message: 'sync3: Error'}, + {name: 'TypeError', message: 'sync4: TypeError'}, + {name: 'Error', message: 'sync5: Error'}, + {name: 'TypeError', message: 'sync6: TypeError'}, + {name: 'Error', message: 'Task "async2" failed.'}, + {name: 'Error', message: 'async3: Error'}, + {name: 'TypeError', message: 'async4: TypeError'} + ], 'The specified tasks should have run, in-order.'); + test.done(); + } + }); + task.run('syncs', 'asyncs').start(); + }, 'Task#run (nested, exception handling)': function(test) { test.expect(2); var task = this.task; @@ -188,7 +181,7 @@ exports['Tasks'] = { task.options({ done: test.done }); - task.run('yay nay').start(); + task.run('yay', 'nay').start(); }, 'Task#run (signatures, queue order)': function(test) { test.expect(1); @@ -198,11 +191,10 @@ exports['Tasks'] = { task.registerTask('c', 'Push task name onto result.', result.pushTaskname); task.registerTask('d', 'Push task name onto result.', result.pushTaskname); task.registerTask('e', 'Push task name onto result.', result.pushTaskname); - task.registerTask('f', 'Push task name onto result.', result.pushTaskname); - task.registerTask('g', 'Push task name onto result.', result.pushTaskname); + task.registerTask('f g', 'Push task name onto result.', result.pushTaskname); task.options({ done: function() { - test.strictEqual(result.getJoined(), 'abcdefg', 'The specified tasks should have run, in-order.'); + test.strictEqual(result.getJoined(), 'abcdef g', 'The specified tasks should have run, in-order.'); test.done(); } }); @@ -211,60 +203,73 @@ exports['Tasks'] = { 'Task#run (colon separated arguments)': function(test) { test.expect(1); var task = this.task; - task.registerTask('a', 'Push task name and args onto result.', function(x, y) { result.push([1, this.name, this.nameArgs, x, y]); }); - task.registerTask('a:b', 'Push task name and args onto result.', function(x, y) { result.push([2, this.name, this.nameArgs, x, y]); }); - task.registerTask('a:b:c', 'Push task name and args onto result.', function(x, y) { result.push([3, this.name, this.nameArgs, x, y]); }); + task.registerTask('a', 'Push task name and args onto result.', function(x, y) { result.push([this.nameArgs, 1, this.name, x, y]); }); + task.registerTask('a:b', 'Push task name and args onto result.', function(x, y) { result.push([this.nameArgs, 2, this.name, x, y]); }); + task.registerTask('a:b:c', 'Push task name and args onto result.', function(x, y) { result.push([this.nameArgs, 3, this.name, x, y]); }); task.options({ done: function() { test.deepEqual(result.get(), [ - [1, 'a', 'a', undefined, undefined], - [2, 'a:b', 'a:b', undefined, undefined], - [3, 'a:b:c', 'a:b:c', undefined, undefined], - [1, 'a', 'a:x', 'x', undefined], - [1, 'a', 'a:x:y', 'x', 'y'], - [2, 'a:b', 'a:b:x', 'x', undefined], - [2, 'a:b', 'a:b:x:y', 'x', 'y'] + ['a', 1, 'a', undefined, undefined], + ['a:x', 1, 'a', 'x', undefined], + ['a:x:c', 1, 'a', 'x', 'c'], + ['a:b ', 1, 'a', 'b ', undefined], + ['a: b:c', 1, 'a', ' b', 'c'], + ['a:x\\:y:\\:z\\:', 1, 'a', 'x:y', ':z:'], + + ['a:b', 2, 'a:b', undefined, undefined], + ['a:b:x', 2, 'a:b', 'x', undefined], + ['a:b:x:y', 2, 'a:b', 'x', 'y'], + ['a:b:c ', 2, 'a:b', 'c ', undefined], + ['a:b:x\\:y:\\:z\\:', 2, 'a:b', 'x:y', ':z:'], + + ['a:b:c', 3, 'a:b:c', undefined, undefined], + ['a:b:c: d', 3, 'a:b:c', ' d', undefined], ], 'Named tasks should be called as-specified if possible, and arguments should be passed properly.'); test.done(); } }); - task.run('a a:b a:b:c a:x a:x:y a:b:x a:b:x:y').start(); + task.run( + 'a', 'a:x', 'a:x:c', 'a:b ', 'a: b:c', 'a:x\\:y:\\:z\\:', + 'a:b', 'a:b:x', 'a:b:x:y', 'a:b:c ', 'a:b:x\\:y:\\:z\\:', + 'a:b:c', 'a:b:c: d' + ).start(); }, 'Task#run (nested tasks, queue order)': function(test) { test.expect(1); var task = this.task; - task.registerTask('a', 'Push task name onto result and run other tasks.', function() { result.push(this.name); task.run('b e'); }); - task.registerTask('b', 'Push task name onto result and run other tasks.', function() { result.push(this.name); task.run('c d'); }); + task.registerTask('a', 'Push task name onto result and run other tasks.', function() { result.push(this.name); task.run('b', 'e'); }); + task.registerTask('b', 'Push task name onto result and run other tasks.', function() { result.push(this.name); task.run('c', 'd d'); }); task.registerTask('c', 'Push task name onto result.', result.pushTaskname); - task.registerTask('d', 'Push task name onto result.', result.pushTaskname); - task.registerTask('e', 'Push task name onto result and run other tasks.', function() { result.push(this.name); task.run('f'); }); - task.registerTask('f', 'Push task name onto result.', result.pushTaskname); + task.registerTask('d d', 'Push task name onto result.', result.pushTaskname); + task.registerTask('e', 'Push task name onto result and run other tasks.', function() { result.push(this.name); task.run('f f'); }); + task.registerTask('f f', 'Push task name onto result.', result.pushTaskname); task.registerTask('g', 'Push task name onto result.', result.pushTaskname); task.options({ done: function() { - test.strictEqual(result.getJoined(), 'abcdefg', 'The specified tasks should have run, in-order.'); + test.strictEqual(result.getJoined(), 'abcd def fg', 'The specified tasks should have run, in-order.'); test.done(); } }); - task.run('a g').start(); + task.run('a', 'g').start(); }, 'Task#run (async, nested tasks, queue order)': function(test) { test.expect(1); var task = this.task; - task.registerTask('a', 'Push task name onto result and run other tasks.', function() { result.push(this.name); task.run('b e'); delay(this.async()); }); - task.registerTask('b', 'Push task name onto result and run other tasks.', function() { result.push(this.name); delay(this.async()); task.run('c d'); }); + task.registerTask('a', 'Push task name onto result and run other tasks.', function() { result.push(this.name); task.run('b', 'e'); delay(this.async()); }); + task.registerTask('b', 'Push task name onto result and run other tasks.', function() { result.push(this.name); delay(this.async()); task.run('c', 'd d'); }); task.registerTask('c', 'Push task name onto result.', result.pushTaskname); - task.registerTask('d', 'Push task name onto result.', result.pushTaskname); - task.registerTask('e', 'Push task name onto result and run other tasks.', function() { delay(this.async()); result.push(this.name); task.run('f'); }); - task.registerTask('f', 'Push task name onto result.', result.pushTaskname); + task.registerTask('d d', 'Push task name onto result.', result.pushTaskname); + task.registerTask('e', 'Push task name onto result and run other tasks.', function() { delay(this.async()); result.push(this.name); task.run('f f'); }); + task.registerTask('f f', 'Push task name onto result and run other tasks.', function() { this.async()(); result.push(this.name); task.run('g'); }); task.registerTask('g', 'Push task name onto result.', result.pushTaskname); + task.registerTask('h', 'Push task name onto result.', result.pushTaskname); task.options({ done: function() { - test.strictEqual(result.getJoined(), 'abcdefg', 'The specified tasks should have run, in-order.'); + test.strictEqual(result.getJoined(), 'abcd def fgh', 'The specified tasks should have run, in-order.'); test.done(); } }); - task.run('a g').start(); + task.run('a', 'h').start(); }, 'Task#current': function(test) { test.expect(8); @@ -304,10 +309,10 @@ exports['Tasks'] = { test.done(); } }); - task.run('a b c d e').start(); + task.run('a', 'b', 'c', 'd', 'e').start(); }, 'Task#mark': function(test) { - // test.expect(1); + test.expect(1); var task = this.task; task.registerTask('a', 'Explode.', function() { throw task.taskError('whoops.'); @@ -348,7 +353,7 @@ exports['Tasks'] = { task.registerTask('p', 'Push task name onto result.', result.pushTaskname); task.options({ - error: function(e) { + error: function() { result.push('!' + this.name); task.clearQueue({untilMarker: true}); }, @@ -357,48 +362,49 @@ exports['Tasks'] = { test.done(); } }); - task.run('a b c').mark().run('d e f').mark().run('g h i').mark().run('j l').mark().run('m n').mark().run('p').mark().start(); + task.run('a', 'b', 'c').mark().run('d', 'e', 'f').mark().run('g', 'h', 'i').mark().run('j', 'l').mark().run('m', 'n').mark().run('p').mark().start(); }, 'Task#requires': function(test) { test.expect(1); var task = this.task; task.registerTask('notrun', 'This task is never run.', function() {}); - task.registerTask('a', 'Push task name onto result, but fail.', function() { + task.registerTask('a a', 'Push task name onto result, but fail.', function() { result.push(this.name); return false; }); task.registerTask('b', 'Push task name onto result, but fail.', function() { - delay(this.async().bind(this, false)); + var done = this.async(); + delay(function() { done(false); }); result.push(this.name); }); task.registerTask('c', 'Succeed.', result.pushTaskname); task.registerTask('d', 'Succeed.', result.pushTaskname); task.registerTask('e', 'Succeed because all required tasks ran and succeeded.', function() { - task.requires('c d'); + task.requires('c', 'd'); result.push(this.name); }); task.registerTask('x', 'Fail because a required task never ran.', function() { - task.requires('c notrun d'); + task.requires('c', 'notrun', 'd'); result.push(this.name); }); task.registerTask('y', 'Fail because a synchronous required task has failed.', function() { - task.requires('a c d'); + task.requires('a a', 'c', 'd'); result.push(this.name); }); task.registerTask('z', 'Fail because an asynchronous required task has failed.', function() { - task.requires('b c d'); + task.requires('b', 'c', 'd'); result.push(this.name); }); task.options({ - error: function(e) { + error: function() { result.push('!' + this.name); }, done: function() { - test.strictEqual(result.getJoined(), 'a!ab!bcde!x!y!z', 'Tasks whose requirements have failed or are missing should not run.'); + test.strictEqual(result.getJoined(), 'a a!a ab!bcde!x!y!z', 'Tasks whose requirements have failed or are missing should not run.'); test.done(); } }); - task.run('a b c d e x y z').start(); + task.run('a a', 'b', 'c', 'd', 'e', 'x', 'y', 'z').start(); } }; @@ -410,24 +416,17 @@ exports['Task#parseArgs'] = { }; done(); }, - 'single task string': function(test) { - test.expect(1); - test.deepEqual(this.parseTest('foo'), ['foo'], 'string should be split into array.'); - test.done(); - }, - 'multiple task string': function(test) { - test.expect(1); - test.deepEqual(this.parseTest('foo bar baz'), ['foo', 'bar', 'baz'], 'string should be split into array.'); - test.done(); - }, 'arguments': function(test) { - test.expect(1); - test.deepEqual(this.parseTest('foo', 'bar', 'baz'), ['foo', 'bar', 'baz'], 'arguments should be converted to array.'); + test.expect(4); + test.deepEqual(this.parseTest('foo bar'), ['foo bar'], 'single argument should be converted to array.'); + test.deepEqual(this.parseTest('foo bar: aa : bb '), ['foo bar: aa : bb '], 'single argument should be converted to array.'); + test.deepEqual(this.parseTest('foo bar', 'baz', 'test 1 2 3'), ['foo bar', 'baz', 'test 1 2 3'], 'arguments should be converted to array.'); + test.deepEqual(this.parseTest('foo bar', 'baz:x y z', 'test 1 2 3: 4 : 5'), ['foo bar', 'baz:x y z', 'test 1 2 3: 4 : 5'], 'arguments should be converted to array.'); test.done(); }, 'array': function(test) { test.expect(1); - test.deepEqual(this.parseTest(['foo', 'bar', 'baz']), ['foo', 'bar', 'baz'], 'passed array should be used.'); + test.deepEqual(this.parseTest(['foo bar', 'baz:x y z', 'test 1 2 3: 4 : 5']), ['foo bar', 'baz:x y z', 'test 1 2 3: 4 : 5'], 'passed array should be used.'); test.done(); }, 'object': function(test) { @@ -442,3 +441,24 @@ exports['Task#parseArgs'] = { test.done(); } }; + +exports['Task#splitArgs'] = { + setUp: function(done) { + this.task = requireTask().create(); + done(); + }, + 'arguments': function(test) { + test.expect(9); + var task = this.task; + test.deepEqual(task.splitArgs(), [], 'missing items = empty array.'); + test.deepEqual(task.splitArgs(''), [], 'missing items = empty array.'); + test.deepEqual(task.splitArgs('a'), ['a'], 'single item should be parsed.'); + test.deepEqual(task.splitArgs('a:b:c'), ['a', 'b', 'c'], 'mutliple items should be parsed.'); + test.deepEqual(task.splitArgs('a::c'), ['a', '', 'c'], 'missing items should be parsed.'); + test.deepEqual(task.splitArgs('::'), ['', '', ''], 'missing items should be parsed.'); + test.deepEqual(task.splitArgs('\\:a:\\:b\\::c\\:'), [':a', ':b:', 'c:'], 'escaped colons should be unescaped.'); + test.deepEqual(task.splitArgs('a\\\\:b\\\\:c'), ['a\\', 'b\\', 'c'], 'escaped backslashes should not be parsed.'); + test.deepEqual(task.splitArgs('\\:a\\\\:\\\\\\:b\\:\\\\:c\\\\\\:\\\\'), [':a\\', '\\:b:\\', 'c\\:\\'], 'please avoid doing this, ok?'); + test.done(); + } +}; diff --git a/node/package.json b/node/package.json index 887ff979c..a475c6669 100755 --- a/node/package.json +++ b/node/package.json @@ -40,8 +40,7 @@ "docpad-plugin-partials": "2.x", "docpad-plugin-stylus": "2.x", "docpad-plugin-text": "2.x", - "grunt": "~0.3.17", - "grunt-css": "~0.3.2", + "grunt": "~0.4.0", "bal-util": "~1.15.3", "underscore": "~1.4.3", "docpad-plugin-html2coffee": "~2.1.3", @@ -52,7 +51,10 @@ "docpad-plugin-handlebars": "~2.2.1" }, "devDependencies": { - "docpad-plugin-livereload": "2.x" + "docpad-plugin-livereload": "2.x", + "grunt-contrib-watch": "~0.4.0", + "grunt-css": "~0.5.4", + "grunt-bower-task": "~0.2.2" }, "main": "node_modules/docpad/bin/docpad-server" }