1
0
mirror of https://github.com/invoiceninja/invoiceninja.git synced 2024-11-08 12:12:48 +01:00

Adding Grunt for file concat

This commit is contained in:
Hillel Coren 2014-04-28 23:05:37 +03:00
parent 8595ba6113
commit 113cf9b482
474 changed files with 170251 additions and 4 deletions

57
Gruntfile.js Normal file
View File

@ -0,0 +1,57 @@
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
js: {
src: [
'public/vendor/jquery/dist/jquery.js',
'public/vendor/jquery-ui/ui/minified/jquery-ui.min.js',
'public/vendor/bootstrap/dist/js/bootstrap.min.js',
'public/vendor/datatables/media/js/jquery.dataTables.js',
'public/vendor/datatables-bootstrap3/BS3/assets/js/datatables.js',
'public/vendor/knockout.js/knockout.js',
'public/vendor/knockout-mapping/build/output/knockout.mapping-latest.js',
'public/vendor/knockout-sortable/build/knockout-sortable.min.js',
'public/vendor/underscore/underscore.js',
'public/vendor/bootstrap-datepicker/js/bootstrap-datepicker.js',
'public/vendor/typeahead.js/dist/typeahead.min.js',
'public/vendor/accounting/accounting.min.js',
'public/js/bootstrap-combobox.js',
'public/js/jspdf.source.js',
'public/js/jspdf.plugin.split_text_to_size.js',
'public/js/script.js',
],
dest: 'public/built.js'
},
css: {
src: [
'public/vendor/bootstrap/dist/css/bootstrap.min.css',
'public/vendor/datatables/media/css/jquery.dataTables.css',
'public/vendor/datatables-bootstrap3/BS3/assets/css/datatables.css',
'public/vendor/font-awesome/css/font-awesome.min.css',
'public/vendor/bootstrap-datepicker/css/datepicker.css',
'public/css/bootstrap-combobox.css',
'public/css/typeahead.js-bootstrap.css',
'public/css/style.css',
],
dest: 'public/built.css'
},
/*
css_public: {
src: [
'public/vendor/bootstrap/dist/css/bootstrap.min.css',
'public/css/bootstrap.splash.css',
'public/css/splash.css',
],
dest: 'public/built.public.css'
}
*/
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('default', ['concat']);
};

View File

@ -4,6 +4,9 @@
@section('head')
<meta name="csrf-token" content="<?= csrf_token() ?>">
<link href="{{ asset('built.css') }}" rel="stylesheet" type="text/css"/>
<!--
<script src="{{ asset('vendor/jquery-ui/ui/minified/jquery-ui.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('vendor/bootstrap/dist/js/bootstrap.min.js') }}" type="text/javascript"></script>
<script src="{{ asset('vendor/datatables/media/js/jquery.dataTables.js') }}" type="text/javascript"></script>
@ -19,7 +22,9 @@
<script src="{{ asset('js/jspdf.source.js') }}" type="text/javascript"></script>
<script src="{{ asset('js/jspdf.plugin.split_text_to_size.js') }}" type="text/javascript"></script>
<script src="{{ asset('js/script.js') }}" type="text/javascript"></script>
-->
<!--
<link href="{{ asset('vendor/bootstrap/dist/css/bootstrap.min.css') }}" rel="stylesheet" type="text/css"/>
<link href="{{ asset('vendor/datatables/media/css/jquery.dataTables.css') }}" rel="stylesheet" type="text/css">
<link href="{{ asset('vendor/datatables-bootstrap3/BS3/assets/css/datatables.css') }}" rel="stylesheet" type="text/css">
@ -28,7 +33,7 @@
<link href="{{ asset('css/bootstrap-combobox.css') }}" rel="stylesheet" type="text/css"/>
<link href="{{ asset('css/typeahead.js-bootstrap.css') }}" rel="stylesheet" type="text/css"/>
<link href="{{ asset('css/style.css') }}" rel="stylesheet" type="text/css"/>
-->
<style type="text/css">

View File

@ -19,6 +19,8 @@
<meta property="og:description" content="Simple, Intuitive Invoicing."></meta>
<meta name="keywords" content="Invoice Ninja"></meta>
<script src="{{ asset('built.js') }}" type="text/javascript"></script>
<!--
@if (File::exists('vendor/jquery/jquery.js'))
<script src="{{ asset('vendor/jquery/jquery.js') }}" type="text/javascript"></script>
@elseif (File::exists('vendor/jquery/dist/jquery.js'))
@ -26,7 +28,8 @@
@else
{{ die('Error: Failed to find jQuery') }}
@endif
-->
<script type="text/javascript">
var NINJA = NINJA || {};
NINJA.isRegistered = {{ Utils::isRegistered() ? 'true' : 'false' }};

View File

@ -1,13 +1,18 @@
@extends('master')
@section('head')
<link href="{{ asset('built.public.css') }}" rel="stylesheet" type="text/css"/>
<!--
<link href="{{ asset('vendor/bootstrap/dist/css/bootstrap.min.css') }}" rel="stylesheet" type="text/css"/>
<link href="{{ asset('css/bootstrap.splash.css') }}" rel="stylesheet" type="text/css"/>
<link href="{{ asset('css/splash.css') }}" rel="stylesheet" type="text/css"/>
-->
<link href="{{ asset('images/apple-touch-icon-114x114-precomposed.png') }}" rel="apple-touch-icon-precomposed" sizes="114x114">
<link href="{{ asset('images/apple-touch-icon-72x72-precomposed.png') }}" rel="apple-touch-icon-precomposed" sizes="72x72">
<link href="{{ asset('images/apple-touch-icon-57x57-precomposed.png') }}" rel="apple-touch-icon-precomposed">
<script src="{{ asset('js/simpleexpand.js') }}" type="text/javascript"></script>
<!-- <script src="{{ asset('js/simpleexpand.js') }}" type="text/javascript"></script> -->
@stop
@section('body')
@ -145,10 +150,11 @@
</footer>
<!-- <script src="{{ asset('/js/retina-1.1.0.min.js') }}" type="text/javascript"></script> -->
<!--
<script type="text/javascript">
$('.expander').simpleexpand();
</script>
-->
@stop

22
node_modules/grunt-contrib-concat/LICENSE-MIT generated vendored Normal file
View File

@ -0,0 +1,22 @@
Copyright (c) 2014 "Cowboy" Ben Alman, 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.

280
node_modules/grunt-contrib-concat/README.md generated vendored Normal file
View File

@ -0,0 +1,280 @@
# grunt-contrib-concat v0.4.0 [![Build Status](https://travis-ci.org/gruntjs/grunt-contrib-concat.png?branch=master)](https://travis-ci.org/gruntjs/grunt-contrib-concat)
> Concatenate files.
## Getting Started
This plugin requires Grunt `~0.4.0`
If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:
```shell
npm install grunt-contrib-concat --save-dev
```
Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
```js
grunt.loadNpmTasks('grunt-contrib-concat');
```
## Concat task
_Run this task with the `grunt concat` command._
Task targets, files and options may be specified according to the Grunt [Configuring tasks](http://gruntjs.com/configuring-tasks) guide.
### Options
#### separator
Type: `String`
Default: `grunt.util.linefeed`
Concatenated files will be joined on this string. If you're post-processing concatenated JavaScript files with a minifier, you may need to use a semicolon `';'` as the separator.
#### banner
Type: `String`
Default: empty string
This string will be prepended to the beginning of the concatenated output. It is processed using [grunt.template.process][], using the default options.
_(Default processing options are explained in the [grunt.template.process][] documentation)_
#### footer
Type: `String`
Default: empty string
This string will be appended to the end of the concatenated output. It is processed using [grunt.template.process][], using the default options.
_(Default processing options are explained in the [grunt.template.process][] documentation)_
#### stripBanners
Type: `Boolean` `Object`
Default: `false`
Strip JavaScript banner comments from source files.
* `false` - No comments are stripped.
* `true` - `/* ... */` block comments are stripped, but _NOT_ `/*! ... */` comments.
* `options` object:
* By default, behaves as if `true` were specified.
* `block` - If true, _all_ block comments are stripped.
* `line` - If true, any contiguous _leading_ `//` line comments are stripped.
#### process
Type: `Boolean` `Object` `Function`
Default: `false`
Process source files before concatenating, either as [templates][] or with a custom function.
* `false` - No processing will occur.
* `true` - Process source files using [grunt.template.process][] defaults.
* `data` object - Process source files using [grunt.template.process][], using the specified options.
* `function(src, filepath)` - Process source files using the given function, called once for each file. The returned value will be used as source code.
_(Default processing options are explained in the [grunt.template.process][] documentation)_
[templates]: https://github.com/gruntjs/grunt-docs/blob/master/grunt.template.md
[grunt.template.process]: https://github.com/gruntjs/grunt-docs/blob/master/grunt.template.md#grunttemplateprocess
### Usage Examples
#### Concatenating with a custom separator
In this example, running `grunt concat:dist` (or `grunt concat` because `concat` is a [multi task][multitask]) will concatenate the three specified source files (in order), joining files with `;` and writing the output to `dist/built.js`.
```js
// Project configuration.
grunt.initConfig({
concat: {
options: {
separator: ';',
},
dist: {
src: ['src/intro.js', 'src/project.js', 'src/outro.js'],
dest: 'dist/built.js',
},
},
});
```
#### Banner comments
In this example, running `grunt concat:dist` will first strip any preexisting banner comment from the `src/project.js` file, then concatenate the result with a newly-generated banner comment, writing the output to `dist/built.js`.
This generated banner will be the contents of the `banner` template string interpolated with the config object. In this case, those properties are the values imported from the `package.json` file (which are available via the `pkg` config property) plus today's date.
_Note: you don't have to use an external JSON file. It's also valid to create the `pkg` object inline in the config. That being said, if you already have a JSON file, you might as well reference it._
```js
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
options: {
stripBanners: true,
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> */',
},
dist: {
src: ['src/project.js'],
dest: 'dist/built.js',
},
},
});
```
#### Multiple targets
In this example, running `grunt concat` will build two separate files. One "basic" version, with the main file essentially just copied to `dist/basic.js`, and another "with_extras" concatenated version written to `dist/with_extras.js`.
While each concat target can be built individually by running `grunt concat:basic` or `grunt concat:extras`, running `grunt concat` will build all concat targets. This is because `concat` is a [multi task][multitask].
```js
// Project configuration.
grunt.initConfig({
concat: {
basic: {
src: ['src/main.js'],
dest: 'dist/basic.js',
},
extras: {
src: ['src/main.js', 'src/extras.js'],
dest: 'dist/with_extras.js',
},
},
});
```
#### Multiple files per target
Like the previous example, in this example running `grunt concat` will build two separate files. One "basic" version, with the main file essentially just copied to `dist/basic.js`, and another "with_extras" concatenated version written to `dist/with_extras.js`.
This example differs in that both files are built under the same target.
Using the `files` object, you can have list any number of source-destination pairs.
```js
// Project configuration.
grunt.initConfig({
concat: {
basic_and_extras: {
files: {
'dist/basic.js': ['src/main.js'],
'dist/with_extras.js': ['src/main.js', 'src/extras.js'],
},
},
},
});
```
#### Dynamic filenames
Filenames can be generated dynamically by using `<%= %>` delimited underscore templates as filenames.
In this example, running `grunt concat:dist` generates a destination file whose name is generated from the `name` and `version` properties of the referenced `package.json` file (via the `pkg` config property).
```js
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
concat: {
dist: {
src: ['src/main.js'],
dest: 'dist/<%= pkg.name %>-<%= pkg.version %>.js',
},
},
});
```
#### Advanced dynamic filenames
In this more involved example, running `grunt concat` will build two separate files (because `concat` is a [multi task][multitask]). The destination file paths will be expanded dynamically based on the specified templates, recursively if necessary.
For example, if the `package.json` file contained `{"name": "awesome", "version": "1.0.0"}`, the files `dist/awesome/1.0.0/basic.js` and `dist/awesome/1.0.0/with_extras.js` would be generated.
```js
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
dirs: {
src: 'src/files',
dest: 'dist/<%= pkg.name %>/<%= pkg.version %>',
},
concat: {
basic: {
src: ['<%= dirs.src %>/main.js'],
dest: '<%= dirs.dest %>/basic.js',
},
extras: {
src: ['<%= dirs.src %>/main.js', '<%= dirs.src %>/extras.js'],
dest: '<%= dirs.dest %>/with_extras.js',
},
},
});
```
#### Invalid or Missing Files Warning
If you would like the `concat` task to warn if a given file is missing or invalid be sure to set `nonull` to `true`:
```js
grunt.initConfig({
concat: {
missing: {
src: ['src/invalid_or_missing_file'],
dest: 'compiled.js',
nonull: true,
},
},
});
```
See [configuring files for a task](http://gruntjs.com/configuring-tasks#files) for how to configure file globbing in Grunt.
#### Custom process function
If you would like to do any custom processing before concatenating, use a custom process function:
```js
grunt.initConfig({
concat: {
dist: {
options: {
// Replace all 'use strict' statements in the code with a single one at the top
banner: "'use strict';\n",
process: function(src, filepath) {
return '// Source: ' + filepath + '\n' +
src.replace(/(^|\n)[ \t]*('use strict'|"use strict");?\s*/g, '$1');
},
},
files: {
'dist/built.js': ['src/project.js'],
},
},
},
});
```
[multitask]: http://gruntjs.com/creating-tasks#multi-tasks
## Release History
* 2014-03-21v0.4.0README updates. Output updates.
* 2013-04-25v0.3.0Add option to process files with a custom function.
* 2013-04-08v0.2.0Don't normalize separator to allow user to set LF even on a Windows environment.
* 2013-02-22v0.1.3Support footer option.
* 2013-02-15v0.1.2First official release for Grunt 0.4.0.
* 2013-01-18v0.1.2rc6Updating grunt/gruntplugin dependencies to rc6. Changing in-development grunt/gruntplugin dependency versions from tilde version ranges to specific versions.
* 2013-01-09v0.1.2rc5Updating to work with grunt v0.4.0rc5. Switching back to this.files api.
* 2012-11-13v0.1.1Switch to this.file api internally.
* 2012-10-03v0.1.0Work in progress, not yet officially released.
---
Task submitted by ["Cowboy" Ben Alman](http://benalman.com/)
*This file was generated on Mon Mar 31 2014 11:20:28.*

View File

@ -0,0 +1,63 @@
'use strict';
var ansi = require('ansi-styles');
var stripAnsi = require('strip-ansi');
var hasColor = require('has-color');
var defineProps = Object.defineProperties;
var chalk = module.exports;
var styles = (function () {
var ret = {};
ansi.grey = ansi.gray;
Object.keys(ansi).forEach(function (key) {
ret[key] = {
get: function () {
this._styles.push(key);
return this;
}
};
});
return ret;
})();
function init() {
var ret = {};
Object.keys(styles).forEach(function (name) {
ret[name] = {
get: function () {
var obj = defineProps(function self() {
var str = [].slice.call(arguments).join(' ');
if (!chalk.enabled) {
return str;
}
return self._styles.reduce(function (str, name) {
var code = ansi[name];
return str ? code.open + str + code.close : '';
}, str);
}, styles);
obj._styles = [];
return obj[name];
}
}
});
return ret;
}
defineProps(chalk, init());
chalk.styles = ansi;
chalk.stripColor = stripAnsi;
chalk.supportsColor = hasColor;
// detect mode if not set manually
if (chalk.enabled === undefined) {
chalk.enabled = chalk.supportsColor;
}

View File

@ -0,0 +1 @@
../strip-ansi/cli.js

View File

@ -0,0 +1,38 @@
'use strict';
var styles = module.exports;
var codes = {
reset: [0, 0],
bold: [1, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
strikethrough: [9, 29],
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39],
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49]
};
Object.keys(codes).forEach(function (key) {
var val = codes[key];
var style = styles[key] = {};
style.open = '\x1b[' + val[0] + 'm';
style.close = '\x1b[' + val[1] + 'm';
});

View File

@ -0,0 +1,58 @@
{
"name": "ansi-styles",
"version": "1.0.0",
"description": "ANSI escape codes for colorizing strings in the terminal",
"keywords": [
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"homepage": "https://github.com/sindresorhus/ansi-styles",
"bugs": {
"url": "https://github.com/sindresorhus/ansi-styles/issues"
},
"license": "MIT",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "http://sindresorhus.com"
},
"files": [
"ansi-styles.js"
],
"main": "ansi-styles",
"repository": {
"type": "git",
"url": "git://github.com/sindresorhus/ansi-styles.git"
},
"scripts": {
"test": "mocha"
},
"devDependencies": {
"mocha": "~1.12.0"
},
"engines": {
"node": ">=0.8.0"
},
"readme": "# ansi-styles [![Build Status](https://secure.travis-ci.org/sindresorhus/ansi-styles.png?branch=master)](http://travis-ci.org/sindresorhus/ansi-styles)\n\n> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for colorizing strings in the terminal.\n\nYou probably want the higher-level [chalk](https://github.com/sindresorhus/chalk) module for styling your strings.\n\n![screenshot](screenshot.png)\n\n\n## Install\n\nInstall with [npm](https://npmjs.org/package/ansi-styles): `npm install --save ansi-styles`\n\n\n## Example\n\n```js\nvar ansi = require('ansi-styles');\n\nconsole.log(ansi.green.open + 'Hello world!' + ansi.green.close);\n```\n\n## API\n\nEach style has an `open` and `close` property.\n\n\n## Styles\n\n### General\n\n- reset\n- bold\n- italic\n- underline\n- inverse\n- strikethrough\n\n### Text colors\n\n- black\n- red\n- green\n- yellow\n- blue\n- magenta\n- cyan\n- white\n- gray\n\n### Background colors\n\n- bgBlack\n- bgRed\n- bgGreen\n- bgYellow\n- bgBlue\n- bgMagenta\n- bgCyan\n- bgWhite\n\n\n## License\n\nMIT © [Sindre Sorhus](http://sindresorhus.com)\n",
"readmeFilename": "readme.md",
"_id": "ansi-styles@1.0.0",
"_from": "ansi-styles@~1.0.0"
}

View File

@ -0,0 +1,65 @@
# ansi-styles [![Build Status](https://secure.travis-ci.org/sindresorhus/ansi-styles.png?branch=master)](http://travis-ci.org/sindresorhus/ansi-styles)
> [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for colorizing strings in the terminal.
You probably want the higher-level [chalk](https://github.com/sindresorhus/chalk) module for styling your strings.
![screenshot](screenshot.png)
## Install
Install with [npm](https://npmjs.org/package/ansi-styles): `npm install --save ansi-styles`
## Example
```js
var ansi = require('ansi-styles');
console.log(ansi.green.open + 'Hello world!' + ansi.green.close);
```
## API
Each style has an `open` and `close` property.
## Styles
### General
- reset
- bold
- italic
- underline
- inverse
- strikethrough
### Text colors
- black
- red
- green
- yellow
- blue
- magenta
- cyan
- white
- gray
### Background colors
- bgBlack
- bgRed
- bgGreen
- bgYellow
- bgBlue
- bgMagenta
- bgCyan
- bgWhite
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@ -0,0 +1,32 @@
'use strict';
module.exports = (function () {
if (process.argv.indexOf('--no-color') !== -1) {
return false;
}
if (process.argv.indexOf('--color') !== -1) {
return true;
}
if (process.stdout && !process.stdout.isTTY) {
return false;
}
if (process.platform === 'win32') {
return true;
}
if ('COLORTERM' in process.env) {
return true;
}
if (process.env.TERM === 'dumb') {
return false;
}
if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) {
return true;
}
return false;
})();

View File

@ -0,0 +1,58 @@
{
"name": "has-color",
"version": "0.1.7",
"description": "Detect whether a terminal supports color",
"license": "MIT",
"repository": {
"type": "git",
"url": "git://github.com/sindresorhus/has-color"
},
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "http://sindresorhus.com"
},
"engines": {
"node": ">=0.10.0"
},
"scripts": {
"test": "mocha"
},
"files": [
"index.js"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"ansi",
"styles",
"tty",
"rgb",
"256",
"shell",
"xterm",
"command-line",
"support",
"capability",
"detect"
],
"devDependencies": {
"mocha": "*"
},
"readme": "# has-color [![Build Status](https://travis-ci.org/sindresorhus/has-color.svg?branch=master)](https://travis-ci.org/sindresorhus/has-color)\n\n> Detect whether a terminal supports color.\n\nUsed in the terminal color module [chalk](https://github.com/sindresorhus/chalk).\n\n\n## Install\n\n```bash\n$ npm install --save has-color\n```\n\n\n## Usage\n\n```js\nvar hasColor = require('has-color');\n\nif (hasColor) {\n\tconsole.log('Terminal supports color.');\n}\n```\n\nIt obeys the `--color` and `--no-color` CLI flags.\n\n\n## License\n\n[MIT](http://opensource.org/licenses/MIT) © [Sindre Sorhus](http://sindresorhus.com)\n",
"readmeFilename": "readme.md",
"bugs": {
"url": "https://github.com/sindresorhus/has-color/issues"
},
"homepage": "https://github.com/sindresorhus/has-color",
"_id": "has-color@0.1.7",
"dist": {
"shasum": "1b80986f9e0b4cd0a22bd67b4cd4f04c0363375f"
},
"_from": "has-color@~0.1.0",
"_resolved": "https://registry.npmjs.org/has-color/-/has-color-0.1.7.tgz"
}

View File

@ -0,0 +1,30 @@
# has-color [![Build Status](https://travis-ci.org/sindresorhus/has-color.svg?branch=master)](https://travis-ci.org/sindresorhus/has-color)
> Detect whether a terminal supports color.
Used in the terminal color module [chalk](https://github.com/sindresorhus/chalk).
## Install
```bash
$ npm install --save has-color
```
## Usage
```js
var hasColor = require('has-color');
if (hasColor) {
console.log('Terminal supports color.');
}
```
It obeys the `--color` and `--no-color` CLI flags.
## License
[MIT](http://opensource.org/licenses/MIT) © [Sindre Sorhus](http://sindresorhus.com)

View File

@ -0,0 +1,27 @@
#!/usr/bin/env node
'use strict';
var fs = require('fs');
var strip = require('./index');
var input = process.argv[2];
if (process.argv.indexOf('-h') !== -1 || process.argv.indexOf('--help') !== -1) {
console.log('strip-ansi <input file> > <output file>');
console.log('or');
console.log('cat <input file> | strip-ansi > <output file>');
return;
}
if (process.argv.indexOf('-v') !== -1 || process.argv.indexOf('--version') !== -1) {
console.log(require('./package').version);
return;
}
if (input) {
process.stdout.write(strip(fs.readFileSync(input, 'utf8')));
return;
}
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (data) {
process.stdout.write(strip(data));
});

View File

@ -0,0 +1,4 @@
'use strict';
module.exports = function (str) {
return typeof str === 'string' ? str.replace(/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]/g, '') : str;
};

View File

@ -0,0 +1,64 @@
{
"name": "strip-ansi",
"version": "0.1.1",
"description": "Strip ANSI escape codes (used for colorizing strings in the terminal)",
"license": "MIT",
"bin": {
"strip-ansi": "cli.js"
},
"repository": {
"type": "git",
"url": "git://github.com/sindresorhus/strip-ansi"
},
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "http://sindresorhus.com"
},
"engines": {
"node": ">=0.8.0"
},
"scripts": {
"test": "mocha"
},
"files": [
"index.js",
"cli.js"
],
"keywords": [
"strip",
"trim",
"remove",
"ansi",
"styles",
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"tty",
"escape",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"devDependencies": {
"mocha": "~1.x"
},
"readme": "# strip-ansi [![Build Status](https://secure.travis-ci.org/sindresorhus/strip-ansi.png?branch=master)](http://travis-ci.org/sindresorhus/strip-ansi)\n\n> Strip [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) (used for colorizing strings in the terminal)\n\nUsed in the terminal color module [chalk](https://github.com/sindresorhus/chalk).\n\n\n## Install\n\nInstall locally with [npm](https://npmjs.org/package/strip-ansi):\n\n```\nnpm install --save strip-ansi\n```\n\nOr globally if you want to use it as a CLI app:\n\n```\nnpm install --global strip-ansi\n```\n\nYou can then use it in your Terminal like:\n\n```\nstrip-ansi file-with-color-codes\n```\n\nOr pipe something to it:\n\n```\nls | strip-ansi\n```\n\n\n## Example\n\n```js\nvar stripAnsi = require('strip-ansi');\nstripAnsi('\\x1b[4mcake\\x1b[0m');\n//=> cake\n```\n\n\n## License\n\nMIT © [Sindre Sorhus](http://sindresorhus.com)\n",
"readmeFilename": "readme.md",
"bugs": {
"url": "https://github.com/sindresorhus/strip-ansi/issues"
},
"homepage": "https://github.com/sindresorhus/strip-ansi",
"_id": "strip-ansi@0.1.1",
"_from": "strip-ansi@~0.1.0"
}

View File

@ -0,0 +1,46 @@
# strip-ansi [![Build Status](https://secure.travis-ci.org/sindresorhus/strip-ansi.png?branch=master)](http://travis-ci.org/sindresorhus/strip-ansi)
> Strip [ANSI escape codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) (used for colorizing strings in the terminal)
Used in the terminal color module [chalk](https://github.com/sindresorhus/chalk).
## Install
Install locally with [npm](https://npmjs.org/package/strip-ansi):
```
npm install --save strip-ansi
```
Or globally if you want to use it as a CLI app:
```
npm install --global strip-ansi
```
You can then use it in your Terminal like:
```
strip-ansi file-with-color-codes
```
Or pipe something to it:
```
ls | strip-ansi
```
## Example
```js
var stripAnsi = require('strip-ansi');
stripAnsi('\x1b[4mcake\x1b[0m');
//=> cake
```
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)

View File

@ -0,0 +1,61 @@
{
"name": "chalk",
"version": "0.4.0",
"description": "Terminal string styling done right. Created because the `colors` module does some really horrible things.",
"license": "MIT",
"repository": {
"type": "git",
"url": "git://github.com/sindresorhus/chalk"
},
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "http://sindresorhus.com"
},
"engines": {
"node": ">=0.8.0"
},
"scripts": {
"test": "mocha"
},
"files": [
"index.js"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"ansi",
"styles",
"tty",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"dependencies": {
"has-color": "~0.1.0",
"ansi-styles": "~1.0.0",
"strip-ansi": "~0.1.0"
},
"devDependencies": {
"mocha": "~1.x"
},
"readme": "# <img width=\"250\" src=\"logo.png\" alt=\"chalk\">\n\n> Terminal string styling done right\n\n[![Build Status](https://secure.travis-ci.org/sindresorhus/chalk.png?branch=master)](http://travis-ci.org/sindresorhus/chalk)\n\n[colors.js](https://github.com/Marak/colors.js) is currently the most popular string styling module, but it has serious deficiencies like extending String.prototype which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68). Although there are other ones, they either do too much or not enough.\n\n**Chalk is a clean and focused alternative.**\n\n![screenshot](screenshot.png)\n\n\n## Why\n\n- **Doesn't extend String.prototype**\n- Expressive API\n- Clean and focused\n- Auto-detects color support\n- Actively maintained\n- [Used by 150+ modules](https://npmjs.org/browse/depended/chalk)\n\n\n## Install\n\nInstall with [npm](https://npmjs.org/package/chalk): `npm install --save chalk`\n\n\n## Example\n\nChalk comes with an easy to use composable API where you just chain and nest the styles you want.\n\n```js\nvar chalk = require('chalk');\n\n// style a string\nconsole.log( chalk.blue('Hello world!') );\n\n// combine styled and normal strings\nconsole.log( chalk.blue('Hello'), 'World' + chalk.red('!') );\n\n// compose multiple styles using the chainable API\nconsole.log( chalk.blue.bgRed.bold('Hello world!') );\n\n// nest styles\nconsole.log( chalk.red('Hello', chalk.underline.bgBlue('world') + '!') );\n\n// pass in multiple arguments\nconsole.log( chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz') );\n```\n\nYou can easily define your own themes.\n\n```js\nvar chalk = require('chalk');\nvar error = chalk.bold.red;\nconsole.log(error('Error!'));\n```\n\n\n## API\n\n### chalk.`<style>[.<style>...](string, [string...])`\n\nExample: `chalk.red.bold.underline('Hello', 'world');`\n\nChain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter.\n\nMultiple arguments will be separated by space.\n\n### chalk.enabled\n\nColor support is automatically detected, but you can override it.\n\n### chalk.supportsColor\n\nDetect whether the terminal [supports color](https://github.com/sindresorhus/has-color).\n\nCan be overridden by the user with the flags `--color` and `--no-color`.\n\nUsed internally and handled for you, but exposed for convenience.\n\n### chalk.styles\n\nExposes the styles as [ANSI escape codes](https://github.com/sindresorhus/ansi-styles).\n\nGenerally not useful, but you might need just the `.open` or `.close` escape code if you're mixing externally styled strings with yours.\n\n```js\nvar chalk = require('chalk');\n\nconsole.log(chalk.styles.red);\n//=> {open: '\\x1b[31m', close: '\\x1b[39m'}\n\nconsole.log(chalk.styles.red.open + 'Hello' + chalk.styles.red.close);\n```\n\n### chalk.stripColor(string)\n\n[Strip color](https://github.com/sindresorhus/strip-ansi) from a string.\n\nCan be useful in combination with `.supportsColor` to strip color on externally styled text when it's not supported.\n\nExample:\n\n```js\nvar chalk = require('chalk');\nvar styledString = fromExternal();\n\nif (!chalk.supportsColor) {\n\tchalk.stripColor(styledString);\n}\n```\n\n\n## Styles\n\n### General\n\n- reset\n- bold\n- italic\n- underline\n- inverse\n- strikethrough\n\n### Text colors\n\n- black\n- red\n- green\n- yellow\n- blue\n- magenta\n- cyan\n- white\n- gray\n\n### Background colors\n\n- bgBlack\n- bgRed\n- bgGreen\n- bgYellow\n- bgBlue\n- bgMagenta\n- bgCyan\n- bgWhite\n\n\n## License\n\nMIT © [Sindre Sorhus](http://sindresorhus.com)\n\n\n-\n\n[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/sindresorhus/chalk/trend.png)](https://bitdeli.com/free \"Bitdeli Badge\")\n",
"readmeFilename": "readme.md",
"bugs": {
"url": "https://github.com/sindresorhus/chalk/issues"
},
"homepage": "https://github.com/sindresorhus/chalk",
"_id": "chalk@0.4.0",
"_from": "chalk@~0.4.0"
}

View File

@ -0,0 +1,158 @@
# <img width="250" src="logo.png" alt="chalk">
> Terminal string styling done right
[![Build Status](https://secure.travis-ci.org/sindresorhus/chalk.png?branch=master)](http://travis-ci.org/sindresorhus/chalk)
[colors.js](https://github.com/Marak/colors.js) is currently the most popular string styling module, but it has serious deficiencies like extending String.prototype which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68). Although there are other ones, they either do too much or not enough.
**Chalk is a clean and focused alternative.**
![screenshot](screenshot.png)
## Why
- **Doesn't extend String.prototype**
- Expressive API
- Clean and focused
- Auto-detects color support
- Actively maintained
- [Used by 150+ modules](https://npmjs.org/browse/depended/chalk)
## Install
Install with [npm](https://npmjs.org/package/chalk): `npm install --save chalk`
## Example
Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
```js
var chalk = require('chalk');
// style a string
console.log( chalk.blue('Hello world!') );
// combine styled and normal strings
console.log( chalk.blue('Hello'), 'World' + chalk.red('!') );
// compose multiple styles using the chainable API
console.log( chalk.blue.bgRed.bold('Hello world!') );
// nest styles
console.log( chalk.red('Hello', chalk.underline.bgBlue('world') + '!') );
// pass in multiple arguments
console.log( chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz') );
```
You can easily define your own themes.
```js
var chalk = require('chalk');
var error = chalk.bold.red;
console.log(error('Error!'));
```
## API
### chalk.`<style>[.<style>...](string, [string...])`
Example: `chalk.red.bold.underline('Hello', 'world');`
Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter.
Multiple arguments will be separated by space.
### chalk.enabled
Color support is automatically detected, but you can override it.
### chalk.supportsColor
Detect whether the terminal [supports color](https://github.com/sindresorhus/has-color).
Can be overridden by the user with the flags `--color` and `--no-color`.
Used internally and handled for you, but exposed for convenience.
### chalk.styles
Exposes the styles as [ANSI escape codes](https://github.com/sindresorhus/ansi-styles).
Generally not useful, but you might need just the `.open` or `.close` escape code if you're mixing externally styled strings with yours.
```js
var chalk = require('chalk');
console.log(chalk.styles.red);
//=> {open: '\x1b[31m', close: '\x1b[39m'}
console.log(chalk.styles.red.open + 'Hello' + chalk.styles.red.close);
```
### chalk.stripColor(string)
[Strip color](https://github.com/sindresorhus/strip-ansi) from a string.
Can be useful in combination with `.supportsColor` to strip color on externally styled text when it's not supported.
Example:
```js
var chalk = require('chalk');
var styledString = fromExternal();
if (!chalk.supportsColor) {
chalk.stripColor(styledString);
}
```
## Styles
### General
- reset
- bold
- italic
- underline
- inverse
- strikethrough
### Text colors
- black
- red
- green
- yellow
- blue
- magenta
- cyan
- white
- gray
### Background colors
- bgBlack
- bgRed
- bgGreen
- bgYellow
- bgBlue
- bgMagenta
- bgCyan
- bgWhite
## License
MIT © [Sindre Sorhus](http://sindresorhus.com)
-
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/sindresorhus/chalk/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

57
node_modules/grunt-contrib-concat/package.json generated vendored Normal file

File diff suppressed because one or more lines are too long

70
node_modules/grunt-contrib-concat/tasks/concat.js generated vendored Normal file
View File

@ -0,0 +1,70 @@
/*
* grunt-contrib-concat
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
// Internal lib.
var comment = require('./lib/comment').init(grunt);
var chalk = require('chalk');
grunt.registerMultiTask('concat', 'Concatenate files.', function() {
// Merge task-specific and/or target-specific options with these defaults.
var options = this.options({
separator: grunt.util.linefeed,
banner: '',
footer: '',
stripBanners: false,
process: false
});
// Normalize boolean options that accept options objects.
if (options.stripBanners === true) { options.stripBanners = {}; }
if (options.process === true) { options.process = {}; }
// Process banner and footer.
var banner = grunt.template.process(options.banner);
var footer = grunt.template.process(options.footer);
// Iterate over all src-dest file pairs.
this.files.forEach(function(f) {
// Concat banner + specified files + footer.
var src = banner + f.src.filter(function(filepath) {
// Warn on and remove invalid source files (if nonull was set).
if (!grunt.file.exists(filepath)) {
grunt.log.warn('Source file "' + filepath + '" not found.');
return false;
} else {
return true;
}
}).map(function(filepath) {
// Read file source.
var src = grunt.file.read(filepath);
// Process files as templates if requested.
if (typeof options.process === 'function') {
src = options.process(src, filepath);
} else if (options.process) {
src = grunt.template.process(src, options.process);
}
// Strip banners if requested.
if (options.stripBanners) {
src = comment.stripBanner(src, options.stripBanners);
}
return src;
}).join(options.separator) + footer;
// Write the destination file.
grunt.file.write(f.dest, src);
// Print a success message.
grunt.log.writeln('File ' + chalk.cyan(f.dest) + ' created.');
});
});
};

34
node_modules/grunt-contrib-concat/tasks/lib/comment.js generated vendored Normal file
View File

@ -0,0 +1,34 @@
/*
* grunt-contrib-concat
* http://gruntjs.com/
*
* Copyright (c) 2013 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
exports.init = function(/*grunt*/) {
var exports = {};
// Return the given source code with any leading banner comment stripped.
exports.stripBanner = function(src, options) {
if (!options) { options = {}; }
var m = [];
if (options.line) {
// Strip // ... leading banners.
m.push('(?:.*\\/\\/.*\\r?\\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, '');
};
return exports;
};

8
node_modules/grunt/.npmignore generated vendored Normal file
View File

@ -0,0 +1,8 @@
docs
test
.travis.yml
AUTHORS
CHANGELOG
CONTRIBUTING.md
custom-gruntfile.js
Gruntfile.js

22
node_modules/grunt/LICENSE-MIT generated vendored Normal file
View File

@ -0,0 +1,22 @@
Copyright (c) 2014 "Cowboy" Ben Alman
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.

19
node_modules/grunt/README.md generated vendored Normal file
View File

@ -0,0 +1,19 @@
# Grunt: The JavaScript Task Runner
[![Build Status](https://secure.travis-ci.org/gruntjs/grunt.png?branch=master)](http://travis-ci.org/gruntjs/grunt)
[![Built with Grunt](https://cdn.gruntjs.com/builtwith.png)](http://gruntjs.com/)
<img align="right" height="260" src="http://gruntjs.com/img/grunt-logo-no-wordmark.svg">
### Documentation
Visit the [gruntjs.com](http://gruntjs.com/) website for all the things.
### Support / Contributing
Before you make an issue, please read our [Contributing](http://gruntjs.com/contributing) guide.
You can find the grunt team in [#grunt on irc.freenode.net](http://webchat.freenode.net/?channels=grunt).
### Release History
See the [CHANGELOG](CHANGELOG).

151
node_modules/grunt/internal-tasks/bump.js generated vendored Normal file
View File

@ -0,0 +1,151 @@
/*
* grunt-contrib-bump
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman, contributors
* Licensed under the MIT license.
*/
'use strict';
var semver = require('semver');
var shell = require('shelljs');
module.exports = function(grunt) {
grunt.registerTask('bump', 'Bump the version property of a JSON file.', function() {
// Validate specified semver increment modes.
var valids = ['major', 'minor', 'patch', 'prerelease'];
var modes = [];
this.args.forEach(function(mode) {
var matches = [];
valids.forEach(function(valid) {
if (valid.indexOf(mode) === 0) { matches.push(valid); }
});
if (matches.length === 0) {
grunt.log.error('Error: mode "' + mode + '" does not match any known modes.');
} else if (matches.length > 1) {
grunt.log.error('Error: mode "' + mode + '" is ambiguous (possibly: ' + matches.join(', ') + ').');
} else {
modes.push(matches[0]);
}
});
if (this.errorCount === 0 && modes.length === 0) {
grunt.log.error('Error: no modes specified.');
}
if (this.errorCount > 0) {
grunt.log.error('Valid modes are: ' + valids.join(', ') + '.');
throw new Error('Use valid modes (or unambiguous mode abbreviations).');
}
// Options.
var options = this.options({
filepaths: ['package.json'],
syncVersions: false,
commit: true,
commitMessage: 'Bumping version to {%= version %}.',
tag: true,
tagName: 'v{%= version %}',
tagMessage: 'Version {%= version %}',
tagPrerelease: false,
});
// Normalize filepaths to array.
var filepaths = Array.isArray(options.filepaths) ? options.filepaths : [options.filepaths];
// Process JSON files, in-order.
var versions = {};
filepaths.forEach(function(filepath) {
var o = grunt.file.readJSON(filepath);
var origVersion = o.version;
// If syncVersions is enabled, only grab version from the first file,
// guaranteeing new versions will always be in sync.
var firstVersion = Object.keys(versions)[0];
if (options.syncVersions && firstVersion) {
o.version = firstVersion;
}
modes.forEach(function(mode) {
var orig = o.version;
var s = semver.parse(o.version);
s.inc(mode);
o.version = String(s);
// Workaround for https://github.com/isaacs/node-semver/issues/50
if (/-/.test(orig) && mode === 'patch') {
o.version = o.version.replace(/\d+$/, function(n) { return n - 1; });
}
// If prerelease on an un-prerelease version, bump patch version first
if (!/-/.test(orig) && mode === 'prerelease') {
s.inc('patch');
s.inc('prerelease');
o.version = String(s);
}
});
if (versions[origVersion]) {
versions[origVersion].filepaths.push(filepath);
} else {
versions[origVersion] = {version: o.version, filepaths: [filepath]};
}
// Actually *do* something.
grunt.log.write('Bumping version in ' + filepath + ' from ' + origVersion + ' to ' + o.version + '...');
grunt.file.write(filepath, JSON.stringify(o, null, 2));
grunt.log.ok();
});
// Commit changed files?
if (options.commit) {
Object.keys(versions).forEach(function(origVersion) {
var o = versions[origVersion];
commit(o.filepaths, processTemplate(options.commitMessage, {
version: o.version,
origVersion: origVersion
}));
});
}
// We're only going to create one tag. And it's going to be the new
// version of the first bumped file. Because, sanity.
var newVersion = versions[Object.keys(versions)[0]].version;
if (options.tag) {
if (options.tagPrerelease || modes.indexOf('prerelease') === -1) {
tag(
processTemplate(options.tagName, {version: newVersion}),
processTemplate(options.tagMessage, {version: newVersion})
);
} else {
grunt.log.writeln('Not tagging (prerelease version).');
}
}
if (this.errorCount > 0) {
grunt.warn('There were errors.');
}
});
// Using custom delimiters keeps templates from being auto-processed.
grunt.template.addDelimiters('bump', '{%', '%}');
function processTemplate(message, data) {
return grunt.template.process(message, {
delimiters: 'bump',
data: data,
});
}
// Kinda borrowed from https://github.com/geddski/grunt-release
function commit(filepaths, message) {
grunt.log.writeln('Committing ' + filepaths.join(', ') + ' with message: ' + message);
run("git commit -m '" + message + "' '" + filepaths.join("' '") + "'");
}
function tag(name, message) {
grunt.log.writeln('Tagging ' + name + ' with message: ' + message);
run("git tag '" + name + "' -m '" + message + "'");
}
function run(cmd) {
if (grunt.option('no-write')) {
grunt.verbose.writeln('Not actually running: ' + cmd);
} else {
grunt.verbose.writeln('Running: ' + cmd);
var result = shell.exec(cmd, {silent:true});
if (result.code !== 0) {
grunt.log.error('Error (' + result.code + ') ' + result.output);
}
}
}
};

34
node_modules/grunt/internal-tasks/subgrunt.js generated vendored Normal file
View File

@ -0,0 +1,34 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
module.exports = function(grunt) {
// Run sub-grunt files, because right now, testing tasks is a pain.
grunt.registerMultiTask('subgrunt', 'Run a sub-gruntfile.', function() {
var path = require('path');
grunt.util.async.forEachSeries(this.filesSrc, function(gruntfile, next) {
grunt.log.write('Loading ' + gruntfile + '...');
grunt.util.spawn({
grunt: true,
args: ['--gruntfile', path.resolve(gruntfile)],
}, function(error, result) {
if (error) {
grunt.log.error().error(result.stdout).writeln();
next(new Error('Error running sub-gruntfile "' + gruntfile + '".'));
} else {
grunt.log.ok().verbose.ok(result.stdout);
next();
}
});
}, this.async());
});
};

162
node_modules/grunt/lib/grunt.js generated vendored Normal file
View File

@ -0,0 +1,162 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
// Nodejs libs.
var path = require('path');
// This allows grunt to require() .coffee files.
require('coffee-script');
// The module to be exported.
var grunt = module.exports = {};
// Expose internal grunt libs.
function gRequire(name) {
return grunt[name] = require('./grunt/' + name);
}
var util = require('grunt-legacy-util');
grunt.util = util;
grunt.util.task = require('./util/task');
gRequire('template');
gRequire('event');
var fail = gRequire('fail');
gRequire('file');
var option = gRequire('option');
var config = gRequire('config');
var task = gRequire('task');
var log = gRequire('log');
var help = gRequire('help');
gRequire('cli');
var verbose = grunt.verbose = log.verbose;
// Expose some grunt metadata.
grunt.package = require('../package.json');
grunt.version = grunt.package.version;
// Expose specific grunt lib methods on grunt.
function gExpose(obj, methodName, newMethodName) {
grunt[newMethodName || methodName] = obj[methodName].bind(obj);
}
gExpose(task, 'registerTask');
gExpose(task, 'registerMultiTask');
gExpose(task, 'registerInitTask');
gExpose(task, 'renameTask');
gExpose(task, 'loadTasks');
gExpose(task, 'loadNpmTasks');
gExpose(config, 'init', 'initConfig');
gExpose(fail, 'warn');
gExpose(fail, 'fatal');
// Expose the task interface. I've never called this manually, and have no idea
// how it will work. But it might.
grunt.tasks = function(tasks, options, done) {
// Update options with passed-in options.
option.init(options);
// Display the grunt version and quit if the user did --version.
var _tasks, _options;
if (option('version')) {
// Not --verbose.
log.writeln('grunt v' + grunt.version);
if (option('verbose')) {
// --verbose
verbose.writeln('Install path: ' + path.resolve(__dirname, '..'));
// Yes, this is a total hack, but we don't want to log all that verbose
// task initialization stuff here.
grunt.log.muted = true;
// Initialize task system so that available tasks can be listed.
grunt.task.init([], {help: true});
// Re-enable logging.
grunt.log.muted = false;
// Display available tasks (for shell completion, etc).
_tasks = Object.keys(grunt.task._tasks).sort();
verbose.writeln('Available tasks: ' + _tasks.join(' '));
// Display available options (for shell completion, etc).
_options = [];
Object.keys(grunt.cli.optlist).forEach(function(long) {
var o = grunt.cli.optlist[long];
_options.push('--' + (o.negate ? 'no-' : '') + long);
if (o.short) { _options.push('-' + o.short); }
});
verbose.writeln('Available options: ' + _options.join(' '));
}
return;
}
// Init colors.
log.initColors();
// Display help and quit if the user did --help.
if (option('help')) {
help.display();
return;
}
// A little header stuff.
verbose.header('Initializing').writeflags(option.flags(), 'Command-line options');
// Determine and output which tasks will be run.
var tasksSpecified = tasks && tasks.length > 0;
tasks = task.parseArgs([tasksSpecified ? tasks : 'default']);
// Initialize tasks.
task.init(tasks);
verbose.writeln();
if (!tasksSpecified) {
verbose.writeln('No tasks specified, running default tasks.');
}
verbose.writeflags(tasks, 'Running tasks');
// Handle otherwise unhandleable (probably asynchronous) exceptions.
var uncaughtHandler = function(e) {
fail.fatal(e, fail.code.TASK_FAILURE);
};
process.on('uncaughtException', uncaughtHandler);
// Report, etc when all tasks have completed.
task.options({
error: function(e) {
fail.warn(e, fail.code.TASK_FAILURE);
},
done: function() {
// Stop handling uncaught exceptions so that we don't leave any
// unwanted process-level side effects behind. There is no need to do
// this in the error callback, because fail.warn() will either kill
// the process, or with --force keep on going all the way here.
process.removeListener('uncaughtException', uncaughtHandler);
// Output a final fail / success report.
fail.report();
if (done) {
// Execute "done" function when done (only if passed, of course).
done();
} else {
// Otherwise, explicitly exit.
util.exit(0);
}
}
});
// Execute all tasks, in order. Passing each task individually in a forEach
// allows the error callback to execute multiple times.
tasks.forEach(function(name) { task.run(name); });
// Run tasks async internally to reduce call-stack, per:
// https://github.com/gruntjs/grunt/pull/1026
task.start({asyncDone:true});
};

128
node_modules/grunt/lib/grunt/cli.js generated vendored Normal file
View File

@ -0,0 +1,128 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
var grunt = require('../grunt');
// Nodejs libs.
var path = require('path');
// External libs.
var nopt = require('nopt');
// This is only executed when run via command line.
var cli = module.exports = function(options, done) {
// CLI-parsed options override any passed-in "default" options.
if (options) {
// For each default option...
Object.keys(options).forEach(function(key) {
if (!(key in cli.options)) {
// If this option doesn't exist in the parsed cli.options, add it in.
cli.options[key] = options[key];
} else if (cli.optlist[key].type === Array) {
// If this option's type is Array, append it to any existing array
// (or create a new array).
[].push.apply(cli.options[key], options[key]);
}
});
}
// Run tasks.
grunt.tasks(cli.tasks, cli.options, done);
};
// Default options.
var optlist = cli.optlist = {
help: {
short: 'h',
info: 'Display this help text.',
type: Boolean
},
base: {
info: 'Specify an alternate base path. By default, all file paths are relative to the Gruntfile. (grunt.file.setBase) *',
type: path
},
color: {
info: 'Disable colored output.',
type: Boolean,
negate: true
},
gruntfile: {
info: 'Specify an alternate Gruntfile. By default, grunt looks in the current or parent directories for the nearest Gruntfile.js or Gruntfile.coffee file.',
type: path
},
debug: {
short: 'd',
info: 'Enable debugging mode for tasks that support it.',
type: [Number, Boolean]
},
stack: {
info: 'Print a stack trace when exiting with a warning or fatal error.',
type: Boolean
},
force: {
short: 'f',
info: 'A way to force your way past warnings. Want a suggestion? Don\'t use this option, fix your code.',
type: Boolean
},
tasks: {
info: 'Additional directory paths to scan for task and "extra" files. (grunt.loadTasks) *',
type: Array
},
npm: {
info: 'Npm-installed grunt plugins to scan for task and "extra" files. (grunt.loadNpmTasks) *',
type: Array
},
write: {
info: 'Disable writing files (dry run).',
type: Boolean,
negate: true
},
verbose: {
short: 'v',
info: 'Verbose mode. A lot more information output.',
type: Boolean
},
version: {
short: 'V',
info: 'Print the grunt version. Combine with --verbose for more info.',
type: Boolean
},
// Even though shell auto-completion is now handled by grunt-cli, leave this
// option here for display in the --help screen.
completion: {
info: 'Output shell auto-completion rules. See the grunt-cli documentation for more information.',
type: String
},
};
// Parse `optlist` into a form that nopt can handle.
var aliases = {};
var known = {};
Object.keys(optlist).forEach(function(key) {
var short = optlist[key].short;
if (short) {
aliases[short] = '--' + key;
}
known[key] = optlist[key].type;
});
var parsed = nopt(known, aliases, process.argv, 2);
cli.tasks = parsed.argv.remain;
cli.options = parsed;
delete parsed.argv;
// Initialize any Array options that weren't initialized.
Object.keys(optlist).forEach(function(key) {
if (optlist[key].type === Array && !(key in cli.options)) {
cli.options[key] = [];
}
});

118
node_modules/grunt/lib/grunt/config.js generated vendored Normal file
View File

@ -0,0 +1,118 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
var grunt = require('../grunt');
// Get/set config data. If value was passed, set. Otherwise, get.
var config = module.exports = function(prop, value) {
if (arguments.length === 2) {
// Two arguments were passed, set the property's value.
return config.set(prop, value);
} else {
// Get the property's value (or the entire data object).
return config.get(prop);
}
};
// The actual config data.
config.data = {};
// Escape any . in name with \. so dot-based namespacing works properly.
config.escape = function(str) {
return str.replace(/\./g, '\\.');
};
// Return prop as a string.
config.getPropString = function(prop) {
return Array.isArray(prop) ? prop.map(config.escape).join('.') : prop;
};
// Get raw, unprocessed config data.
config.getRaw = function(prop) {
if (prop) {
// Prop was passed, get that specific property's value.
return grunt.util.namespace.get(config.data, config.getPropString(prop));
} else {
// No prop was passed, return the entire config.data object.
return config.data;
}
};
// Match '<%= FOO %>' where FOO is a propString, eg. foo or foo.bar but not
// a method call like foo() or foo.bar().
var propStringTmplRe = /^<%=\s*([a-z0-9_$]+(?:\.[a-z0-9_$]+)*)\s*%>$/i;
// Get config data, recursively processing templates.
config.get = function(prop) {
return config.process(config.getRaw(prop));
};
// Expand a config value recursively. Used for post-processing raw values
// already retrieved from the config.
config.process = function(raw) {
return grunt.util.recurse(raw, function(value) {
// If the value is not a string, return it.
if (typeof value !== 'string') { return value; }
// If possible, access the specified property via config.get, in case it
// doesn't refer to a string, but instead refers to an object or array.
var matches = value.match(propStringTmplRe);
var result;
if (matches) {
result = config.get(matches[1]);
// If the result retrieved from the config data wasn't null or undefined,
// return it.
if (result != null) { return result; }
}
// Process the string as a template.
return grunt.template.process(value, {data: config.data});
});
};
// Set config data.
config.set = function(prop, value) {
return grunt.util.namespace.set(config.data, config.getPropString(prop), value);
};
// Initialize config data.
config.init = function(obj) {
grunt.verbose.write('Initializing config...').ok();
// Initialize and return data.
return (config.data = obj || {});
};
// Test to see if required config params have been defined. If not, throw an
// exception (use this inside of a task).
config.requires = function() {
var p = grunt.util.pluralize;
var props = grunt.util.toArray(arguments).map(config.getPropString);
var msg = 'Verifying propert' + p(props.length, 'y/ies') +
' ' + grunt.log.wordlist(props) + ' exist' + p(props.length, 's') +
' in config...';
grunt.verbose.write(msg);
var failProps = config.data && props.filter(function(prop) {
return config.get(prop) == null;
}).map(function(prop) {
return '"' + prop + '"';
});
if (config.data && failProps.length === 0) {
grunt.verbose.ok();
return true;
} else {
grunt.verbose.or.write(msg);
grunt.log.error().error('Unable to process task.');
if (!config.data) {
throw grunt.util.error('Unable to load config.');
} else {
throw grunt.util.error('Required config propert' +
p(failProps.length, 'y/ies') + ' ' + failProps.join(', ') + ' missing.');
}
}
};

16
node_modules/grunt/lib/grunt/event.js generated vendored Normal file
View File

@ -0,0 +1,16 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
// External lib.
var EventEmitter2 = require('eventemitter2').EventEmitter2;
// Awesome.
module.exports = new EventEmitter2({wildcard: true});

84
node_modules/grunt/lib/grunt/fail.js generated vendored Normal file
View File

@ -0,0 +1,84 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
var grunt = require('../grunt');
// The module to be exported.
var fail = module.exports = {};
// Error codes.
fail.code = {
FATAL_ERROR: 1,
MISSING_GRUNTFILE: 2,
TASK_FAILURE: 3,
TEMPLATE_ERROR: 4,
INVALID_AUTOCOMPLETE: 5,
WARNING: 6,
};
// DRY it up!
function writeln(e, mode) {
grunt.log.muted = false;
var msg = String(e.message || e);
if (!grunt.option('no-color')) { msg += '\x07'; } // Beep!
if (mode === 'warn') {
msg = 'Warning: ' + msg + ' ';
msg += (grunt.option('force') ? 'Used --force, continuing.'.underline : 'Use --force to continue.');
msg = msg.yellow;
} else {
msg = ('Fatal error: ' + msg).red;
}
grunt.log.writeln(msg);
}
// If --stack is enabled, log the appropriate error stack (if it exists).
function dumpStack(e) {
if (grunt.option('stack')) {
if (e.origError && e.origError.stack) {
console.log(e.origError.stack);
} else if (e.stack) {
console.log(e.stack);
}
}
}
// A fatal error occurred. Abort immediately.
fail.fatal = function(e, errcode) {
writeln(e, 'fatal');
dumpStack(e);
grunt.util.exit(typeof errcode === 'number' ? errcode : fail.code.FATAL_ERROR);
};
// Keep track of error and warning counts.
fail.errorcount = 0;
fail.warncount = 0;
// A warning occurred. Abort immediately unless -f or --force was used.
fail.warn = function(e, errcode) {
var message = typeof e === 'string' ? e : e.message;
fail.warncount++;
writeln(message, 'warn');
// If -f or --force aren't used, stop script processing.
if (!grunt.option('force')) {
dumpStack(e);
grunt.log.writeln().fail('Aborted due to warnings.');
grunt.util.exit(typeof errcode === 'number' ? errcode : fail.code.WARNING);
}
};
// This gets called at the very end.
fail.report = function() {
if (fail.warncount > 0) {
grunt.log.writeln().fail('Done, but with warnings.');
} else {
grunt.log.writeln().success('Done, without errors.');
}
};

448
node_modules/grunt/lib/grunt/file.js generated vendored Normal file
View File

@ -0,0 +1,448 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
var grunt = require('../grunt');
// Nodejs libs.
var fs = require('fs');
var path = require('path');
// The module to be exported.
var file = module.exports = {};
// External libs.
file.glob = require('glob');
file.minimatch = require('minimatch');
file.findup = require('findup-sync');
var YAML = require('js-yaml');
var rimraf = require('rimraf');
var iconv = require('iconv-lite');
// Windows?
var win32 = process.platform === 'win32';
// Normalize \\ paths to / paths.
var unixifyPath = function(filepath) {
if (win32) {
return filepath.replace(/\\/g, '/');
} else {
return filepath;
}
};
// Change the current base path (ie, CWD) to the specified path.
file.setBase = function() {
var dirpath = path.join.apply(path, arguments);
process.chdir(dirpath);
};
// Process specified wildcard glob patterns or filenames against a
// callback, excluding and uniquing files in the result set.
var processPatterns = function(patterns, fn) {
// Filepaths to return.
var result = [];
// Iterate over flattened patterns array.
grunt.util._.flatten(patterns).forEach(function(pattern) {
// If the first character is ! it should be omitted
var exclusion = pattern.indexOf('!') === 0;
// If the pattern is an exclusion, remove the !
if (exclusion) { pattern = pattern.slice(1); }
// Find all matching files for this pattern.
var matches = fn(pattern);
if (exclusion) {
// If an exclusion, remove matching files.
result = grunt.util._.difference(result, matches);
} else {
// Otherwise add matching files.
result = grunt.util._.union(result, matches);
}
});
return result;
};
// Match a filepath or filepaths against one or more wildcard patterns. Returns
// all matching filepaths.
file.match = function(options, patterns, filepaths) {
if (grunt.util.kindOf(options) !== 'object') {
filepaths = patterns;
patterns = options;
options = {};
}
// Return empty set if either patterns or filepaths was omitted.
if (patterns == null || filepaths == null) { return []; }
// Normalize patterns and filepaths to arrays.
if (!Array.isArray(patterns)) { patterns = [patterns]; }
if (!Array.isArray(filepaths)) { filepaths = [filepaths]; }
// Return empty set if there are no patterns or filepaths.
if (patterns.length === 0 || filepaths.length === 0) { return []; }
// Return all matching filepaths.
return processPatterns(patterns, function(pattern) {
return file.minimatch.match(filepaths, pattern, options);
});
};
// Match a filepath or filepaths against one or more wildcard patterns. Returns
// true if any of the patterns match.
file.isMatch = function() {
return file.match.apply(file, arguments).length > 0;
};
// Return an array of all file paths that match the given wildcard patterns.
file.expand = function() {
var args = grunt.util.toArray(arguments);
// If the first argument is an options object, save those options to pass
// into the file.glob.sync method.
var options = grunt.util.kindOf(args[0]) === 'object' ? args.shift() : {};
// Use the first argument if it's an Array, otherwise convert the arguments
// object to an array and use that.
var patterns = Array.isArray(args[0]) ? args[0] : args;
// Return empty set if there are no patterns or filepaths.
if (patterns.length === 0) { return []; }
// Return all matching filepaths.
var matches = processPatterns(patterns, function(pattern) {
// Find all matching files for this pattern.
return file.glob.sync(pattern, options);
});
// Filter result set?
if (options.filter) {
matches = matches.filter(function(filepath) {
filepath = path.join(options.cwd || '', filepath);
try {
if (typeof options.filter === 'function') {
return options.filter(filepath);
} else {
// If the file is of the right type and exists, this should work.
return fs.statSync(filepath)[options.filter]();
}
} catch(e) {
// Otherwise, it's probably not the right type.
return false;
}
});
}
return matches;
};
var pathSeparatorRe = /[\/\\]/g;
// The "ext" option refers to either everything after the first dot (default)
// or everything after the last dot.
var extDotRe = {
first: /(\.[^\/]*)?$/,
last: /(\.[^\/\.]*)?$/,
};
// Build a multi task "files" object dynamically.
file.expandMapping = function(patterns, destBase, options) {
options = grunt.util._.defaults({}, options, {
extDot: 'first',
rename: function(destBase, destPath) {
return path.join(destBase || '', destPath);
}
});
var files = [];
var fileByDest = {};
// Find all files matching pattern, using passed-in options.
file.expand(options, patterns).forEach(function(src) {
var destPath = src;
// Flatten?
if (options.flatten) {
destPath = path.basename(destPath);
}
// Change the extension?
if ('ext' in options) {
destPath = destPath.replace(extDotRe[options.extDot], options.ext);
}
// Generate destination filename.
var dest = options.rename(destBase, destPath, options);
// Prepend cwd to src path if necessary.
if (options.cwd) { src = path.join(options.cwd, src); }
// Normalize filepaths to be unix-style.
dest = dest.replace(pathSeparatorRe, '/');
src = src.replace(pathSeparatorRe, '/');
// Map correct src path to dest path.
if (fileByDest[dest]) {
// If dest already exists, push this src onto that dest's src array.
fileByDest[dest].src.push(src);
} else {
// Otherwise create a new src-dest file mapping object.
files.push({
src: [src],
dest: dest,
});
// And store a reference for later use.
fileByDest[dest] = files[files.length - 1];
}
});
return files;
};
// Like mkdir -p. Create a directory and any intermediary directories.
file.mkdir = function(dirpath, mode) {
if (grunt.option('no-write')) { return; }
// Set directory mode in a strict-mode-friendly way.
if (mode == null) {
mode = parseInt('0777', 8) & (~process.umask());
}
dirpath.split(pathSeparatorRe).reduce(function(parts, part) {
parts += part + '/';
var subpath = path.resolve(parts);
if (!file.exists(subpath)) {
try {
fs.mkdirSync(subpath, mode);
} catch(e) {
throw grunt.util.error('Unable to create directory "' + subpath + '" (Error code: ' + e.code + ').', e);
}
}
return parts;
}, '');
};
// Recurse into a directory, executing callback for each file.
file.recurse = function recurse(rootdir, callback, subdir) {
var abspath = subdir ? path.join(rootdir, subdir) : rootdir;
fs.readdirSync(abspath).forEach(function(filename) {
var filepath = path.join(abspath, filename);
if (fs.statSync(filepath).isDirectory()) {
recurse(rootdir, callback, unixifyPath(path.join(subdir || '', filename || '')));
} else {
callback(unixifyPath(filepath), rootdir, subdir, filename);
}
});
};
// The default file encoding to use.
file.defaultEncoding = 'utf8';
// Whether to preserve the BOM on file.read rather than strip it.
file.preserveBOM = false;
// Read a file, return its contents.
file.read = function(filepath, options) {
if (!options) { options = {}; }
var contents;
grunt.verbose.write('Reading ' + filepath + '...');
try {
contents = fs.readFileSync(String(filepath));
// If encoding is not explicitly null, convert from encoded buffer to a
// string. If no encoding was specified, use the default.
if (options.encoding !== null) {
contents = iconv.decode(contents, options.encoding || file.defaultEncoding);
// Strip any BOM that might exist.
if (!file.preserveBOM && contents.charCodeAt(0) === 0xFEFF) {
contents = contents.substring(1);
}
}
grunt.verbose.ok();
return contents;
} catch(e) {
grunt.verbose.error();
throw grunt.util.error('Unable to read "' + filepath + '" file (Error code: ' + e.code + ').', e);
}
};
// Read a file, parse its contents, return an object.
file.readJSON = function(filepath, options) {
var src = file.read(filepath, options);
var result;
grunt.verbose.write('Parsing ' + filepath + '...');
try {
result = JSON.parse(src);
grunt.verbose.ok();
return result;
} catch(e) {
grunt.verbose.error();
throw grunt.util.error('Unable to parse "' + filepath + '" file (' + e.message + ').', e);
}
};
// Read a YAML file, parse its contents, return an object.
file.readYAML = function(filepath, options) {
var src = file.read(filepath, options);
var result;
grunt.verbose.write('Parsing ' + filepath + '...');
try {
result = YAML.load(src);
grunt.verbose.ok();
return result;
} catch(e) {
grunt.verbose.error();
throw grunt.util.error('Unable to parse "' + filepath + '" file (' + e.problem + ').', e);
}
};
// Write a file.
file.write = function(filepath, contents, options) {
if (!options) { options = {}; }
var nowrite = grunt.option('no-write');
grunt.verbose.write((nowrite ? 'Not actually writing ' : 'Writing ') + filepath + '...');
// Create path, if necessary.
file.mkdir(path.dirname(filepath));
try {
// If contents is already a Buffer, don't try to encode it. If no encoding
// was specified, use the default.
if (!Buffer.isBuffer(contents)) {
contents = iconv.encode(contents, options.encoding || file.defaultEncoding);
}
// Actually write file.
if (!nowrite) {
fs.writeFileSync(filepath, contents);
}
grunt.verbose.ok();
return true;
} catch(e) {
grunt.verbose.error();
throw grunt.util.error('Unable to write "' + filepath + '" file (Error code: ' + e.code + ').', e);
}
};
// Read a file, optionally processing its content, then write the output.
file.copy = function(srcpath, destpath, options) {
if (!options) { options = {}; }
// If a process function was specified, and noProcess isn't true or doesn't
// match the srcpath, process the file's source.
var process = options.process && options.noProcess !== true &&
!(options.noProcess && file.isMatch(options.noProcess, srcpath));
// If the file will be processed, use the encoding as-specified. Otherwise,
// use an encoding of null to force the file to be read/written as a Buffer.
var readWriteOptions = process ? options : {encoding: null};
// Actually read the file.
var contents = file.read(srcpath, readWriteOptions);
if (process) {
grunt.verbose.write('Processing source...');
try {
contents = options.process(contents, srcpath);
grunt.verbose.ok();
} catch(e) {
grunt.verbose.error();
throw grunt.util.error('Error while processing "' + srcpath + '" file.', e);
}
}
// Abort copy if the process function returns false.
if (contents === false) {
grunt.verbose.writeln('Write aborted.');
} else {
file.write(destpath, contents, readWriteOptions);
}
};
// Delete folders and files recursively
file.delete = function(filepath, options) {
filepath = String(filepath);
var nowrite = grunt.option('no-write');
if (!options) {
options = {force: grunt.option('force') || false};
}
grunt.verbose.write((nowrite ? 'Not actually deleting ' : 'Deleting ') + filepath + '...');
if (!file.exists(filepath)) {
grunt.verbose.error();
grunt.log.warn('Cannot delete nonexistent file.');
return false;
}
// Only delete cwd or outside cwd if --force enabled. Be careful, people!
if (!options.force) {
if (file.isPathCwd(filepath)) {
grunt.verbose.error();
grunt.fail.warn('Cannot delete the current working directory.');
return false;
} else if (!file.isPathInCwd(filepath)) {
grunt.verbose.error();
grunt.fail.warn('Cannot delete files outside the current working directory.');
return false;
}
}
try {
// Actually delete. Or not.
if (!nowrite) {
rimraf.sync(filepath);
}
grunt.verbose.ok();
return true;
} catch(e) {
grunt.verbose.error();
throw grunt.util.error('Unable to delete "' + filepath + '" file (' + e.message + ').', e);
}
};
// True if the file path exists.
file.exists = function() {
var filepath = path.join.apply(path, arguments);
return fs.existsSync(filepath);
};
// True if the file is a symbolic link.
file.isLink = function() {
var filepath = path.join.apply(path, arguments);
return file.exists(filepath) && fs.lstatSync(filepath).isSymbolicLink();
};
// True if the path is a directory.
file.isDir = function() {
var filepath = path.join.apply(path, arguments);
return file.exists(filepath) && fs.statSync(filepath).isDirectory();
};
// True if the path is a file.
file.isFile = function() {
var filepath = path.join.apply(path, arguments);
return file.exists(filepath) && fs.statSync(filepath).isFile();
};
// Is a given file path absolute?
file.isPathAbsolute = function() {
var filepath = path.join.apply(path, arguments);
return path.resolve(filepath) === filepath.replace(/[\/\\]+$/, '');
};
// Do all the specified paths refer to the same path?
file.arePathsEquivalent = function(first) {
first = path.resolve(first);
for (var i = 1; i < arguments.length; i++) {
if (first !== path.resolve(arguments[i])) { return false; }
}
return true;
};
// Are descendant path(s) contained within ancestor path? Note: does not test
// if paths actually exist.
file.doesPathContain = function(ancestor) {
ancestor = path.resolve(ancestor);
var relative;
for (var i = 1; i < arguments.length; i++) {
relative = path.relative(path.resolve(arguments[i]), ancestor);
if (relative === '' || /\w+/.test(relative)) { return false; }
}
return true;
};
// Test to see if a filepath is the CWD.
file.isPathCwd = function() {
var filepath = path.join.apply(path, arguments);
try {
return file.arePathsEquivalent(process.cwd(), fs.realpathSync(filepath));
} catch(e) {
return false;
}
};
// Test to see if a filepath is contained within the CWD.
file.isPathInCwd = function() {
var filepath = path.join.apply(path, arguments);
try {
return file.doesPathContain(process.cwd(), fs.realpathSync(filepath));
} catch(e) {
return false;
}
};

129
node_modules/grunt/lib/grunt/help.js generated vendored Normal file
View File

@ -0,0 +1,129 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
var grunt = require('../grunt');
// Nodejs libs.
var path = require('path');
// Set column widths.
var col1len = 0;
exports.initCol1 = function(str) {
col1len = Math.max(col1len, str.length);
};
exports.initWidths = function() {
// Widths for options/tasks table output.
exports.widths = [1, col1len, 2, 76 - col1len];
};
// Render an array in table form.
exports.table = function(arr) {
arr.forEach(function(item) {
grunt.log.writetableln(exports.widths, ['', grunt.util._.pad(item[0], col1len), '', item[1]]);
});
};
// Methods to run, in-order.
exports.queue = [
'initOptions',
'initTasks',
'initWidths',
'header',
'usage',
'options',
'optionsFooter',
'tasks',
'footer',
];
// Actually display stuff.
exports.display = function() {
exports.queue.forEach(function(name) { exports[name](); });
};
// Header.
exports.header = function() {
grunt.log.writeln('Grunt: The JavaScript Task Runner (v' + grunt.version + ')');
};
// Usage info.
exports.usage = function() {
grunt.log.header('Usage');
grunt.log.writeln(' ' + path.basename(process.argv[1]) + ' [options] [task [task ...]]');
};
// Options.
exports.initOptions = function() {
// Build 2-column array for table view.
exports._options = Object.keys(grunt.cli.optlist).map(function(long) {
var o = grunt.cli.optlist[long];
var col1 = '--' + (o.negate ? 'no-' : '') + long + (o.short ? ', -' + o.short : '');
exports.initCol1(col1);
return [col1, o.info];
});
};
exports.options = function() {
grunt.log.header('Options');
exports.table(exports._options);
};
exports.optionsFooter = function() {
grunt.log.writeln().writelns(
'Options marked with * have methods exposed via the grunt API and should ' +
'instead be specified inside the Gruntfile wherever possible.'
);
};
// Tasks.
exports.initTasks = function() {
// Initialize task system so that the tasks can be listed.
grunt.task.init([], {help: true});
// Build object of tasks by info (where they were loaded from).
exports._tasks = [];
Object.keys(grunt.task._tasks).forEach(function(name) {
exports.initCol1(name);
var task = grunt.task._tasks[name];
exports._tasks.push(task);
});
};
exports.tasks = function() {
grunt.log.header('Available tasks');
if (exports._tasks.length === 0) {
grunt.log.writeln('(no tasks found)');
} else {
exports.table(exports._tasks.map(function(task) {
var info = task.info;
if (task.multi) { info += ' *'; }
return [task.name, info];
}));
grunt.log.writeln().writelns(
'Tasks run in the order specified. Arguments may be passed to tasks that ' +
'accept them by using colons, like "lint:files". Tasks marked with * are ' +
'"multi tasks" and will iterate over all sub-targets if no argument is ' +
'specified.'
);
}
grunt.log.writeln().writelns(
'The list of available tasks may change based on tasks directories or ' +
'grunt plugins specified in the Gruntfile or via command-line options.'
);
};
// Footer.
exports.footer = function() {
grunt.log.writeln().writeln('For more information, see http://gruntjs.com/');
};

352
node_modules/grunt/lib/grunt/log.js generated vendored Normal file
View File

@ -0,0 +1,352 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
var grunt = require('../grunt');
// Nodejs libs.
var util = require('util');
// The module to be exported.
var log = module.exports = {};
// External lib. Requiring this here modifies the String prototype!
var colors = require('colors');
// Disable colors if --no-colors was passed.
log.initColors = function() {
var util = grunt.util;
if (grunt.option('no-color')) {
// String color getters should just return the string.
colors.mode = 'none';
// Strip colors from strings passed to console.log.
util.hooker.hook(console, 'log', function() {
var args = util.toArray(arguments);
return util.hooker.filter(this, args.map(function(arg) {
return util.kindOf(arg) === 'string' ? colors.stripColors(arg) : arg;
}));
});
}
};
// Temporarily suppress output.
var suppressOutput;
// Allow external muting of output.
log.muted = false;
// True once anything has actually been logged.
var hasLogged;
// Parse certain markup in strings to be logged.
function markup(str) {
str = str || '';
// Make _foo_ underline.
str = str.replace(/(\s|^)_(\S|\S[\s\S]+?\S)_(?=[\s,.!?]|$)/g, '$1' + '$2'.underline);
// Make *foo* bold.
str = str.replace(/(\s|^)\*(\S|\S[\s\S]+?\S)\*(?=[\s,.!?]|$)/g, '$1' + '$2'.bold);
return str;
}
// Similar to util.format in the standard library, however it'll always
// cast the first argument to a string and treat it as the format string.
function format(args) {
// Args is a argument array so copy it in order to avoid wonky behavior.
args = [].slice.call(args, 0);
if (args.length > 0) {
args[0] = String(args[0]);
}
return util.format.apply(util, args);
}
function write(msg) {
msg = msg || '';
// Actually write output.
if (!log.muted && !suppressOutput) {
hasLogged = true;
// Users should probably use the colors-provided methods, but if they
// don't, this should strip extraneous color codes.
if (grunt.option('no-color')) { msg = colors.stripColors(msg); }
// Actually write to stdout.
process.stdout.write(markup(msg));
}
}
function writeln(msg) {
// Write blank line if no msg is passed in.
msg = msg || '';
write(msg + '\n');
}
// Write output.
log.write = function() {
write(format(arguments));
return log;
};
// Write a line of output.
log.writeln = function() {
writeln(format(arguments));
return log;
};
log.warn = function() {
var msg = format(arguments);
if (arguments.length > 0) {
writeln('>> '.red + grunt.util._.trim(msg).replace(/\n/g, '\n>> '.red));
} else {
writeln('ERROR'.red);
}
return log;
};
log.error = function() {
grunt.fail.errorcount++;
log.warn.apply(log, arguments);
return log;
};
log.ok = function() {
var msg = format(arguments);
if (arguments.length > 0) {
writeln('>> '.green + grunt.util._.trim(msg).replace(/\n/g, '\n>> '.green));
} else {
writeln('OK'.green);
}
return log;
};
log.errorlns = function() {
var msg = format(arguments);
log.error(log.wraptext(77, msg));
return log;
};
log.oklns = function() {
var msg = format(arguments);
log.ok(log.wraptext(77, msg));
return log;
};
log.success = function() {
var msg = format(arguments);
writeln(msg.green);
return log;
};
log.fail = function() {
var msg = format(arguments);
writeln(msg.red);
return log;
};
log.header = function() {
var msg = format(arguments);
// Skip line before header, but not if header is the very first line output.
if (hasLogged) { writeln(); }
writeln(msg.underline);
return log;
};
log.subhead = function() {
var msg = format(arguments);
// Skip line before subhead, but not if subhead is the very first line output.
if (hasLogged) { writeln(); }
writeln(msg.bold);
return log;
};
// For debugging.
log.debug = function() {
var msg = format(arguments);
if (grunt.option('debug')) {
writeln('[D] ' + msg.magenta);
}
return log;
};
// Write a line of a table.
log.writetableln = function(widths, texts) {
writeln(log.table(widths, texts));
return log;
};
// Wrap a long line of text to 80 columns.
log.writelns = function() {
var msg = format(arguments);
writeln(log.wraptext(80, msg));
return log;
};
// Display flags in verbose mode.
log.writeflags = function(obj, prefix) {
var wordlist;
if (Array.isArray(obj)) {
wordlist = log.wordlist(obj);
} else if (typeof obj === 'object' && obj) {
wordlist = log.wordlist(Object.keys(obj).map(function(key) {
var val = obj[key];
return key + (val === true ? '' : '=' + JSON.stringify(val));
}));
}
writeln((prefix || 'Flags') + ': ' + (wordlist || '(none)'.cyan));
return log;
};
// Create explicit "verbose" and "notverbose" functions, one for each already-
// defined log function, that do the same thing but ONLY if -v or --verbose is
// specified (or not specified).
log.verbose = {};
log.notverbose = {};
// Iterate over all exported functions.
Object.keys(log).filter(function(key) {
return typeof log[key] === 'function';
}).forEach(function(key) {
// Like any other log function, but suppresses output if the "verbose" option
// IS NOT set.
log.verbose[key] = function() {
suppressOutput = !grunt.option('verbose');
log[key].apply(log, arguments);
suppressOutput = false;
return log.verbose;
};
// Like any other log function, but suppresses output if the "verbose" option
// IS set.
log.notverbose[key] = function() {
suppressOutput = grunt.option('verbose');
log[key].apply(log, arguments);
suppressOutput = false;
return log.notverbose;
};
});
// A way to switch between verbose and notverbose modes. For example, this will
// write 'foo' if verbose logging is enabled, otherwise write 'bar':
// verbose.write('foo').or.write('bar');
log.verbose.or = log.notverbose;
log.notverbose.or = log.verbose;
// Static methods.
// Pretty-format a word list.
log.wordlist = function(arr, options) {
options = grunt.util._.defaults(options || {}, {
separator: ', ',
color: 'cyan'
});
return arr.map(function(item) {
return options.color ? String(item)[options.color] : item;
}).join(options.separator);
};
// Return a string, uncolored (suitable for testing .length, etc).
log.uncolor = function(str) {
return str.replace(/\x1B\[\d+m/g, '');
};
// Word-wrap text to a given width, permitting ANSI color codes.
log.wraptext = function(width, text) {
// notes to self:
// grab 1st character or ansi code from string
// if ansi code, add to array and save for later, strip from front of string
// if character, add to array and increment counter, strip from front of string
// if width + 1 is reached and current character isn't space:
// slice off everything after last space in array and prepend it to string
// etc
// This result array will be joined on \n.
var result = [];
var matches, color, tmp;
var captured = [];
var charlen = 0;
while (matches = text.match(/(?:(\x1B\[\d+m)|\n|(.))([\s\S]*)/)) {
// Updated text to be everything not matched.
text = matches[3];
// Matched a color code?
if (matches[1]) {
// Save last captured color code for later use.
color = matches[1];
// Capture color code.
captured.push(matches[1]);
continue;
// Matched a non-newline character?
} else if (matches[2]) {
// If this is the first character and a previous color code was set, push
// that onto the captured array first.
if (charlen === 0 && color) { captured.push(color); }
// Push the matched character.
captured.push(matches[2]);
// Increment the current charlen.
charlen++;
// If not yet at the width limit or a space was matched, continue.
if (charlen <= width || matches[2] === ' ') { continue; }
// The current charlen exceeds the width and a space wasn't matched.
// "Roll everything back" until the last space character.
tmp = captured.lastIndexOf(' ');
text = captured.slice(tmp === -1 ? tmp : tmp + 1).join('') + text;
captured = captured.slice(0, tmp);
}
// The limit has been reached. Push captured string onto result array.
result.push(captured.join(''));
// Reset captured array and charlen.
captured = [];
charlen = 0;
}
result.push(captured.join(''));
return result.join('\n');
};
// todo: write unit tests
//
// function logs(text) {
// [4, 6, 10, 15, 20, 25, 30, 40].forEach(function(n) {
// log(n, text);
// });
// }
//
// function log(n, text) {
// console.log(Array(n + 1).join('-'));
// console.log(wrap(n, text));
// }
//
// var text = 'this is '.red + 'a simple'.yellow.inverse + ' test of'.green + ' ' + 'some wrapped'.blue + ' text over '.inverse.magenta + 'many lines'.red;
// logs(text);
//
// var text = 'foolish '.red.inverse + 'monkeys'.yellow + ' eating'.green + ' ' + 'delicious'.inverse.blue + ' bananas '.magenta + 'forever'.red;
// logs(text);
//
// var text = 'foolish monkeys eating delicious bananas forever'.rainbow;
// logs(text);
// Format output into columns, wrapping words as-necessary.
log.table = function(widths, texts) {
var rows = [];
widths.forEach(function(width, i) {
var lines = log.wraptext(width, texts[i]).split('\n');
lines.forEach(function(line, j) {
var row = rows[j];
if (!row) { row = rows[j] = []; }
row[i] = line;
});
});
var lines = [];
rows.forEach(function(row) {
var txt = '';
var column;
for (var i = 0; i < row.length; i++) {
column = row[i] || '';
txt += column;
var diff = widths[i] - log.uncolor(column).length;
if (diff > 0) { txt += grunt.util.repeat(diff, ' '); }
}
lines.push(txt);
});
return lines.join('\n');
};

42
node_modules/grunt/lib/grunt/option.js generated vendored Normal file
View File

@ -0,0 +1,42 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
// The actual option data.
var data = {};
// Get or set an option value.
var option = module.exports = function(key, value) {
var no = key.match(/^no-(.+)$/);
if (arguments.length === 2) {
return (data[key] = value);
} else if (no) {
return data[no[1]] === false;
} else {
return data[key];
}
};
// Initialize option data.
option.init = function(obj) {
return (data = obj || {});
};
// List of options as flags.
option.flags = function() {
return Object.keys(data).filter(function(key) {
// Don't display empty arrays.
return !(Array.isArray(data[key]) && data[key].length === 0);
}).map(function(key) {
var val = data[key];
return '--' + (val === false ? 'no-' : '') + key +
(typeof val === 'boolean' ? '' : '=' + val);
});
};

458
node_modules/grunt/lib/grunt/task.js generated vendored Normal file
View File

@ -0,0 +1,458 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
var grunt = require('../grunt');
// Nodejs libs.
var path = require('path');
// Extend generic "task" util lib.
var parent = grunt.util.task.create();
// The module to be exported.
var task = module.exports = Object.create(parent);
// A temporary registry of tasks and metadata.
var registry = {tasks: [], untasks: [], meta: {}};
// The last specified tasks message.
var lastInfo;
// Number of levels of recursion when loading tasks in collections.
var loadTaskDepth = 0;
// Keep track of the number of log.error() calls.
var errorcount;
// Override built-in registerTask.
task.registerTask = function(name) {
// Add task to registry.
registry.tasks.push(name);
// Register task.
parent.registerTask.apply(task, arguments);
// This task, now that it's been registered.
var thisTask = task._tasks[name];
// Metadata about the current task.
thisTask.meta = grunt.util._.clone(registry.meta);
// Override task function.
var _fn = thisTask.fn;
thisTask.fn = function(arg) {
// Guaranteed to always be the actual task name.
var name = thisTask.name;
// Initialize the errorcount for this task.
errorcount = grunt.fail.errorcount;
// Return the number of errors logged during this task.
Object.defineProperty(this, 'errorCount', {
enumerable: true,
get: function() {
return grunt.fail.errorcount - errorcount;
}
});
// Expose task.requires on `this`.
this.requires = task.requires.bind(task);
// Expose config.requires on `this`.
this.requiresConfig = grunt.config.requires;
// Return an options object with the specified defaults overwritten by task-
// specific overrides, via the "options" property.
this.options = function() {
var args = [{}].concat(grunt.util.toArray(arguments)).concat([
grunt.config([name, 'options'])
]);
var options = grunt.util._.extend.apply(null, args);
grunt.verbose.writeflags(options, 'Options');
return options;
};
// If this task was an alias or a multi task called without a target,
// only log if in verbose mode.
var logger = _fn.alias || (thisTask.multi && (!arg || arg === '*')) ? 'verbose' : 'log';
// Actually log.
grunt[logger].header('Running "' + this.nameArgs + '"' +
(this.name !== this.nameArgs ? ' (' + this.name + ')' : '') + ' task');
// If --debug was specified, log the path to this task's source file.
grunt[logger].debug('Task source: ' + thisTask.meta.filepath);
// Actually run the task.
return _fn.apply(this, arguments);
};
return task;
};
// Multi task targets can't start with _ or be a reserved property (options).
function isValidMultiTaskTarget(target) {
return !/^_|^options$/.test(target);
}
// Normalize multi task files.
task.normalizeMultiTaskFiles = function(data, target) {
var prop, obj;
var files = [];
if (grunt.util.kindOf(data) === 'object') {
if ('src' in data || 'dest' in data) {
obj = {};
for (prop in data) {
if (prop !== 'options') {
obj[prop] = data[prop];
}
}
files.push(obj);
} else if (grunt.util.kindOf(data.files) === 'object') {
for (prop in data.files) {
files.push({src: data.files[prop], dest: grunt.config.process(prop)});
}
} else if (Array.isArray(data.files)) {
grunt.util._.flatten(data.files).forEach(function(obj) {
var prop;
if ('src' in obj || 'dest' in obj) {
files.push(obj);
} else {
for (prop in obj) {
files.push({src: obj[prop], dest: grunt.config.process(prop)});
}
}
});
}
} else {
files.push({src: data, dest: grunt.config.process(target)});
}
// If no src/dest or files were specified, return an empty files array.
if (files.length === 0) {
grunt.verbose.writeln('File: ' + '[no files]'.yellow);
return [];
}
// Process all normalized file objects.
files = grunt.util._(files).chain().forEach(function(obj) {
if (!('src' in obj) || !obj.src) { return; }
// Normalize .src properties to flattened array.
if (Array.isArray(obj.src)) {
obj.src = grunt.util._.flatten(obj.src);
} else {
obj.src = [obj.src];
}
}).map(function(obj) {
// Build options object, removing unwanted properties.
var expandOptions = grunt.util._.extend({}, obj);
delete expandOptions.src;
delete expandOptions.dest;
// Expand file mappings.
if (obj.expand) {
return grunt.file.expandMapping(obj.src, obj.dest, expandOptions).map(function(mapObj) {
// Copy obj properties to result.
var result = grunt.util._.extend({}, obj);
// Make a clone of the orig obj available.
result.orig = grunt.util._.extend({}, obj);
// Set .src and .dest, processing both as templates.
result.src = grunt.config.process(mapObj.src);
result.dest = grunt.config.process(mapObj.dest);
// Remove unwanted properties.
['expand', 'cwd', 'flatten', 'rename', 'ext'].forEach(function(prop) {
delete result[prop];
});
return result;
});
}
// Copy obj properties to result, adding an .orig property.
var result = grunt.util._.extend({}, obj);
// Make a clone of the orig obj available.
result.orig = grunt.util._.extend({}, obj);
if ('src' in result) {
// Expose an expand-on-demand getter method as .src.
Object.defineProperty(result, 'src', {
enumerable: true,
get: function fn() {
var src;
if (!('result' in fn)) {
src = obj.src;
// If src is an array, flatten it. Otherwise, make it into an array.
src = Array.isArray(src) ? grunt.util._.flatten(src) : [src];
// Expand src files, memoizing result.
fn.result = grunt.file.expand(expandOptions, src);
}
return fn.result;
}
});
}
if ('dest' in result) {
result.dest = obj.dest;
}
return result;
}).flatten().value();
// Log this.file src and dest properties when --verbose is specified.
if (grunt.option('verbose')) {
files.forEach(function(obj) {
var output = [];
if ('src' in obj) {
output.push(obj.src.length > 0 ? grunt.log.wordlist(obj.src) : '[no src]'.yellow);
}
if ('dest' in obj) {
output.push('-> ' + (obj.dest ? String(obj.dest).cyan : '[no dest]'.yellow));
}
if (output.length > 0) {
grunt.verbose.writeln('Files: ' + output.join(' '));
}
});
}
return files;
};
// This is the most common "multi task" pattern.
task.registerMultiTask = function(name, info, fn) {
// If optional "info" string is omitted, shuffle arguments a bit.
if (fn == null) {
fn = info;
info = 'Custom multi task.';
}
// Store a reference to the task object, in case the task gets renamed.
var thisTask;
task.registerTask(name, info, function(target) {
// Guaranteed to always be the actual task name.
var name = thisTask.name;
// Arguments (sans target) as an array.
this.args = grunt.util.toArray(arguments).slice(1);
// If a target wasn't specified, run this task once for each target.
if (!target || target === '*') {
return task.runAllTargets(name, this.args);
} else if (!isValidMultiTaskTarget(target)) {
throw new Error('Invalid target "' + target + '" specified.');
}
// Fail if any required config properties have been omitted.
this.requiresConfig([name, target]);
// Return an options object with the specified defaults overwritten by task-
// and/or target-specific overrides, via the "options" property.
this.options = function() {
var targetObj = grunt.config([name, target]);
var args = [{}].concat(grunt.util.toArray(arguments)).concat([
grunt.config([name, 'options']),
grunt.util.kindOf(targetObj) === 'object' ? targetObj.options : {}
]);
var options = grunt.util._.extend.apply(null, args);
grunt.verbose.writeflags(options, 'Options');
return options;
};
// Expose the current target.
this.target = target;
// Recreate flags object so that the target isn't set as a flag.
this.flags = {};
this.args.forEach(function(arg) { this.flags[arg] = true; }, this);
// Expose data on `this` (as well as task.current).
this.data = grunt.config([name, target]);
// Expose normalized files object.
this.files = task.normalizeMultiTaskFiles(this.data, target);
// Expose normalized, flattened, uniqued array of src files.
Object.defineProperty(this, 'filesSrc', {
enumerable: true,
get: function() {
return grunt.util._(this.files).chain().pluck('src').flatten().uniq().value();
}.bind(this)
});
// Call original task function, passing in the target and any other args.
return fn.apply(this, this.args);
});
thisTask = task._tasks[name];
thisTask.multi = true;
};
// Init tasks don't require properties in config, and as such will preempt
// config loading errors.
task.registerInitTask = function(name, info, fn) {
task.registerTask(name, info, fn);
task._tasks[name].init = true;
};
// Override built-in renameTask to use the registry.
task.renameTask = function(oldname, newname) {
var result;
try {
// Actually rename task.
result = parent.renameTask.apply(task, arguments);
// Add and remove task.
registry.untasks.push(oldname);
registry.tasks.push(newname);
// Return result.
return result;
} catch(e) {
grunt.log.error(e.message);
}
};
// If a property wasn't passed, run all task targets in turn.
task.runAllTargets = function(taskname, args) {
// Get an array of sub-property keys under the given config object.
var targets = Object.keys(grunt.config.getRaw(taskname) || {});
// Fail if there are no actual properties to iterate over.
if (targets.length === 0) {
grunt.log.error('No "' + taskname + '" targets found.');
return false;
}
// Iterate over all valid target properties, running a task for each.
targets.filter(isValidMultiTaskTarget).forEach(function(target) {
// Be sure to pass in any additionally specified args.
task.run([taskname, target].concat(args || []).join(':'));
});
};
// Load tasks and handlers from a given tasks file.
var loadTaskStack = [];
function loadTask(filepath) {
// In case this was called recursively, save registry for later.
loadTaskStack.push(registry);
// Reset registry.
registry = {tasks: [], untasks: [], meta: {info: lastInfo, filepath: filepath}};
var filename = path.basename(filepath);
var msg = 'Loading "' + filename + '" tasks...';
var regCount = 0;
var fn;
try {
// Load taskfile.
fn = require(path.resolve(filepath));
if (typeof fn === 'function') {
fn.call(grunt, grunt);
}
grunt.verbose.write(msg).ok();
// Log registered/renamed/unregistered tasks.
['un', ''].forEach(function(prefix) {
var list = grunt.util._.chain(registry[prefix + 'tasks']).uniq().sort().value();
if (list.length > 0) {
regCount++;
grunt.verbose.writeln((prefix ? '- ' : '+ ') + grunt.log.wordlist(list));
}
});
if (regCount === 0) {
grunt.verbose.error('No tasks were registered or unregistered.');
}
} catch(e) {
// Something went wrong.
grunt.log.write(msg).error().verbose.error(e.stack).or.error(e);
}
// Restore registry.
registry = loadTaskStack.pop() || {};
}
// Log a message when loading tasks.
function loadTasksMessage(info) {
// Only keep track of names of top-level loaded tasks and collections,
// not sub-tasks.
if (loadTaskDepth === 0) { lastInfo = info; }
grunt.verbose.subhead('Registering ' + info + ' tasks.');
}
// Load tasks and handlers from a given directory.
function loadTasks(tasksdir) {
try {
var files = grunt.file.glob.sync('*.{js,coffee}', {cwd: tasksdir, maxDepth: 1});
// Load tasks from files.
files.forEach(function(filename) {
loadTask(path.join(tasksdir, filename));
});
} catch(e) {
grunt.log.verbose.error(e.stack).or.error(e);
}
}
// Load tasks and handlers from a given directory.
task.loadTasks = function(tasksdir) {
loadTasksMessage('"' + tasksdir + '"');
if (grunt.file.exists(tasksdir)) {
loadTasks(tasksdir);
} else {
grunt.log.error('Tasks directory "' + tasksdir + '" not found.');
}
};
// Load tasks and handlers from a given locally-installed Npm module (installed
// relative to the base dir).
task.loadNpmTasks = function(name) {
loadTasksMessage('"' + name + '" local Npm module');
var root = path.resolve('node_modules');
var pkgfile = path.join(root, name, 'package.json');
var pkg = grunt.file.exists(pkgfile) ? grunt.file.readJSON(pkgfile) : {keywords: []};
// Process collection plugins.
if (pkg.keywords && pkg.keywords.indexOf('gruntcollection') !== -1) {
loadTaskDepth++;
Object.keys(pkg.dependencies).forEach(function(depName) {
// Npm sometimes pulls dependencies out if they're shared, so find
// upwards if not found locally.
var filepath = grunt.file.findup('node_modules/' + depName, {
cwd: path.resolve('node_modules', name),
nocase: true
});
if (filepath) {
// Load this task plugin recursively.
task.loadNpmTasks(path.relative(root, filepath));
}
});
loadTaskDepth--;
return;
}
// Process task plugins.
var tasksdir = path.join(root, name, 'tasks');
if (grunt.file.exists(tasksdir)) {
loadTasks(tasksdir);
} else {
grunt.log.error('Local Npm module "' + name + '" not found. Is it installed?');
}
};
// Initialize tasks.
task.init = function(tasks, options) {
if (!options) { options = {}; }
// Were only init tasks specified?
var allInit = tasks.length > 0 && tasks.every(function(name) {
var obj = task._taskPlusArgs(name).task;
return obj && obj.init;
});
// Get any local Gruntfile or tasks that might exist. Use --gruntfile override
// if specified, otherwise search the current directory or any parent.
var gruntfile = allInit ? null : grunt.option('gruntfile') ||
grunt.file.findup('Gruntfile.{js,coffee}', {nocase: true});
var msg = 'Reading "' + (gruntfile ? path.basename(gruntfile) : '???') + '" Gruntfile...';
if (gruntfile && grunt.file.exists(gruntfile)) {
grunt.verbose.writeln().write(msg).ok();
// Change working directory so that all paths are relative to the
// Gruntfile's location (or the --base option, if specified).
process.chdir(grunt.option('base') || path.dirname(gruntfile));
// Load local tasks, if the file exists.
loadTasksMessage('Gruntfile');
loadTask(gruntfile);
} else if (options.help || allInit) {
// Don't complain about missing Gruntfile.
} else if (grunt.option('gruntfile')) {
// If --config override was specified and it doesn't exist, complain.
grunt.log.writeln().write(msg).error();
grunt.fatal('Unable to find "' + gruntfile + '" Gruntfile.', grunt.fail.code.MISSING_GRUNTFILE);
} else if (!grunt.option('help')) {
grunt.verbose.writeln().write(msg).error();
grunt.log.writelns(
'A valid Gruntfile could not be found. Please see the getting ' +
'started guide for more information on how to configure grunt: ' +
'http://gruntjs.com/getting-started'
);
grunt.fatal('Unable to find Gruntfile.', grunt.fail.code.MISSING_GRUNTFILE);
}
// Load all user-specified --npm tasks.
(grunt.option('npm') || []).forEach(task.loadNpmTasks);
// Load all user-specified --tasks.
(grunt.option('tasks') || []).forEach(task.loadTasks);
};

95
node_modules/grunt/lib/grunt/template.js generated vendored Normal file
View File

@ -0,0 +1,95 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
'use strict';
var grunt = require('../grunt');
// The module to be exported.
var template = module.exports = {};
// External libs.
template.date = require('dateformat');
// Format today's date.
template.today = function(format) {
return template.date(new Date(), format);
};
// Template delimiters.
var allDelimiters = {};
// Initialize template delimiters.
template.addDelimiters = function(name, opener, closer) {
var delimiters = allDelimiters[name] = {};
// Used by grunt.
delimiters.opener = opener;
delimiters.closer = closer;
// Generate RegExp patterns dynamically.
var a = delimiters.opener.replace(/(.)/g, '\\$1');
var b = '([\\s\\S]+?)' + delimiters.closer.replace(/(.)/g, '\\$1');
// Used by Lo-Dash.
delimiters.lodash = {
evaluate: new RegExp(a + b, 'g'),
interpolate: new RegExp(a + '=' + b, 'g'),
escape: new RegExp(a + '-' + b, 'g')
};
};
// The underscore default template syntax should be a pretty sane default for
// the config system.
template.addDelimiters('config', '<%', '%>');
// Set Lo-Dash template delimiters.
template.setDelimiters = function(name) {
// Get the appropriate delimiters.
var delimiters = allDelimiters[name in allDelimiters ? name : 'config'];
// Tell Lo-Dash which delimiters to use.
grunt.util._.templateSettings = delimiters.lodash;
// Return the delimiters.
return delimiters;
};
// Process template + data with Lo-Dash.
template.process = function(tmpl, options) {
if (!options) { options = {}; }
// Set delimiters, and get a opening match character.
var delimiters = template.setDelimiters(options.delimiters);
// Clone data, initializing to config data or empty object if omitted.
var data = Object.create(options.data || grunt.config.data || {});
// Expose grunt so that grunt utilities can be accessed, but only if it
// doesn't conflict with an existing .grunt property.
if (!('grunt' in data)) { data.grunt = grunt; }
// Keep track of last change.
var last = tmpl;
try {
// As long as tmpl contains template tags, render it and get the result,
// otherwise just use the template string.
while (tmpl.indexOf(delimiters.opener) >= 0) {
tmpl = grunt.util._.template(tmpl, data);
// Abort if template didn't change - nothing left to process!
if (tmpl === last) { break; }
last = tmpl;
}
} catch (e) {
// In upgrading to Lo-Dash (or Underscore.js 1.3.3), \n and \r in template
// tags now causes an exception to be thrown. Warn the user why this is
// happening. https://github.com/documentcloud/underscore/issues/553
if (String(e) === 'SyntaxError: Unexpected token ILLEGAL' && /\n|\r/.test(tmpl)) {
grunt.log.errorlns('A special character was detected in this template. ' +
'Inside template tags, the \\n and \\r special characters must be ' +
'escaped as \\\\n and \\\\r. (grunt 0.4.0+)');
}
// Slightly better error message.
e.message = 'An error occurred while processing a template (' + e.message + ').';
grunt.warn(e, grunt.fail.code.TEMPLATE_ERROR);
}
// Normalize linefeeds and return.
return grunt.util.normalizelf(tmpl);
};

337
node_modules/grunt/lib/util/task.js generated vendored Normal file
View File

@ -0,0 +1,337 @@
/*
* grunt
* http://gruntjs.com/
*
* Copyright (c) 2014 "Cowboy" Ben Alman
* Licensed under the MIT license.
* https://github.com/gruntjs/grunt/blob/master/LICENSE-MIT
*/
(function(exports) {
'use strict';
// Construct-o-rama.
function Task() {
// Information about the currently-running task.
this.current = {};
// Tasks.
this._tasks = {};
// Task queue.
this._queue = [];
// Queue placeholder (for dealing with nested tasks).
this._placeholder = {placeholder: true};
// Queue marker (for clearing the queue programmatically).
this._marker = {marker: true};
// Options.
this._options = {};
// Is the queue running?
this._running = false;
// Success status of completed tasks.
this._success = {};
}
// Expose the constructor function.
exports.Task = Task;
// Create a new Task instance.
exports.create = function() {
return new Task();
};
// If the task runner is running or an error handler is not defined, throw
// an exception. Otherwise, call the error handler directly.
Task.prototype._throwIfRunning = function(obj) {
if (this._running || !this._options.error) {
// Throw an exception that the task runner will catch.
throw obj;
} else {
// Not inside the task runner. Call the error handler and abort.
this._options.error.call({name: null}, obj);
}
};
// Register a new task.
Task.prototype.registerTask = function(name, info, fn) {
// If optional "info" string is omitted, shuffle arguments a bit.
if (fn == null) {
fn = info;
info = null;
}
// String or array of strings was passed instead of fn.
var tasks;
if (typeof fn !== 'function') {
// Array of task names.
tasks = this.parseArgs([fn]);
// This task function just runs the specified tasks.
fn = this.run.bind(this, fn);
fn.alias = true;
// Generate an info string if one wasn't explicitly passed.
if (!info) {
info = 'Alias for "' + tasks.join('", "') + '" task' +
(tasks.length === 1 ? '' : 's') + '.';
}
} else if (!info) {
info = 'Custom task.';
}
// Add task into cache.
this._tasks[name] = {name: name, info: info, fn: fn};
// Make chainable!
return this;
};
// Is the specified task an alias?
Task.prototype.isTaskAlias = function(name) {
return !!this._tasks[name].fn.alias;
};
// Rename a task. This might be useful if you want to override the default
// behavior of a task, while retaining the old name. This is a billion times
// easier to implement than some kind of in-task "super" functionality.
Task.prototype.renameTask = function(oldname, newname) {
if (!this._tasks[oldname]) {
throw new Error('Cannot rename missing "' + oldname + '" task.');
}
// Rename task.
this._tasks[newname] = this._tasks[oldname];
// Update name property of task.
this._tasks[newname].name = newname;
// Remove old name.
delete this._tasks[oldname];
// Make chainable!
return this;
};
// Argument parsing helper. Supports these signatures:
// fn('foo') // ['foo']
// fn('foo', 'bar', 'baz') // ['foo', 'bar', 'baz']
// fn(['foo', 'bar', 'baz']) // ['foo', 'bar', 'baz']
Task.prototype.parseArgs = function(args) {
// Return the first argument if it's an array, otherwise return an array
// of all arguments.
return Array.isArray(args[0]) ? args[0] : [].slice.call(args);
};
// Split a colon-delimited string into an array, unescaping (but not
// splitting on) any \: escaped colons.
Task.prototype.splitArgs = function(str) {
if (!str) { return []; }
// Store placeholder for \\ followed by \:
str = str.replace(/\\\\/g, '\uFFFF').replace(/\\:/g, '\uFFFE');
// Split on :
return str.split(':').map(function(s) {
// Restore place-held : followed by \\
return s.replace(/\uFFFE/g, ':').replace(/\uFFFF/g, '\\');
});
};
// Given a task name, determine which actual task will be called, and what
// arguments will be passed into the task callback. "foo" -> task "foo", no
// args. "foo:bar:baz" -> task "foo:bar:baz" with no args (if "foo:bar:baz"
// task exists), otherwise task "foo:bar" with arg "baz" (if "foo:bar" task
// exists), otherwise task "foo" with args "bar" and "baz".
Task.prototype._taskPlusArgs = function(name) {
// Get task name / argument parts.
var parts = this.splitArgs(name);
// Start from the end, not the beginning!
var i = parts.length;
var task;
do {
// Get a task.
task = this._tasks[parts.slice(0, i).join(':')];
// If the task doesn't exist, decrement `i`, and if `i` is greater than
// 0, repeat.
} while (!task && --i > 0);
// Just the args.
var args = parts.slice(i);
// Maybe you want to use them as flags instead of as positional args?
var flags = {};
args.forEach(function(arg) { flags[arg] = true; });
// The task to run and the args to run it with.
return {task: task, nameArgs: name, args: args, flags: flags};
};
// Append things to queue in the correct spot.
Task.prototype._push = function(things) {
// Get current placeholder index.
var index = this._queue.indexOf(this._placeholder);
if (index === -1) {
// No placeholder, add task+args objects to end of queue.
this._queue = this._queue.concat(things);
} else {
// Placeholder exists, add task+args objects just before placeholder.
[].splice.apply(this._queue, [index, 0].concat(things));
}
};
// Enqueue a task.
Task.prototype.run = function() {
// Parse arguments into an array, returning an array of task+args objects.
var things = this.parseArgs(arguments).map(this._taskPlusArgs, this);
// Throw an exception if any tasks weren't found.
var fails = things.filter(function(thing) { return !thing.task; });
if (fails.length > 0) {
this._throwIfRunning(new Error('Task "' + fails[0].nameArgs + '" not found.'));
return this;
}
// Append things to queue in the correct spot.
this._push(things);
// Make chainable!
return this;
};
// Add a marker to the queue to facilitate clearing it programmatically.
Task.prototype.mark = function() {
this._push(this._marker);
// Make chainable!
return this;
};
// Run a task function, handling this.async / return value.
Task.prototype.runTaskFn = function(context, fn, done, asyncDone) {
// Async flag.
var async = false;
// Update the internal status object and run the next task.
var complete = function(success) {
var err = null;
if (success === false) {
// Since false was passed, the task failed generically.
err = new Error('Task "' + context.nameArgs + '" failed.');
} else if (success instanceof Error || {}.toString.call(success) === '[object Error]') {
// An error object was passed, so the task failed specifically.
err = success;
success = false;
} else {
// The task succeeded.
success = true;
}
// The task has ended, reset the current task object.
this.current = {};
// A task has "failed" only if it returns false (async) or if the
// function returned by .async is passed false.
this._success[context.nameArgs] = success;
// If task failed, call error handler.
if (!success && this._options.error) {
this._options.error.call({name: context.name, nameArgs: context.nameArgs}, err);
}
// only call done async if explicitly requested to
// see: https://github.com/gruntjs/grunt/pull/1026
if (asyncDone) {
process.nextTick(function () {
done(err, success);
});
} else {
done(err, success);
}
}.bind(this);
// When called, sets the async flag and returns a function that can
// be used to continue processing the queue.
context.async = function() {
async = true;
// The returned function should execute asynchronously in case
// someone tries to do this.async()(); inside a task (WTF).
return function(success) {
setTimeout(function() { complete(success); }, 1);
};
};
// Expose some information about the currently-running task.
this.current = context;
try {
// Get the current task and run it, setting `this` inside the task
// function to be something useful.
var success = fn.call(context);
// If the async flag wasn't set, process the next task in the queue.
if (!async) {
complete(success);
}
} catch (err) {
complete(err);
}
};
// Begin task queue processing. Ie. run all tasks.
Task.prototype.start = function(opts) {
if (!opts) {
opts = {};
}
// Abort if already running.
if (this._running) { return false; }
// Actually process the next task.
var nextTask = function() {
// Get next task+args object from queue.
var thing;
// Skip any placeholders or markers.
do {
thing = this._queue.shift();
} while (thing === this._placeholder || thing === this._marker);
// If queue was empty, we're all done.
if (!thing) {
this._running = false;
if (this._options.done) {
this._options.done();
}
return;
}
// Add a placeholder to the front of the queue.
this._queue.unshift(this._placeholder);
// Expose some information about the currently-running task.
var context = {
// The current task name plus args, as-passed.
nameArgs: thing.nameArgs,
// The current task name.
name: thing.task.name,
// The current task arguments.
args: thing.args,
// The current arguments, available as named flags.
flags: thing.flags
};
// Actually run the task function (handling this.async, etc)
this.runTaskFn(context, function() {
return thing.task.fn.apply(this, this.args);
}, nextTask, !!opts.asyncDone);
}.bind(this);
// Update flag.
this._running = true;
// Process the next task.
nextTask();
};
// Clear remaining tasks from the queue.
Task.prototype.clearQueue = function(options) {
if (!options) { options = {}; }
if (options.untilMarker) {
this._queue.splice(0, this._queue.indexOf(this._marker) + 1);
} else {
this._queue = [];
}
// Make chainable!
return this;
};
// Test to see if all of the given tasks have succeeded.
Task.prototype.requires = function() {
this.parseArgs(arguments).forEach(function(name) {
var success = this._success[name];
if (!success) {
throw new Error('Required task "' + name +
'" ' + (success === false ? 'failed' : 'must be run first') + '.');
}
}.bind(this));
};
// Override default options.
Task.prototype.options = function(options) {
Object.keys(options).forEach(function(name) {
this._options[name] = options[name];
}.bind(this));
};
}(typeof exports === 'object' && exports || this));

1
node_modules/grunt/node_modules/.bin/cake generated vendored Symbolic link
View File

@ -0,0 +1 @@
../coffee-script/bin/cake

1
node_modules/grunt/node_modules/.bin/coffee generated vendored Symbolic link
View File

@ -0,0 +1 @@
../coffee-script/bin/coffee

1
node_modules/grunt/node_modules/.bin/js-yaml generated vendored Symbolic link
View File

@ -0,0 +1 @@
../js-yaml/bin/js-yaml.js

1
node_modules/grunt/node_modules/.bin/nopt generated vendored Symbolic link
View File

@ -0,0 +1 @@
../nopt/bin/nopt.js

1
node_modules/grunt/node_modules/.bin/rimraf generated vendored Symbolic link
View File

@ -0,0 +1 @@
../rimraf/bin.js

1
node_modules/grunt/node_modules/.bin/which generated vendored Symbolic link
View File

@ -0,0 +1 @@
../which/bin/which

9
node_modules/grunt/node_modules/async/.gitmodules generated vendored Normal file
View File

@ -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

4
node_modules/grunt/node_modules/async/.npmignore generated vendored Normal file
View File

@ -0,0 +1,4 @@
deps
dist
test
nodelint.cfg

19
node_modules/grunt/node_modules/async/LICENSE generated vendored Normal file
View File

@ -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.

25
node_modules/grunt/node_modules/async/Makefile generated vendored Normal file
View File

@ -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

1021
node_modules/grunt/node_modules/async/README.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

3
node_modules/grunt/node_modules/async/index.js generated vendored Normal file
View File

@ -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');

692
node_modules/grunt/node_modules/async/lib/async.js generated vendored Normal file
View File

@ -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);
};
};
}());

32
node_modules/grunt/node_modules/async/package.json generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,11 @@
*.coffee
*.html
.DS_Store
.git*
Cakefile
documentation/
examples/
extras/coffee-script.js
raw/
src/
test/

1
node_modules/grunt/node_modules/coffee-script/CNAME generated vendored Normal file
View File

@ -0,0 +1 @@
coffeescript.org

22
node_modules/grunt/node_modules/coffee-script/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
Copyright (c) 2009-2012 Jeremy Ashkenas
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

51
node_modules/grunt/node_modules/coffee-script/README generated vendored Normal file
View File

@ -0,0 +1,51 @@
{
} } {
{ { } }
} }{ {
{ }{ } } _____ __ __
( }{ }{ { ) / ____| / _|/ _|
.- { { } { }} -. | | ___ | |_| |_ ___ ___
( ( } { } { } } ) | | / _ \| _| _/ _ \/ _ \
|`-..________ ..-'| | |___| (_) | | | || __/ __/
| | \_____\___/|_| |_| \___|\___|
| ;--.
| (__ \ _____ _ _
| | ) ) / ____| (_) | |
| |/ / | (___ ___ _ __ _ _ __ | |_
| ( / \___ \ / __| '__| | '_ \| __|
| |/ ____) | (__| | | | |_) | |_
| | |_____/ \___|_| |_| .__/ \__|
`-.._________..-' | |
|_|
CoffeeScript is a little language that compiles into JavaScript.
Install Node.js, and then the CoffeeScript compiler:
sudo bin/cake install
Or, if you have the Node Package Manager installed:
npm install -g coffee-script
(Leave off the -g if you don't wish to install globally.)
Execute a script:
coffee /path/to/script.coffee
Compile a script:
coffee -c /path/to/script.coffee
For documentation, usage, and examples, see:
http://coffeescript.org/
To suggest a feature, report a bug, or general discussion:
http://github.com/jashkenas/coffee-script/issues/
If you'd like to chat, drop by #coffeescript on Freenode IRC,
or on webchat.freenode.net.
The source repository:
git://github.com/jashkenas/coffee-script.git
All contributors are listed here:
http://github.com/jashkenas/coffee-script/contributors

78
node_modules/grunt/node_modules/coffee-script/Rakefile generated vendored Normal file
View File

@ -0,0 +1,78 @@
require 'rubygems'
require 'erb'
require 'fileutils'
require 'rake/testtask'
require 'json'
desc "Build the documentation page"
task :doc do
source = 'documentation/index.html.erb'
child = fork { exec "bin/coffee -bcw -o documentation/js documentation/coffee/*.coffee" }
at_exit { Process.kill("INT", child) }
Signal.trap("INT") { exit }
loop do
mtime = File.stat(source).mtime
if !@mtime || mtime > @mtime
rendered = ERB.new(File.read(source)).result(binding)
File.open('index.html', 'w+') {|f| f.write(rendered) }
end
@mtime = mtime
sleep 1
end
end
desc "Build coffee-script-source gem"
task :gem do
require 'rubygems'
require 'rubygems/package'
gemspec = Gem::Specification.new do |s|
s.name = 'coffee-script-source'
s.version = JSON.parse(File.read('package.json'))["version"]
s.date = Time.now.strftime("%Y-%m-%d")
s.homepage = "http://jashkenas.github.com/coffee-script/"
s.summary = "The CoffeeScript Compiler"
s.description = <<-EOS
CoffeeScript is a little language that compiles into JavaScript.
Underneath all of those embarrassing braces and semicolons,
JavaScript has always had a gorgeous object model at its heart.
CoffeeScript is an attempt to expose the good parts of JavaScript
in a simple way.
EOS
s.files = [
'lib/coffee_script/coffee-script.js',
'lib/coffee_script/source.rb'
]
s.authors = ['Jeremy Ashkenas']
s.email = 'jashkenas@gmail.com'
s.rubyforge_project = 'coffee-script-source'
end
file = File.open("coffee-script-source.gem", "w")
Gem::Package.open(file, 'w') do |pkg|
pkg.metadata = gemspec.to_yaml
path = "lib/coffee_script/source.rb"
contents = <<-ERUBY
module CoffeeScript
module Source
def self.bundled_path
File.expand_path("../coffee-script.js", __FILE__)
end
end
end
ERUBY
pkg.add_file_simple(path, 0644, contents.size) do |tar_io|
tar_io.write(contents)
end
contents = File.read("extras/coffee-script.js")
path = "lib/coffee_script/coffee-script.js"
pkg.add_file_simple(path, 0644, contents.size) do |tar_io|
tar_io.write(contents)
end
end
end

7
node_modules/grunt/node_modules/coffee-script/bin/cake generated vendored Executable file
View File

@ -0,0 +1,7 @@
#!/usr/bin/env node
var path = require('path');
var fs = require('fs');
var lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');
require(lib + '/coffee-script/cake').run();

7
node_modules/grunt/node_modules/coffee-script/bin/coffee generated vendored Executable file
View File

@ -0,0 +1,7 @@
#!/usr/bin/env node
var path = require('path');
var fs = require('fs');
var lib = path.join(path.dirname(fs.realpathSync(__filename)), '../lib');
require(lib + '/coffee-script/command').run();

View File

@ -0,0 +1,44 @@
# JavaScriptLint configuration file for CoffeeScript.
+no_return_value # function {0} does not always return a value
+duplicate_formal # duplicate formal argument {0}
-equal_as_assign # test for equality (==) mistyped as assignment (=)?{0}
+var_hides_arg # variable {0} hides argument
+redeclared_var # redeclaration of {0} {1}
-anon_no_return_value # anonymous function does not always return a value
+missing_semicolon # missing semicolon
+meaningless_block # meaningless block; curly braces have no impact
-comma_separated_stmts # multiple statements separated by commas (use semicolons?)
+unreachable_code # unreachable code
+missing_break # missing break statement
-missing_break_for_last_case # missing break statement for last case in switch
-comparison_type_conv # comparisons against null, 0, true, false, or an empty string allowing implicit type conversion (use === or !==)
-inc_dec_within_stmt # increment (++) and decrement (--) operators used as part of greater statement
-useless_void # use of the void type may be unnecessary (void is always undefined)
+multiple_plus_minus # unknown order of operations for successive plus (e.g. x+++y) or minus (e.g. x---y) signs
+use_of_label # use of label
-block_without_braces # block statement without curly braces
+leading_decimal_point # leading decimal point may indicate a number or an object member
+trailing_decimal_point # trailing decimal point may indicate a number or an object member
+octal_number # leading zeros make an octal number
+nested_comment # nested comment
+misplaced_regex # regular expressions should be preceded by a left parenthesis, assignment, colon, or comma
+ambiguous_newline # unexpected end of line; it is ambiguous whether these lines are part of the same statement
+empty_statement # empty statement or extra semicolon
-missing_option_explicit # the "option explicit" control comment is missing
+partial_option_explicit # the "option explicit" control comment, if used, must be in the first script tag
+dup_option_explicit # duplicate "option explicit" control comment
+useless_assign # useless assignment
+ambiguous_nested_stmt # block statements containing block statements should use curly braces to resolve ambiguity
+ambiguous_else_stmt # the else statement could be matched with one of multiple if statements (use curly braces to indicate intent)
-missing_default_case # missing default case in switch statement
+duplicate_case_in_switch # duplicate case in switch statements
+default_not_at_end # the default case is not at the end of the switch statement
+legacy_cc_not_understood # couldn't understand control comment using /*@keyword@*/ syntax
+jsl_cc_not_understood # couldn't understand control comment using /*jsl:keyword*/ syntax
+useless_comparison # useless comparison; comparing identical expressions
+with_statement # with statement hides undeclared variables; use temporary variable instead
+trailing_comma_in_array # extra comma is not recommended in array initializers
+assign_to_function_call # assignment to a function call
+parseint_missing_radix # parseInt missing radix parameter
+lambda_assign_requires_semicolon

View File

@ -0,0 +1,92 @@
// Generated by CoffeeScript 1.3.3
(function() {
var CoffeeScript, runScripts;
CoffeeScript = require('./coffee-script');
CoffeeScript.require = require;
CoffeeScript["eval"] = function(code, options) {
var _ref;
if (options == null) {
options = {};
}
if ((_ref = options.bare) == null) {
options.bare = true;
}
return eval(CoffeeScript.compile(code, options));
};
CoffeeScript.run = function(code, options) {
if (options == null) {
options = {};
}
options.bare = true;
return Function(CoffeeScript.compile(code, options))();
};
if (typeof window === "undefined" || window === null) {
return;
}
CoffeeScript.load = function(url, callback) {
var xhr;
xhr = new (window.ActiveXObject || XMLHttpRequest)('Microsoft.XMLHTTP');
xhr.open('GET', url, true);
if ('overrideMimeType' in xhr) {
xhr.overrideMimeType('text/plain');
}
xhr.onreadystatechange = function() {
var _ref;
if (xhr.readyState === 4) {
if ((_ref = xhr.status) === 0 || _ref === 200) {
CoffeeScript.run(xhr.responseText);
} else {
throw new Error("Could not load " + url);
}
if (callback) {
return callback();
}
}
};
return xhr.send(null);
};
runScripts = function() {
var coffees, execute, index, length, s, scripts;
scripts = document.getElementsByTagName('script');
coffees = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = scripts.length; _i < _len; _i++) {
s = scripts[_i];
if (s.type === 'text/coffeescript') {
_results.push(s);
}
}
return _results;
})();
index = 0;
length = coffees.length;
(execute = function() {
var script;
script = coffees[index++];
if ((script != null ? script.type : void 0) === 'text/coffeescript') {
if (script.src) {
return CoffeeScript.load(script.src, execute);
} else {
CoffeeScript.run(script.innerHTML);
return execute();
}
}
})();
return null;
};
if (window.addEventListener) {
addEventListener('DOMContentLoaded', runScripts, false);
} else {
attachEvent('onload', runScripts);
}
}).call(this);

View File

@ -0,0 +1,111 @@
// Generated by CoffeeScript 1.3.3
(function() {
var CoffeeScript, cakefileDirectory, fatalError, fs, helpers, missingTask, oparse, options, optparse, path, printTasks, switches, tasks;
fs = require('fs');
path = require('path');
helpers = require('./helpers');
optparse = require('./optparse');
CoffeeScript = require('./coffee-script');
tasks = {};
options = {};
switches = [];
oparse = null;
helpers.extend(global, {
task: function(name, description, action) {
var _ref;
if (!action) {
_ref = [description, action], action = _ref[0], description = _ref[1];
}
return tasks[name] = {
name: name,
description: description,
action: action
};
},
option: function(letter, flag, description) {
return switches.push([letter, flag, description]);
},
invoke: function(name) {
if (!tasks[name]) {
missingTask(name);
}
return tasks[name].action(options);
}
});
exports.run = function() {
var arg, args, _i, _len, _ref, _results;
global.__originalDirname = fs.realpathSync('.');
process.chdir(cakefileDirectory(__originalDirname));
args = process.argv.slice(2);
CoffeeScript.run(fs.readFileSync('Cakefile').toString(), {
filename: 'Cakefile'
});
oparse = new optparse.OptionParser(switches);
if (!args.length) {
return printTasks();
}
try {
options = oparse.parse(args);
} catch (e) {
return fatalError("" + e);
}
_ref = options["arguments"];
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
arg = _ref[_i];
_results.push(invoke(arg));
}
return _results;
};
printTasks = function() {
var cakefilePath, desc, name, relative, spaces, task;
relative = path.relative || path.resolve;
cakefilePath = path.join(relative(__originalDirname, process.cwd()), 'Cakefile');
console.log("" + cakefilePath + " defines the following tasks:\n");
for (name in tasks) {
task = tasks[name];
spaces = 20 - name.length;
spaces = spaces > 0 ? Array(spaces + 1).join(' ') : '';
desc = task.description ? "# " + task.description : '';
console.log("cake " + name + spaces + " " + desc);
}
if (switches.length) {
return console.log(oparse.help());
}
};
fatalError = function(message) {
console.error(message + '\n');
console.log('To see a list of all tasks/options, run "cake"');
return process.exit(1);
};
missingTask = function(task) {
return fatalError("No such task: " + task);
};
cakefileDirectory = function(dir) {
var parent;
if (path.existsSync(path.join(dir, 'Cakefile'))) {
return dir;
}
parent = path.normalize(path.join(dir, '..'));
if (parent !== dir) {
return cakefileDirectory(parent);
}
throw new Error("Cakefile not found in " + (process.cwd()));
};
}).call(this);

View File

@ -0,0 +1,167 @@
// Generated by CoffeeScript 1.3.3
(function() {
var Lexer, RESERVED, compile, fs, lexer, parser, path, vm, _ref,
__hasProp = {}.hasOwnProperty;
fs = require('fs');
path = require('path');
_ref = require('./lexer'), Lexer = _ref.Lexer, RESERVED = _ref.RESERVED;
parser = require('./parser').parser;
vm = require('vm');
if (require.extensions) {
require.extensions['.coffee'] = function(module, filename) {
var content;
content = compile(fs.readFileSync(filename, 'utf8'), {
filename: filename
});
return module._compile(content, filename);
};
} else if (require.registerExtension) {
require.registerExtension('.coffee', function(content) {
return compile(content);
});
}
exports.VERSION = '1.3.3';
exports.RESERVED = RESERVED;
exports.helpers = require('./helpers');
exports.compile = compile = function(code, options) {
var header, js, merge;
if (options == null) {
options = {};
}
merge = exports.helpers.merge;
try {
js = (parser.parse(lexer.tokenize(code))).compile(options);
if (!options.header) {
return js;
}
} catch (err) {
if (options.filename) {
err.message = "In " + options.filename + ", " + err.message;
}
throw err;
}
header = "Generated by CoffeeScript " + this.VERSION;
return "// " + header + "\n" + js;
};
exports.tokens = function(code, options) {
return lexer.tokenize(code, options);
};
exports.nodes = function(source, options) {
if (typeof source === 'string') {
return parser.parse(lexer.tokenize(source, options));
} else {
return parser.parse(source);
}
};
exports.run = function(code, options) {
var mainModule;
if (options == null) {
options = {};
}
mainModule = require.main;
mainModule.filename = process.argv[1] = options.filename ? fs.realpathSync(options.filename) : '.';
mainModule.moduleCache && (mainModule.moduleCache = {});
mainModule.paths = require('module')._nodeModulePaths(path.dirname(fs.realpathSync(options.filename)));
if (path.extname(mainModule.filename) !== '.coffee' || require.extensions) {
return mainModule._compile(compile(code, options), mainModule.filename);
} else {
return mainModule._compile(code, mainModule.filename);
}
};
exports["eval"] = function(code, options) {
var Module, Script, js, k, o, r, sandbox, v, _i, _len, _module, _ref1, _ref2, _require;
if (options == null) {
options = {};
}
if (!(code = code.trim())) {
return;
}
Script = vm.Script;
if (Script) {
if (options.sandbox != null) {
if (options.sandbox instanceof Script.createContext().constructor) {
sandbox = options.sandbox;
} else {
sandbox = Script.createContext();
_ref1 = options.sandbox;
for (k in _ref1) {
if (!__hasProp.call(_ref1, k)) continue;
v = _ref1[k];
sandbox[k] = v;
}
}
sandbox.global = sandbox.root = sandbox.GLOBAL = sandbox;
} else {
sandbox = global;
}
sandbox.__filename = options.filename || 'eval';
sandbox.__dirname = path.dirname(sandbox.__filename);
if (!(sandbox !== global || sandbox.module || sandbox.require)) {
Module = require('module');
sandbox.module = _module = new Module(options.modulename || 'eval');
sandbox.require = _require = function(path) {
return Module._load(path, _module, true);
};
_module.filename = sandbox.__filename;
_ref2 = Object.getOwnPropertyNames(require);
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
r = _ref2[_i];
if (r !== 'paths') {
_require[r] = require[r];
}
}
_require.paths = _module.paths = Module._nodeModulePaths(process.cwd());
_require.resolve = function(request) {
return Module._resolveFilename(request, _module);
};
}
}
o = {};
for (k in options) {
if (!__hasProp.call(options, k)) continue;
v = options[k];
o[k] = v;
}
o.bare = true;
js = compile(code, o);
if (sandbox === global) {
return vm.runInThisContext(js);
} else {
return vm.runInContext(js, sandbox);
}
};
lexer = new Lexer;
parser.lexer = {
lex: function() {
var tag, _ref1;
_ref1 = this.tokens[this.pos++] || [''], tag = _ref1[0], this.yytext = _ref1[1], this.yylineno = _ref1[2];
return tag;
},
setInput: function(tokens) {
this.tokens = tokens;
return this.pos = 0;
},
upcomingInput: function() {
return "";
}
};
parser.yy = require('./nodes');
}).call(this);

View File

@ -0,0 +1,500 @@
// Generated by CoffeeScript 1.3.3
(function() {
var BANNER, CoffeeScript, EventEmitter, SWITCHES, compileJoin, compileOptions, compilePath, compileScript, compileStdio, exec, forkNode, fs, helpers, hidden, joinTimeout, lint, loadRequires, notSources, optionParser, optparse, opts, outputPath, parseOptions, path, printLine, printTokens, printWarn, removeSource, sourceCode, sources, spawn, timeLog, unwatchDir, usage, version, wait, watch, watchDir, watchers, writeJs, _ref;
fs = require('fs');
path = require('path');
helpers = require('./helpers');
optparse = require('./optparse');
CoffeeScript = require('./coffee-script');
_ref = require('child_process'), spawn = _ref.spawn, exec = _ref.exec;
EventEmitter = require('events').EventEmitter;
helpers.extend(CoffeeScript, new EventEmitter);
printLine = function(line) {
return process.stdout.write(line + '\n');
};
printWarn = function(line) {
return process.stderr.write(line + '\n');
};
hidden = function(file) {
return /^\.|~$/.test(file);
};
BANNER = 'Usage: coffee [options] path/to/script.coffee -- [args]\n\nIf called without options, `coffee` will run your script.';
SWITCHES = [['-b', '--bare', 'compile without a top-level function wrapper'], ['-c', '--compile', 'compile to JavaScript and save as .js files'], ['-e', '--eval', 'pass a string from the command line as input'], ['-h', '--help', 'display this help message'], ['-i', '--interactive', 'run an interactive CoffeeScript REPL'], ['-j', '--join [FILE]', 'concatenate the source CoffeeScript before compiling'], ['-l', '--lint', 'pipe the compiled JavaScript through JavaScript Lint'], ['-n', '--nodes', 'print out the parse tree that the parser produces'], ['--nodejs [ARGS]', 'pass options directly to the "node" binary'], ['-o', '--output [DIR]', 'set the output directory for compiled JavaScript'], ['-p', '--print', 'print out the compiled JavaScript'], ['-r', '--require [FILE*]', 'require a library before executing your script'], ['-s', '--stdio', 'listen for and compile scripts over stdio'], ['-t', '--tokens', 'print out the tokens that the lexer/rewriter produce'], ['-v', '--version', 'display the version number'], ['-w', '--watch', 'watch scripts for changes and rerun commands']];
opts = {};
sources = [];
sourceCode = [];
notSources = {};
watchers = {};
optionParser = null;
exports.run = function() {
var literals, source, _i, _len, _results;
parseOptions();
if (opts.nodejs) {
return forkNode();
}
if (opts.help) {
return usage();
}
if (opts.version) {
return version();
}
if (opts.require) {
loadRequires();
}
if (opts.interactive) {
return require('./repl');
}
if (opts.watch && !fs.watch) {
return printWarn("The --watch feature depends on Node v0.6.0+. You are running " + process.version + ".");
}
if (opts.stdio) {
return compileStdio();
}
if (opts["eval"]) {
return compileScript(null, sources[0]);
}
if (!sources.length) {
return require('./repl');
}
literals = opts.run ? sources.splice(1) : [];
process.argv = process.argv.slice(0, 2).concat(literals);
process.argv[0] = 'coffee';
process.execPath = require.main.filename;
_results = [];
for (_i = 0, _len = sources.length; _i < _len; _i++) {
source = sources[_i];
_results.push(compilePath(source, true, path.normalize(source)));
}
return _results;
};
compilePath = function(source, topLevel, base) {
return fs.stat(source, function(err, stats) {
if (err && err.code !== 'ENOENT') {
throw err;
}
if ((err != null ? err.code : void 0) === 'ENOENT') {
if (topLevel && source.slice(-7) !== '.coffee') {
source = sources[sources.indexOf(source)] = "" + source + ".coffee";
return compilePath(source, topLevel, base);
}
if (topLevel) {
console.error("File not found: " + source);
process.exit(1);
}
return;
}
if (stats.isDirectory()) {
if (opts.watch) {
watchDir(source, base);
}
return fs.readdir(source, function(err, files) {
var file, index, _ref1, _ref2;
if (err && err.code !== 'ENOENT') {
throw err;
}
if ((err != null ? err.code : void 0) === 'ENOENT') {
return;
}
index = sources.indexOf(source);
files = files.filter(function(file) {
return !hidden(file);
});
[].splice.apply(sources, [index, index - index + 1].concat(_ref1 = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = files.length; _i < _len; _i++) {
file = files[_i];
_results.push(path.join(source, file));
}
return _results;
})())), _ref1;
[].splice.apply(sourceCode, [index, index - index + 1].concat(_ref2 = files.map(function() {
return null;
}))), _ref2;
return files.forEach(function(file) {
return compilePath(path.join(source, file), false, base);
});
});
} else if (topLevel || path.extname(source) === '.coffee') {
if (opts.watch) {
watch(source, base);
}
return fs.readFile(source, function(err, code) {
if (err && err.code !== 'ENOENT') {
throw err;
}
if ((err != null ? err.code : void 0) === 'ENOENT') {
return;
}
return compileScript(source, code.toString(), base);
});
} else {
notSources[source] = true;
return removeSource(source, base);
}
});
};
compileScript = function(file, input, base) {
var o, options, t, task;
o = opts;
options = compileOptions(file);
try {
t = task = {
file: file,
input: input,
options: options
};
CoffeeScript.emit('compile', task);
if (o.tokens) {
return printTokens(CoffeeScript.tokens(t.input));
} else if (o.nodes) {
return printLine(CoffeeScript.nodes(t.input).toString().trim());
} else if (o.run) {
return CoffeeScript.run(t.input, t.options);
} else if (o.join && t.file !== o.join) {
sourceCode[sources.indexOf(t.file)] = t.input;
return compileJoin();
} else {
t.output = CoffeeScript.compile(t.input, t.options);
CoffeeScript.emit('success', task);
if (o.print) {
return printLine(t.output.trim());
} else if (o.compile) {
return writeJs(t.file, t.output, base);
} else if (o.lint) {
return lint(t.file, t.output);
}
}
} catch (err) {
CoffeeScript.emit('failure', err, task);
if (CoffeeScript.listeners('failure').length) {
return;
}
if (o.watch) {
return printLine(err.message + '\x07');
}
printWarn(err instanceof Error && err.stack || ("ERROR: " + err));
return process.exit(1);
}
};
compileStdio = function() {
var code, stdin;
code = '';
stdin = process.openStdin();
stdin.on('data', function(buffer) {
if (buffer) {
return code += buffer.toString();
}
});
return stdin.on('end', function() {
return compileScript(null, code);
});
};
joinTimeout = null;
compileJoin = function() {
if (!opts.join) {
return;
}
if (!sourceCode.some(function(code) {
return code === null;
})) {
clearTimeout(joinTimeout);
return joinTimeout = wait(100, function() {
return compileScript(opts.join, sourceCode.join('\n'), opts.join);
});
}
};
loadRequires = function() {
var realFilename, req, _i, _len, _ref1;
realFilename = module.filename;
module.filename = '.';
_ref1 = opts.require;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
req = _ref1[_i];
require(req);
}
return module.filename = realFilename;
};
watch = function(source, base) {
var compile, compileTimeout, prevStats, rewatch, watchErr, watcher;
prevStats = null;
compileTimeout = null;
watchErr = function(e) {
if (e.code === 'ENOENT') {
if (sources.indexOf(source) === -1) {
return;
}
try {
rewatch();
return compile();
} catch (e) {
removeSource(source, base, true);
return compileJoin();
}
} else {
throw e;
}
};
compile = function() {
clearTimeout(compileTimeout);
return compileTimeout = wait(25, function() {
return fs.stat(source, function(err, stats) {
if (err) {
return watchErr(err);
}
if (prevStats && stats.size === prevStats.size && stats.mtime.getTime() === prevStats.mtime.getTime()) {
return rewatch();
}
prevStats = stats;
return fs.readFile(source, function(err, code) {
if (err) {
return watchErr(err);
}
compileScript(source, code.toString(), base);
return rewatch();
});
});
});
};
try {
watcher = fs.watch(source, compile);
} catch (e) {
watchErr(e);
}
return rewatch = function() {
if (watcher != null) {
watcher.close();
}
return watcher = fs.watch(source, compile);
};
};
watchDir = function(source, base) {
var readdirTimeout, watcher;
readdirTimeout = null;
try {
return watcher = fs.watch(source, function() {
clearTimeout(readdirTimeout);
return readdirTimeout = wait(25, function() {
return fs.readdir(source, function(err, files) {
var file, _i, _len, _results;
if (err) {
if (err.code !== 'ENOENT') {
throw err;
}
watcher.close();
return unwatchDir(source, base);
}
_results = [];
for (_i = 0, _len = files.length; _i < _len; _i++) {
file = files[_i];
if (!(!hidden(file) && !notSources[file])) {
continue;
}
file = path.join(source, file);
if (sources.some(function(s) {
return s.indexOf(file) >= 0;
})) {
continue;
}
sources.push(file);
sourceCode.push(null);
_results.push(compilePath(file, false, base));
}
return _results;
});
});
});
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
}
};
unwatchDir = function(source, base) {
var file, prevSources, toRemove, _i, _len;
prevSources = sources.slice(0);
toRemove = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = sources.length; _i < _len; _i++) {
file = sources[_i];
if (file.indexOf(source) >= 0) {
_results.push(file);
}
}
return _results;
})();
for (_i = 0, _len = toRemove.length; _i < _len; _i++) {
file = toRemove[_i];
removeSource(file, base, true);
}
if (!sources.some(function(s, i) {
return prevSources[i] !== s;
})) {
return;
}
return compileJoin();
};
removeSource = function(source, base, removeJs) {
var index, jsPath;
index = sources.indexOf(source);
sources.splice(index, 1);
sourceCode.splice(index, 1);
if (removeJs && !opts.join) {
jsPath = outputPath(source, base);
return path.exists(jsPath, function(exists) {
if (exists) {
return fs.unlink(jsPath, function(err) {
if (err && err.code !== 'ENOENT') {
throw err;
}
return timeLog("removed " + source);
});
}
});
}
};
outputPath = function(source, base) {
var baseDir, dir, filename, srcDir;
filename = path.basename(source, path.extname(source)) + '.js';
srcDir = path.dirname(source);
baseDir = base === '.' ? srcDir : srcDir.substring(base.length);
dir = opts.output ? path.join(opts.output, baseDir) : srcDir;
return path.join(dir, filename);
};
writeJs = function(source, js, base) {
var compile, jsDir, jsPath;
jsPath = outputPath(source, base);
jsDir = path.dirname(jsPath);
compile = function() {
if (js.length <= 0) {
js = ' ';
}
return fs.writeFile(jsPath, js, function(err) {
if (err) {
return printLine(err.message);
} else if (opts.compile && opts.watch) {
return timeLog("compiled " + source);
}
});
};
return path.exists(jsDir, function(exists) {
if (exists) {
return compile();
} else {
return exec("mkdir -p " + jsDir, compile);
}
});
};
wait = function(milliseconds, func) {
return setTimeout(func, milliseconds);
};
timeLog = function(message) {
return console.log("" + ((new Date).toLocaleTimeString()) + " - " + message);
};
lint = function(file, js) {
var conf, jsl, printIt;
printIt = function(buffer) {
return printLine(file + ':\t' + buffer.toString().trim());
};
conf = __dirname + '/../../extras/jsl.conf';
jsl = spawn('jsl', ['-nologo', '-stdin', '-conf', conf]);
jsl.stdout.on('data', printIt);
jsl.stderr.on('data', printIt);
jsl.stdin.write(js);
return jsl.stdin.end();
};
printTokens = function(tokens) {
var strings, tag, token, value;
strings = (function() {
var _i, _len, _ref1, _results;
_results = [];
for (_i = 0, _len = tokens.length; _i < _len; _i++) {
token = tokens[_i];
_ref1 = [token[0], token[1].toString().replace(/\n/, '\\n')], tag = _ref1[0], value = _ref1[1];
_results.push("[" + tag + " " + value + "]");
}
return _results;
})();
return printLine(strings.join(' '));
};
parseOptions = function() {
var i, o, source, _i, _len;
optionParser = new optparse.OptionParser(SWITCHES, BANNER);
o = opts = optionParser.parse(process.argv.slice(2));
o.compile || (o.compile = !!o.output);
o.run = !(o.compile || o.print || o.lint);
o.print = !!(o.print || (o["eval"] || o.stdio && o.compile));
sources = o["arguments"];
for (i = _i = 0, _len = sources.length; _i < _len; i = ++_i) {
source = sources[i];
sourceCode[i] = null;
}
};
compileOptions = function(filename) {
return {
filename: filename,
bare: opts.bare,
header: opts.compile
};
};
forkNode = function() {
var args, nodeArgs;
nodeArgs = opts.nodejs.split(/\s+/);
args = process.argv.slice(1);
args.splice(args.indexOf('--nodejs'), 2);
return spawn(process.execPath, nodeArgs.concat(args), {
cwd: process.cwd(),
env: process.env,
customFds: [0, 1, 2]
});
};
usage = function() {
return printLine((new optparse.OptionParser(SWITCHES, BANNER)).help());
};
version = function() {
return printLine("CoffeeScript version " + CoffeeScript.VERSION);
};
}).call(this);

View File

@ -0,0 +1,606 @@
// Generated by CoffeeScript 1.3.3
(function() {
var Parser, alt, alternatives, grammar, name, o, operators, token, tokens, unwrap;
Parser = require('jison').Parser;
unwrap = /^function\s*\(\)\s*\{\s*return\s*([\s\S]*);\s*\}/;
o = function(patternString, action, options) {
var match;
patternString = patternString.replace(/\s{2,}/g, ' ');
if (!action) {
return [patternString, '$$ = $1;', options];
}
action = (match = unwrap.exec(action)) ? match[1] : "(" + action + "())";
action = action.replace(/\bnew /g, '$&yy.');
action = action.replace(/\b(?:Block\.wrap|extend)\b/g, 'yy.$&');
return [patternString, "$$ = " + action + ";", options];
};
grammar = {
Root: [
o('', function() {
return new Block;
}), o('Body'), o('Block TERMINATOR')
],
Body: [
o('Line', function() {
return Block.wrap([$1]);
}), o('Body TERMINATOR Line', function() {
return $1.push($3);
}), o('Body TERMINATOR')
],
Line: [o('Expression'), o('Statement')],
Statement: [
o('Return'), o('Comment'), o('STATEMENT', function() {
return new Literal($1);
})
],
Expression: [o('Value'), o('Invocation'), o('Code'), o('Operation'), o('Assign'), o('If'), o('Try'), o('While'), o('For'), o('Switch'), o('Class'), o('Throw')],
Block: [
o('INDENT OUTDENT', function() {
return new Block;
}), o('INDENT Body OUTDENT', function() {
return $2;
})
],
Identifier: [
o('IDENTIFIER', function() {
return new Literal($1);
})
],
AlphaNumeric: [
o('NUMBER', function() {
return new Literal($1);
}), o('STRING', function() {
return new Literal($1);
})
],
Literal: [
o('AlphaNumeric'), o('JS', function() {
return new Literal($1);
}), o('REGEX', function() {
return new Literal($1);
}), o('DEBUGGER', function() {
return new Literal($1);
}), o('UNDEFINED', function() {
return new Undefined;
}), o('NULL', function() {
return new Null;
}), o('BOOL', function() {
return new Bool($1);
})
],
Assign: [
o('Assignable = Expression', function() {
return new Assign($1, $3);
}), o('Assignable = TERMINATOR Expression', function() {
return new Assign($1, $4);
}), o('Assignable = INDENT Expression OUTDENT', function() {
return new Assign($1, $4);
})
],
AssignObj: [
o('ObjAssignable', function() {
return new Value($1);
}), o('ObjAssignable : Expression', function() {
return new Assign(new Value($1), $3, 'object');
}), o('ObjAssignable :\
INDENT Expression OUTDENT', function() {
return new Assign(new Value($1), $4, 'object');
}), o('Comment')
],
ObjAssignable: [o('Identifier'), o('AlphaNumeric'), o('ThisProperty')],
Return: [
o('RETURN Expression', function() {
return new Return($2);
}), o('RETURN', function() {
return new Return;
})
],
Comment: [
o('HERECOMMENT', function() {
return new Comment($1);
})
],
Code: [
o('PARAM_START ParamList PARAM_END FuncGlyph Block', function() {
return new Code($2, $5, $4);
}), o('FuncGlyph Block', function() {
return new Code([], $2, $1);
})
],
FuncGlyph: [
o('->', function() {
return 'func';
}), o('=>', function() {
return 'boundfunc';
})
],
OptComma: [o(''), o(',')],
ParamList: [
o('', function() {
return [];
}), o('Param', function() {
return [$1];
}), o('ParamList , Param', function() {
return $1.concat($3);
}), o('ParamList OptComma TERMINATOR Param', function() {
return $1.concat($4);
}), o('ParamList OptComma INDENT ParamList OptComma OUTDENT', function() {
return $1.concat($4);
})
],
Param: [
o('ParamVar', function() {
return new Param($1);
}), o('ParamVar ...', function() {
return new Param($1, null, true);
}), o('ParamVar = Expression', function() {
return new Param($1, $3);
})
],
ParamVar: [o('Identifier'), o('ThisProperty'), o('Array'), o('Object')],
Splat: [
o('Expression ...', function() {
return new Splat($1);
})
],
SimpleAssignable: [
o('Identifier', function() {
return new Value($1);
}), o('Value Accessor', function() {
return $1.add($2);
}), o('Invocation Accessor', function() {
return new Value($1, [].concat($2));
}), o('ThisProperty')
],
Assignable: [
o('SimpleAssignable'), o('Array', function() {
return new Value($1);
}), o('Object', function() {
return new Value($1);
})
],
Value: [
o('Assignable'), o('Literal', function() {
return new Value($1);
}), o('Parenthetical', function() {
return new Value($1);
}), o('Range', function() {
return new Value($1);
}), o('This')
],
Accessor: [
o('. Identifier', function() {
return new Access($2);
}), o('?. Identifier', function() {
return new Access($2, 'soak');
}), o(':: Identifier', function() {
return [new Access(new Literal('prototype')), new Access($2)];
}), o('::', function() {
return new Access(new Literal('prototype'));
}), o('Index')
],
Index: [
o('INDEX_START IndexValue INDEX_END', function() {
return $2;
}), o('INDEX_SOAK Index', function() {
return extend($2, {
soak: true
});
})
],
IndexValue: [
o('Expression', function() {
return new Index($1);
}), o('Slice', function() {
return new Slice($1);
})
],
Object: [
o('{ AssignList OptComma }', function() {
return new Obj($2, $1.generated);
})
],
AssignList: [
o('', function() {
return [];
}), o('AssignObj', function() {
return [$1];
}), o('AssignList , AssignObj', function() {
return $1.concat($3);
}), o('AssignList OptComma TERMINATOR AssignObj', function() {
return $1.concat($4);
}), o('AssignList OptComma INDENT AssignList OptComma OUTDENT', function() {
return $1.concat($4);
})
],
Class: [
o('CLASS', function() {
return new Class;
}), o('CLASS Block', function() {
return new Class(null, null, $2);
}), o('CLASS EXTENDS Expression', function() {
return new Class(null, $3);
}), o('CLASS EXTENDS Expression Block', function() {
return new Class(null, $3, $4);
}), o('CLASS SimpleAssignable', function() {
return new Class($2);
}), o('CLASS SimpleAssignable Block', function() {
return new Class($2, null, $3);
}), o('CLASS SimpleAssignable EXTENDS Expression', function() {
return new Class($2, $4);
}), o('CLASS SimpleAssignable EXTENDS Expression Block', function() {
return new Class($2, $4, $5);
})
],
Invocation: [
o('Value OptFuncExist Arguments', function() {
return new Call($1, $3, $2);
}), o('Invocation OptFuncExist Arguments', function() {
return new Call($1, $3, $2);
}), o('SUPER', function() {
return new Call('super', [new Splat(new Literal('arguments'))]);
}), o('SUPER Arguments', function() {
return new Call('super', $2);
})
],
OptFuncExist: [
o('', function() {
return false;
}), o('FUNC_EXIST', function() {
return true;
})
],
Arguments: [
o('CALL_START CALL_END', function() {
return [];
}), o('CALL_START ArgList OptComma CALL_END', function() {
return $2;
})
],
This: [
o('THIS', function() {
return new Value(new Literal('this'));
}), o('@', function() {
return new Value(new Literal('this'));
})
],
ThisProperty: [
o('@ Identifier', function() {
return new Value(new Literal('this'), [new Access($2)], 'this');
})
],
Array: [
o('[ ]', function() {
return new Arr([]);
}), o('[ ArgList OptComma ]', function() {
return new Arr($2);
})
],
RangeDots: [
o('..', function() {
return 'inclusive';
}), o('...', function() {
return 'exclusive';
})
],
Range: [
o('[ Expression RangeDots Expression ]', function() {
return new Range($2, $4, $3);
})
],
Slice: [
o('Expression RangeDots Expression', function() {
return new Range($1, $3, $2);
}), o('Expression RangeDots', function() {
return new Range($1, null, $2);
}), o('RangeDots Expression', function() {
return new Range(null, $2, $1);
}), o('RangeDots', function() {
return new Range(null, null, $1);
})
],
ArgList: [
o('Arg', function() {
return [$1];
}), o('ArgList , Arg', function() {
return $1.concat($3);
}), o('ArgList OptComma TERMINATOR Arg', function() {
return $1.concat($4);
}), o('INDENT ArgList OptComma OUTDENT', function() {
return $2;
}), o('ArgList OptComma INDENT ArgList OptComma OUTDENT', function() {
return $1.concat($4);
})
],
Arg: [o('Expression'), o('Splat')],
SimpleArgs: [
o('Expression'), o('SimpleArgs , Expression', function() {
return [].concat($1, $3);
})
],
Try: [
o('TRY Block', function() {
return new Try($2);
}), o('TRY Block Catch', function() {
return new Try($2, $3[0], $3[1]);
}), o('TRY Block FINALLY Block', function() {
return new Try($2, null, null, $4);
}), o('TRY Block Catch FINALLY Block', function() {
return new Try($2, $3[0], $3[1], $5);
})
],
Catch: [
o('CATCH Identifier Block', function() {
return [$2, $3];
})
],
Throw: [
o('THROW Expression', function() {
return new Throw($2);
})
],
Parenthetical: [
o('( Body )', function() {
return new Parens($2);
}), o('( INDENT Body OUTDENT )', function() {
return new Parens($3);
})
],
WhileSource: [
o('WHILE Expression', function() {
return new While($2);
}), o('WHILE Expression WHEN Expression', function() {
return new While($2, {
guard: $4
});
}), o('UNTIL Expression', function() {
return new While($2, {
invert: true
});
}), o('UNTIL Expression WHEN Expression', function() {
return new While($2, {
invert: true,
guard: $4
});
})
],
While: [
o('WhileSource Block', function() {
return $1.addBody($2);
}), o('Statement WhileSource', function() {
return $2.addBody(Block.wrap([$1]));
}), o('Expression WhileSource', function() {
return $2.addBody(Block.wrap([$1]));
}), o('Loop', function() {
return $1;
})
],
Loop: [
o('LOOP Block', function() {
return new While(new Literal('true')).addBody($2);
}), o('LOOP Expression', function() {
return new While(new Literal('true')).addBody(Block.wrap([$2]));
})
],
For: [
o('Statement ForBody', function() {
return new For($1, $2);
}), o('Expression ForBody', function() {
return new For($1, $2);
}), o('ForBody Block', function() {
return new For($2, $1);
})
],
ForBody: [
o('FOR Range', function() {
return {
source: new Value($2)
};
}), o('ForStart ForSource', function() {
$2.own = $1.own;
$2.name = $1[0];
$2.index = $1[1];
return $2;
})
],
ForStart: [
o('FOR ForVariables', function() {
return $2;
}), o('FOR OWN ForVariables', function() {
$3.own = true;
return $3;
})
],
ForValue: [
o('Identifier'), o('ThisProperty'), o('Array', function() {
return new Value($1);
}), o('Object', function() {
return new Value($1);
})
],
ForVariables: [
o('ForValue', function() {
return [$1];
}), o('ForValue , ForValue', function() {
return [$1, $3];
})
],
ForSource: [
o('FORIN Expression', function() {
return {
source: $2
};
}), o('FOROF Expression', function() {
return {
source: $2,
object: true
};
}), o('FORIN Expression WHEN Expression', function() {
return {
source: $2,
guard: $4
};
}), o('FOROF Expression WHEN Expression', function() {
return {
source: $2,
guard: $4,
object: true
};
}), o('FORIN Expression BY Expression', function() {
return {
source: $2,
step: $4
};
}), o('FORIN Expression WHEN Expression BY Expression', function() {
return {
source: $2,
guard: $4,
step: $6
};
}), o('FORIN Expression BY Expression WHEN Expression', function() {
return {
source: $2,
step: $4,
guard: $6
};
})
],
Switch: [
o('SWITCH Expression INDENT Whens OUTDENT', function() {
return new Switch($2, $4);
}), o('SWITCH Expression INDENT Whens ELSE Block OUTDENT', function() {
return new Switch($2, $4, $6);
}), o('SWITCH INDENT Whens OUTDENT', function() {
return new Switch(null, $3);
}), o('SWITCH INDENT Whens ELSE Block OUTDENT', function() {
return new Switch(null, $3, $5);
})
],
Whens: [
o('When'), o('Whens When', function() {
return $1.concat($2);
})
],
When: [
o('LEADING_WHEN SimpleArgs Block', function() {
return [[$2, $3]];
}), o('LEADING_WHEN SimpleArgs Block TERMINATOR', function() {
return [[$2, $3]];
})
],
IfBlock: [
o('IF Expression Block', function() {
return new If($2, $3, {
type: $1
});
}), o('IfBlock ELSE IF Expression Block', function() {
return $1.addElse(new If($4, $5, {
type: $3
}));
})
],
If: [
o('IfBlock'), o('IfBlock ELSE Block', function() {
return $1.addElse($3);
}), o('Statement POST_IF Expression', function() {
return new If($3, Block.wrap([$1]), {
type: $2,
statement: true
});
}), o('Expression POST_IF Expression', function() {
return new If($3, Block.wrap([$1]), {
type: $2,
statement: true
});
})
],
Operation: [
o('UNARY Expression', function() {
return new Op($1, $2);
}), o('- Expression', (function() {
return new Op('-', $2);
}), {
prec: 'UNARY'
}), o('+ Expression', (function() {
return new Op('+', $2);
}), {
prec: 'UNARY'
}), o('-- SimpleAssignable', function() {
return new Op('--', $2);
}), o('++ SimpleAssignable', function() {
return new Op('++', $2);
}), o('SimpleAssignable --', function() {
return new Op('--', $1, null, true);
}), o('SimpleAssignable ++', function() {
return new Op('++', $1, null, true);
}), o('Expression ?', function() {
return new Existence($1);
}), o('Expression + Expression', function() {
return new Op('+', $1, $3);
}), o('Expression - Expression', function() {
return new Op('-', $1, $3);
}), o('Expression MATH Expression', function() {
return new Op($2, $1, $3);
}), o('Expression SHIFT Expression', function() {
return new Op($2, $1, $3);
}), o('Expression COMPARE Expression', function() {
return new Op($2, $1, $3);
}), o('Expression LOGIC Expression', function() {
return new Op($2, $1, $3);
}), o('Expression RELATION Expression', function() {
if ($2.charAt(0) === '!') {
return new Op($2.slice(1), $1, $3).invert();
} else {
return new Op($2, $1, $3);
}
}), o('SimpleAssignable COMPOUND_ASSIGN\
Expression', function() {
return new Assign($1, $3, $2);
}), o('SimpleAssignable COMPOUND_ASSIGN\
INDENT Expression OUTDENT', function() {
return new Assign($1, $4, $2);
}), o('SimpleAssignable EXTENDS Expression', function() {
return new Extends($1, $3);
})
]
};
operators = [['left', '.', '?.', '::'], ['left', 'CALL_START', 'CALL_END'], ['nonassoc', '++', '--'], ['left', '?'], ['right', 'UNARY'], ['left', 'MATH'], ['left', '+', '-'], ['left', 'SHIFT'], ['left', 'RELATION'], ['left', 'COMPARE'], ['left', 'LOGIC'], ['nonassoc', 'INDENT', 'OUTDENT'], ['right', '=', ':', 'COMPOUND_ASSIGN', 'RETURN', 'THROW', 'EXTENDS'], ['right', 'FORIN', 'FOROF', 'BY', 'WHEN'], ['right', 'IF', 'ELSE', 'FOR', 'WHILE', 'UNTIL', 'LOOP', 'SUPER', 'CLASS'], ['right', 'POST_IF']];
tokens = [];
for (name in grammar) {
alternatives = grammar[name];
grammar[name] = (function() {
var _i, _j, _len, _len1, _ref, _results;
_results = [];
for (_i = 0, _len = alternatives.length; _i < _len; _i++) {
alt = alternatives[_i];
_ref = alt[0].split(' ');
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
token = _ref[_j];
if (!grammar[token]) {
tokens.push(token);
}
}
if (name === 'Root') {
alt[1] = "return " + alt[1];
}
_results.push(alt);
}
return _results;
})();
}
exports.parser = new Parser({
tokens: tokens.join(' '),
bnf: grammar,
operators: operators.reverse(),
startSymbol: 'Root'
});
}).call(this);

View File

@ -0,0 +1,77 @@
// Generated by CoffeeScript 1.3.3
(function() {
var extend, flatten;
exports.starts = function(string, literal, start) {
return literal === string.substr(start, literal.length);
};
exports.ends = function(string, literal, back) {
var len;
len = literal.length;
return literal === string.substr(string.length - len - (back || 0), len);
};
exports.compact = function(array) {
var item, _i, _len, _results;
_results = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
item = array[_i];
if (item) {
_results.push(item);
}
}
return _results;
};
exports.count = function(string, substr) {
var num, pos;
num = pos = 0;
if (!substr.length) {
return 1 / 0;
}
while (pos = 1 + string.indexOf(substr, pos)) {
num++;
}
return num;
};
exports.merge = function(options, overrides) {
return extend(extend({}, options), overrides);
};
extend = exports.extend = function(object, properties) {
var key, val;
for (key in properties) {
val = properties[key];
object[key] = val;
}
return object;
};
exports.flatten = flatten = function(array) {
var element, flattened, _i, _len;
flattened = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
element = array[_i];
if (element instanceof Array) {
flattened = flattened.concat(flatten(element));
} else {
flattened.push(element);
}
}
return flattened;
};
exports.del = function(obj, key) {
var val;
val = obj[key];
delete obj[key];
return val;
};
exports.last = function(array, back) {
return array[array.length - (back || 0) - 1];
};
}).call(this);

View File

@ -0,0 +1,11 @@
// Generated by CoffeeScript 1.3.3
(function() {
var key, val, _ref;
_ref = require('./coffee-script');
for (key in _ref) {
val = _ref[key];
exports[key] = val;
}
}).call(this);

View File

@ -0,0 +1,788 @@
// Generated by CoffeeScript 1.3.3
(function() {
var BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, HEREDOC, HEREDOC_ILLEGAL, HEREDOC_INDENT, HEREGEX, HEREGEX_OMIT, IDENTIFIER, INDEXABLE, INVERSES, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LINE_BREAK, LINE_CONTINUER, LOGIC, Lexer, MATH, MULTILINER, MULTI_DENT, NOT_REGEX, NOT_SPACED_REGEX, NUMBER, OPERATOR, REGEX, RELATION, RESERVED, Rewriter, SHIFT, SIMPLESTR, STRICT_PROSCRIBED, TRAILING_SPACES, UNARY, WHITESPACE, compact, count, key, last, starts, _ref, _ref1,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
_ref = require('./rewriter'), Rewriter = _ref.Rewriter, INVERSES = _ref.INVERSES;
_ref1 = require('./helpers'), count = _ref1.count, starts = _ref1.starts, compact = _ref1.compact, last = _ref1.last;
exports.Lexer = Lexer = (function() {
function Lexer() {}
Lexer.prototype.tokenize = function(code, opts) {
var i, tag;
if (opts == null) {
opts = {};
}
if (WHITESPACE.test(code)) {
code = "\n" + code;
}
code = code.replace(/\r/g, '').replace(TRAILING_SPACES, '');
this.code = code;
this.line = opts.line || 0;
this.indent = 0;
this.indebt = 0;
this.outdebt = 0;
this.indents = [];
this.ends = [];
this.tokens = [];
i = 0;
while (this.chunk = code.slice(i)) {
i += this.identifierToken() || this.commentToken() || this.whitespaceToken() || this.lineToken() || this.heredocToken() || this.stringToken() || this.numberToken() || this.regexToken() || this.jsToken() || this.literalToken();
}
this.closeIndentation();
if (tag = this.ends.pop()) {
this.error("missing " + tag);
}
if (opts.rewrite === false) {
return this.tokens;
}
return (new Rewriter).rewrite(this.tokens);
};
Lexer.prototype.identifierToken = function() {
var colon, forcedIdentifier, id, input, match, prev, tag, _ref2, _ref3;
if (!(match = IDENTIFIER.exec(this.chunk))) {
return 0;
}
input = match[0], id = match[1], colon = match[2];
if (id === 'own' && this.tag() === 'FOR') {
this.token('OWN', id);
return id.length;
}
forcedIdentifier = colon || (prev = last(this.tokens)) && (((_ref2 = prev[0]) === '.' || _ref2 === '?.' || _ref2 === '::') || !prev.spaced && prev[0] === '@');
tag = 'IDENTIFIER';
if (!forcedIdentifier && (__indexOf.call(JS_KEYWORDS, id) >= 0 || __indexOf.call(COFFEE_KEYWORDS, id) >= 0)) {
tag = id.toUpperCase();
if (tag === 'WHEN' && (_ref3 = this.tag(), __indexOf.call(LINE_BREAK, _ref3) >= 0)) {
tag = 'LEADING_WHEN';
} else if (tag === 'FOR') {
this.seenFor = true;
} else if (tag === 'UNLESS') {
tag = 'IF';
} else if (__indexOf.call(UNARY, tag) >= 0) {
tag = 'UNARY';
} else if (__indexOf.call(RELATION, tag) >= 0) {
if (tag !== 'INSTANCEOF' && this.seenFor) {
tag = 'FOR' + tag;
this.seenFor = false;
} else {
tag = 'RELATION';
if (this.value() === '!') {
this.tokens.pop();
id = '!' + id;
}
}
}
}
if (__indexOf.call(JS_FORBIDDEN, id) >= 0) {
if (forcedIdentifier) {
tag = 'IDENTIFIER';
id = new String(id);
id.reserved = true;
} else if (__indexOf.call(RESERVED, id) >= 0) {
this.error("reserved word \"" + id + "\"");
}
}
if (!forcedIdentifier) {
if (__indexOf.call(COFFEE_ALIASES, id) >= 0) {
id = COFFEE_ALIAS_MAP[id];
}
tag = (function() {
switch (id) {
case '!':
return 'UNARY';
case '==':
case '!=':
return 'COMPARE';
case '&&':
case '||':
return 'LOGIC';
case 'true':
case 'false':
return 'BOOL';
case 'break':
case 'continue':
return 'STATEMENT';
default:
return tag;
}
})();
}
this.token(tag, id);
if (colon) {
this.token(':', ':');
}
return input.length;
};
Lexer.prototype.numberToken = function() {
var binaryLiteral, lexedLength, match, number, octalLiteral;
if (!(match = NUMBER.exec(this.chunk))) {
return 0;
}
number = match[0];
if (/^0[BOX]/.test(number)) {
this.error("radix prefix '" + number + "' must be lowercase");
} else if (/E/.test(number) && !/^0x/.test(number)) {
this.error("exponential notation '" + number + "' must be indicated with a lowercase 'e'");
} else if (/^0\d*[89]/.test(number)) {
this.error("decimal literal '" + number + "' must not be prefixed with '0'");
} else if (/^0\d+/.test(number)) {
this.error("octal literal '" + number + "' must be prefixed with '0o'");
}
lexedLength = number.length;
if (octalLiteral = /^0o([0-7]+)/.exec(number)) {
number = '0x' + (parseInt(octalLiteral[1], 8)).toString(16);
}
if (binaryLiteral = /^0b([01]+)/.exec(number)) {
number = '0x' + (parseInt(binaryLiteral[1], 2)).toString(16);
}
this.token('NUMBER', number);
return lexedLength;
};
Lexer.prototype.stringToken = function() {
var match, octalEsc, string;
switch (this.chunk.charAt(0)) {
case "'":
if (!(match = SIMPLESTR.exec(this.chunk))) {
return 0;
}
this.token('STRING', (string = match[0]).replace(MULTILINER, '\\\n'));
break;
case '"':
if (!(string = this.balancedString(this.chunk, '"'))) {
return 0;
}
if (0 < string.indexOf('#{', 1)) {
this.interpolateString(string.slice(1, -1));
} else {
this.token('STRING', this.escapeLines(string));
}
break;
default:
return 0;
}
if (octalEsc = /^(?:\\.|[^\\])*\\(?:0[0-7]|[1-7])/.test(string)) {
this.error("octal escape sequences " + string + " are not allowed");
}
this.line += count(string, '\n');
return string.length;
};
Lexer.prototype.heredocToken = function() {
var doc, heredoc, match, quote;
if (!(match = HEREDOC.exec(this.chunk))) {
return 0;
}
heredoc = match[0];
quote = heredoc.charAt(0);
doc = this.sanitizeHeredoc(match[2], {
quote: quote,
indent: null
});
if (quote === '"' && 0 <= doc.indexOf('#{')) {
this.interpolateString(doc, {
heredoc: true
});
} else {
this.token('STRING', this.makeString(doc, quote, true));
}
this.line += count(heredoc, '\n');
return heredoc.length;
};
Lexer.prototype.commentToken = function() {
var comment, here, match;
if (!(match = this.chunk.match(COMMENT))) {
return 0;
}
comment = match[0], here = match[1];
if (here) {
this.token('HERECOMMENT', this.sanitizeHeredoc(here, {
herecomment: true,
indent: Array(this.indent + 1).join(' ')
}));
}
this.line += count(comment, '\n');
return comment.length;
};
Lexer.prototype.jsToken = function() {
var match, script;
if (!(this.chunk.charAt(0) === '`' && (match = JSTOKEN.exec(this.chunk)))) {
return 0;
}
this.token('JS', (script = match[0]).slice(1, -1));
return script.length;
};
Lexer.prototype.regexToken = function() {
var flags, length, match, prev, regex, _ref2, _ref3;
if (this.chunk.charAt(0) !== '/') {
return 0;
}
if (match = HEREGEX.exec(this.chunk)) {
length = this.heregexToken(match);
this.line += count(match[0], '\n');
return length;
}
prev = last(this.tokens);
if (prev && (_ref2 = prev[0], __indexOf.call((prev.spaced ? NOT_REGEX : NOT_SPACED_REGEX), _ref2) >= 0)) {
return 0;
}
if (!(match = REGEX.exec(this.chunk))) {
return 0;
}
_ref3 = match, match = _ref3[0], regex = _ref3[1], flags = _ref3[2];
if (regex.slice(0, 2) === '/*') {
this.error('regular expressions cannot begin with `*`');
}
if (regex === '//') {
regex = '/(?:)/';
}
this.token('REGEX', "" + regex + flags);
return match.length;
};
Lexer.prototype.heregexToken = function(match) {
var body, flags, heregex, re, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4, _ref5;
heregex = match[0], body = match[1], flags = match[2];
if (0 > body.indexOf('#{')) {
re = body.replace(HEREGEX_OMIT, '').replace(/\//g, '\\/');
if (re.match(/^\*/)) {
this.error('regular expressions cannot begin with `*`');
}
this.token('REGEX', "/" + (re || '(?:)') + "/" + flags);
return heregex.length;
}
this.token('IDENTIFIER', 'RegExp');
this.tokens.push(['CALL_START', '(']);
tokens = [];
_ref2 = this.interpolateString(body, {
regex: true
});
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
_ref3 = _ref2[_i], tag = _ref3[0], value = _ref3[1];
if (tag === 'TOKENS') {
tokens.push.apply(tokens, value);
} else {
if (!(value = value.replace(HEREGEX_OMIT, ''))) {
continue;
}
value = value.replace(/\\/g, '\\\\');
tokens.push(['STRING', this.makeString(value, '"', true)]);
}
tokens.push(['+', '+']);
}
tokens.pop();
if (((_ref4 = tokens[0]) != null ? _ref4[0] : void 0) !== 'STRING') {
this.tokens.push(['STRING', '""'], ['+', '+']);
}
(_ref5 = this.tokens).push.apply(_ref5, tokens);
if (flags) {
this.tokens.push([',', ','], ['STRING', '"' + flags + '"']);
}
this.token(')', ')');
return heregex.length;
};
Lexer.prototype.lineToken = function() {
var diff, indent, match, noNewlines, prev, size;
if (!(match = MULTI_DENT.exec(this.chunk))) {
return 0;
}
indent = match[0];
this.line += count(indent, '\n');
this.seenFor = false;
prev = last(this.tokens, 1);
size = indent.length - 1 - indent.lastIndexOf('\n');
noNewlines = this.unfinished();
if (size - this.indebt === this.indent) {
if (noNewlines) {
this.suppressNewlines();
} else {
this.newlineToken();
}
return indent.length;
}
if (size > this.indent) {
if (noNewlines) {
this.indebt = size - this.indent;
this.suppressNewlines();
return indent.length;
}
diff = size - this.indent + this.outdebt;
this.token('INDENT', diff);
this.indents.push(diff);
this.ends.push('OUTDENT');
this.outdebt = this.indebt = 0;
} else {
this.indebt = 0;
this.outdentToken(this.indent - size, noNewlines);
}
this.indent = size;
return indent.length;
};
Lexer.prototype.outdentToken = function(moveOut, noNewlines) {
var dent, len;
while (moveOut > 0) {
len = this.indents.length - 1;
if (this.indents[len] === void 0) {
moveOut = 0;
} else if (this.indents[len] === this.outdebt) {
moveOut -= this.outdebt;
this.outdebt = 0;
} else if (this.indents[len] < this.outdebt) {
this.outdebt -= this.indents[len];
moveOut -= this.indents[len];
} else {
dent = this.indents.pop() - this.outdebt;
moveOut -= dent;
this.outdebt = 0;
this.pair('OUTDENT');
this.token('OUTDENT', dent);
}
}
if (dent) {
this.outdebt -= moveOut;
}
while (this.value() === ';') {
this.tokens.pop();
}
if (!(this.tag() === 'TERMINATOR' || noNewlines)) {
this.token('TERMINATOR', '\n');
}
return this;
};
Lexer.prototype.whitespaceToken = function() {
var match, nline, prev;
if (!((match = WHITESPACE.exec(this.chunk)) || (nline = this.chunk.charAt(0) === '\n'))) {
return 0;
}
prev = last(this.tokens);
if (prev) {
prev[match ? 'spaced' : 'newLine'] = true;
}
if (match) {
return match[0].length;
} else {
return 0;
}
};
Lexer.prototype.newlineToken = function() {
while (this.value() === ';') {
this.tokens.pop();
}
if (this.tag() !== 'TERMINATOR') {
this.token('TERMINATOR', '\n');
}
return this;
};
Lexer.prototype.suppressNewlines = function() {
if (this.value() === '\\') {
this.tokens.pop();
}
return this;
};
Lexer.prototype.literalToken = function() {
var match, prev, tag, value, _ref2, _ref3, _ref4, _ref5;
if (match = OPERATOR.exec(this.chunk)) {
value = match[0];
if (CODE.test(value)) {
this.tagParameters();
}
} else {
value = this.chunk.charAt(0);
}
tag = value;
prev = last(this.tokens);
if (value === '=' && prev) {
if (!prev[1].reserved && (_ref2 = prev[1], __indexOf.call(JS_FORBIDDEN, _ref2) >= 0)) {
this.error("reserved word \"" + (this.value()) + "\" can't be assigned");
}
if ((_ref3 = prev[1]) === '||' || _ref3 === '&&') {
prev[0] = 'COMPOUND_ASSIGN';
prev[1] += '=';
return value.length;
}
}
if (value === ';') {
this.seenFor = false;
tag = 'TERMINATOR';
} else if (__indexOf.call(MATH, value) >= 0) {
tag = 'MATH';
} else if (__indexOf.call(COMPARE, value) >= 0) {
tag = 'COMPARE';
} else if (__indexOf.call(COMPOUND_ASSIGN, value) >= 0) {
tag = 'COMPOUND_ASSIGN';
} else if (__indexOf.call(UNARY, value) >= 0) {
tag = 'UNARY';
} else if (__indexOf.call(SHIFT, value) >= 0) {
tag = 'SHIFT';
} else if (__indexOf.call(LOGIC, value) >= 0 || value === '?' && (prev != null ? prev.spaced : void 0)) {
tag = 'LOGIC';
} else if (prev && !prev.spaced) {
if (value === '(' && (_ref4 = prev[0], __indexOf.call(CALLABLE, _ref4) >= 0)) {
if (prev[0] === '?') {
prev[0] = 'FUNC_EXIST';
}
tag = 'CALL_START';
} else if (value === '[' && (_ref5 = prev[0], __indexOf.call(INDEXABLE, _ref5) >= 0)) {
tag = 'INDEX_START';
switch (prev[0]) {
case '?':
prev[0] = 'INDEX_SOAK';
}
}
}
switch (value) {
case '(':
case '{':
case '[':
this.ends.push(INVERSES[value]);
break;
case ')':
case '}':
case ']':
this.pair(value);
}
this.token(tag, value);
return value.length;
};
Lexer.prototype.sanitizeHeredoc = function(doc, options) {
var attempt, herecomment, indent, match, _ref2;
indent = options.indent, herecomment = options.herecomment;
if (herecomment) {
if (HEREDOC_ILLEGAL.test(doc)) {
this.error("block comment cannot contain \"*/\", starting");
}
if (doc.indexOf('\n') <= 0) {
return doc;
}
} else {
while (match = HEREDOC_INDENT.exec(doc)) {
attempt = match[1];
if (indent === null || (0 < (_ref2 = attempt.length) && _ref2 < indent.length)) {
indent = attempt;
}
}
}
if (indent) {
doc = doc.replace(RegExp("\\n" + indent, "g"), '\n');
}
if (!herecomment) {
doc = doc.replace(/^\n/, '');
}
return doc;
};
Lexer.prototype.tagParameters = function() {
var i, stack, tok, tokens;
if (this.tag() !== ')') {
return this;
}
stack = [];
tokens = this.tokens;
i = tokens.length;
tokens[--i][0] = 'PARAM_END';
while (tok = tokens[--i]) {
switch (tok[0]) {
case ')':
stack.push(tok);
break;
case '(':
case 'CALL_START':
if (stack.length) {
stack.pop();
} else if (tok[0] === '(') {
tok[0] = 'PARAM_START';
return this;
} else {
return this;
}
}
}
return this;
};
Lexer.prototype.closeIndentation = function() {
return this.outdentToken(this.indent);
};
Lexer.prototype.balancedString = function(str, end) {
var continueCount, i, letter, match, prev, stack, _i, _ref2;
continueCount = 0;
stack = [end];
for (i = _i = 1, _ref2 = str.length; 1 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 1 <= _ref2 ? ++_i : --_i) {
if (continueCount) {
--continueCount;
continue;
}
switch (letter = str.charAt(i)) {
case '\\':
++continueCount;
continue;
case end:
stack.pop();
if (!stack.length) {
return str.slice(0, i + 1 || 9e9);
}
end = stack[stack.length - 1];
continue;
}
if (end === '}' && (letter === '"' || letter === "'")) {
stack.push(end = letter);
} else if (end === '}' && letter === '/' && (match = HEREGEX.exec(str.slice(i)) || REGEX.exec(str.slice(i)))) {
continueCount += match[0].length - 1;
} else if (end === '}' && letter === '{') {
stack.push(end = '}');
} else if (end === '"' && prev === '#' && letter === '{') {
stack.push(end = '}');
}
prev = letter;
}
return this.error("missing " + (stack.pop()) + ", starting");
};
Lexer.prototype.interpolateString = function(str, options) {
var expr, heredoc, i, inner, interpolated, len, letter, nested, pi, regex, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4;
if (options == null) {
options = {};
}
heredoc = options.heredoc, regex = options.regex;
tokens = [];
pi = 0;
i = -1;
while (letter = str.charAt(i += 1)) {
if (letter === '\\') {
i += 1;
continue;
}
if (!(letter === '#' && str.charAt(i + 1) === '{' && (expr = this.balancedString(str.slice(i + 1), '}')))) {
continue;
}
if (pi < i) {
tokens.push(['NEOSTRING', str.slice(pi, i)]);
}
inner = expr.slice(1, -1);
if (inner.length) {
nested = new Lexer().tokenize(inner, {
line: this.line,
rewrite: false
});
nested.pop();
if (((_ref2 = nested[0]) != null ? _ref2[0] : void 0) === 'TERMINATOR') {
nested.shift();
}
if (len = nested.length) {
if (len > 1) {
nested.unshift(['(', '(', this.line]);
nested.push([')', ')', this.line]);
}
tokens.push(['TOKENS', nested]);
}
}
i += expr.length;
pi = i + 1;
}
if ((i > pi && pi < str.length)) {
tokens.push(['NEOSTRING', str.slice(pi)]);
}
if (regex) {
return tokens;
}
if (!tokens.length) {
return this.token('STRING', '""');
}
if (tokens[0][0] !== 'NEOSTRING') {
tokens.unshift(['', '']);
}
if (interpolated = tokens.length > 1) {
this.token('(', '(');
}
for (i = _i = 0, _len = tokens.length; _i < _len; i = ++_i) {
_ref3 = tokens[i], tag = _ref3[0], value = _ref3[1];
if (i) {
this.token('+', '+');
}
if (tag === 'TOKENS') {
(_ref4 = this.tokens).push.apply(_ref4, value);
} else {
this.token('STRING', this.makeString(value, '"', heredoc));
}
}
if (interpolated) {
this.token(')', ')');
}
return tokens;
};
Lexer.prototype.pair = function(tag) {
var size, wanted;
if (tag !== (wanted = last(this.ends))) {
if ('OUTDENT' !== wanted) {
this.error("unmatched " + tag);
}
this.indent -= size = last(this.indents);
this.outdentToken(size, true);
return this.pair(tag);
}
return this.ends.pop();
};
Lexer.prototype.token = function(tag, value) {
return this.tokens.push([tag, value, this.line]);
};
Lexer.prototype.tag = function(index, tag) {
var tok;
return (tok = last(this.tokens, index)) && (tag ? tok[0] = tag : tok[0]);
};
Lexer.prototype.value = function(index, val) {
var tok;
return (tok = last(this.tokens, index)) && (val ? tok[1] = val : tok[1]);
};
Lexer.prototype.unfinished = function() {
var _ref2;
return LINE_CONTINUER.test(this.chunk) || ((_ref2 = this.tag()) === '\\' || _ref2 === '.' || _ref2 === '?.' || _ref2 === 'UNARY' || _ref2 === 'MATH' || _ref2 === '+' || _ref2 === '-' || _ref2 === 'SHIFT' || _ref2 === 'RELATION' || _ref2 === 'COMPARE' || _ref2 === 'LOGIC' || _ref2 === 'THROW' || _ref2 === 'EXTENDS');
};
Lexer.prototype.escapeLines = function(str, heredoc) {
return str.replace(MULTILINER, heredoc ? '\\n' : '');
};
Lexer.prototype.makeString = function(body, quote, heredoc) {
if (!body) {
return quote + quote;
}
body = body.replace(/\\([\s\S])/g, function(match, contents) {
if (contents === '\n' || contents === quote) {
return contents;
} else {
return match;
}
});
body = body.replace(RegExp("" + quote, "g"), '\\$&');
return quote + this.escapeLines(body, heredoc) + quote;
};
Lexer.prototype.error = function(message) {
throw SyntaxError("" + message + " on line " + (this.line + 1));
};
return Lexer;
})();
JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super'];
COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when'];
COFFEE_ALIAS_MAP = {
and: '&&',
or: '||',
is: '==',
isnt: '!=',
not: '!',
yes: 'true',
no: 'false',
on: 'true',
off: 'false'
};
COFFEE_ALIASES = (function() {
var _results;
_results = [];
for (key in COFFEE_ALIAS_MAP) {
_results.push(key);
}
return _results;
})();
COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat(COFFEE_ALIASES);
RESERVED = ['case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'export', 'import', 'native', '__hasProp', '__extends', '__slice', '__bind', '__indexOf', 'implements', 'interface', 'let', 'package', 'private', 'protected', 'public', 'static', 'yield'];
STRICT_PROSCRIBED = ['arguments', 'eval'];
JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED);
exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED);
exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED;
IDENTIFIER = /^([$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*)([^\n\S]*:(?!:))?/;
NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i;
HEREDOC = /^("""|''')([\s\S]*?)(?:\n[^\n\S]*)?\1/;
OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/;
WHITESPACE = /^[^\n\S]+/;
COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|(?:###)?$)|^(?:\s*#(?!##[^#]).*)+/;
CODE = /^[-=]>/;
MULTI_DENT = /^(?:\n[^\n\S]*)+/;
SIMPLESTR = /^'[^\\']*(?:\\.[^\\']*)*'/;
JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/;
REGEX = /^(\/(?![\s=])[^[\/\n\\]*(?:(?:\\[\s\S]|\[[^\]\n\\]*(?:\\[\s\S][^\]\n\\]*)*])[^[\/\n\\]*)*\/)([imgy]{0,4})(?!\w)/;
HEREGEX = /^\/{3}([\s\S]+?)\/{3}([imgy]{0,4})(?!\w)/;
HEREGEX_OMIT = /\s+(?:#.*)?/g;
MULTILINER = /\n/g;
HEREDOC_INDENT = /\n+([^\n\S]*)/g;
HEREDOC_ILLEGAL = /\*\//;
LINE_CONTINUER = /^\s*(?:,|\??\.(?![.\d])|::)/;
TRAILING_SPACES = /\s+$/;
COMPOUND_ASSIGN = ['-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>=', '&=', '^=', '|='];
UNARY = ['!', '~', 'NEW', 'TYPEOF', 'DELETE', 'DO'];
LOGIC = ['&&', '||', '&', '|', '^'];
SHIFT = ['<<', '>>', '>>>'];
COMPARE = ['==', '!=', '<', '>', '<=', '>='];
MATH = ['*', '/', '%'];
RELATION = ['IN', 'OF', 'INSTANCEOF'];
BOOL = ['TRUE', 'FALSE'];
NOT_REGEX = ['NUMBER', 'REGEX', 'BOOL', 'NULL', 'UNDEFINED', '++', '--', ']'];
NOT_SPACED_REGEX = NOT_REGEX.concat(')', '}', 'THIS', 'IDENTIFIER', 'STRING');
CALLABLE = ['IDENTIFIER', 'STRING', 'REGEX', ')', ']', '}', '?', '::', '@', 'THIS', 'SUPER'];
INDEXABLE = CALLABLE.concat('NUMBER', 'BOOL', 'NULL', 'UNDEFINED');
LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR'];
}).call(this);

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,138 @@
// Generated by CoffeeScript 1.3.3
(function() {
var LONG_FLAG, MULTI_FLAG, OPTIONAL, OptionParser, SHORT_FLAG, buildRule, buildRules, normalizeArguments;
exports.OptionParser = OptionParser = (function() {
function OptionParser(rules, banner) {
this.banner = banner;
this.rules = buildRules(rules);
}
OptionParser.prototype.parse = function(args) {
var arg, i, isOption, matchedRule, options, originalArgs, pos, rule, seenNonOptionArg, skippingArgument, value, _i, _j, _len, _len1, _ref;
options = {
"arguments": []
};
skippingArgument = false;
originalArgs = args;
args = normalizeArguments(args);
for (i = _i = 0, _len = args.length; _i < _len; i = ++_i) {
arg = args[i];
if (skippingArgument) {
skippingArgument = false;
continue;
}
if (arg === '--') {
pos = originalArgs.indexOf('--');
options["arguments"] = options["arguments"].concat(originalArgs.slice(pos + 1));
break;
}
isOption = !!(arg.match(LONG_FLAG) || arg.match(SHORT_FLAG));
seenNonOptionArg = options["arguments"].length > 0;
if (!seenNonOptionArg) {
matchedRule = false;
_ref = this.rules;
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
rule = _ref[_j];
if (rule.shortFlag === arg || rule.longFlag === arg) {
value = true;
if (rule.hasArgument) {
skippingArgument = true;
value = args[i + 1];
}
options[rule.name] = rule.isList ? (options[rule.name] || []).concat(value) : value;
matchedRule = true;
break;
}
}
if (isOption && !matchedRule) {
throw new Error("unrecognized option: " + arg);
}
}
if (seenNonOptionArg || !isOption) {
options["arguments"].push(arg);
}
}
return options;
};
OptionParser.prototype.help = function() {
var letPart, lines, rule, spaces, _i, _len, _ref;
lines = [];
if (this.banner) {
lines.unshift("" + this.banner + "\n");
}
_ref = this.rules;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
rule = _ref[_i];
spaces = 15 - rule.longFlag.length;
spaces = spaces > 0 ? Array(spaces + 1).join(' ') : '';
letPart = rule.shortFlag ? rule.shortFlag + ', ' : ' ';
lines.push(' ' + letPart + rule.longFlag + spaces + rule.description);
}
return "\n" + (lines.join('\n')) + "\n";
};
return OptionParser;
})();
LONG_FLAG = /^(--\w[\w\-]*)/;
SHORT_FLAG = /^(-\w)$/;
MULTI_FLAG = /^-(\w{2,})/;
OPTIONAL = /\[(\w+(\*?))\]/;
buildRules = function(rules) {
var tuple, _i, _len, _results;
_results = [];
for (_i = 0, _len = rules.length; _i < _len; _i++) {
tuple = rules[_i];
if (tuple.length < 3) {
tuple.unshift(null);
}
_results.push(buildRule.apply(null, tuple));
}
return _results;
};
buildRule = function(shortFlag, longFlag, description, options) {
var match;
if (options == null) {
options = {};
}
match = longFlag.match(OPTIONAL);
longFlag = longFlag.match(LONG_FLAG)[1];
return {
name: longFlag.substr(2),
shortFlag: shortFlag,
longFlag: longFlag,
description: description,
hasArgument: !!(match && match[1]),
isList: !!(match && match[2])
};
};
normalizeArguments = function(args) {
var arg, l, match, result, _i, _j, _len, _len1, _ref;
args = args.slice(0);
result = [];
for (_i = 0, _len = args.length; _i < _len; _i++) {
arg = args[_i];
if (match = arg.match(MULTI_FLAG)) {
_ref = match[1].split('');
for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) {
l = _ref[_j];
result.push('-' + l);
}
} else {
result.push(arg);
}
}
return result;
};
}).call(this);

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,261 @@
// Generated by CoffeeScript 1.3.3
(function() {
var ACCESSOR, CoffeeScript, Module, REPL_PROMPT, REPL_PROMPT_CONTINUATION, REPL_PROMPT_MULTILINE, SIMPLEVAR, Script, autocomplete, backlog, completeAttribute, completeVariable, enableColours, error, getCompletions, inspect, multilineMode, pipedInput, readline, repl, run, stdin, stdout;
stdin = process.openStdin();
stdout = process.stdout;
CoffeeScript = require('./coffee-script');
readline = require('readline');
inspect = require('util').inspect;
Script = require('vm').Script;
Module = require('module');
REPL_PROMPT = 'coffee> ';
REPL_PROMPT_MULTILINE = '------> ';
REPL_PROMPT_CONTINUATION = '......> ';
enableColours = false;
if (process.platform !== 'win32') {
enableColours = !process.env.NODE_DISABLE_COLORS;
}
error = function(err) {
return stdout.write((err.stack || err.toString()) + '\n');
};
ACCESSOR = /\s*([\w\.]+)(?:\.(\w*))$/;
SIMPLEVAR = /(\w+)$/i;
autocomplete = function(text) {
return completeAttribute(text) || completeVariable(text) || [[], text];
};
completeAttribute = function(text) {
var all, completions, key, match, obj, possibilities, prefix, val;
if (match = text.match(ACCESSOR)) {
all = match[0], obj = match[1], prefix = match[2];
try {
val = Script.runInThisContext(obj);
} catch (error) {
return;
}
val = Object(val);
possibilities = Object.getOwnPropertyNames(val);
for (key in val) {
if (~possibilities.indexOf(val)) {
possibilities.push(key);
}
}
completions = getCompletions(prefix, possibilities);
return [completions, prefix];
}
};
completeVariable = function(text) {
var completions, free, keywords, possibilities, r, vars, _ref;
free = (_ref = text.match(SIMPLEVAR)) != null ? _ref[1] : void 0;
if (text === "") {
free = "";
}
if (free != null) {
vars = Script.runInThisContext('Object.getOwnPropertyNames(Object(this))');
keywords = (function() {
var _i, _len, _ref1, _results;
_ref1 = CoffeeScript.RESERVED;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
r = _ref1[_i];
if (r.slice(0, 2) !== '__') {
_results.push(r);
}
}
return _results;
})();
possibilities = vars.concat(keywords);
completions = getCompletions(free, possibilities);
return [completions, free];
}
};
getCompletions = function(prefix, candidates) {
var el, _i, _len, _results;
_results = [];
for (_i = 0, _len = candidates.length; _i < _len; _i++) {
el = candidates[_i];
if (el.indexOf(prefix) === 0) {
_results.push(el);
}
}
return _results;
};
process.on('uncaughtException', error);
backlog = '';
run = function(buffer) {
var code, returnValue, _;
buffer = buffer.replace(/(^|[\r\n]+)(\s*)##?(?:[^#\r\n][^\r\n]*|)($|[\r\n])/, "$1$2$3");
buffer = buffer.replace(/[\r\n]+$/, "");
if (multilineMode) {
backlog += "" + buffer + "\n";
repl.setPrompt(REPL_PROMPT_CONTINUATION);
repl.prompt();
return;
}
if (!buffer.toString().trim() && !backlog) {
repl.prompt();
return;
}
code = backlog += buffer;
if (code[code.length - 1] === '\\') {
backlog = "" + backlog.slice(0, -1) + "\n";
repl.setPrompt(REPL_PROMPT_CONTINUATION);
repl.prompt();
return;
}
repl.setPrompt(REPL_PROMPT);
backlog = '';
try {
_ = global._;
returnValue = CoffeeScript["eval"]("_=(" + code + "\n)", {
filename: 'repl',
modulename: 'repl'
});
if (returnValue === void 0) {
global._ = _;
}
repl.output.write("" + (inspect(returnValue, false, 2, enableColours)) + "\n");
} catch (err) {
error(err);
}
return repl.prompt();
};
if (stdin.readable) {
pipedInput = '';
repl = {
prompt: function() {
return stdout.write(this._prompt);
},
setPrompt: function(p) {
return this._prompt = p;
},
input: stdin,
output: stdout,
on: function() {}
};
stdin.on('data', function(chunk) {
var line, lines, _i, _len, _ref;
pipedInput += chunk;
if (!/\n/.test(pipedInput)) {
return;
}
lines = pipedInput.split("\n");
pipedInput = lines[lines.length - 1];
_ref = lines.slice(0, -1);
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
line = _ref[_i];
if (!(line)) {
continue;
}
stdout.write("" + line + "\n");
run(line);
}
});
stdin.on('end', function() {
var line, _i, _len, _ref;
_ref = pipedInput.trim().split("\n");
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
line = _ref[_i];
if (!(line)) {
continue;
}
stdout.write("" + line + "\n");
run(line);
}
stdout.write('\n');
return process.exit(0);
});
} else {
if (readline.createInterface.length < 3) {
repl = readline.createInterface(stdin, autocomplete);
stdin.on('data', function(buffer) {
return repl.write(buffer);
});
} else {
repl = readline.createInterface(stdin, stdout, autocomplete);
}
}
multilineMode = false;
repl.input.on('keypress', function(char, key) {
var cursorPos, newPrompt;
if (!(key && key.ctrl && !key.meta && !key.shift && key.name === 'v')) {
return;
}
cursorPos = repl.cursor;
repl.output.cursorTo(0);
repl.output.clearLine(1);
multilineMode = !multilineMode;
if (!multilineMode && backlog) {
repl._line();
}
backlog = '';
repl.setPrompt((newPrompt = multilineMode ? REPL_PROMPT_MULTILINE : REPL_PROMPT));
repl.prompt();
return repl.output.cursorTo(newPrompt.length + (repl.cursor = cursorPos));
});
repl.input.on('keypress', function(char, key) {
if (!(multilineMode && repl.line)) {
return;
}
if (!(key && key.ctrl && !key.meta && !key.shift && key.name === 'd')) {
return;
}
multilineMode = false;
return repl._line();
});
repl.on('attemptClose', function() {
if (multilineMode) {
multilineMode = false;
repl.output.cursorTo(0);
repl.output.clearLine(1);
repl._onLine(repl.line);
return;
}
if (backlog) {
backlog = '';
repl.output.write('\n');
repl.setPrompt(REPL_PROMPT);
return repl.prompt();
} else {
return repl.close();
}
});
repl.on('close', function() {
repl.output.write('\n');
return repl.input.destroy();
});
repl.on('line', run);
repl.setPrompt(REPL_PROMPT);
repl.prompt();
}).call(this);

View File

@ -0,0 +1,349 @@
// Generated by CoffeeScript 1.3.3
(function() {
var BALANCED_PAIRS, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_BLOCK, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, SINGLE_CLOSERS, SINGLE_LINERS, left, rite, _i, _len, _ref,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
__slice = [].slice;
exports.Rewriter = (function() {
function Rewriter() {}
Rewriter.prototype.rewrite = function(tokens) {
this.tokens = tokens;
this.removeLeadingNewlines();
this.removeMidExpressionNewlines();
this.closeOpenCalls();
this.closeOpenIndexes();
this.addImplicitIndentation();
this.tagPostfixConditionals();
this.addImplicitBraces();
this.addImplicitParentheses();
return this.tokens;
};
Rewriter.prototype.scanTokens = function(block) {
var i, token, tokens;
tokens = this.tokens;
i = 0;
while (token = tokens[i]) {
i += block.call(this, token, i, tokens);
}
return true;
};
Rewriter.prototype.detectEnd = function(i, condition, action) {
var levels, token, tokens, _ref, _ref1;
tokens = this.tokens;
levels = 0;
while (token = tokens[i]) {
if (levels === 0 && condition.call(this, token, i)) {
return action.call(this, token, i);
}
if (!token || levels < 0) {
return action.call(this, token, i - 1);
}
if (_ref = token[0], __indexOf.call(EXPRESSION_START, _ref) >= 0) {
levels += 1;
} else if (_ref1 = token[0], __indexOf.call(EXPRESSION_END, _ref1) >= 0) {
levels -= 1;
}
i += 1;
}
return i - 1;
};
Rewriter.prototype.removeLeadingNewlines = function() {
var i, tag, _i, _len, _ref;
_ref = this.tokens;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
tag = _ref[i][0];
if (tag !== 'TERMINATOR') {
break;
}
}
if (i) {
return this.tokens.splice(0, i);
}
};
Rewriter.prototype.removeMidExpressionNewlines = function() {
return this.scanTokens(function(token, i, tokens) {
var _ref;
if (!(token[0] === 'TERMINATOR' && (_ref = this.tag(i + 1), __indexOf.call(EXPRESSION_CLOSE, _ref) >= 0))) {
return 1;
}
tokens.splice(i, 1);
return 0;
});
};
Rewriter.prototype.closeOpenCalls = function() {
var action, condition;
condition = function(token, i) {
var _ref;
return ((_ref = token[0]) === ')' || _ref === 'CALL_END') || token[0] === 'OUTDENT' && this.tag(i - 1) === ')';
};
action = function(token, i) {
return this.tokens[token[0] === 'OUTDENT' ? i - 1 : i][0] = 'CALL_END';
};
return this.scanTokens(function(token, i) {
if (token[0] === 'CALL_START') {
this.detectEnd(i + 1, condition, action);
}
return 1;
});
};
Rewriter.prototype.closeOpenIndexes = function() {
var action, condition;
condition = function(token, i) {
var _ref;
return (_ref = token[0]) === ']' || _ref === 'INDEX_END';
};
action = function(token, i) {
return token[0] = 'INDEX_END';
};
return this.scanTokens(function(token, i) {
if (token[0] === 'INDEX_START') {
this.detectEnd(i + 1, condition, action);
}
return 1;
});
};
Rewriter.prototype.addImplicitBraces = function() {
var action, condition, sameLine, stack, start, startIndent, startIndex, startsLine;
stack = [];
start = null;
startsLine = null;
sameLine = true;
startIndent = 0;
startIndex = 0;
condition = function(token, i) {
var one, tag, three, two, _ref, _ref1;
_ref = this.tokens.slice(i + 1, (i + 3) + 1 || 9e9), one = _ref[0], two = _ref[1], three = _ref[2];
if ('HERECOMMENT' === (one != null ? one[0] : void 0)) {
return false;
}
tag = token[0];
if (__indexOf.call(LINEBREAKS, tag) >= 0) {
sameLine = false;
}
return (((tag === 'TERMINATOR' || tag === 'OUTDENT') || (__indexOf.call(IMPLICIT_END, tag) >= 0 && sameLine && !(i - startIndex === 1))) && ((!startsLine && this.tag(i - 1) !== ',') || !((two != null ? two[0] : void 0) === ':' || (one != null ? one[0] : void 0) === '@' && (three != null ? three[0] : void 0) === ':'))) || (tag === ',' && one && ((_ref1 = one[0]) !== 'IDENTIFIER' && _ref1 !== 'NUMBER' && _ref1 !== 'STRING' && _ref1 !== '@' && _ref1 !== 'TERMINATOR' && _ref1 !== 'OUTDENT'));
};
action = function(token, i) {
var tok;
tok = this.generate('}', '}', token[2]);
return this.tokens.splice(i, 0, tok);
};
return this.scanTokens(function(token, i, tokens) {
var ago, idx, prevTag, tag, tok, value, _ref, _ref1;
if (_ref = (tag = token[0]), __indexOf.call(EXPRESSION_START, _ref) >= 0) {
stack.push([(tag === 'INDENT' && this.tag(i - 1) === '{' ? '{' : tag), i]);
return 1;
}
if (__indexOf.call(EXPRESSION_END, tag) >= 0) {
start = stack.pop();
return 1;
}
if (!(tag === ':' && ((ago = this.tag(i - 2)) === ':' || ((_ref1 = stack[stack.length - 1]) != null ? _ref1[0] : void 0) !== '{'))) {
return 1;
}
sameLine = true;
startIndex = i + 1;
stack.push(['{']);
idx = ago === '@' ? i - 2 : i - 1;
while (this.tag(idx - 2) === 'HERECOMMENT') {
idx -= 2;
}
prevTag = this.tag(idx - 1);
startsLine = !prevTag || (__indexOf.call(LINEBREAKS, prevTag) >= 0);
value = new String('{');
value.generated = true;
tok = this.generate('{', value, token[2]);
tokens.splice(idx, 0, tok);
this.detectEnd(i + 2, condition, action);
return 2;
});
};
Rewriter.prototype.addImplicitParentheses = function() {
var action, condition, noCall, seenControl, seenSingle;
noCall = seenSingle = seenControl = false;
condition = function(token, i) {
var post, tag, _ref, _ref1;
tag = token[0];
if (!seenSingle && token.fromThen) {
return true;
}
if (tag === 'IF' || tag === 'ELSE' || tag === 'CATCH' || tag === '->' || tag === '=>' || tag === 'CLASS') {
seenSingle = true;
}
if (tag === 'IF' || tag === 'ELSE' || tag === 'SWITCH' || tag === 'TRY' || tag === '=') {
seenControl = true;
}
if ((tag === '.' || tag === '?.' || tag === '::') && this.tag(i - 1) === 'OUTDENT') {
return true;
}
return !token.generated && this.tag(i - 1) !== ',' && (__indexOf.call(IMPLICIT_END, tag) >= 0 || (tag === 'INDENT' && !seenControl)) && (tag !== 'INDENT' || (((_ref = this.tag(i - 2)) !== 'CLASS' && _ref !== 'EXTENDS') && (_ref1 = this.tag(i - 1), __indexOf.call(IMPLICIT_BLOCK, _ref1) < 0) && !((post = this.tokens[i + 1]) && post.generated && post[0] === '{')));
};
action = function(token, i) {
return this.tokens.splice(i, 0, this.generate('CALL_END', ')', token[2]));
};
return this.scanTokens(function(token, i, tokens) {
var callObject, current, next, prev, tag, _ref, _ref1, _ref2;
tag = token[0];
if (tag === 'CLASS' || tag === 'IF' || tag === 'FOR' || tag === 'WHILE') {
noCall = true;
}
_ref = tokens.slice(i - 1, (i + 1) + 1 || 9e9), prev = _ref[0], current = _ref[1], next = _ref[2];
callObject = !noCall && tag === 'INDENT' && next && next.generated && next[0] === '{' && prev && (_ref1 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref1) >= 0);
seenSingle = false;
seenControl = false;
if (__indexOf.call(LINEBREAKS, tag) >= 0) {
noCall = false;
}
if (prev && !prev.spaced && tag === '?') {
token.call = true;
}
if (token.fromThen) {
return 1;
}
if (!(callObject || (prev != null ? prev.spaced : void 0) && (prev.call || (_ref2 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref2) >= 0)) && (__indexOf.call(IMPLICIT_CALL, tag) >= 0 || !(token.spaced || token.newLine) && __indexOf.call(IMPLICIT_UNSPACED_CALL, tag) >= 0))) {
return 1;
}
tokens.splice(i, 0, this.generate('CALL_START', '(', token[2]));
this.detectEnd(i + 1, condition, action);
if (prev[0] === '?') {
prev[0] = 'FUNC_EXIST';
}
return 2;
});
};
Rewriter.prototype.addImplicitIndentation = function() {
var action, condition, indent, outdent, starter;
starter = indent = outdent = null;
condition = function(token, i) {
var _ref;
return token[1] !== ';' && (_ref = token[0], __indexOf.call(SINGLE_CLOSERS, _ref) >= 0) && !(token[0] === 'ELSE' && (starter !== 'IF' && starter !== 'THEN'));
};
action = function(token, i) {
return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent);
};
return this.scanTokens(function(token, i, tokens) {
var tag, _ref, _ref1;
tag = token[0];
if (tag === 'TERMINATOR' && this.tag(i + 1) === 'THEN') {
tokens.splice(i, 1);
return 0;
}
if (tag === 'ELSE' && this.tag(i - 1) !== 'OUTDENT') {
tokens.splice.apply(tokens, [i, 0].concat(__slice.call(this.indentation(token))));
return 2;
}
if (tag === 'CATCH' && ((_ref = this.tag(i + 2)) === 'OUTDENT' || _ref === 'TERMINATOR' || _ref === 'FINALLY')) {
tokens.splice.apply(tokens, [i + 2, 0].concat(__slice.call(this.indentation(token))));
return 4;
}
if (__indexOf.call(SINGLE_LINERS, tag) >= 0 && this.tag(i + 1) !== 'INDENT' && !(tag === 'ELSE' && this.tag(i + 1) === 'IF')) {
starter = tag;
_ref1 = this.indentation(token, true), indent = _ref1[0], outdent = _ref1[1];
if (starter === 'THEN') {
indent.fromThen = true;
}
tokens.splice(i + 1, 0, indent);
this.detectEnd(i + 2, condition, action);
if (tag === 'THEN') {
tokens.splice(i, 1);
}
return 1;
}
return 1;
});
};
Rewriter.prototype.tagPostfixConditionals = function() {
var action, condition, original;
original = null;
condition = function(token, i) {
var _ref;
return (_ref = token[0]) === 'TERMINATOR' || _ref === 'INDENT';
};
action = function(token, i) {
if (token[0] !== 'INDENT' || (token.generated && !token.fromThen)) {
return original[0] = 'POST_' + original[0];
}
};
return this.scanTokens(function(token, i) {
if (token[0] !== 'IF') {
return 1;
}
original = token;
this.detectEnd(i + 1, condition, action);
return 1;
});
};
Rewriter.prototype.indentation = function(token, implicit) {
var indent, outdent;
if (implicit == null) {
implicit = false;
}
indent = ['INDENT', 2, token[2]];
outdent = ['OUTDENT', 2, token[2]];
if (implicit) {
indent.generated = outdent.generated = true;
}
return [indent, outdent];
};
Rewriter.prototype.generate = function(tag, value, line) {
var tok;
tok = [tag, value, line];
tok.generated = true;
return tok;
};
Rewriter.prototype.tag = function(i) {
var _ref;
return (_ref = this.tokens[i]) != null ? _ref[0] : void 0;
};
return Rewriter;
})();
BALANCED_PAIRS = [['(', ')'], ['[', ']'], ['{', '}'], ['INDENT', 'OUTDENT'], ['CALL_START', 'CALL_END'], ['PARAM_START', 'PARAM_END'], ['INDEX_START', 'INDEX_END']];
exports.INVERSES = INVERSES = {};
EXPRESSION_START = [];
EXPRESSION_END = [];
for (_i = 0, _len = BALANCED_PAIRS.length; _i < _len; _i++) {
_ref = BALANCED_PAIRS[_i], left = _ref[0], rite = _ref[1];
EXPRESSION_START.push(INVERSES[rite] = left);
EXPRESSION_END.push(INVERSES[left] = rite);
}
EXPRESSION_CLOSE = ['CATCH', 'WHEN', 'ELSE', 'FINALLY'].concat(EXPRESSION_END);
IMPLICIT_FUNC = ['IDENTIFIER', 'SUPER', ')', 'CALL_END', ']', 'INDEX_END', '@', 'THIS'];
IMPLICIT_CALL = ['IDENTIFIER', 'NUMBER', 'STRING', 'JS', 'REGEX', 'NEW', 'PARAM_START', 'CLASS', 'IF', 'TRY', 'SWITCH', 'THIS', 'BOOL', 'NULL', 'UNDEFINED', 'UNARY', 'SUPER', '@', '->', '=>', '[', '(', '{', '--', '++'];
IMPLICIT_UNSPACED_CALL = ['+', '-'];
IMPLICIT_BLOCK = ['->', '=>', '{', '[', ','];
IMPLICIT_END = ['POST_IF', 'FOR', 'WHILE', 'UNTIL', 'WHEN', 'BY', 'LOOP', 'TERMINATOR'];
SINGLE_LINERS = ['ELSE', '->', '=>', 'TRY', 'FINALLY', 'THEN'];
SINGLE_CLOSERS = ['TERMINATOR', 'CATCH', 'FINALLY', 'ELSE', 'OUTDENT', 'LEADING_WHEN'];
LINEBREAKS = ['TERMINATOR', 'INDENT', 'OUTDENT'];
}).call(this);

View File

@ -0,0 +1,146 @@
// Generated by CoffeeScript 1.3.3
(function() {
var Scope, extend, last, _ref;
_ref = require('./helpers'), extend = _ref.extend, last = _ref.last;
exports.Scope = Scope = (function() {
Scope.root = null;
function Scope(parent, expressions, method) {
this.parent = parent;
this.expressions = expressions;
this.method = method;
this.variables = [
{
name: 'arguments',
type: 'arguments'
}
];
this.positions = {};
if (!this.parent) {
Scope.root = this;
}
}
Scope.prototype.add = function(name, type, immediate) {
if (this.shared && !immediate) {
return this.parent.add(name, type, immediate);
}
if (Object.prototype.hasOwnProperty.call(this.positions, name)) {
return this.variables[this.positions[name]].type = type;
} else {
return this.positions[name] = this.variables.push({
name: name,
type: type
}) - 1;
}
};
Scope.prototype.namedMethod = function() {
if (this.method.name || !this.parent) {
return this.method;
}
return this.parent.namedMethod();
};
Scope.prototype.find = function(name) {
if (this.check(name)) {
return true;
}
this.add(name, 'var');
return false;
};
Scope.prototype.parameter = function(name) {
if (this.shared && this.parent.check(name, true)) {
return;
}
return this.add(name, 'param');
};
Scope.prototype.check = function(name) {
var _ref1;
return !!(this.type(name) || ((_ref1 = this.parent) != null ? _ref1.check(name) : void 0));
};
Scope.prototype.temporary = function(name, index) {
if (name.length > 1) {
return '_' + name + (index > 1 ? index - 1 : '');
} else {
return '_' + (index + parseInt(name, 36)).toString(36).replace(/\d/g, 'a');
}
};
Scope.prototype.type = function(name) {
var v, _i, _len, _ref1;
_ref1 = this.variables;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
v = _ref1[_i];
if (v.name === name) {
return v.type;
}
}
return null;
};
Scope.prototype.freeVariable = function(name, reserve) {
var index, temp;
if (reserve == null) {
reserve = true;
}
index = 0;
while (this.check((temp = this.temporary(name, index)))) {
index++;
}
if (reserve) {
this.add(temp, 'var', true);
}
return temp;
};
Scope.prototype.assign = function(name, value) {
this.add(name, {
value: value,
assigned: true
}, true);
return this.hasAssignments = true;
};
Scope.prototype.hasDeclarations = function() {
return !!this.declaredVariables().length;
};
Scope.prototype.declaredVariables = function() {
var realVars, tempVars, v, _i, _len, _ref1;
realVars = [];
tempVars = [];
_ref1 = this.variables;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
v = _ref1[_i];
if (v.type === 'var') {
(v.name.charAt(0) === '_' ? tempVars : realVars).push(v.name);
}
}
return realVars.sort().concat(tempVars.sort());
};
Scope.prototype.assignedVariables = function() {
var v, _i, _len, _ref1, _results;
_ref1 = this.variables;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
v = _ref1[_i];
if (v.type.assigned) {
_results.push("" + v.name + " = " + v.type.value);
}
}
return _results;
};
return Scope;
})();
}).call(this);

View File

@ -0,0 +1,47 @@
{
"name": "coffee-script",
"description": "Unfancy JavaScript",
"keywords": [
"javascript",
"language",
"coffeescript",
"compiler"
],
"author": {
"name": "Jeremy Ashkenas"
},
"version": "1.3.3",
"licenses": [
{
"type": "MIT",
"url": "https://raw.github.com/jashkenas/coffee-script/master/LICENSE"
}
],
"engines": {
"node": ">=0.4.0"
},
"directories": {
"lib": "./lib/coffee-script"
},
"main": "./lib/coffee-script/coffee-script",
"bin": {
"coffee": "./bin/coffee",
"cake": "./bin/cake"
},
"homepage": "http://coffeescript.org",
"bugs": {
"url": "https://github.com/jashkenas/coffee-script/issues"
},
"repository": {
"type": "git",
"url": "git://github.com/jashkenas/coffee-script.git"
},
"devDependencies": {
"uglify-js": ">=1.0.0",
"jison": ">=0.2.0"
},
"readme": "\n {\n } } {\n { { } }\n } }{ {\n { }{ } } _____ __ __\n ( }{ }{ { ) / ____| / _|/ _|\n .- { { } { }} -. | | ___ | |_| |_ ___ ___\n ( ( } { } { } } ) | | / _ \\| _| _/ _ \\/ _ \\\n |`-..________ ..-'| | |___| (_) | | | || __/ __/\n | | \\_____\\___/|_| |_| \\___|\\___|\n | ;--.\n | (__ \\ _____ _ _\n | | ) ) / ____| (_) | |\n | |/ / | (___ ___ _ __ _ _ __ | |_\n | ( / \\___ \\ / __| '__| | '_ \\| __|\n | |/ ____) | (__| | | | |_) | |_\n | | |_____/ \\___|_| |_| .__/ \\__|\n `-.._________..-' | |\n |_|\n\n\n CoffeeScript is a little language that compiles into JavaScript.\n\n Install Node.js, and then the CoffeeScript compiler:\n sudo bin/cake install\n\n Or, if you have the Node Package Manager installed:\n npm install -g coffee-script\n (Leave off the -g if you don't wish to install globally.)\n\n Execute a script:\n coffee /path/to/script.coffee\n\n Compile a script:\n coffee -c /path/to/script.coffee\n\n For documentation, usage, and examples, see:\n http://coffeescript.org/\n\n To suggest a feature, report a bug, or general discussion:\n http://github.com/jashkenas/coffee-script/issues/\n\n If you'd like to chat, drop by #coffeescript on Freenode IRC,\n or on webchat.freenode.net.\n\n The source repository:\n git://github.com/jashkenas/coffee-script.git\n\n All contributors are listed here:\n http://github.com/jashkenas/coffee-script/contributors\n",
"readmeFilename": "README",
"_id": "coffee-script@1.3.3",
"_from": "coffee-script@~1.3.3"
}

22
node_modules/grunt/node_modules/colors/MIT-LICENSE.txt generated vendored Normal file
View File

@ -0,0 +1,22 @@
Copyright (c) 2010
Marak Squires
Alexis Sellier (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.

77
node_modules/grunt/node_modules/colors/ReadMe.md generated vendored Normal file
View File

@ -0,0 +1,77 @@
# colors.js - get color and style in your node.js console ( and browser ) like what
<img src="http://i.imgur.com/goJdO.png" border = "0"/>
## Installation
npm install colors
## colors and styles!
- bold
- italic
- underline
- inverse
- yellow
- cyan
- white
- magenta
- green
- red
- grey
- blue
- rainbow
- zebra
- random
## Usage
``` js
var colors = require('./colors');
console.log('hello'.green); // outputs green text
console.log('i like cake and pies'.underline.red) // outputs red underlined text
console.log('inverse the color'.inverse); // inverses the color
console.log('OMG Rainbows!'.rainbow); // rainbow (ignores spaces)
```
# Creating Custom themes
```js
var colors = require('colors');
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log("this is an error".error);
// outputs yellow text
console.log("this is a warning".warn);
```
### Contributors
Marak (Marak Squires)
Alexis Sellier (cloudhead)
mmalecki (Maciej Małecki)
nicoreed (Nico Reed)
morganrallen (Morgan Allen)
JustinCampbell (Justin Campbell)
ded (Dustin Diaz)
#### , Marak Squires , Justin Campbell, Dustin Diaz (@ded)

342
node_modules/grunt/node_modules/colors/colors.js generated vendored Normal file
View File

@ -0,0 +1,342 @@
/*
colors.js
Copyright (c) 2010
Marak Squires
Alexis Sellier (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.
*/
var isHeadless = false;
if (typeof module !== 'undefined') {
isHeadless = true;
}
if (!isHeadless) {
var exports = {};
var module = {};
var colors = exports;
exports.mode = "browser";
} else {
exports.mode = "console";
}
//
// Prototypes the string object to have additional method calls that add terminal colors
//
var addProperty = function (color, func) {
exports[color] = function (str) {
return func.apply(str);
};
String.prototype.__defineGetter__(color, func);
};
function stylize(str, style) {
var styles;
if (exports.mode === 'console') {
styles = {
//styles
'bold' : ['\x1B[1m', '\x1B[22m'],
'italic' : ['\x1B[3m', '\x1B[23m'],
'underline' : ['\x1B[4m', '\x1B[24m'],
'inverse' : ['\x1B[7m', '\x1B[27m'],
'strikethrough' : ['\x1B[9m', '\x1B[29m'],
//text colors
//grayscale
'white' : ['\x1B[37m', '\x1B[39m'],
'grey' : ['\x1B[90m', '\x1B[39m'],
'black' : ['\x1B[30m', '\x1B[39m'],
//colors
'blue' : ['\x1B[34m', '\x1B[39m'],
'cyan' : ['\x1B[36m', '\x1B[39m'],
'green' : ['\x1B[32m', '\x1B[39m'],
'magenta' : ['\x1B[35m', '\x1B[39m'],
'red' : ['\x1B[31m', '\x1B[39m'],
'yellow' : ['\x1B[33m', '\x1B[39m'],
//background colors
//grayscale
'whiteBG' : ['\x1B[47m', '\x1B[49m'],
'greyBG' : ['\x1B[49;5;8m', '\x1B[49m'],
'blackBG' : ['\x1B[40m', '\x1B[49m'],
//colors
'blueBG' : ['\x1B[44m', '\x1B[49m'],
'cyanBG' : ['\x1B[46m', '\x1B[49m'],
'greenBG' : ['\x1B[42m', '\x1B[49m'],
'magentaBG' : ['\x1B[45m', '\x1B[49m'],
'redBG' : ['\x1B[41m', '\x1B[49m'],
'yellowBG' : ['\x1B[43m', '\x1B[49m']
};
} else if (exports.mode === 'browser') {
styles = {
//styles
'bold' : ['<b>', '</b>'],
'italic' : ['<i>', '</i>'],
'underline' : ['<u>', '</u>'],
'inverse' : ['<span style="background-color:black;color:white;">', '</span>'],
'strikethrough' : ['<del>', '</del>'],
//text colors
//grayscale
'white' : ['<span style="color:white;">', '</span>'],
'grey' : ['<span style="color:gray;">', '</span>'],
'black' : ['<span style="color:black;">', '</span>'],
//colors
'blue' : ['<span style="color:blue;">', '</span>'],
'cyan' : ['<span style="color:cyan;">', '</span>'],
'green' : ['<span style="color:green;">', '</span>'],
'magenta' : ['<span style="color:magenta;">', '</span>'],
'red' : ['<span style="color:red;">', '</span>'],
'yellow' : ['<span style="color:yellow;">', '</span>'],
//background colors
//grayscale
'whiteBG' : ['<span style="background-color:white;">', '</span>'],
'greyBG' : ['<span style="background-color:gray;">', '</span>'],
'blackBG' : ['<span style="background-color:black;">', '</span>'],
//colors
'blueBG' : ['<span style="background-color:blue;">', '</span>'],
'cyanBG' : ['<span style="background-color:cyan;">', '</span>'],
'greenBG' : ['<span style="background-color:green;">', '</span>'],
'magentaBG' : ['<span style="background-color:magenta;">', '</span>'],
'redBG' : ['<span style="background-color:red;">', '</span>'],
'yellowBG' : ['<span style="background-color:yellow;">', '</span>']
};
} else if (exports.mode === 'none') {
return str + '';
} else {
console.log('unsupported mode, try "browser", "console" or "none"');
}
return styles[style][0] + str + styles[style][1];
}
function applyTheme(theme) {
//
// Remark: This is a list of methods that exist
// on String that you should not overwrite.
//
var stringPrototypeBlacklist = [
'__defineGetter__', '__defineSetter__', '__lookupGetter__', '__lookupSetter__', 'charAt', 'constructor',
'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf', 'charCodeAt',
'indexOf', 'lastIndexof', 'length', 'localeCompare', 'match', 'replace', 'search', 'slice', 'split', 'substring',
'toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase', 'trim', 'trimLeft', 'trimRight'
];
Object.keys(theme).forEach(function (prop) {
if (stringPrototypeBlacklist.indexOf(prop) !== -1) {
console.log('warn: '.red + ('String.prototype' + prop).magenta + ' is probably something you don\'t want to override. Ignoring style name');
}
else {
if (typeof(theme[prop]) === 'string') {
addProperty(prop, function () {
return exports[theme[prop]](this);
});
}
else {
addProperty(prop, function () {
var ret = this;
for (var t = 0; t < theme[prop].length; t++) {
ret = exports[theme[prop][t]](ret);
}
return ret;
});
}
}
});
}
//
// Iterate through all default styles and colors
//
var x = ['bold', 'underline', 'strikethrough', 'italic', 'inverse', 'grey', 'black', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta', 'greyBG', 'blackBG', 'yellowBG', 'redBG', 'greenBG', 'blueBG', 'whiteBG', 'cyanBG', 'magentaBG'];
x.forEach(function (style) {
// __defineGetter__ at the least works in more browsers
// http://robertnyman.com/javascript/javascript-getters-setters.html
// Object.defineProperty only works in Chrome
addProperty(style, function () {
return stylize(this, style);
});
});
function sequencer(map) {
return function () {
if (!isHeadless) {
return this.replace(/( )/, '$1');
}
var exploded = this.split(""), i = 0;
exploded = exploded.map(map);
return exploded.join("");
};
}
var rainbowMap = (function () {
var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; //RoY G BiV
return function (letter, i, exploded) {
if (letter === " ") {
return letter;
} else {
return stylize(letter, rainbowColors[i++ % rainbowColors.length]);
}
};
})();
exports.themes = {};
exports.addSequencer = function (name, map) {
addProperty(name, sequencer(map));
};
exports.addSequencer('rainbow', rainbowMap);
exports.addSequencer('zebra', function (letter, i, exploded) {
return i % 2 === 0 ? letter : letter.inverse;
});
exports.setTheme = function (theme) {
if (typeof theme === 'string') {
try {
exports.themes[theme] = require(theme);
applyTheme(exports.themes[theme]);
return exports.themes[theme];
} catch (err) {
console.log(err);
return err;
}
} else {
applyTheme(theme);
}
};
addProperty('stripColors', function () {
return ("" + this).replace(/\x1B\[\d+m/g, '');
});
// please no
function zalgo(text, options) {
var soul = {
"up" : [
'̍', '̎', '̄', '̅',
'̿', '̑', '̆', '̐',
'͒', '͗', '͑', '̇',
'̈', '̊', '͂', '̓',
'̈', '͊', '͋', '͌',
'̃', '̂', '̌', '͐',
'̀', '́', '̋', '̏',
'̒', '̓', '̔', '̽',
'̉', 'ͣ', 'ͤ', 'ͥ',
'ͦ', 'ͧ', 'ͨ', 'ͩ',
'ͪ', 'ͫ', 'ͬ', 'ͭ',
'ͮ', 'ͯ', '̾', '͛',
'͆', '̚'
],
"down" : [
'̖', '̗', '̘', '̙',
'̜', '̝', '̞', '̟',
'̠', '̤', '̥', '̦',
'̩', '̪', '̫', '̬',
'̭', '̮', '̯', '̰',
'̱', '̲', '̳', '̹',
'̺', '̻', '̼', 'ͅ',
'͇', '͈', '͉', '͍',
'͎', '͓', '͔', '͕',
'͖', '͙', '͚', '̣'
],
"mid" : [
'̕', '̛', '̀', '́',
'͘', '̡', '̢', '̧',
'̨', '̴', '̵', '̶',
'͜', '͝', '͞',
'͟', '͠', '͢', '̸',
'̷', '͡', ' ҉'
]
},
all = [].concat(soul.up, soul.down, soul.mid),
zalgo = {};
function randomNumber(range) {
var r = Math.floor(Math.random() * range);
return r;
}
function is_char(character) {
var bool = false;
all.filter(function (i) {
bool = (i === character);
});
return bool;
}
function heComes(text, options) {
var result = '', counts, l;
options = options || {};
options["up"] = options["up"] || true;
options["mid"] = options["mid"] || true;
options["down"] = options["down"] || true;
options["size"] = options["size"] || "maxi";
text = text.split('');
for (l in text) {
if (is_char(l)) {
continue;
}
result = result + text[l];
counts = {"up" : 0, "down" : 0, "mid" : 0};
switch (options.size) {
case 'mini':
counts.up = randomNumber(8);
counts.min = randomNumber(2);
counts.down = randomNumber(8);
break;
case 'maxi':
counts.up = randomNumber(16) + 3;
counts.min = randomNumber(4) + 1;
counts.down = randomNumber(64) + 3;
break;
default:
counts.up = randomNumber(8) + 1;
counts.mid = randomNumber(6) / 2;
counts.down = randomNumber(8) + 1;
break;
}
var arr = ["up", "mid", "down"];
for (var d in arr) {
var index = arr[d];
for (var i = 0 ; i <= counts[index]; i++) {
if (options[index]) {
result = result + soul[index][randomNumber(soul[index].length)];
}
}
}
}
return result;
}
return heComes(text);
}
// don't summon zalgo
addProperty('zalgo', function () {
return zalgo(this);
});

76
node_modules/grunt/node_modules/colors/example.html generated vendored Normal file
View File

@ -0,0 +1,76 @@
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Colors Example</title>
<script src="colors.js"></script>
</head>
<body>
<script>
var test = colors.red("hopefully colorless output");
document.write('Rainbows are fun!'.rainbow + '<br/>');
document.write('So '.italic + 'are'.underline + ' styles! '.bold + 'inverse'.inverse); // styles not widely supported
document.write('Chains are also cool.'.bold.italic.underline.red); // styles not widely supported
//document.write('zalgo time!'.zalgo);
document.write(test.stripColors);
document.write("a".grey + " b".black);
document.write("Zebras are so fun!".zebra);
document.write(colors.rainbow('Rainbows are fun!'));
document.write("This is " + "not".strikethrough + " fun.");
document.write(colors.italic('So ') + colors.underline('are') + colors.bold(' styles! ') + colors.inverse('inverse')); // styles not widely supported
document.write(colors.bold(colors.italic(colors.underline(colors.red('Chains are also cool.'))))); // styles not widely supported
//document.write(colors.zalgo('zalgo time!'));
document.write(colors.stripColors(test));
document.write(colors.grey("a") + colors.black(" b"));
colors.addSequencer("america", function(letter, i, exploded) {
if(letter === " ") return letter;
switch(i%3) {
case 0: return letter.red;
case 1: return letter.white;
case 2: return letter.blue;
}
});
colors.addSequencer("random", (function() {
var available = ['bold', 'underline', 'italic', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta'];
return function(letter, i, exploded) {
return letter === " " ? letter : letter[available[Math.round(Math.random() * (available.length - 1))]];
};
})());
document.write("AMERICA! F--K YEAH!".america);
document.write("So apparently I've been to Mars, with all the little green men. But you know, I don't recall.".random);
//
// Custom themes
//
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
document.write("this is an error".error);
// outputs yellow text
document.write("this is a warning".warn);
</script>
</body>
</html>

77
node_modules/grunt/node_modules/colors/example.js generated vendored Normal file
View File

@ -0,0 +1,77 @@
var colors = require('./colors');
//colors.mode = "browser";
var test = colors.red("hopefully colorless output");
console.log('Rainbows are fun!'.rainbow);
console.log('So '.italic + 'are'.underline + ' styles! '.bold + 'inverse'.inverse); // styles not widely supported
console.log('Chains are also cool.'.bold.italic.underline.red); // styles not widely supported
//console.log('zalgo time!'.zalgo);
console.log(test.stripColors);
console.log("a".grey + " b".black);
console.log("Zebras are so fun!".zebra);
console.log('background color attack!'.black.whiteBG)
//
// Remark: .strikethrough may not work with Mac OS Terminal App
//
console.log("This is " + "not".strikethrough + " fun.");
console.log(colors.rainbow('Rainbows are fun!'));
console.log(colors.italic('So ') + colors.underline('are') + colors.bold(' styles! ') + colors.inverse('inverse')); // styles not widely supported
console.log(colors.bold(colors.italic(colors.underline(colors.red('Chains are also cool.'))))); // styles not widely supported
//console.log(colors.zalgo('zalgo time!'));
console.log(colors.stripColors(test));
console.log(colors.grey("a") + colors.black(" b"));
colors.addSequencer("america", function(letter, i, exploded) {
if(letter === " ") return letter;
switch(i%3) {
case 0: return letter.red;
case 1: return letter.white;
case 2: return letter.blue;
}
});
colors.addSequencer("random", (function() {
var available = ['bold', 'underline', 'italic', 'inverse', 'grey', 'yellow', 'red', 'green', 'blue', 'white', 'cyan', 'magenta'];
return function(letter, i, exploded) {
return letter === " " ? letter : letter[available[Math.round(Math.random() * (available.length - 1))]];
};
})());
console.log("AMERICA! F--K YEAH!".america);
console.log("So apparently I've been to Mars, with all the little green men. But you know, I don't recall.".random);
//
// Custom themes
//
// Load theme with JSON literal
colors.setTheme({
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
});
// outputs red text
console.log("this is an error".error);
// outputs yellow text
console.log("this is a warning".warn);
// outputs grey text
console.log("this is an input".input);
// Load a theme from file
colors.setTheme('./themes/winston-dark.js');
console.log("this is an input".input);

29
node_modules/grunt/node_modules/colors/package.json generated vendored Normal file
View File

@ -0,0 +1,29 @@
{
"name": "colors",
"description": "get colors in your node.js console like what",
"version": "0.6.2",
"author": {
"name": "Marak Squires"
},
"homepage": "https://github.com/Marak/colors.js",
"bugs": {
"url": "https://github.com/Marak/colors.js/issues"
},
"keywords": [
"ansi",
"terminal",
"colors"
],
"repository": {
"type": "git",
"url": "http://github.com/Marak/colors.js.git"
},
"engines": {
"node": ">=0.1.90"
},
"main": "colors",
"readme": "# colors.js - get color and style in your node.js console ( and browser ) like what\n\n<img src=\"http://i.imgur.com/goJdO.png\" border = \"0\"/>\n\n\n## Installation\n\n npm install colors\n\n## colors and styles!\n\n- bold\n- italic\n- underline\n- inverse\n- yellow\n- cyan\n- white\n- magenta\n- green\n- red\n- grey\n- blue\n- rainbow\n- zebra\n- random\n\n## Usage\n\n``` js\nvar colors = require('./colors');\n\nconsole.log('hello'.green); // outputs green text\nconsole.log('i like cake and pies'.underline.red) // outputs red underlined text\nconsole.log('inverse the color'.inverse); // inverses the color\nconsole.log('OMG Rainbows!'.rainbow); // rainbow (ignores spaces)\n```\n\n# Creating Custom themes\n\n```js\n\nvar colors = require('colors');\n\ncolors.setTheme({\n silly: 'rainbow',\n input: 'grey',\n verbose: 'cyan',\n prompt: 'grey',\n info: 'green',\n data: 'grey',\n help: 'cyan',\n warn: 'yellow',\n debug: 'blue',\n error: 'red'\n});\n\n// outputs red text\nconsole.log(\"this is an error\".error);\n\n// outputs yellow text\nconsole.log(\"this is a warning\".warn);\n```\n\n\n### Contributors \n\nMarak (Marak Squires)\nAlexis Sellier (cloudhead)\nmmalecki (Maciej Małecki)\nnicoreed (Nico Reed)\nmorganrallen (Morgan Allen)\nJustinCampbell (Justin Campbell)\nded (Dustin Diaz)\n\n\n#### , Marak Squires , Justin Campbell, Dustin Diaz (@ded)\n",
"readmeFilename": "ReadMe.md",
"_id": "colors@0.6.2",
"_from": "colors@~0.6.2"
}

70
node_modules/grunt/node_modules/colors/test.js generated vendored Normal file
View File

@ -0,0 +1,70 @@
var assert = require('assert'),
colors = require('./colors');
var s = 'string';
function a(s, code) {
return '\x1B[' + code.toString() + 'm' + s + '\x1B[39m';
}
function aE(s, color, code) {
assert.equal(s[color], a(s, code));
assert.equal(colors[color](s), a(s, code));
assert.equal(s[color], colors[color](s));
assert.equal(s[color].stripColors, s);
assert.equal(s[color].stripColors, colors.stripColors(s));
}
function h(s, color) {
return '<span style="color:' + color + ';">' + s + '</span>';
}
var stylesColors = ['white', 'black', 'blue', 'cyan', 'green', 'magenta', 'red', 'yellow'];
var stylesAll = stylesColors.concat(['bold', 'italic', 'underline', 'inverse', 'rainbow']);
colors.mode = 'console';
assert.equal(s.bold, '\x1B[1m' + s + '\x1B[22m');
assert.equal(s.italic, '\x1B[3m' + s + '\x1B[23m');
assert.equal(s.underline, '\x1B[4m' + s + '\x1B[24m');
assert.equal(s.strikethrough, '\x1B[9m' + s + '\x1B[29m');
assert.equal(s.inverse, '\x1B[7m' + s + '\x1B[27m');
assert.ok(s.rainbow);
aE(s, 'white', 37);
aE(s, 'grey', 90);
aE(s, 'black', 30);
aE(s, 'blue', 34);
aE(s, 'cyan', 36);
aE(s, 'green', 32);
aE(s, 'magenta', 35);
aE(s, 'red', 31);
aE(s, 'yellow', 33);
assert.equal(s, 'string');
colors.setTheme({error:'red'});
assert.equal(typeof("astring".red),'string');
assert.equal(typeof("astring".error),'string');
colors.mode = 'browser';
assert.equal(s.bold, '<b>' + s + '</b>');
assert.equal(s.italic, '<i>' + s + '</i>');
assert.equal(s.underline, '<u>' + s + '</u>');
assert.equal(s.strikethrough, '<del>' + s + '</del>');
assert.equal(s.inverse, '<span style="background-color:black;color:white;">' + s + '</span>');
assert.ok(s.rainbow);
stylesColors.forEach(function (color) {
assert.equal(s[color], h(s, color));
assert.equal(colors[color](s), h(s, color));
});
assert.equal(typeof("astring".red),'string');
assert.equal(typeof("astring".error),'string');
colors.mode = 'none';
stylesAll.forEach(function (style) {
assert.equal(s[style], s);
assert.equal(colors[style](s), s);
});
assert.equal(typeof("astring".red),'string');
assert.equal(typeof("astring".error),'string');

View File

@ -0,0 +1,12 @@
module['exports'] = {
silly: 'rainbow',
input: 'black',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
};

View File

@ -0,0 +1,12 @@
module['exports'] = {
silly: 'rainbow',
input: 'grey',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red'
};

67
node_modules/grunt/node_modules/dateformat/Readme.md generated vendored Normal file
View File

@ -0,0 +1,67 @@
# node-dateformat
A node.js package for Steven Levithan's excellent [dateFormat()][dateformat] function.
## Modifications
* Removed the `Date.prototype.format` method. Sorry folks, but extending native prototypes is for suckers.
* Added a `module.exports = dateFormat;` statement at the bottom
## Usage
As taken from Steven's post, modified to match the Modifications listed above:
var dateFormat = require('dateformat');
var now = new Date();
// Basic usage
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM
// You can use one of several named masks
dateFormat(now, "isoDateTime");
// 2007-06-09T17:46:21
// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
dateFormat(now, "hammerTime");
// 17:46! Can't touch this!
// When using the standalone dateFormat function,
// you can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007
// Note that if you don't include the mask argument,
// dateFormat.masks.default is used
dateFormat(now);
// Sat Jun 09 2007 17:46:21
// And if you don't include the date argument,
// the current date and time is used
dateFormat();
// Sat Jun 09 2007 17:46:22
// You can also skip the date argument (as long as your mask doesn't
// contain any numbers), in which case the current date/time is used
dateFormat("longTime");
// 5:46:22 PM EST
// And finally, you can convert local time to UTC time. Simply pass in
// true as an additional argument (no argument skipping allowed in this case):
dateFormat(now, "longTime", true);
// 10:46:21 PM UTC
// ...Or add the prefix "UTC:" to your mask.
dateFormat(now, "UTC:h:MM:ss TT Z");
// 10:46:21 PM UTC
// You can also get the ISO 8601 week of the year:
dateFormat(now, "W");
// 42
## License
(c) 2007-2009 Steven Levithan [stevenlevithan.com][stevenlevithan], MIT license.
[dateformat]: http://blog.stevenlevithan.com/archives/date-time-format
[stevenlevithan]: http://stevenlevithan.com/

View File

@ -0,0 +1,165 @@
/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/
var dateFormat = function () {
var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZW]|"[^"]*"|'[^']*'/g,
timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
timezoneClip = /[^-+\dA-Z]/g,
pad = function (val, len) {
val = String(val);
len = len || 2;
while (val.length < len) val = "0" + val;
return val;
},
/**
* Get the ISO 8601 week number
* Based on comments from
* http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html
*/
getWeek = function (date) {
// Remove time components of date
var targetThursday = new Date(date.getFullYear(), date.getMonth(), date.getDate());
// Change date to Thursday same week
targetThursday.setDate(targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3);
// Take January 4th as it is always in week 1 (see ISO 8601)
var firstThursday = new Date(targetThursday.getFullYear(), 0, 4);
// Change date to Thursday same week
firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3);
// Check if daylight-saving-time-switch occured and correct for it
var ds = targetThursday.getTimezoneOffset()/firstThursday.getTimezoneOffset()-1;
targetThursday.setHours(targetThursday.getHours()+ds);
// Number of weeks between target Thursday and first Thursday
var weekDiff = (targetThursday - firstThursday) / (86400000*7);
return 1 + weekDiff;
};
// Regexes and supporting functions are cached through closure
return function (date, mask, utc) {
var dF = dateFormat;
// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
mask = date;
date = undefined;
}
date = date || new Date;
if(!(date instanceof Date)) {
date = new Date(date);
}
if (isNaN(date)) {
throw TypeError("Invalid date");
}
mask = String(dF.masks[mask] || mask || dF.masks["default"]);
// Allow setting the utc argument via the mask
if (mask.slice(0, 4) == "UTC:") {
mask = mask.slice(4);
utc = true;
}
var _ = utc ? "getUTC" : "get",
d = date[_ + "Date"](),
D = date[_ + "Day"](),
m = date[_ + "Month"](),
y = date[_ + "FullYear"](),
H = date[_ + "Hours"](),
M = date[_ + "Minutes"](),
s = date[_ + "Seconds"](),
L = date[_ + "Milliseconds"](),
o = utc ? 0 : date.getTimezoneOffset(),
W = getWeek(date),
flags = {
d: d,
dd: pad(d),
ddd: dF.i18n.dayNames[D],
dddd: dF.i18n.dayNames[D + 7],
m: m + 1,
mm: pad(m + 1),
mmm: dF.i18n.monthNames[m],
mmmm: dF.i18n.monthNames[m + 12],
yy: String(y).slice(2),
yyyy: y,
h: H % 12 || 12,
hh: pad(H % 12 || 12),
H: H,
HH: pad(H),
M: M,
MM: pad(M),
s: s,
ss: pad(s),
l: pad(L, 3),
L: pad(L > 99 ? Math.round(L / 10) : L),
t: H < 12 ? "a" : "p",
tt: H < 12 ? "am" : "pm",
T: H < 12 ? "A" : "P",
TT: H < 12 ? "AM" : "PM",
Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10],
W: W
};
return mask.replace(token, function ($0) {
return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
});
};
}();
// Some common format strings
dateFormat.masks = {
"default": "ddd mmm dd yyyy HH:MM:ss",
shortDate: "m/d/yy",
mediumDate: "mmm d, yyyy",
longDate: "mmmm d, yyyy",
fullDate: "dddd, mmmm d, yyyy",
shortTime: "h:MM TT",
mediumTime: "h:MM:ss TT",
longTime: "h:MM:ss TT Z",
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
// Internationalization strings
dateFormat.i18n = {
dayNames: [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
]
};
/*
// For convenience...
Date.prototype.format = function (mask, utc) {
return dateFormat(this, mask, utc);
};
*/
if (typeof exports !== "undefined") {
module.exports = dateFormat;
}

View File

@ -0,0 +1,24 @@
{
"name": "dateformat",
"description": "A node.js package for Steven Levithan's excellent dateFormat() function.",
"maintainers": "Felix Geisendörfer <felix@debuggable.com>",
"homepage": "https://github.com/felixge/node-dateformat",
"author": {
"name": "Steven Levithan"
},
"version": "1.0.2-1.2.3",
"main": "./lib/dateformat",
"dependencies": {},
"devDependencies": {},
"engines": {
"node": "*"
},
"readme": "# node-dateformat\n\nA node.js package for Steven Levithan's excellent [dateFormat()][dateformat] function.\n\n## Modifications\n\n* Removed the `Date.prototype.format` method. Sorry folks, but extending native prototypes is for suckers.\n* Added a `module.exports = dateFormat;` statement at the bottom\n\n## Usage\n\nAs taken from Steven's post, modified to match the Modifications listed above:\n\n var dateFormat = require('dateformat');\n var now = new Date();\n\n // Basic usage\n dateFormat(now, \"dddd, mmmm dS, yyyy, h:MM:ss TT\");\n // Saturday, June 9th, 2007, 5:46:21 PM\n\n // You can use one of several named masks\n dateFormat(now, \"isoDateTime\");\n // 2007-06-09T17:46:21\n\n // ...Or add your own\n dateFormat.masks.hammerTime = 'HH:MM! \"Can\\'t touch this!\"';\n dateFormat(now, \"hammerTime\");\n // 17:46! Can't touch this!\n\n // When using the standalone dateFormat function,\n // you can also provide the date as a string\n dateFormat(\"Jun 9 2007\", \"fullDate\");\n // Saturday, June 9, 2007\n\n // Note that if you don't include the mask argument,\n // dateFormat.masks.default is used\n dateFormat(now);\n // Sat Jun 09 2007 17:46:21\n\n // And if you don't include the date argument,\n // the current date and time is used\n dateFormat();\n // Sat Jun 09 2007 17:46:22\n\n // You can also skip the date argument (as long as your mask doesn't\n // contain any numbers), in which case the current date/time is used\n dateFormat(\"longTime\");\n // 5:46:22 PM EST\n\n // And finally, you can convert local time to UTC time. Simply pass in\n // true as an additional argument (no argument skipping allowed in this case):\n dateFormat(now, \"longTime\", true);\n // 10:46:21 PM UTC\n\n // ...Or add the prefix \"UTC:\" to your mask.\n dateFormat(now, \"UTC:h:MM:ss TT Z\");\n // 10:46:21 PM UTC\n\n // You can also get the ISO 8601 week of the year:\n dateFormat(now, \"W\");\n // 42\n## License\n\n(c) 2007-2009 Steven Levithan [stevenlevithan.com][stevenlevithan], MIT license.\n\n[dateformat]: http://blog.stevenlevithan.com/archives/date-time-format\n[stevenlevithan]: http://stevenlevithan.com/\n",
"readmeFilename": "Readme.md",
"_id": "dateformat@1.0.2-1.2.3",
"dist": {
"shasum": "ab20933c408e06a81b20940f9b39a46280a445b3"
},
"_from": "dateformat@1.0.2-1.2.3",
"_resolved": "https://registry.npmjs.org/dateformat/-/dateformat-1.0.2-1.2.3.tgz"
}

View File

@ -0,0 +1,4 @@
var dateFormat = require('../lib/dateformat.js');
var val = process.argv[2] || new Date();
console.log(dateFormat(val, 'W'));

View File

@ -0,0 +1,27 @@
#!/bin/bash
# this just takes php's date() function as a reference to check if week of year
# is calculated correctly in the range from 1970 .. 2038 by brute force...
SEQ="seq"
SYSTEM=`uname`
if [ "$SYSTEM" = "Darwin" ]; then
SEQ="jot"
fi
for YEAR in {1970..2038}; do
for MONTH in {1..12}; do
DAYS=$(cal $MONTH $YEAR | egrep "28|29|30|31" |tail -1 |awk '{print $NF}')
for DAY in $( $SEQ $DAYS ); do
DATE=$YEAR-$MONTH-$DAY
echo -n $DATE ...
NODEVAL=$(node test_weekofyear.js $DATE)
PHPVAL=$(php -r "echo intval(date('W', strtotime('$DATE')));")
if [ "$NODEVAL" -ne "$PHPVAL" ]; then
echo "MISMATCH: node: $NODEVAL vs php: $PHPVAL for date $DATE"
else
echo " OK"
fi
done
done
done

212
node_modules/grunt/node_modules/eventemitter2/README.md generated vendored Normal file
View File

@ -0,0 +1,212 @@
# EventEmitter2
EventEmitter2 is an implementation of the EventEmitter found in Node.js
## Features
- Namespaces/Wildcards.
- Times To Listen (TTL), extends the `once` concept with `many`.
- Browser environment compatibility.
- Demonstrates good performance in benchmarks
```
EventEmitterHeatUp x 3,728,965 ops/sec \302\2610.68% (60 runs sampled)
EventEmitter x 2,822,904 ops/sec \302\2610.74% (63 runs sampled)
EventEmitter2 x 7,251,227 ops/sec \302\2610.55% (58 runs sampled)
EventEmitter2 (wild) x 3,220,268 ops/sec \302\2610.44% (65 runs sampled)
Fastest is EventEmitter2
```
## Differences (Non breaking, compatible with existing EventEmitter)
- The constructor takes a configuration object.
```javascript
var EventEmitter2 = require('eventemitter2').EventEmitter2;
var server = new EventEmitter2({
wildcard: true, // should the event emitter use wildcards.
delimiter: '::', // the delimiter used to segment namespaces, defaults to `.`.
newListener: false, // if you want to emit the newListener event set to true.
maxListeners: 20, // the max number of listeners that can be assigned to an event, defaults to 10.
});
```
- Getting the actual event that fired.
```javascript
server.on('foo.*', function(value1, value2) {
console.log(this.event, value1, value2);
});
```
- Fire an event N times and then remove it, an extension of the `once` concept.
```javascript
server.many('foo', 4, function() {
console.log('hello');
});
```
- Pass in a namespaced event as an array rather than a delimited string.
```javascript
server.many(['foo', 'bar', 'bazz'], function() {
console.log('hello');
});
```
## API
When an `EventEmitter` instance experiences an error, the typical action is
to emit an `error` event. Error events are treated as a special case.
If there is no listener for it, then the default action is to print a stack
trace and exit the program.
All EventEmitters emit the event `newListener` when new listeners are
added.
**Namespaces** with **Wildcards**
To use namespaces/wildcards, pass the `wildcard` option into the EventEmitter constructor.
When namespaces/wildcards are enabled, events can either be strings (`foo.bar`) separated
by a delimiter or arrays (`['foo', 'bar']`). The delimiter is also configurable as a
constructor option.
An event name passed to any event emitter method can contain a wild card (the `*` character).
If the event name is a string, a wildcard may appear as `foo.*`. If the event name is an array,
the wildcard may appear as `['foo', '*']`.
If either of the above described events were passed to the `on` method, subsequent emits such
as the following would be observed...
```javascript
emitter.emit('foo.bazz');
emitter.emit(['foo', 'bar']);
```
#### emitter.addListener(event, listener)
#### emitter.on(event, listener)
Adds a listener to the end of the listeners array for the specified event.
```javascript
server.on('data', function(value1, value2, value3 /* accepts any number of expected values... */) {
console.log('The event was raised!');
});
```
```javascript
server.on('data', function(value) {
console.log('The event was raised!');
});
```
#### emitter.onAny(listener)
Adds a listener that will be fired when any event is emitted.
```javascript
server.onAny(function(value) {
console.log('All events trigger this.');
});
```
#### emitter.offAny(listener)
Removes the listener that will be fired when any event is emitted.
```javascript
server.offAny(function(value) {
console.log('The event was raised!');
});
```
#### emitter.once(event, listener)
Adds a **one time** listener for the event. The listener is invoked only the first time the event is fired, after which it is removed.
```javascript
server.once('get', function (value) {
console.log('Ah, we have our first value!');
});
```
#### emitter.many(event, timesToListen, listener)
Adds a listener that will execute **n times** for the event before being removed. The listener is invoked only the first time the event is fired, after which it is removed.
```javascript
server.many('get', 4, function (value) {
console.log('This event will be listened to exactly four times.');
});
```
#### emitter.removeListener(event, listener)
#### emitter.off(event, listener)
Remove a listener from the listener array for the specified event. **Caution**: changes array indices in the listener array behind the listener.
```javascript
var callback = function(value) {
console.log('someone connected!');
};
server.on('get', callback);
// ...
server.removeListener('get', callback);
```
#### emitter.removeAllListeners([event])
Removes all listeners, or those of the specified event.
#### emitter.setMaxListeners(n)
By default EventEmitters will print a warning if more than 10 listeners are added to it. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. This function allows that to be increased. Set to zero for unlimited.
#### emitter.listeners(event)
Returns an array of listeners for the specified event. This array can be manipulated, e.g. to remove listeners.
```javascript
server.on('get', function(value) {
console.log('someone connected!');
});
console.log(console.log(server.listeners('get')); // [ [Function] ]
```
#### emitter.listenersAny()
Returns an array of listeners that are listening for any event that is specified. This array can be manipulated, e.g. to remove listeners.
```javascript
server.onAny(function(value) {
console.log('someone connected!');
});
console.log(console.log(server.listenersAny()[0]); // [ [Function] ] // someone connected!
```
#### emitter.emit(event, [arg1], [arg2], [...])
Execute each of the listeners that may be listening for the specified event name in order with the list of arguments.
## Test coverage
There is a test suite that tries to cover each use case, it can be found <a href="https://github.com/hij1nx/EventEmitter2/tree/master/test">here</a>.
## Licence
(The MIT License)
Copyright (c) 2011 hij1nx <http://www.twitter.com/hij1nx>
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.

View File

@ -0,0 +1 @@
module.exports = require('./lib/eventemitter2');

View File

@ -0,0 +1,561 @@
;!function(exports, undefined) {
var isArray = Array.isArray ? Array.isArray : function _isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
var defaultMaxListeners = 10;
function init() {
this._events = {};
if (this._conf) {
configure.call(this, this._conf);
}
}
function configure(conf) {
if (conf) {
this._conf = conf;
conf.delimiter && (this.delimiter = conf.delimiter);
conf.maxListeners && (this._events.maxListeners = conf.maxListeners);
conf.wildcard && (this.wildcard = conf.wildcard);
conf.newListener && (this.newListener = conf.newListener);
if (this.wildcard) {
this.listenerTree = {};
}
}
}
function EventEmitter(conf) {
this._events = {};
this.newListener = false;
configure.call(this, conf);
}
//
// Attention, function return type now is array, always !
// It has zero elements if no any matches found and one or more
// elements (leafs) if there are matches
//
function searchListenerTree(handlers, type, tree, i) {
if (!tree) {
return [];
}
var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached,
typeLength = type.length, currentType = type[i], nextType = type[i+1];
if (i === typeLength && tree._listeners) {
//
// If at the end of the event(s) list and the tree has listeners
// invoke those listeners.
//
if (typeof tree._listeners === 'function') {
handlers && handlers.push(tree._listeners);
return [tree];
} else {
for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) {
handlers && handlers.push(tree._listeners[leaf]);
}
return [tree];
}
}
if ((currentType === '*' || currentType === '**') || tree[currentType]) {
//
// If the event emitted is '*' at this part
// or there is a concrete match at this patch
//
if (currentType === '*') {
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1));
}
}
return listeners;
} else if(currentType === '**') {
endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*'));
if(endReached && tree._listeners) {
// The next element has a _listeners, add it to the handlers.
listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength));
}
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
if(branch === '*' || branch === '**') {
if(tree[branch]._listeners && !endReached) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength));
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
} else if(branch === nextType) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2));
} else {
// No match on this one, shift into the tree but not in the type array.
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
}
}
}
return listeners;
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1));
}
xTree = tree['*'];
if (xTree) {
//
// If the listener tree will allow any match for this part,
// then recursively explore all branches of the tree
//
searchListenerTree(handlers, type, xTree, i+1);
}
xxTree = tree['**'];
if(xxTree) {
if(i < typeLength) {
if(xxTree._listeners) {
// If we have a listener on a '**', it will catch all, so add its handler.
searchListenerTree(handlers, type, xxTree, typeLength);
}
// Build arrays of matching next branches and others.
for(branch in xxTree) {
if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) {
if(branch === nextType) {
// We know the next element will match, so jump twice.
searchListenerTree(handlers, type, xxTree[branch], i+2);
} else if(branch === currentType) {
// Current node matches, move into the tree.
searchListenerTree(handlers, type, xxTree[branch], i+1);
} else {
isolatedBranch = {};
isolatedBranch[branch] = xxTree[branch];
searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1);
}
}
}
} else if(xxTree._listeners) {
// We have reached the end and still on a '**'
searchListenerTree(handlers, type, xxTree, typeLength);
} else if(xxTree['*'] && xxTree['*']._listeners) {
searchListenerTree(handlers, type, xxTree['*'], typeLength);
}
}
return listeners;
}
function growListenerTree(type, listener) {
type = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
//
// Looks for two consecutive '**', if so, don't add the event at all.
//
for(var i = 0, len = type.length; i+1 < len; i++) {
if(type[i] === '**' && type[i+1] === '**') {
return;
}
}
var tree = this.listenerTree;
var name = type.shift();
while (name) {
if (!tree[name]) {
tree[name] = {};
}
tree = tree[name];
if (type.length === 0) {
if (!tree._listeners) {
tree._listeners = listener;
}
else if(typeof tree._listeners === 'function') {
tree._listeners = [tree._listeners, listener];
}
else if (isArray(tree._listeners)) {
tree._listeners.push(listener);
if (!tree._listeners.warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && tree._listeners.length > m) {
tree._listeners.warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
tree._listeners.length);
console.trace();
}
}
}
return true;
}
name = type.shift();
}
return true;
}
// By default EventEmitters will print a warning if more than
// 10 listeners are added to it. This is a useful default which
// helps finding memory leaks.
//
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.delimiter = '.';
EventEmitter.prototype.setMaxListeners = function(n) {
this._events || init.call(this);
this._events.maxListeners = n;
if (!this._conf) this._conf = {};
this._conf.maxListeners = n;
};
EventEmitter.prototype.event = '';
EventEmitter.prototype.once = function(event, fn) {
this.many(event, 1, fn);
return this;
};
EventEmitter.prototype.many = function(event, ttl, fn) {
var self = this;
if (typeof fn !== 'function') {
throw new Error('many only accepts instances of Function');
}
function listener() {
if (--ttl === 0) {
self.off(event, listener);
}
fn.apply(this, arguments);
}
listener._origin = fn;
this.on(event, listener);
return self;
};
EventEmitter.prototype.emit = function() {
this._events || init.call(this);
var type = arguments[0];
if (type === 'newListener' && !this.newListener) {
if (!this._events.newListener) { return false; }
}
// Loop through the *_all* functions and invoke them.
if (this._all) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
for (i = 0, l = this._all.length; i < l; i++) {
this.event = type;
this._all[i].apply(this, args);
}
}
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._all &&
!this._events.error &&
!(this.wildcard && this.listenerTree.error)) {
if (arguments[1] instanceof Error) {
throw arguments[1]; // Unhandled 'error' event
} else {
throw new Error("Uncaught, unspecified 'error' event.");
}
return false;
}
}
var handler;
if(this.wildcard) {
handler = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handler, ns, this.listenerTree, 0);
}
else {
handler = this._events[type];
}
if (typeof handler === 'function') {
this.event = type;
if (arguments.length === 1) {
handler.call(this);
}
else if (arguments.length > 1)
switch (arguments.length) {
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
handler.apply(this, args);
}
return true;
}
else if (handler) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
this.event = type;
listeners[i].apply(this, args);
}
return (listeners.length > 0) || this._all;
}
else {
return this._all;
}
};
EventEmitter.prototype.on = function(type, listener) {
if (typeof type === 'function') {
this.onAny(type);
return this;
}
if (typeof listener !== 'function') {
throw new Error('on only accepts instances of Function');
}
this._events || init.call(this);
// To avoid recursion in the case that type == "newListeners"! Before
// adding it to the listeners, first emit "newListeners".
this.emit('newListener', type, listener);
if(this.wildcard) {
growListenerTree.call(this, type, listener);
return this;
}
if (!this._events[type]) {
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
}
else if(typeof this._events[type] === 'function') {
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
}
else if (isArray(this._events[type])) {
// If we've already got an array, just append.
this._events[type].push(listener);
// Check for listener leak
if (!this._events[type].warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.onAny = function(fn) {
if(!this._all) {
this._all = [];
}
if (typeof fn !== 'function') {
throw new Error('onAny only accepts instances of Function');
}
// Add the function to the event listener collection.
this._all.push(fn);
return this;
};
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
EventEmitter.prototype.off = function(type, listener) {
if (typeof listener !== 'function') {
throw new Error('removeListener only takes instances of Function');
}
var handlers,leafs=[];
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
}
else {
// does not use listeners(), so no side effect of creating _events[type]
if (!this._events[type]) return this;
handlers = this._events[type];
leafs.push({_listeners:handlers});
}
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
handlers = leaf._listeners;
if (isArray(handlers)) {
var position = -1;
for (var i = 0, length = handlers.length; i < length; i++) {
if (handlers[i] === listener ||
(handlers[i].listener && handlers[i].listener === listener) ||
(handlers[i]._origin && handlers[i]._origin === listener)) {
position = i;
break;
}
}
if (position < 0) {
continue;
}
if(this.wildcard) {
leaf._listeners.splice(position, 1);
}
else {
this._events[type].splice(position, 1);
}
if (handlers.length === 0) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
return this;
}
else if (handlers === listener ||
(handlers.listener && handlers.listener === listener) ||
(handlers._origin && handlers._origin === listener)) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
}
return this;
};
EventEmitter.prototype.offAny = function(fn) {
var i = 0, l = 0, fns;
if (fn && this._all && this._all.length > 0) {
fns = this._all;
for(i = 0, l = fns.length; i < l; i++) {
if(fn === fns[i]) {
fns.splice(i, 1);
return this;
}
}
} else {
this._all = [];
}
return this;
};
EventEmitter.prototype.removeListener = EventEmitter.prototype.off;
EventEmitter.prototype.removeAllListeners = function(type) {
if (arguments.length === 0) {
!this._events || init.call(this);
return this;
}
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
leaf._listeners = null;
}
}
else {
if (!this._events[type]) return this;
this._events[type] = null;
}
return this;
};
EventEmitter.prototype.listeners = function(type) {
if(this.wildcard) {
var handlers = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handlers, ns, this.listenerTree, 0);
return handlers;
}
this._events || init.call(this);
if (!this._events[type]) this._events[type] = [];
if (!isArray(this._events[type])) {
this._events[type] = [this._events[type]];
}
return this._events[type];
};
EventEmitter.prototype.listenersAny = function() {
if(this._all) {
return this._all;
}
else {
return [];
}
};
if (typeof define === 'function' && define.amd) {
define(function() {
return EventEmitter;
});
} else {
exports.EventEmitter2 = EventEmitter;
}
}(typeof process !== 'undefined' && typeof process.title !== 'undefined' && typeof exports !== 'undefined' ? exports : window);

File diff suppressed because one or more lines are too long

14
node_modules/grunt/node_modules/exit/.jshintrc generated vendored Normal file
View File

@ -0,0 +1,14 @@
{
"curly": true,
"eqeqeq": true,
"immed": true,
"latedef": "nofunc",
"newcap": true,
"noarg": true,
"sub": true,
"undef": true,
"unused": true,
"boss": true,
"eqnull": true,
"node": true
}

0
node_modules/grunt/node_modules/exit/.npmignore generated vendored Normal file
View File

6
node_modules/grunt/node_modules/exit/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,6 @@
language: node_js
node_js:
- 0.8
- '0.10'
before_script:
- npm install -g grunt-cli

48
node_modules/grunt/node_modules/exit/Gruntfile.js generated vendored Normal file
View File

@ -0,0 +1,48 @@
'use strict';
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
nodeunit: {
files: ['test/**/*_test.js'],
},
jshint: {
options: {
jshintrc: '.jshintrc'
},
gruntfile: {
src: 'Gruntfile.js'
},
lib: {
src: ['lib/**/*.js']
},
test: {
src: ['test/**/*.js']
},
},
watch: {
gruntfile: {
files: '<%= jshint.gruntfile.src %>',
tasks: ['jshint:gruntfile']
},
lib: {
files: '<%= jshint.lib.src %>',
tasks: ['jshint:lib', 'nodeunit']
},
test: {
files: '<%= jshint.test.src %>',
tasks: ['jshint:test', 'nodeunit']
},
},
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
// Default task.
grunt.registerTask('default', ['jshint', 'nodeunit']);
};

22
node_modules/grunt/node_modules/exit/LICENSE-MIT generated vendored Normal file
View File

@ -0,0 +1,22 @@
Copyright (c) 2013 "Cowboy" Ben Alman
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.

Some files were not shown because too many files have changed in this diff Show More