Added node-modules

This commit is contained in:
Dobie Wollert
2014-09-14 07:04:16 -04:00
parent 663941bf57
commit 6a92348cf5
4870 changed files with 670395 additions and 0 deletions

2
node_modules/piler/.npmignore generated vendored Normal file
View File

@ -0,0 +1,2 @@
.idea
node_modules/

4
node_modules/piler/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,4 @@
language: node_js
node_js:
- 0.6
- 0.8

22
node_modules/piler/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2013 Esa-Matti <esa-matti@suuronen.org>
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.

566
node_modules/piler/README.md generated vendored Normal file
View File

@ -0,0 +1,566 @@
# Piler
[![Build Status](https://secure.travis-ci.org/epeli/piler.png)](http://travis-ci.org/epeli/piler)
Feature highlights
* Minify and concatenate JS and CSS for fast page loads
* Tag rendering
* Namespaces
* Transparent preprocessor
* Push CSS changes to the browser using Socket.IO
* Easy code sharing with server
## Awesome Asset Manager for Node.js
*Piler* allows you to manage all your JavaScript and CSS assets cleanly and
directly from code. It will concatenate and minify them in production and it
takes care of rendering the tags. The idea is to make your pages load as
quickly as possible.
So why create a yet another asset manager? Because Node.js is special. In
Node.js a JavaScript asset isn't just a pile of bits that are sent to the
browser. It's code. It's code that can be also used in the server and I think
that it's the job of asset managers to help with it. So in *Piler* you can take
code directly from your Javascript objects, not just from JavaScript files.
Copying things from Rails is just not enough. This is just a one reason why
*Piler* was created.
Server-side code:
```javascript
clientjs.addOb({BROWSER_GLOBAL: {
aFunction: function() {
console.log("Hello I'm in the browser also. Here I have", window, "and other friends");
}
}});
```
You can also tell *Piler* to directly execute some function in the browser:
```javascript
clientjs.addExec(function() {
BROWSER_GLOBAL.aFunction();
alert("Hello" + window.navigator.appVersion);
});
```
Currently *Piler* works only with [Express], but other frameworks are planned
as well.
*Piler* is written following principles in mind:
* Creating best possible production setup for assets should be as easy as
including script/link to a page.
* Namespaces. You don't want to serve huge blob of admin view code for all
anonymous users.
* Support any JS- or CSS-files. No need to create special structure for your
assets. Just include your jQueries or whatever.
* Preprocessor languages are first class citizens. Eg. Just change the file
extension to .coffee to use CoffeeScript. That's it. No need to worry about
compiled files.
* Use heavy caching. Browser caches are killed automatically using the hash
sum of the assets.
* Awesome development mode. Build-in support for pushing CSS changes to
browsr using Socket.IO.
**Full example Express 2.x**
```javascript
var createServer = require("express").createServer;
var piler = require("piler");
var app = createServer();
var clientjs = piler.createJSManager();
var clientcss = piler.createCSSManager();
app.configure(function() {
clientjs.bind(app);
clientcss.bind(app);
clientcss.addFile(__dirname + "/style.css");
clientjs.addUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js");
clientjs.addFile(__dirname + "/client/hello.js");
});
app.configure("development", function() {
clientjs.liveUpdate(clientcss);
});
clientjs.addOb({ VERSION: "1.0.0" });
clientjs.addExec(function() {
alert("Hello browser" + window.navigator.appVersion);
});
app.get("/", function(req, res){
res.render("index.jade", {
layout: false,
js: clientjs.renderTags(),
css: clientcss.renderTags()
});
});
app.listen(8080);
```
**Full example Express 3.x**
```javascript
var express = require('express'),
http = require('http'),
piler = require("piler"),
app = express();
var clientjs = piler.createJSManager();
var clientcss = piler.createCSSManager();
var srv = require('http').createServer(app);
app.configure(function(){
clientjs.bind(app,srv);
clientcss.bind(app,srv);
clientcss.addFile(__dirname + "/style.css");
clientjs.addUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js");
clientjs.addFile(__dirname + "/client/hello.js");
});
app.configure("development", function() {
clientjs.liveUpdate(clientcss);
});
clientjs.addOb({ VERSION: "1.0.0" });
clientjs.addExec(function() {
alert("Hello browser" + window.navigator.appVersion);
});
app.get("/", function(req, res){
res.render("index.jade", {
layout: false,
js: clientjs.renderTags(),
css: clientcss.renderTags()
});
});
srv.listen(8080);
```
index.jade:
```jade
!!! 5
html
head
!{css}
!{js}
body
h1 Hello Piler
```
## Namespaces
The example above uses just a one pile. The global pile.
If you for example want to add big editor files only for administration pages
you can create a pile for it:
```javascript
clientjs.addFile("admin", __dirname + "/editor.js");
clientjs.addFile("admin", __dirname + "/editor.extension.js");
```
This will add file editor.js and editor.extension.js to a admin pile. Now you
can add that to your admin pages by using giving it as parameter for
*renderTags*.
```javascript
js.renderTags("admin");
```
This will render script-tags for the global pile and the admin-pile.
*js.renderTags* and *css.renderTags* can take variable amount of arguments.
Use *js.renderTags("pile1", "pile2", ....)* to render multiple namespaces
Piling works just the same with css.
## Sharing code with the server
Ok, that's pretty much what every asset manager does, but with *Piler* you can
share code directly from your server code.
Let's say that you want to share a email-validating function with a server and
the client
```javascript
function isEmail(s) {
return !! s.match(/.\w+@\w+\.\w/);
}
```
You can share it with *addOb* -method:
```javascript
clientjs.addOb({MY: {
isEmail: isEmail
}
});
```
Now on the client you can find the isEmail-function from MY.isEmail.
*addOb* takes an object which will be merged to global window-object on the
client. So be carefull when choosing the keys. The object can be almost any
JavaScript object. It will be serialized and sent to the browser. Few caveats:
1. No circural references
1. Functions will be serialized using Function.prototype.toString. So closures
won't transferred to the client!
### Pattern for sharing full modules
This is nothing specific to *Piler*, but this is a nice pattern which can be
used to share modules between the server and the client.
share.js
```javascript
(function(exports){
exports.test = function(){
return 'This is a function from shared module';
};
}(typeof exports === 'undefined' ? this.share = {} : exports));
```
In Node.js you can use it by just requiring it as any other module
```javascript
var share = require("./share.js");
```
and you can share it the client using *addFile*:
```javascript
clientjs.addFile(__dirname + "./share.js");
```
Now you can use it in both as you would expect
```javascript
share.test();
```
You can read more about the pattern from [here](http://caolanmcmahon.com/posts/writing_for_node_and_the_browser)
## Logging
Sometimes it is nessesary to control pilers output based on the system environment your running your application in.
In default mode Pilers logger will output any information it has by using the "console" javascript object. The following example shows
how to configure a custom logger
### Logger interface
The basic logger facility implements the following methods.
```javascript
exports.debug = console.debug
exports.notice = console.log
exports.info = console.info
exports.warn = console.warn
exports.warning = console.warn
exports.error = console.error
exports.critical = console.error
```
### Inject a custom logger
The following example injects "winston", a multi-transport async logging library into pilers logging mechanism.
```javascript
var piler = require('piler');
var logger = require('winston');
// [More logger configuration can take place here]
global.js = js = piler.createJSManager({ outputDirectory: assetTmpDir , "logger": logger});
global.css = css = piler.createCSSManager({ outputDirectory: assetTmpDir, "logger": logger});
```
More information about winston can be found [here](https://github.com/flatiron/winston).
## Awesome development mode!
Development and production modes works as in Express. By default the
development mode is active. To activate production mode set NODE\_ENV
environment variable to *production*.
### Live CSS editing
This is really cool! You don't want to edit CSS at all without this after you
try it!
Because *Piler* handles the script-tag rendering it can add some development
tools when in development mode.
Using Express you can add Live CSS editing in development mode:
```javascript
app.configure("development", function() {
clientjs.liveUpdate(clientcss);
});
```
This is similar to [Live.js][], but it does not use polling. It will add
Socket.IO which will push the CSS-changes to your browser as you edit them.
If your app already uses Socket.IO you need to add the *io*-object as second
parameter to liveUpdate:
```javascript
var io = require('socket.io').listen(app);
clientjs.liveUpdate(clientcss, io);
```
### Script-tag rendering
In development mode every JS- and CSS-file will be rendered as a separate tag.
For example js.renderTags("admin") will render
```javascript
clientjs.addFile(__dirname + "/helpers.js");
clientjs.addFile("admin", __dirname + "/editor.js");
clientjs.addFile("admin", __dirname + "/editor.extension.js");
```
to
```html
<script type="text/javascript" src="/pile/dev/_global/1710d-helpers.js?v=1317298508710" ></script>
<script type="text/javascript" src="/pile/dev/admin/3718d-editor.js?v=1317298508714" ></script>
<script type="text/javascript" src="/pile/dev/admin/1411d-editor.extension.js?v=1317298508716" ></script>
```
in development mode, but in production it will render to
```html
<script type="text/javascript" src="/pile/min/_global.js?v=f1d27a8d9b92447439f6ebd5ef8f7ea9d25bc41c" ></script>
<script type="text/javascript" src="/pile/min/admin.js?v=2d730ac54f9e63e1a7e99cd669861bda33905365" ></script>
```
So debugging should be as easy as directly using script-tags. Line numbers
will match your real files in the filesystem. No need to debug huge Javascript
bundle!
## Examples
Visit
[this](https://github.com/epeli/piler/blob/master/examples/simple/app.js)
directory to see a simple example using ExpressJS 2.x.
This
[example](https://github.com/epeli/piler/blob/master/examples/simple/app.js)
uses ExpressJS 3.x a custom logger (winston) and a global socket.io instance
together with Piler.
## API summary
Code will be rendered in the order you call these functions with the exception
of *addUrl* which will be rendered as first.
### createJSManager and createCSSManager
Can take an optional configuration object as an argument with following keys.
var jsclient = piler.createJSManager({
outputDirectory: __dirname + "/mydir",
urlRoot: "/my/root"
});
#### urlRoot
Url root to which Piler's paths are appended. For example urlRoot "/my/root"
will result in following script tag:
<script type="text/javascript" src="/my/root/min/code.js?v=f4ec8d2b2be16a4ae8743039c53a1a2c31e50570" ></script>
#### outputDirectory
If specified *Piler* will write the minified assets to this folder. Useful if
you want to share you assets from Apache etc. instead of directly serving from
Piler's Connect middleware.
### JavaScript pile
#### addFile( [namespace], path to a asset file )
File on filesystem.
#### addUrl( [namespace], url to a asset file )
Useful for CDNs and for dynamic assets in other libraries such as socket.io.
#### addOb( [namespace string], any Javascript object )
Keys of the object will be added to the global window object. So take care when
choosing those. Also remember that parent scope of functions will be lost.
You can also give a nested namespace for it
clientjs.addOb({"foo.bar": "my thing"});
Now on the client "my thing" string will be found from window.foo.bar.
The object will be serialized at the second it is passed to this method so you
won't be able modify it other than between server restarts. This is usefull for
sharing utility functions etc.
Use *res.addOb* to share more dynamically objects.
#### addExec( [namespace], Javascript function )
A function that will executed immediately in browser as it is parsed. Parent
scope is also lost here.
#### addRaw( [namespace], raw Javascript string )
Any valid Javascript string.
### CSS pile
These are similar to ones in JS pile.
#### addFile( [namespace], path to a asset file )
CSS asset on your filesystem.
#### addUrl( [namespace], url to a asset file )
CSS asset behind a url. Can be remote too. This will be directly linked to you
page. Use addFile if you want it be minified.
#### addRaw( [namespace], raw CSS string )
Any valid CSS string.
## Supported preprocessors
### JavaScript
For JavaScript the only supported one is [CoffeeScript][] and the compiler is
included in *Piler*.
### CSS
CSS-compilers are not included in *Piler*. Just install what you need using
[npm][].
* [Stylus][] with [nib][] (npm install stylus nib)
* [LESS][] (npm install less)
Adding support for new compilers should be
[easy](https://github.com/epeli/pile/blob/master/lib/compilers.coffee).
Feel free to contribute!
## Installing
From [npm][]
npm install piler
## Source code
Source code is licenced under [The MIT
License](https://github.com/epeli/piler/blob/master/LICENSE) and it is hosted
on [Github](https://github.com/epeli/piler).
## Changelog
v0.4.2 - 2013-04-16
* Fixes to work with ExpressJS 3.x
* Unit test fixes
* Make console output configurable
v0.4.1 - 2012-06-12
* Add getSources
* Put cache key to resource url instead of query string
v0.4.0 - 2012-06-17
* Remove Dynamic Helpers.
Dynamic Helpers where an Express 2.0 only API. This makes Piler more framework
agnostic and it will work with Express 3.0. This also removes support for
response object functions. We'll add those back if there is a need for them
(open up a issue if you miss them!) and we'll find good framework agnostic way
to implement them.
v0.3.6 - 2012-06-17
* Bind all production dependency versions
v0.3.5 - 2012-06-17
* Fix LESS @imports
* Fix Stylus without nib
* Use path module for Windows compatibility
v0.3.4 - 2012-03-29
* Fix Stylus @imports
v0.3.3 - noop
v0.3.2 - 2011-12-11
* Workaround compiler bug in CoffeeScript
v0.3.1 - 2011-11-17
* Fix CSS namespaces
v0.3.0 - 2011-10-13
* Rename to Piler
* Really minify CSS
* Implemented res.addOb
* Implement outputDirectory and urlRoot options.
* addOb can now take nested namespace string and it won't override existing
namespaces.
## Contact
Questions and suggestions are very welcome
- [Esa-Matti Suuronen](http://esa-matti.suuronen.org/)
- esa-matti [aet] suuronen dot org
- [EsaMatti](https://twitter.com/#!/EsaMatti) @ Twitter
- Epeli @ freenode/IRCnet
[Express]: http://expressjs.com/
[Node.js]: http://nodejs.org/
[Live.js]: http://livejs.com/
[LESS]: http://lesscss.org/
[Stylus]: http://learnboost.github.com/stylus/
[nib]: https://github.com/visionmedia/nib
[npm]: http://npmjs.org/
[CoffeeScript]: http://jashkenas.github.com/coffee-script/

1
node_modules/piler/examples/logger/.npmignore generated vendored Normal file
View File

@ -0,0 +1 @@
node_modules

12
node_modules/piler/examples/logger/README.md generated vendored Normal file
View File

@ -0,0 +1,12 @@
# This is a port of the simple example using ExpressJS 3.x custom logger and socket.io configuration
Install dependencies
npm install express@3.x winston socket.io stylus less
And run it
node app.js
Then open up http://localhost:8001/ and try editing `style.css`.

115
node_modules/piler/examples/logger/app.js generated vendored Normal file
View File

@ -0,0 +1,115 @@
var express = require('express');
var app = express();
var http = require('http');
var socketio = require('socket.io');
var pile = require("../../index");
var logger = {};
var share = require("./share");
console.log(share.test());
function isEmail(s) {
return !! s.match(/.\w+@\w+\.\w/);
}
var loggerConf = {
levels: {
debug: 0,
info: 1,
notice: 2,
warn: 3,
warning: 3,
error: 4,
critical: 5,
crit: 5,
alert: 6,
emerg: 7
},
colors: {
debug: 'grey',
info: 'blue',
notice: 'green',
warn: 'yellow',
warning: 'yellow',
error: 'red',
critical: 'red',
crit: 'red',
alert: 'red',
emerg: 'red'
},
transports: [
new (require('winston').transports.Console)({
colorize: true,
timestampe: true,
"level": 'debug',
"silent": false
})
]
};
var logger = new (require('winston').Logger)(loggerConf);
var srv = http.createServer(app);
// Socket.IO
var io = socketio.listen(srv,{"logger":logger});
io.configure(function(){
io.enable('browser client gzip');
io.enable('browser client minification');
io.disable('flash policy server');
});
// Piler config
var js = pile.createJSManager({ outputDirectory: __dirname + "/out", "logger":logger });
var css = pile.createCSSManager({ outputDirectory: __dirname + "/out", "logger":logger });
js.bind(app,srv);
css.bind(app,srv);
app.configure(function() {
app.set('views', __dirname + "/views");
});
app.configure("development", function() {
js.liveUpdate(css,io);
});
css.addFile(__dirname + "/style.css");
css.addFile(__dirname + "/style.styl");
css.addFile(__dirname + "/style.less");
js.addOb({MY: {
isEmail: isEmail
}
});
js.addOb({FOO: "bar"});
js.addUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js");
js.addFile(__dirname + "/client/underscore.js");
js.addFile(__dirname + "/client/backbone.js");
js.addFile(__dirname + "/client/hello.js");
js.addFile(__dirname + "/client/hello.coffee");
js.addFile("foo", __dirname + "/client/foo.coffee");
js.addFile("bar", __dirname + "/client/bar.coffee");
js.addFile(__dirname + "/share.js");
app.get("/", function(req, res){
res.exec(function() {
console.log("Run client code from the response", FOO);
console.log(share.test());
});
res.render("index.jade", {
layout: false,
js: js.renderTags("foo"),
css: css.renderTags()
});
});
srv.listen(8001, function(){
logger.notice("listening on 8001");
});

1158
node_modules/piler/examples/logger/client/backbone.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

2
node_modules/piler/examples/logger/client/bar.coffee generated vendored Normal file
View File

@ -0,0 +1,2 @@
console.log "hlleo bar coffee"

5
node_modules/piler/examples/logger/client/foo.coffee generated vendored Normal file
View File

@ -0,0 +1,5 @@
console.log "hello foo coffee"

View File

@ -0,0 +1,5 @@
console.log "hello coffee"

6
node_modules/piler/examples/logger/client/hello.js generated vendored Normal file
View File

@ -0,0 +1,6 @@
console.log("hello js");

839
node_modules/piler/examples/logger/client/underscore.js generated vendored Normal file
View File

@ -0,0 +1,839 @@
// Underscore.js 1.1.7
// (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the MIT license.
// Portions of Underscore are inspired or borrowed from Prototype,
// Oliver Steele's Functional, and John Resig's Micro-Templating.
// For all details and documentation:
// http://documentcloud.github.com/underscore
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var slice = ArrayProto.slice,
unshift = ArrayProto.unshift,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) { return new wrapper(obj); };
// Export the Underscore object for **CommonJS**, with backwards-compatibility
// for the old `require()` API. If we're not in CommonJS, add `_` to the
// global object.
if (typeof module !== 'undefined' && module.exports) {
module.exports = _;
_._ = _;
} else {
// Exported as a string, for Closure Compiler "advanced" mode.
root['_'] = _;
}
// Current version.
_.VERSION = '1.1.7';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
return results;
};
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = memo !== void 0;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError("Reduce of empty array with no initial value");
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse();
return _.reduce(reversed, iterator, memo, context);
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
each(obj, function(value, index, list) {
if (!iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator = iterator || _.identity;
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result |= iterator.call(context, value, index, list)) return breaker;
});
return !!result;
};
// Determine if a given value is included in the array or object using `===`.
// Aliased as `contains`.
_.include = _.contains = function(obj, target) {
var found = false;
if (obj == null) return found;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
any(obj, function(value) {
if (found = value === target) return true;
});
return found;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
return _.map(obj, function(value) {
return (method.call ? method || value : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Return the maximum element or (element-based computation).
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
var result = {computed : -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
var result = {computed : Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, iterator, context) {
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}), 'value');
};
// Groups the object's values by a criterion produced by an iterator
_.groupBy = function(obj, iterator) {
var result = {};
each(obj, function(value, index) {
var key = iterator(value, index);
(result[key] || (result[key] = [])).push(value);
});
return result;
};
// Use a comparator function to figure out at what index an object should
// be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator) {
iterator || (iterator = _.identity);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >> 1;
iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
if (_.isArray(iterable)) return slice.call(iterable);
if (_.isArguments(iterable)) return slice.call(iterable);
return _.values(iterable);
};
// Return the number of elements in an object.
_.size = function(obj) {
return _.toArray(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head`. The **guard** check allows it to work
// with `_.map`.
_.first = _.head = function(array, n, guard) {
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the first entry of the array. Aliased as `tail`.
// Especially useful on the arguments object. Passing an **index** will return
// the rest of the values in the array from that index onward. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = function(array, index, guard) {
return slice.call(array, (index == null) || guard ? 1 : index);
};
// Get the last element of an array.
_.last = function(array) {
return array[array.length - 1];
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, function(value){ return !!value; });
};
// Return a completely flattened version of an array.
_.flatten = function(array) {
return _.reduce(array, function(memo, value) {
if (_.isArray(value)) return memo.concat(_.flatten(value));
memo[memo.length] = value;
return memo;
}, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted) {
return _.reduce(array, function(memo, el, i) {
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el;
return memo;
}, []);
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(_.flatten(arguments));
};
// Produce an array that contains every item shared between all the
// passed-in arrays. (Aliased as "intersect" for back-compat.)
_.intersection = _.intersect = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and another.
// Only the elements present in just the first array will remain.
_.difference = function(array, other) {
return _.filter(array, function(value){ return !_.include(other, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = slice.call(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
return results;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i, l;
if (isSorted) {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item) {
if (array == null) return -1;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
var i = array.length;
while (i--) if (array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while(idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Binding with arguments is also known as `curry`.
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
// We check for `func.bind` first, to fail fast when `func` is undefined.
_.bind = function(func, obj) {
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
var args = slice.call(arguments, 2);
return function() {
return func.apply(obj, args.concat(slice.call(arguments)));
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length == 0) funcs = _.functions(obj);
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(func, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Internal function used to implement `_.throttle` and `_.debounce`.
var limit = function(func, wait, debounce) {
var timeout;
return function() {
var context = this, args = arguments;
var throttler = function() {
timeout = null;
func.apply(context, args);
};
if (debounce) clearTimeout(timeout);
if (debounce || !timeout) timeout = setTimeout(throttler, wait);
};
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
_.throttle = function(func, wait) {
return limit(func, wait, false);
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
_.debounce = function(func, wait) {
return limit(func, wait, true);
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
return memo = func.apply(this, arguments);
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func].concat(slice.call(arguments));
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = slice.call(arguments);
return function() {
var args = slice.call(arguments);
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
return function() {
if (--times < 1) { return func.apply(this, arguments); }
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
return _.map(obj, _.identity);
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (source[prop] !== void 0) obj[prop] = source[prop];
}
});
return obj;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
// Check object identity.
if (a === b) return true;
// Different types?
var atype = typeof(a), btype = typeof(b);
if (atype != btype) return false;
// Basic equality test (watch out for coercions).
if (a == b) return true;
// One is falsy and the other truthy.
if ((!a && b) || (a && !b)) return false;
// Unwrap any wrapped objects.
if (a._chain) a = a._wrapped;
if (b._chain) b = b._wrapped;
// One of them implements an isEqual()?
if (a.isEqual) return a.isEqual(b);
if (b.isEqual) return b.isEqual(a);
// Check dates' integer values.
if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();
// Both are NaN?
if (_.isNaN(a) && _.isNaN(b)) return false;
// Compare regular expressions.
if (_.isRegExp(a) && _.isRegExp(b))
return a.source === b.source &&
a.global === b.global &&
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline;
// If a is not an object by this point, we can't handle it.
if (atype !== 'object') return false;
// Check for different array lengths before comparing contents.
if (a.length && (a.length !== b.length)) return false;
// Nothing else worked, deep compare the contents.
var aKeys = _.keys(a), bKeys = _.keys(b);
// Different object sizes?
if (aKeys.length != bKeys.length) return false;
// Recursive comparison of contents.
for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false;
return true;
};
// Is a given array or object empty?
_.isEmpty = function(obj) {
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType == 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Is a given variable an arguments object?
_.isArguments = function(obj) {
return !!(obj && hasOwnProperty.call(obj, 'callee'));
};
// Is a given value a function?
_.isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
// Is a given value a string?
_.isString = function(obj) {
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
};
// Is a given value a number?
_.isNumber = function(obj) {
return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
};
// Is the given value `NaN`? `NaN` happens to be the only value in JavaScript
// that does not equal itself.
_.isNaN = function(obj) {
return obj !== obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false;
};
// Is a given value a date?
_.isDate = function(obj) {
return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
};
// Is the given value a regular expression?
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function (n, iterator, context) {
for (var i = 0; i < n; i++) iterator.call(context, i);
};
// Add your own custom functions to the Underscore object, ensuring that
// they're correctly added to the OOP wrapper as well.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
addToWrapper(name, _[name] = obj[name]);
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = idCounter++;
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(str, data) {
var c = _.templateSettings;
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(c.interpolate, function(match, code) {
return "'," + code.replace(/\\'/g, "'") + ",'";
})
.replace(c.evaluate || null, function(match, code) {
return "');" + code.replace(/\\'/g, "'")
.replace(/[\r\n\t]/g, ' ') + "__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');";
var func = new Function('obj', tmpl);
return data ? func(data) : func;
};
// The OOP Wrapper
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
var wrapper = function(obj) { this._wrapped = obj; };
// Expose `wrapper.prototype` as `_.prototype`
_.prototype = wrapper.prototype;
// Helper function to continue chaining intermediate results.
var result = function(obj, chain) {
return chain ? _(obj).chain() : obj;
};
// A method to easily add functions to the OOP wrapper.
var addToWrapper = function(name, func) {
wrapper.prototype[name] = function() {
var args = slice.call(arguments);
unshift.call(args, this._wrapped);
return result(func.apply(_, args), this._chain);
};
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
method.apply(this._wrapped, arguments);
return result(this._wrapped, this._chain);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
return result(method.apply(this._wrapped, arguments), this._chain);
};
});
// Start chaining a wrapped Underscore object.
wrapper.prototype.chain = function() {
this._chain = true;
return this;
};
// Extracts the result from a wrapped and chained object.
wrapper.prototype.value = function() {
return this._wrapped;
};
})();

7
node_modules/piler/examples/logger/share.js generated vendored Normal file
View File

@ -0,0 +1,7 @@
(function(exports){
exports.test = function(){
return 'This is a shared module';
};
}(typeof exports === 'undefined' ? this.share = {} : exports));

7
node_modules/piler/examples/logger/style.css generated vendored Normal file
View File

@ -0,0 +1,7 @@
h1 {
color: blue;
}

3
node_modules/piler/examples/logger/style.less generated vendored Normal file
View File

@ -0,0 +1,3 @@
h1 {
font-size: 25px * 2;
}

9
node_modules/piler/examples/logger/style.styl generated vendored Normal file
View File

@ -0,0 +1,9 @@
@import 'nib'
h2
color green
background-color brown
border-radius 50px

8
node_modules/piler/examples/logger/views/index.jade generated vendored Normal file
View File

@ -0,0 +1,8 @@
!!! 5
html(lang="en")
head
!{css}
!{js}
body
h1 Piler Example
p View the source :)

14
node_modules/piler/examples/simple/README.md generated vendored Normal file
View File

@ -0,0 +1,14 @@
# Example Express application using Piler
Install dependencies
npm install express@2.x.x socket.io stylus less
And run it
node app.js
Then open up http://localhost:8001/ and try editing `style.css`.

68
node_modules/piler/examples/simple/app.js generated vendored Normal file
View File

@ -0,0 +1,68 @@
var createServer = require("express").createServer;
var pile = require("../../index");
var js = pile.createJSManager({ outputDirectory: __dirname + "/out" });
var css = pile.createCSSManager({ outputDirectory: __dirname + "/out" });
var share = require("./share");
console.log(share.test());
function isEmail(s) {
return !! s.match(/.\w+@\w+\.\w/);
}
var app = createServer();
js.bind(app);
css.bind(app);
app.configure(function() {
app.set('views', __dirname + "/views");
});
app.configure("development", function() {
js.liveUpdate(css);
});
css.addFile(__dirname + "/style.css");
css.addFile(__dirname + "/style.styl");
css.addFile(__dirname + "/style.less");
js.addOb({MY: {
isEmail: isEmail
}
});
js.addOb({FOO: "bar"});
js.addUrl("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js");
js.addFile(__dirname + "/client/underscore.js");
js.addFile(__dirname + "/client/backbone.js");
js.addFile(__dirname + "/client/hello.js");
js.addFile(__dirname + "/client/hello.coffee");
js.addFile("foo", __dirname + "/client/foo.coffee");
js.addFile("bar", __dirname + "/client/bar.coffee");
js.addFile(__dirname + "/share.js");
app.get("/", function(req, res){
res.exec(function() {
console.log("Run client code from the response", FOO);
console.log(share.test());
});
res.render("index.jade", {
layout: false,
js: js.renderTags("foo"),
css: css.renderTags(),
});
});
app.listen(8001, function(){
console.log("listening on 8001");
});

1158
node_modules/piler/examples/simple/client/backbone.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

2
node_modules/piler/examples/simple/client/bar.coffee generated vendored Normal file
View File

@ -0,0 +1,2 @@
console.log "hlleo bar coffee"

5
node_modules/piler/examples/simple/client/foo.coffee generated vendored Normal file
View File

@ -0,0 +1,5 @@
console.log "hello foo coffee"

View File

@ -0,0 +1,5 @@
console.log "hello coffee"

6
node_modules/piler/examples/simple/client/hello.js generated vendored Normal file
View File

@ -0,0 +1,6 @@
console.log("hello js");

839
node_modules/piler/examples/simple/client/underscore.js generated vendored Normal file
View File

@ -0,0 +1,839 @@
// Underscore.js 1.1.7
// (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the MIT license.
// Portions of Underscore are inspired or borrowed from Prototype,
// Oliver Steele's Functional, and John Resig's Micro-Templating.
// For all details and documentation:
// http://documentcloud.github.com/underscore
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var slice = ArrayProto.slice,
unshift = ArrayProto.unshift,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) { return new wrapper(obj); };
// Export the Underscore object for **CommonJS**, with backwards-compatibility
// for the old `require()` API. If we're not in CommonJS, add `_` to the
// global object.
if (typeof module !== 'undefined' && module.exports) {
module.exports = _;
_._ = _;
} else {
// Exported as a string, for Closure Compiler "advanced" mode.
root['_'] = _;
}
// Current version.
_.VERSION = '1.1.7';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
return results;
};
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = memo !== void 0;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError("Reduce of empty array with no initial value");
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse();
return _.reduce(reversed, iterator, memo, context);
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
each(obj, function(value, index, list) {
if (!iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator = iterator || _.identity;
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result |= iterator.call(context, value, index, list)) return breaker;
});
return !!result;
};
// Determine if a given value is included in the array or object using `===`.
// Aliased as `contains`.
_.include = _.contains = function(obj, target) {
var found = false;
if (obj == null) return found;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
any(obj, function(value) {
if (found = value === target) return true;
});
return found;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
return _.map(obj, function(value) {
return (method.call ? method || value : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Return the maximum element or (element-based computation).
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
var result = {computed : -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
var result = {computed : Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, iterator, context) {
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}), 'value');
};
// Groups the object's values by a criterion produced by an iterator
_.groupBy = function(obj, iterator) {
var result = {};
each(obj, function(value, index) {
var key = iterator(value, index);
(result[key] || (result[key] = [])).push(value);
});
return result;
};
// Use a comparator function to figure out at what index an object should
// be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator) {
iterator || (iterator = _.identity);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >> 1;
iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
if (_.isArray(iterable)) return slice.call(iterable);
if (_.isArguments(iterable)) return slice.call(iterable);
return _.values(iterable);
};
// Return the number of elements in an object.
_.size = function(obj) {
return _.toArray(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head`. The **guard** check allows it to work
// with `_.map`.
_.first = _.head = function(array, n, guard) {
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the first entry of the array. Aliased as `tail`.
// Especially useful on the arguments object. Passing an **index** will return
// the rest of the values in the array from that index onward. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = function(array, index, guard) {
return slice.call(array, (index == null) || guard ? 1 : index);
};
// Get the last element of an array.
_.last = function(array) {
return array[array.length - 1];
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, function(value){ return !!value; });
};
// Return a completely flattened version of an array.
_.flatten = function(array) {
return _.reduce(array, function(memo, value) {
if (_.isArray(value)) return memo.concat(_.flatten(value));
memo[memo.length] = value;
return memo;
}, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted) {
return _.reduce(array, function(memo, el, i) {
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el;
return memo;
}, []);
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(_.flatten(arguments));
};
// Produce an array that contains every item shared between all the
// passed-in arrays. (Aliased as "intersect" for back-compat.)
_.intersection = _.intersect = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and another.
// Only the elements present in just the first array will remain.
_.difference = function(array, other) {
return _.filter(array, function(value){ return !_.include(other, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = slice.call(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
return results;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i, l;
if (isSorted) {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item) {
if (array == null) return -1;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
var i = array.length;
while (i--) if (array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while(idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Binding with arguments is also known as `curry`.
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
// We check for `func.bind` first, to fail fast when `func` is undefined.
_.bind = function(func, obj) {
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
var args = slice.call(arguments, 2);
return function() {
return func.apply(obj, args.concat(slice.call(arguments)));
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length == 0) funcs = _.functions(obj);
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(func, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Internal function used to implement `_.throttle` and `_.debounce`.
var limit = function(func, wait, debounce) {
var timeout;
return function() {
var context = this, args = arguments;
var throttler = function() {
timeout = null;
func.apply(context, args);
};
if (debounce) clearTimeout(timeout);
if (debounce || !timeout) timeout = setTimeout(throttler, wait);
};
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
_.throttle = function(func, wait) {
return limit(func, wait, false);
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
_.debounce = function(func, wait) {
return limit(func, wait, true);
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
return memo = func.apply(this, arguments);
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func].concat(slice.call(arguments));
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = slice.call(arguments);
return function() {
var args = slice.call(arguments);
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
return function() {
if (--times < 1) { return func.apply(this, arguments); }
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
return _.map(obj, _.identity);
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (source[prop] !== void 0) obj[prop] = source[prop];
}
});
return obj;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
// Check object identity.
if (a === b) return true;
// Different types?
var atype = typeof(a), btype = typeof(b);
if (atype != btype) return false;
// Basic equality test (watch out for coercions).
if (a == b) return true;
// One is falsy and the other truthy.
if ((!a && b) || (a && !b)) return false;
// Unwrap any wrapped objects.
if (a._chain) a = a._wrapped;
if (b._chain) b = b._wrapped;
// One of them implements an isEqual()?
if (a.isEqual) return a.isEqual(b);
if (b.isEqual) return b.isEqual(a);
// Check dates' integer values.
if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();
// Both are NaN?
if (_.isNaN(a) && _.isNaN(b)) return false;
// Compare regular expressions.
if (_.isRegExp(a) && _.isRegExp(b))
return a.source === b.source &&
a.global === b.global &&
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline;
// If a is not an object by this point, we can't handle it.
if (atype !== 'object') return false;
// Check for different array lengths before comparing contents.
if (a.length && (a.length !== b.length)) return false;
// Nothing else worked, deep compare the contents.
var aKeys = _.keys(a), bKeys = _.keys(b);
// Different object sizes?
if (aKeys.length != bKeys.length) return false;
// Recursive comparison of contents.
for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false;
return true;
};
// Is a given array or object empty?
_.isEmpty = function(obj) {
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType == 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Is a given variable an arguments object?
_.isArguments = function(obj) {
return !!(obj && hasOwnProperty.call(obj, 'callee'));
};
// Is a given value a function?
_.isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
// Is a given value a string?
_.isString = function(obj) {
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
};
// Is a given value a number?
_.isNumber = function(obj) {
return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
};
// Is the given value `NaN`? `NaN` happens to be the only value in JavaScript
// that does not equal itself.
_.isNaN = function(obj) {
return obj !== obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false;
};
// Is a given value a date?
_.isDate = function(obj) {
return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
};
// Is the given value a regular expression?
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function (n, iterator, context) {
for (var i = 0; i < n; i++) iterator.call(context, i);
};
// Add your own custom functions to the Underscore object, ensuring that
// they're correctly added to the OOP wrapper as well.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
addToWrapper(name, _[name] = obj[name]);
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = idCounter++;
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(str, data) {
var c = _.templateSettings;
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(c.interpolate, function(match, code) {
return "'," + code.replace(/\\'/g, "'") + ",'";
})
.replace(c.evaluate || null, function(match, code) {
return "');" + code.replace(/\\'/g, "'")
.replace(/[\r\n\t]/g, ' ') + "__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');";
var func = new Function('obj', tmpl);
return data ? func(data) : func;
};
// The OOP Wrapper
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
var wrapper = function(obj) { this._wrapped = obj; };
// Expose `wrapper.prototype` as `_.prototype`
_.prototype = wrapper.prototype;
// Helper function to continue chaining intermediate results.
var result = function(obj, chain) {
return chain ? _(obj).chain() : obj;
};
// A method to easily add functions to the OOP wrapper.
var addToWrapper = function(name, func) {
wrapper.prototype[name] = function() {
var args = slice.call(arguments);
unshift.call(args, this._wrapped);
return result(func.apply(_, args), this._chain);
};
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
method.apply(this._wrapped, arguments);
return result(this._wrapped, this._chain);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
return result(method.apply(this._wrapped, arguments), this._chain);
};
});
// Start chaining a wrapped Underscore object.
wrapper.prototype.chain = function() {
this._chain = true;
return this;
};
// Extracts the result from a wrapped and chained object.
wrapper.prototype.value = function() {
return this._wrapped;
};
})();

7
node_modules/piler/examples/simple/share.js generated vendored Normal file
View File

@ -0,0 +1,7 @@
(function(exports){
exports.test = function(){
return 'This is a shared module';
};
}(typeof exports === 'undefined' ? this.share = {} : exports));

7
node_modules/piler/examples/simple/style.css generated vendored Normal file
View File

@ -0,0 +1,7 @@
h1 {
color: blue;
}

3
node_modules/piler/examples/simple/style.less generated vendored Normal file
View File

@ -0,0 +1,3 @@
h1 {
font-size: 25px * 2;
}

9
node_modules/piler/examples/simple/style.styl generated vendored Normal file
View File

@ -0,0 +1,9 @@
@import 'nib'
h2
color green
background-color brown
border-radius 50px

8
node_modules/piler/examples/simple/views/index.jade generated vendored Normal file
View File

@ -0,0 +1,8 @@
!!! 5
html(lang="en")
head
!{css}
!{js}
body
h1 Piler Example
p View the source :)

2
node_modules/piler/index.js generated vendored Normal file
View File

@ -0,0 +1,2 @@
require("coffee-script");
module.exports = require( __dirname + "/lib/piler");

29
node_modules/piler/lib/asseturlparse.coffee generated vendored Normal file
View File

@ -0,0 +1,29 @@
_ = require 'underscore'
_.mixin require 'underscore.string'
module.exports = p = (url) ->
ob = {}
# remove qs
url = _.first url.split "?"
[__..., mode, cachekey, filename] = url.split "/"
if mode is "dev"
[__..., name, devopt, ext] = filename.split "."
[type, uid] = devopt.split "-"
ob.dev =
uid: uid
type: type
else
[__..., name, ext] = filename.split "."
ob.min = true
ob.name = name
ob.ext = ext
return ob
if require.main is module
console.info p "/pile/dev/my.exec-123.js"

57
node_modules/piler/lib/compilers.coffee generated vendored Normal file
View File

@ -0,0 +1,57 @@
coffeescript = require "coffee-script"
path = require "path"
try
stylus = require "stylus"
catch e
try
nib = require "nib"
catch e
try
less = require "less"
catch e
compilers =
# Dummy compilers
css:
render: (filename, code, cb) -> cb null, code
js:
render: (filename, code, cb) -> cb null, code
# We always have coffee-script compiler ;)
coffee:
render: (filename, code, cb) ->
try
cb null, coffeescript.compile code
catch e
cb e, null
targetExt: "js"
if stylus?
compilers.styl =
targetExt: "css"
render: (filename, code, cb) ->
stylus(code)
.set('filename', filename)
.render cb
if nib?
Renderer = require "stylus/lib/renderer"
compilers.styl.render = (filename, code, cb) ->
stylus(code)
.set('filename', filename)
.use(do nib)
.render cb
if less?
compilers.less =
render: (filename, code, cb) ->
less.render code,
paths: [path.dirname filename]
cb
targetExt: "css"
module.exports = compilers

99
node_modules/piler/lib/livecss.coffee generated vendored Normal file
View File

@ -0,0 +1,99 @@
fs = require "fs"
try
socketio = require('socket.io')
catch e
socketio = null
incUrlSeq = (url) ->
seqRegexp = /(--([0-9]+))\..*$/
match = url.match seqRegexp
seq = parseInt match?[2] or 0, 10
if match
cleanUrl = url.replace match[1], ""
else
cleanUrl = url
cleanUrl = cleanUrl.substr(0,cleanUrl.lastIndexOf('.'))+"--#{ seq+1 }"+cleanUrl.substr(cleanUrl.lastIndexOf('.'))
# Yep, this function will be executed in the browser.
clientUpdater = ->
console.log "CSS updater is active. Waiting for connection..."
pile = io.connect('/pile')
pile.on "connect", ->
console.log "CSS updater has connected"
pile.on "disconnect", ->
console.log "CSS updater has disconnected! Refresh to reconnect"
pile.on "update", (fileId) ->
elem = document.getElementById "pile-" + fileId
if elem
console.log "updating", fileId, elem
elem.href = PILE.incUrlSeq elem.href
else
console.log "id", fileId, "not found"
class LiveUpdateMixin
installSocketIo: (userio) ->
@addUrl "/socket.io/socket.io.js"
@addOb PILE:
incUrlSeq: incUrlSeq
@addExec clientUpdater
if not userio
io = socketio.listen @app
else
io = userio
# Why does not work?
io.configure ->
io.set 'log level', 0
@io = io.of "/pile"
liveUpdate: (cssmanager, userio) ->
if @production
@logger.info "Not activating live update in production"
return
if not @app
throw new Error 'JSManager must be bind to a http server (Express app)
before it can live update CSS'
@installSocketIo userio
listener = if @server then @server else @app
listener.on "listening", =>
@logger.info "Activating CSS updater"
for k, pile of cssmanager.piles
for codeOb in pile.code
@_watch pile, codeOb
_watch: (pile, codeOb) ->
return unless codeOb.type is "file"
@logger.info "watching #{ codeOb.filePath } for changes"
fs.watch codeOb.filePath, =>
@logger.info "updated", codeOb.filePath
@io.emit "update", codeOb.getId()
# For testing
LiveUpdateMixin.incUrlSeq = incUrlSeq
if socketio?
module.exports = LiveUpdateMixin
else
module.exports = class LiveUpdateDisabled
liveUpdate: ->
@logger.error "No socket.io installed. Live update won't work."

8
node_modules/piler/lib/logger.coffee generated vendored Normal file
View File

@ -0,0 +1,8 @@
# Basic Logger functionality
exports.debug = console.debug
exports.notice = console.log
exports.info = console.info
exports.warn = console.warn
exports.warning = console.warn
exports.error = console.error
exports.critical = console.error

35
node_modules/piler/lib/minify.coffee generated vendored Normal file
View File

@ -0,0 +1,35 @@
#
# Simple wrappers for JS and CSS minifiers so that they are easy to change if
# needed.
#
csso = require "csso"
try
uglify = require("uglify-js")
catch error
# uglify-js' packaging currently sucks. Add fallback.
console.log "no uglify", error
exports.jsMinify = (code) -> code
exports.jsBeautify = (code) -> code
exports.cssMinify = (code) -> csso.justDoIt code
if uglify?
jsp = uglify.parser
pro = uglify.uglify
exports.jsMinify = (code) ->
ast = jsp.parse code
ast = pro.ast_mangle ast
ast = pro.ast_squeeze ast
pro.gen_code ast
exports.jsBeautify = (code) ->
ast = jsp.parse(code)
pro.gen_code ast, beautify: true

450
node_modules/piler/lib/piler.coffee generated vendored Normal file
View File

@ -0,0 +1,450 @@
fs = require "fs"
path = require "path"
crypto = require 'crypto'
path = require "path"
_ = require "underscore"
async = require "async"
{jsMinify, cssMinify} = require "./minify"
OB = require "./serialize"
compilers = require "./compilers"
assetUrlParse = require "./asseturlparse"
logger = require "./logger"
toGlobals = (globals) ->
code = ""
for nsString, v of globals
code += "__SET(#{ JSON.stringify nsString }, #{ OB.stringify v });\n"
code
extension = (filename) ->
parts = filename.split "."
parts[parts.length-1]
wrapInScriptTagInline = (code) ->
"<script type=\"text/javascript\" >\n#{ code }\n</script>\n"
getCompiler = (filePath) ->
compiler = compilers[extension filePath]
if not compiler
throw new Error "Could not find compiler for #{ filePath }"
compiler.render
#http://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/
asCodeOb = do ->
getId = ->
sum = crypto.createHash('sha1')
if @type is "file"
# If code is on filesystem the url to the file should only change when
# the path to it changes.
sum.update @filePath
else
# If there is no file for code code. We need to generate id from the code
# itself.
sum.update OB.stringify @
hash = sum.digest('hex').substring 10, 0
if @type in ["file", "module"]
filename = path.basename @filePath
filename = filename.replace /\./g, "_"
filename = filename.replace /\-/g, "_"
hash = filename + "_" + hash
return hash
pilers =
raw: (ob, cb) -> cb null, ob.raw
object: (ob, cb) ->
cb null, toGlobals ob.object
exec: (ob, cb) ->
cb null, executableFrom ob.object
file: (ob, cb) ->
fs.readFile ob.filePath, (err, data) =>
return cb? err if err
getCompiler(ob.filePath) ob.filePath, data.toString(), (err, code) ->
cb err, code
module: (ob, cb) ->
this.file ob, (err, code) ->
return cb? err if err
cb null, """require.register("#{ path.basename(ob.filePath).split(".")[0] }", function(module, exports, require) {
#{ code }
});"""
return ->
@getId = getId
@getCode = (cb) ->
pilers[@type] @, cb
return @
class BasePile
urlRoot: "/piler/"
production: false
constructor: (@name, @production, urlRoot) ->
if urlRoot?
@urlRoot = urlRoot
@code = []
@rawPile = null
@urls = []
@devMapping = {}
@piledUp = false
addFile: (filePath) ->
filePath = path.normalize filePath
@warnPiledUp "addFile"
if filePath not in @getFilePaths()
@code.push asCodeOb.call
type: "file"
filePath: filePath
addRaw: (raw) ->
@warnPiledUp "addRaw"
@code.push asCodeOb.call
type: "raw"
raw: raw
getFilePaths: ->
(ob.filePath for ob in @code when ob.type is "file")
addUrl: (url) ->
if url not in @urls
@urls.push url
getSources: ->
devCacheKey = Date.now()
# Start with plain urls
sources = ([u] for u in @urls)
if @production
sources.push ["#{ @urlRoot }min/#{ @pileHash }/#{ @name }.#{ @ext }"]
else
for ob in @code
sources.push ["#{ @urlRoot }dev/#{ devCacheKey }/#{ @name }.#{ ob.type }-#{ ob.getId() }.#{ @ext }", "id=\"pile-#{ ob.getId() }\""]
return sources
findCodeObById: (id) ->
(codeOb for codeOb in @code when codeOb.getId() is id)[0]
findCodeObByFilePath: (path) ->
(codeOb for codeOb in @code when codeOb.filePath is id)[0]
_computeHash: ->
sum = crypto.createHash('sha1')
sum.update @rawPile
@pileHash = sum.digest('hex')
warnPiledUp: (fnname) ->
if @piledUp
@logger.warn "Warning pile #{ @name } has been already piled up. Calling #{ fnname } does not do anything."
pileUp: (cb) ->
@piledUp = true
async.map @code, (codeOb, cb) =>
codeOb.getCode (err, code) =>
return cb? err if err
cb null, @commentLine("#{ codeOb.type }: #{ codeOb.getId() }") + "\n#{ code }"
, (err, result) =>
return cb? err if err
@rawPile = @minify result.join("\n\n").trim()
@_computeHash()
cb? null, @rawPile
class JSPile extends BasePile
ext: "js"
commentLine: (line) ->
return "// #{ line.trim() }"
minify: (code) ->
if @production
jsMinify code
else
code
constructor: ->
super
@objects = []
# CommonJS module
addModule: (filePath) ->
filePath = path.normalize filePath
@warnPiledUp "addFile"
if filePath not in @getFilePaths()
@code.push asCodeOb.call
type: "module"
filePath: filePath
addOb: (ob) ->
@warnPiledUp "addOb"
@code.push asCodeOb.call
type: "object"
object: ob
addExec: (fn) ->
@warnPiledUp "addExec"
@code.push asCodeOb.call
type: "exec"
object: fn
class CSSPile extends BasePile
ext: "css"
commentLine: (line) ->
return "/* #{ line.trim() } */"
minify: (code) ->
if @production
cssMinify code
else
code
defNs = (fn) ->
(ns, path) ->
if arguments.length is 1
path = ns
ns = "global"
fn.call this, ns, path
class PileManager
Type: null
constructor: (@settings) ->
@production = @settings.production
@settings.urlRoot ?= "/pile/"
@logger = @settings.logger || logger
@piles =
global: new @Type "global", @production, @settings.urlRoot
getPile: (ns) ->
pile = @piles[ns]
if not pile
pile = @piles[ns] = new @Type ns, @production, @settings.urlRoot
pile
addFile: defNs (ns, path) ->
pile = @getPile ns
pile.addFile path
addRaw: defNs (ns, raw) ->
pile = @getPile ns
pile.addRaw raw
addUrl: defNs (ns, url) ->
pile = @getPile ns
pile.addUrl url
pileUp: ->
logger = @logger
logger.notice "Start assets generation for '#{ @Type::ext }'"
for name, pile of @piles then do (pile) =>
pile.pileUp (err, code) =>
throw err if err
if @settings.outputDirectory?
outputPath = path.join @settings.outputDirectory, "#{ pile.name }.#{ pile.ext }"
fs.writeFile outputPath, code, (err) ->
throw err if err
logger.info "Wrote #{ pile.ext } pile #{ pile.name } to #{ outputPath }"
getSources: (namespaces...) ->
if typeof _.last(namespaces) is "object"
opts = namespaces.pop()
else
opts = {}
if not opts.disableGlobal
namespaces.unshift "global"
sources = []
for ns in namespaces
if pile = @piles[ns]
sources.push pile.getSources()...
return sources
renderTags: (namespaces...) ->
tags = ""
for src in @getSources namespaces...
tags += @wrapInTag src[0], src[1]
tags += "\n"
return tags
bind: (app, server=null) ->
@app = app
@server = server
listener = if server then server else app
listener.on "listening", =>
@pileUp()
@setMiddleware app
app.use (req, res, next) =>
if not _.startsWith req.url, @settings.urlRoot
return next()
res.setHeader "Content-type", @contentType
asset = assetUrlParse req.url
# Wrong asset type. Lets skip to next middleware.
if asset.ext isnt @Type::ext
return next()
pile = @piles[asset.name]
if not pile
res.send "Cannot find pile #{ asset.name }", 404
return
# TODO: set cache headers to forever
if asset.min
res.end pile.rawPile
return
codeOb = pile.findCodeObById asset.dev.uid
codeOb.getCode (err, code) ->
throw err if err
res.end code
return
class JSManager extends PileManager
Type: JSPile
contentType: "application/javascript"
constructor: ->
super
@piles.global.addExec ->
window._NS = (nsString) ->
parent = window
for ns in nsString.split "."
# Create new namespace if it is missing
parent = parent[ns] ?= {}
parent # return the asked namespace
window.__SET = (ns, ob) ->
parts = ns.split "."
if parts.length is 1
window[parts[0]] = ob
else
nsOb = _NS(parts.slice(0, -1).join("."))
target = parts.slice(-1)[0]
nsOb[target] = ob
wrapInTag: (uri, extra="") ->
"<script type=\"text/javascript\" src=\"#{ uri }\" #{ extra } ></script>"
addModule: defNs (ns, path) ->
pile = @getPile ns
pile.addModule path
addOb: defNs (ns, ob) ->
pile = @getPile ns
pile.addOb ob
addExec: defNs (ns, fn) ->
pile = @getPile ns
pile.addExec fn
setMiddleware: (app) ->
responseExec = (fn) ->
# "this" is the response object
this._responseFns.push fn
responseOb = (ob) ->
this._responseObs.push ob
# Middleware that adds add & exec methods to response objects.
app.use (req, res, next) ->
res._responseFns ?= []
res._responseObs ?= []
# TODO: deprecate res.exec
res.exec = res.addExec = responseExec
res.addOb = responseOb
next()
class CSSManager extends PileManager
Type: CSSPile
contentType: "text/css"
wrapInTag: (uri, extra="") ->
"<link rel=\"stylesheet\" href=\"#{ uri }\" #{ extra } />"
setMiddleware: (app) ->
# Creates immediately executable string presentation of given function.
# context will be function's "this" if given.
executableFrom = (fn, context) ->
return "(#{ fn })();\n" unless context
return "(#{ fn }).call(#{ context });\n"
LiveUpdateMixin = require "./livecss"
_.extend JSManager::, LiveUpdateMixin::
exports.production = production = process.env.NODE_ENV is "production"
exports.CSSPile = CSSPile
exports.JSPile = JSPile
exports.JSManager = JSManager
exports.CSSManager = CSSManager
exports.createJSManager = (settings={}) ->
settings.production = production
new JSManager settings
exports.createCSSManager = (settings={}) ->
settings.production = production
new CSSManager settings

40
node_modules/piler/lib/serialize.coffee generated vendored Normal file
View File

@ -0,0 +1,40 @@
# Remove last comma from string
removeTrailingComma = (s) ->
s.trim().replace(/,$/, "")
# Map of functions that can convert various Javascript objects to strings.
types =
function: (fn) -> "#{ fn }"
string: (s) -> JSON.stringify s # Knows how to correctly serialize strings to String literals
number: (n) -> n.toString()
boolean: (n) -> n.toString()
object: (obj) ->
# typeof reports array as object
return this._array obj if Array.isArray obj
code = "{"
code += "\"#{ k }\": #{ codeFrom v }," for k, v of obj
removeTrailingComma(code) + "}"
_array: (array) ->
code = "["
code += " #{ codeFrom v }," for v in array
removeTrailingComma(code) + "]"
# Generates code string from given object. Works for numbers, strings, regexes
# and even functions. Does not handle circular references.
exports.stringify = codeFrom = (obj) ->
types[typeof obj]?(obj)
if require.main is module
console.log exports.stringify
foo: 1
bar:
lol: ":D"
hah: 2

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

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

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

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

1
node_modules/piler/node_modules/.bin/csso generated vendored Symbolic link
View File

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

1
node_modules/piler/node_modules/.bin/uglifyjs generated vendored Symbolic link
View File

@ -0,0 +1 @@
../uglify-js/bin/uglifyjs

9
node_modules/piler/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/piler/node_modules/async/.npmignore generated vendored Normal file
View File

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

19
node_modules/piler/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/piler/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/piler/node_modules/async/README.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

3
node_modules/piler/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/piler/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);
};
};
}());

35
node_modules/piler/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/piler/node_modules/coffee-script/CNAME generated vendored Normal file
View File

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

22
node_modules/piler/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/piler/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/piler/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/piler/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/piler/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,49 @@
{
"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": "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",
"dist": {
"shasum": "06861ab76fc76d42a86779b5f7aaae936eed8480"
},
"_from": "coffee-script@1.3.x",
"_resolved": "https://registry.npmjs.org/coffee-script/-/coffee-script-1.3.3.tgz"
}

35
node_modules/piler/node_modules/csso/GNUmakefile generated vendored Normal file
View File

@ -0,0 +1,35 @@
.PHONY: test web shared node
node:
@make shared
@cat src/parser.node.js >> .parser.js
@mv .parser.js lib/parser.js
@cat src/compressor.node.js >> .compressor.js
@mv .compressor.js lib/compressor.js
@cat src/util.node.js >> .util.js
@mv .util.js lib/util.js
@cat src/translator.node.js >> .translator.js
@mv .translator.js lib/translator.js
shared:
@pecode src/csso.pecode > .parser.js
@cat src/csso.other.js >> .parser.js
@cat src/trbl.js > .compressor.js
@cat src/compressor.shared.js >> .compressor.js
@cat src/util.shared.js > .util.js
@cat src/translator.shared.js > .translator.js
test:
@node test/test.js
web:
@make shared
@cat .util.js > web/csso.web.js
@rm .util.js
@cat .parser.js >> web/csso.web.js
@rm .parser.js
@cat src/compressor.web.js >> web/csso.web.js
@cat .compressor.js >> web/csso.web.js
@rm .compressor.js
@cat .translator.js >> web/csso.web.js
@rm .translator.js

619
node_modules/piler/node_modules/csso/MANUAL.en.md generated vendored Normal file
View File

@ -0,0 +1,619 @@
# Table of contents
* 1\. Introduction
* 2\. Minification
* 2.1\. Basic transformations
* 2.1.1\. Removal of whitespace
* 2.1.2\. Removal of trailing ';'
* 2.1.3\. Removal of comments
* 2.1.4\. Removal of invalid @charset and @import declarations
* 2.1.5\. Minification of color properties
* 2.1.6\. Minification of 0
* 2.1.7\. Minification of multi-line strings
* 2.1.8\. Minification of the font-weight property
* 2.2\. Structural optimization
* 2.2.1\. Merging blocks with identical selectors
* 2.2.2\. Merging blocks with idential properties
* 2.2.3\. Removal of overridden properties
* 2.2.3.1\. Removal of overridden shorthand properties
* 2.2.4\. Removal of repeating selectors
* 2.2.5\. Partial merging of blocks
* 2.2.6\. Partial splitting of blocks
* 2.2.7\. Removal of empty ruleset and at-rule
* 2.2.8\. Minification of margin and padding properties
* 3\. Recommendations
* 3.1\. Length of selectors
* 3.2\. Order of properties
* 3.3\. Positioning of similar blocks
* 3.4\. Using !important
# 1. Introduction
CSSO (CSS Optimizer) is a CSS minimizer unlike others. In addition to usual minification techniques it can perform structural optimization of CSS files, resulting in smaller file size compared to other minifiers.
This document describes the minification techniques we employ. If you are looking for an installation and usage guide, you can find it [here](https://github.com/afelix/csso/blob/master/README.md).
# 2. Minification
Minification is a process of transforming a CSS document into a smaller document without losses. The typical strategies of achieving this are:
* basic transformations, such as removal of unnecessary elements (e.g. trailing semicolons) or transforming the values into more compact representations (e.g. `0px` to `0`);
* structural optimizations, such as removal of overridden properties or merging of blocks.
## 2.1. Basic transformations
### 2.1.1. Removal of whitespace
In some cases, whitespace characters (` `, `\n`, `\r`, `\t`, `\f`) are unnecessary and do not affect rendering.
* Before:
.test
{
margin-top: 1em;
margin-left : 2em;
}
* After:
.test{margin-top:1em;margin-left:2em}
The following examples are provided with whitespace left intact for better readability.
### 2.1.2. Removal of trailing ';'
The last semicolon in a block is not required and does not affect rendering.
* Before:
.test {
margin-top: 1em;;
}
* After:
.test {
margin-top: 1em
}
### 2.1.3. Removal of comments
Comments do not affect rendering: \[[CSS 2.1 / 4.1.9 Comments](http://www.w3.org/TR/CSS21/syndata.html#comments)\].
* Before:
/* comment */
.test /* comment */ {
/* comment */ margin-top: /* comment */ 1em;
}
* After:
.test {
margin-top: 1em
}
### 2.1.4. Removal of invalid @charset and @import declarations
According to the specification, `@charset` must be placed at the very beginning of the stylesheet: \[[CSS 2.1 / 4.4 CSS style sheet representation](http://www.w3.org/TR/CSS21/syndata.html#charset)\].
CSSO handles this rule in a slightly relaxed manner - we keep the `@charset` rule which immediately follows whitespace and comments in the beginning of the stylesheet.
Incorrectly placed `@import` rules are deleted according to \[[CSS 2.1 / 6.3 The @import rule](http://www.w3.org/TR/CSS21/cascade.html#at-import)\].
* Before:
/* comment */
@charset 'UTF-8';
@import "test0.css";
@import "test1.css";
@charset 'wrong';
h1 {
color: red
}
@import "wrong";
* After:
@charset 'UTF-8';
@import "test0.css";
@import "test1.css";
h1 {
color: red
}
### 2.1.5. Minification of color properties
Some color values are minimized according to \[[CSS 2.1 / 4.3.6 Colors](http://www.w3.org/TR/CSS21/syndata.html#color-units)\].
* Before:
.test {
color: yellow;
border-color: #c0c0c0;
background: #ffffff;
border-top-color: #f00;
outline-color: rgb(0, 0, 0);
}
* After:
.test {
color: #ff0;
border-color: silver;
background: #fff;
border-top-color: red;
outline-color: #000
}
### 2.1.6. Minification of 0
In some cases, the numeric values can be compacted to `0` or even dropped.
The `0%` value is not being compacted to avoid the following situation: `rgb(100%, 100%, 0)`.
* Before:
.test {
fakeprop: .0 0. 0.0 000 00.00 0px 0.1 0.1em 0.000em 00% 00.00% 010.00
}
* After:
.test {
fakeprop: 0 0 0 0 0 0 .1 .1em 0 0% 0% 10
}
### 2.1.7. Minification of multi-line strings
Multi-line strings are minified according to \[[CSS 2.1 / 4.3.7 Strings](http://www.w3.org/TR/CSS21/syndata.html#strings)\].
* Before:
.test[title="abc\
def"] {
background: url("foo/\
bar")
}
* After:
.test[title="abcdef"] {
background: url("foo/bar")
}
### 2.1.8. Minification of the font-weight property
The `bold` and `normal` values of the `font-weight` property are minimized according to \[[CSS 2.1 / 15.6 Font boldness: the 'font-weight' property](http://www.w3.org/TR/CSS21/fonts.html#font-boldness)\].
* Before:
.test0 {
font-weight: bold
}
.test1 {
font-weight: normal
}
* After:
.test0 {
font-weight: 700
}
.test1 {
font-weight: 400
}
## 2.2. Structural optimizations
### 2.2.1. Merging blocks with identical selectors
Adjacent blocks with identical selectors are merged.
* Before:
.test0 {
margin: 0
}
.test1 {
border: none
}
.test1 {
background-color: green
}
.test0 {
padding: 0
}
* After:
.test0 {
margin: 0
}
.test1 {
border: none;
background-color: green
}
.test0 {
padding: 0
}
### 2.2.2. Merging blocks with identical properties
Adjacent blocks with identical properties are merged.
* Before:
.test0 {
margin: 0
}
.test1 {
border: none
}
.test2 {
border: none
}
.test0 {
padding: 0
}
* After:
.test0 {
margin: 0
}
.test1, .test2 {
border: none
}
.test0 {
padding: 0
}
### 2.2.3. Removal of overridden properties
Properties ignored by the browser can be removed using the following rules:
* the last property in a CSS rule is applied, if none of the properties have an `!important` declaration;
* among `!important` properties, the last one is applied.
* Before:
.test {
color: red;
margin: 0;
line-height: 3cm;
color: green;
}
* After:
.test {
margin: 0;
line-height: 3cm;
color: green
}
#### 2.2.3.1. Removal of overridden shorthand properties
In case of `border`, `margin`, `padding`, `font` and `list-style` properties, the following removal rule will be applied: if the last property is a 'general' one (for example, `border`), then all preceding overridden properties will be removed (for example, `border-top-width` or `border-style`).
* Before:
.test {
border-top-color: red;
border-color: green
}
* After:
.test {
border-color:green
}
### 2.2.4. Removal of repeating selectors
Repeating selectors can be removed.
* Before:
.test, .test {
color: red
}
* After:
.test {
color: red
}
### 2.2.5. Partial merging of blocks
Given two adjacent blocks where one of the blocks is a subset of the other one, the following optimization is possible:
* overlapping properties are removed from the source block;
* the remaining properties of the source block are copied into a receiving block.
Minification will take place if character count of the properties to be copied is smaller than character count of the overlapping properties.
* Before:
.test0 {
color: red
}
.test1 {
color: red;
border: none
}
.test2 {
border: none
}
* After:
.test0, .test1 {
color: red
}
.test1, .test2 {
border: none
}
Minification won't take place if character count of the properties to be copied is larger than character count of the overlapping properties.
* Before:
.test0 {
color: red
}
.longlonglong {
color: red;
border: none
}
.test1 {
border: none
}
* After:
.test0 {
color: red
}
.longlonglong {
color: red;
border: none
}
.test1 {
border: none
}
### 2.2.6. Partial splitting of blocks
If two adjacent blocks contain intersecting properties the following minification is possible:
* property intersection is determined;
* a new block containing the intersection is created in between the two blocks.
Minification will take place if there's a gain in character count.
* Before:
.test0 {
color: red;
border: none;
margin: 0
}
.test1 {
color: green;
border: none;
margin: 0
}
* After:
.test0 {
color: red
}
.test0, .test1 {
border: none;
margin: 0
}
.test1 {
color: green
}
Minification won't take place if there's no gain in character count.
* Before:
.test0 {
color: red;
border: none;
margin: 0
}
.longlonglong {
color: green;
border: none;
margin: 0
}
* After:
.test0 {
color: red;
border: none;
margin: 0
}
.longlonglong {
color: green;
border: none;
margin: 0
}
### 2.2.7. Removal of empty ruleset and at-rule
Empty ruleset and at-rule will be removed.
* Before:
.test {
color: red
}
.empty {}
@font-face {}
@media print {
.empty {}
}
.test {
border: none
}
* After:
.test{color:red;border:none}
### 2.2.8. Minification of margin and padding properties
The `margin` and `padding` properties are minimized according to \[[CSS 2.1 / 8.3 Margin properties](http://www.w3.org/TR/CSS21/box.html#margin-properties)\] и \[[CSS 2.1 / 8.4 Padding properties](http://www.w3.org/TR/CSS21/box.html#padding-properties)\].
* Before:
.test0 {
margin-top: 1em;
margin-right: 2em;
margin-bottom: 3em;
margin-left: 4em;
}
.test1 {
margin: 1 2 3 2
}
.test2 {
margin: 1 2 1 2
}
.test3 {
margin: 1 1 1 1
}
.test4 {
margin: 1 1 1
}
.test5 {
margin: 1 1
}
* After:
.test0 {
margin: 1em 2em 3em 4em
}
.test1 {
margin: 1 2 3
}
.test2 {
margin: 1 2
}
.test3, .test4, .test5 {
margin: 1
}
# 3. Recommendations
Some stylesheets compress better than the others. Sometimes, one character difference can turn a well-compressible stylesheet to a very inconvenient one.
You can help the minimizer by following these recommendations.
## 3.1. Length of selectors
Shorter selectors are easier to re-group.
## 3.2. Order of properties
Stick to the same order of properties throughout the stylesheet - it will allow you to not use the guards. The less manual intervention there is, the easier it is for the minimizer to work optimally.
## 3.3. Positioning of similar blocks
Keep blocks with similar sets of properties close to each other.
Bad:
* Before:
.test0 {
color: red
}
.test1 {
color: green
}
.test2 {
color: red
}
* After (53 characters):
.test0{color:red}.test1{color:green}.test2{color:red}
Good:
* Before:
.test1 {
color: green
}
.test0 {
color: red
}
.test2 {
color: red
}
* After (43 characters):
.test1{color:green}.test0,.test2{color:red}
## 3.4. Using !important
It should go without saying that using the `!important` declaration harms minification performance.
Bad:
* Before:
.test {
margin-left: 2px !important;
margin: 1px;
}
* After (43 characters):
.test{margin-left:2px!important;margin:1px}
Good:
* Before:
.test {
margin-left: 2px;
margin: 1px;
}
* After (17 characters):
.test{margin:1px}

789
node_modules/piler/node_modules/csso/MANUAL.ru.md generated vendored Normal file
View File

@ -0,0 +1,789 @@
# Содержание
* 1\. Описание
* 2\. Минимизация
* 2.1\. Минимизация без изменения структуры
* 2.1.1\. Удаление whitespace
* 2.1.2\. Удаление концевых ';'
* 2.1.3\. Удаление комментариев
* 2.1.4\. Удаление неправильных @charset и @import
* 2.1.5\. Минимизация цвета
* 2.1.6\. Минимизация 0
* 2.1.7\. Слияние многострочных строк в однострочные
* 2.1.8\. Минимизация font-weight
* 2.2\. Минимизация с изменением структуры
* 2.2.1\. Слияние блоков с одинаковыми селекторами
* 2.2.2\. Слияние блоков с одинаковыми свойствами
* 2.2.3\. Удаление перекрываемых свойств
* 2.2.3.1\. Удаление перекрываемых shorthand-свойств
* 2.2.4\. Удаление повторяющихся селекторов
* 2.2.5\. Частичное слияние блоков
* 2.2.6\. Частичное разделение блоков
* 2.2.7\. Удаление пустых ruleset и at-rule
* 2.2.8\. Минимизация margin и padding
* 2.2.9\. Специальная минимизация псевдоклассов
* 2.2.9.1\. Сохранение группы
* 2.2.9.2\. Минимизация общеподдерживаемых псевдоклассов
* 2.2.9.3\. Минимизация :before и :after
* 3\. Рекомендации
* 3.1\. Длина селекторов
* 3.2\. Порядок свойств
* 3.3\. Расположение схожих блоков
* 3.4\. Использование !important
# 1. Описание
CSSO (CSS Optimizer) является минимизатором CSS, выполняющим как минимизацию без изменения структуры, так и структурную минимизацию с целью получить как можно меньший текст.
Этот документ описывает минимизацию детально. Если вам нужна инструкция по установке, она находится [здесь](https://github.com/afelix/csso/blob/master/README.md).
# 2. Минимизация
Цель минимизации заключается в трансформации исходного CSS в CSS меньшего размера. Наиболее распространёнными стратегиями в достижении этой цели являются:
* минимизация без изменения структуры&nbsp;— удаление необязательных элементов (например, `;` у последнего свойства в блоке), сведение значений к меньшим по размеру (например, `0px` к `0`) и т.п.;
* минимизация с изменением структуры&nbsp;— удаление перекрываемых свойств, полное или частичное слияние блоков.
## 2.1. Минимизация без изменения структуры
### 2.1.1. Удаление whitespace
В ряде случаев символы ряда whitespace (` `, `\n`, `\r`, `\t`, `\f`) являются необязательными и не влияют на результат применения таблицы стилей.
* Было:
.test
{
margin-top: 1em;
margin-left : 2em;
}
* Стало:
.test{margin-top:1em;margin-left:2em}
Для большего удобства чтения текст остальных примеров приводится с пробелами (переводом строки и т.п.).
### 2.1.2. Удаление концевых ';'
Символ `;`, завершающий перечисление свойств в блоке, является необязательным и не влияет на результат применения таблицы стилей.
* Было:
.test {
margin-top: 1em;;
}
* Стало:
.test {
margin-top: 1em
}
### 2.1.3. Удаление комментариев
Комментарии не влияют на результат применения таблицы стилей: \[[CSS 2.1 / 4.1.9 Comments](http://www.w3.org/TR/CSS21/syndata.html#comments)\].
* Было:
/* comment */
.test /* comment */ {
/* comment */ margin-top: /* comment */ 1em;
}
* Стало:
.test {
margin-top: 1em
}
### 2.1.4. Удаление неправильных @charset и @import
Единственно верным расположением `@charset` является начало текста: \[[CSS 2.1 / 4.4 CSS style sheet representation](http://www.w3.org/TR/CSS21/syndata.html#charset)\].
Однако CSSO позволяет обходиться с этим правилом достаточно вольно, т.к. оставляет первый после whitespace и комментариев `@charset`.
Правило `@import` на неправильном месте удаляется согласно \[[CSS 2.1 / 6.3 The @import rule](http://www.w3.org/TR/CSS21/cascade.html#at-import)\].
* Было:
/* comment */
@charset 'UTF-8';
@import "test0.css";
@import "test1.css";
@charset 'wrong';
h1 {
color: red
}
@import "wrong";
* Стало:
@charset 'UTF-8';
@import "test0.css";
@import "test1.css";
h1 {
color: red
}
### 2.1.5. Минимизация цвета
Некоторые значения цвета минимизируются согласно \[[CSS 2.1 / 4.3.6 Colors](http://www.w3.org/TR/CSS21/syndata.html#color-units)\].
* Было:
.test {
color: yellow;
border-color: #c0c0c0;
background: #ffffff;
border-top-color: #f00;
outline-color: rgb(0, 0, 0);
}
* Стало:
.test {
color: #ff0;
border-color: silver;
background: #fff;
border-top-color: red;
outline-color: #000
}
### 2.1.6. Минимизация 0
В ряде случаев числовое значение можно сократить до `0` или же отбросить `0`.
Значения `0%` не сокращаются до `0`, чтобы избежать ошибок вида `rgb(100%, 100%, 0)`.
* Было:
.test {
fakeprop: .0 0. 0.0 000 00.00 0px 0.1 0.1em 0.000em 00% 00.00% 010.00
}
* Стало:
.test {
fakeprop: 0 0 0 0 0 0 .1 .1em 0 0% 0% 10
}
### 2.1.7. Слияние многострочных строк в однострочные
Многострочные строки минимизируются согласно \[[CSS 2.1 / 4.3.7 Strings](http://www.w3.org/TR/CSS21/syndata.html#strings)\].
* Было:
.test[title="abc\
def"] {
background: url("foo/\
bar")
}
* Стало:
.test[title="abcdef"] {
background: url("foo/bar")
}
### 2.1.8. Минимизация font-weight
Значения `bold` и `normal` свойства `font-weight` минимизируются согласно \[[CSS 2.1 / 15.6 Font boldness: the 'font-weight' property](http://www.w3.org/TR/CSS21/fonts.html#font-boldness)\].
* Было:
.test0 {
font-weight: bold
}
.test1 {
font-weight: normal
}
* Стало:
.test0 {
font-weight: 700
}
.test1 {
font-weight: 400
}
## 2.2. Минимизация с изменением структуры
### 2.2.1. Слияние блоков с одинаковыми селекторами
В один блок сливаются соседние блоки с одинаковым набором селекторов.
* Было:
.test0 {
margin: 0
}
.test1 {
border: none
}
.test1 {
background-color: green
}
.test0 {
padding: 0
}
* Стало:
.test0 {
margin: 0
}
.test1 {
border: none;
background-color: green
}
.test0 {
padding: 0
}
### 2.2.2. Слияние блоков с одинаковыми свойствами
В один блок сливаются соседние блоки с одинаковым набором свойств.
* Было:
.test0 {
margin: 0
}
.test1 {
border: none
}
.test2 {
border: none
}
.test0 {
padding: 0
}
* Стало:
.test0 {
margin: 0
}
.test1, .test2 {
border: none
}
.test0 {
padding: 0
}
### 2.2.3. Удаление перекрываемых свойств
Минимизация удалением перекрываемых свойств основана на том, что внутри блока применяется:
* последнее по порядку свойство, если все свойства не `!important`;
* последнее по порядку свойство `!important`.
Это позволяет избавиться от всех игнорируемых браузером свойств.
* Было:
.test {
color: red;
margin: 0;
line-height: 3cm;
color: green;
}
* Стало:
.test {
margin: 0;
line-height: 3cm;
color: green
}
#### 2.2.3.1. Удаление перекрываемых shorthand свойств
Для свойств `border`, `margin`, `padding`, `font` и `list-style` используется следующий алгоритм удаления: если последним по порядку свойством является более 'широкое' свойство (например, `border`), то все предыдущие перекрываемые им свойства удаляются (например, `border-top-width` или `border-style`).
* Было:
.test {
border-top-color: red;
border-color: green
}
* Стало:
.test {
border-color:green
}
### 2.2.4. Удаление повторяющихся селекторов
Повторяющиеся селекторы излишни и потому могут быть удалены.
* Было:
.test, .test {
color: red
}
* Стало:
.test {
color: red
}
### 2.2.5. Частичное слияние блоков
Если рядом расположены блоки, один из которых набором свойств полностью входит в другой, возможна следующая минимизация:
* в исходном (наибольшем) блоке удаляется пересекающийся набор свойств;
* селекторы исходного блока копируются в принимающий блок.
Если в символах размер копируемых селекторов меньше размера пересекающегося набора свойств, минимизация происходит.
* Было:
.test0 {
color: red
}
.test1 {
color: red;
border: none
}
.test2 {
border: none
}
* Стало:
.test0, .test1 {
color: red
}
.test1, .test2 {
border: none
}
Если в символах размер копируемых селекторов больше размера пересекающегося набора свойств, минимизация не происходит.
* Было:
.test0 {
color: red
}
.longlonglong {
color: red;
border: none
}
.test1 {
border: none
}
* Стало:
.test0 {
color: red
}
.longlonglong {
color: red;
border: none
}
.test1 {
border: none
}
### 2.2.6. Частичное разделение блоков
Если рядом расположены блоки, частично пересекающиеся набором свойств, возможна следующая минимизация:
* из обоих блоков выделяется пересекающийся набор свойств;
* между блоками создаётся новый блок с выделенным набором свойств и с селекторами обоих блоков.
Если в символах размер копируемых селекторов меньше размера пересекающегося набора свойств, минимизация происходит.
* Было:
.test0 {
color: red;
border: none;
margin: 0
}
.test1 {
color: green;
border: none;
margin: 0
}
* Стало:
.test0 {
color: red
}
.test0, .test1 {
border: none;
margin: 0
}
.test1 {
color: green
}
Если в символах размер копируемых селекторов больше размера пересекающегося набора свойств, минимизация не происходит.
* Было:
.test0 {
color: red;
border: none;
margin: 0
}
.longlonglong {
color: green;
border: none;
margin: 0
}
* Стало:
.test0 {
color: red;
border: none;
margin: 0
}
.longlonglong {
color: green;
border: none;
margin: 0
}
### 2.2.7. Удаление пустых ruleset и at-rule
Пустые ruleset и at-rule удаляются.
* Было:
.test {
color: red
}
.empty {}
@font-face {}
@media print {
.empty {}
}
.test {
border: none
}
* Стало:
.test{color:red;border:none}
### 2.2.8. Минимизация margin и padding
Свойства `margin` и `padding` минимизируются согласно \[[CSS 2.1 / 8.3 Margin properties](http://www.w3.org/TR/CSS21/box.html#margin-properties)\] и \[[CSS 2.1 / 8.4 Padding properties](http://www.w3.org/TR/CSS21/box.html#padding-properties)\].
* Было:
.test0 {
margin-top: 1em;
margin-right: 2em;
margin-bottom: 3em;
margin-left: 4em;
}
.test1 {
margin: 1 2 3 2
}
.test2 {
margin: 1 2 1 2
}
.test3 {
margin: 1 1 1 1
}
.test4 {
margin: 1 1 1
}
.test5 {
margin: 1 1
}
* Стало:
.test0 {
margin: 1em 2em 3em 4em
}
.test1 {
margin: 1 2 3
}
.test2 {
margin: 1 2
}
.test3, .test4, .test5 {
margin: 1
}
Минимизация не происходит в случаях, когда один набор `selector X / shorthands` прерывается другим набором `selector Y / shorthands`.
* Было:
.test1 {
margin-top: 0
}
.test2 {
margin-top: 100px
}
.test1 {
margin-left: 0
}
.test1 {
margin-bottom: 0
}
.test1 {
margin-right: 0
}
* Стало:
.test1 {
margin-top: 0
}
.test2 {
margin-top: 100px
}
.test1 {
margin-left: 0;
margin-bottom: 0;
margin-right: 0
}
* Могло быть (неправильно):
.test2 {
margin-top: 100px
}
.test1 {
margin: 0
}
К сожалению, результат рендеринга последнего варианта отличается от рендеринга исходного стиля, потому такая минимизация недопустима.
### 2.2.9. Специальная минимизация псевдоклассов
Если в группе селекторов UA обнаружит неподдерживаемый селектор, он, согласно \[[CSS 3 / Selectors / 5. Groups of selectors](http://www.w3.org/TR/selectors/#grouping)\], посчитает неподдерживаемой всю группу и не применит стили к перечисленным в ней селекторам. Этим нередко пользуются для разграничения стилей по браузерам. Вот [пример](http://pornel.net/firefoxhack) метода:
#hackme, x:-moz-any-link { Firefox 2.0 here }
#hackme, x:-moz-any-link, x:default { Firefox 3.0 and newer }
Чтобы сохранить такие блоки, но в то же время минимизировать то, что поддаётся оптимизации, CSSO применяет нижеперечисленные правила. Предполагается, что вместе эти правила составляют компромисс, удовлетворяющий большинство пользователей.
#### 2.2.9.1. Сохранение группы
В общем случае (исключения описаны ниже) минимизация удалением перекрываемого селектора не происходит, если группа селекторов включает псевдокласс или псевдоэлемент.
* Было:
a {
property: value0
}
a, x:-vendor-class {
property: value1
}
* Стало (структура не изменилась):
a {
property: value0
}
a, x:-vendor-class {
property: value1
}
Если же группы селекторов образуют одинаковую "сигнатуру псевдоклассов" (исключается ситуация, в которой браузер поддерживает одну группу, но не поддерживает другую), минимизация происходит.
* Было:
a, x:-vendor-class {
property: value0
}
a, b, x:-vendor-class {
property: value1
}
* Стало:
a, b, x:-vendor-class {
property: value1
}
#### 2.2.9.2. Минимизация общеподдерживаемых псевдоклассов и псевдоэлементов
Существуют псевдоклассы и псевдоэлементы, поддерживаемые большинством браузеров: `:link`, `:visited`, `:hover`, `:active`, `:first-letter`, `:first-line`. Для них минимизация происходит в общем порядке без сохранения группы.
* Было:
a, x:active {
color: red
}
a {
color: green
}
* Стало:
x:active {
color: red
}
a {
color: green
}
#### 2.2.9.3. Минимизация :before и :after
Псевдоэлементы `:before` и `:after` обычно поддерживаются браузерами парно, потому объединение блоков с их участием безопасно.
* Было:
a, x:before {
color: red
}
a, x:after {
color: red
}
* Стало:
a, x:before, x:after {
color:red
}
Тем не менее, блоки, в которых участвует только один из этих псевдоэлементов, не объединяются:
* Было:
a {
color: red
}
a, x:after {
color: red
}
* Стало:
a {
color: red
}
a, x:after {
color: red
}
В примере выше можно заметить, что удаление селектора `a` из второго блока не повлияло бы на итоговый рендеринг, но в общем случае это опасная минимизация, потому не применяется.
# 3. Рекомендации
С точки зрения минимизации таблицы стилей можно разделить на две группы: удобные и неудобные. Разница даже в один символ может превратить вполне сокращаемый исходный текст в минимально обрабатываемый.
Если вы хотите помочь минимизатору хорошо выполнить работу, следуйте рекомендациям.
## 3.1. Длина селекторов
Чем короче селектор (whitespace не учитываются), тем больше вероятность удачного группирования.
## 3.2. Порядок свойств
Придерживайтесь во всём CSS одного порядка, в котором перечисляются свойства, так вам не потребуется защита от смены порядка. Соответственно, меньше вероятность допустить ошибку и помешать минимизатору излишним управлением.
## 3.3. Расположение схожих блоков
Располагайте блоки со схожим набором свойств как можно ближе друг к другу.
Плохо:
* Было:
.test0 {
color: red
}
.test1 {
color: green
}
.test2 {
color: red
}
* Стало (53 символа):
.test0{color:red}.test1{color:green}.test2{color:red}
Хорошо:
* Было:
.test1 {
color: green
}
.test0 {
color: red
}
.test2 {
color: red
}
* Стало (43 символа):
.test1{color:green}.test0,.test2{color:red}
## 3.4. Использование !important
Очевидно, `!important` оказывает серьёзное влияние на минимизацию, особенно заметно это может отразиться на минимизации `margin` и `padding`, потому им лучше не злоупотреблять.
Плохо:
* Было:
.test {
margin-left: 2px !important;
margin: 1px;
}
* Стало (43 символа):
.test{margin-left:2px!important;margin:1px}
Хорошо:
* Было:
.test {
margin-left: 2px;
margin: 1px;
}
* Стало (17 символов):
.test{margin:1px}

19
node_modules/piler/node_modules/csso/MIT-LICENSE.txt generated vendored Normal file
View File

@ -0,0 +1,19 @@
Copyright (C) 2011 by Sergey Kryzhanovsky
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.

139
node_modules/piler/node_modules/csso/README.md generated vendored Normal file
View File

@ -0,0 +1,139 @@
# 1. Introduction
CSSO (CSS Optimizer) is a CSS minimizer unlike others. In addition to usual minification techniques it can perform structural optimization of CSS files, resulting in smaller file size compared to other minifiers.
This document describes installation and usage of CSSO. If you want to learn more about the inner workings of CSSO, please consult the [manual] (https://github.com/css/csso/blob/master/MANUAL.en.md).
Please report issues on [Github] (https://github.com/css/csso/issues).
For feedback, suggestions, etc. write to <skryzhanovsky@ya.ru>.
# 2. Installation
## 2.1. Prerequisites
* for browser use: any OS and a modern web browser
* for command line use: Linux / Mac OS X / any OS with working Node.js
## 2.2. Install using git
Prerequisites:
* git&nbsp;— [http://git-scm.com/](http://git-scm.com/)
To install:
* run `git clone git://github.com/css/csso.git`
## 2.3. Install using npm
Prerequisites:
* nodejs 0.4.x&nbsp;— [http://nodejs.org](http://nodejs.org)
* npm&nbsp;— [http://github.com/isaacs/npm/](http://github.com/isaacs/npm/)
To install (global):
* run `npm install csso -g`
To update:
* run `npm update csso`
To uninstall:
* run `npm uninstall csso`
# 3. Usage
## 3.1. In the browser
Open `web/csso.html` or [http://css.github.com/csso/csso.html](http://css.github.com/csso/csso.html) in your browser.
**CSSO is not guaranteed to work in browsers. Preferred way to use this tool is to run it from the command line or via npm modules.**
## 3.2. As an npm module
Sample (`test.js`):
var csso = require('csso'),
css = '.test, .test { color: rgb(255, 255, 255) }';
console.log(csso.justDoIt(css));
Output (`> node test.js`):
.test{color:#fff}
Use `csso.justDoIt(css, true)` to turn structure minimization off.
## 3.3. From the command line
Run `bin/csso` (when installed from git), you will need to have nodejs 0.4.x installed&nbsp;— [http://nodejs.org](http://nodejs.org)
Run `csso` (when installed from npm).
Usage:
csso
shows usage information
csso <filename>
minimizes the CSS in <filename> and outputs the result to stdout
csso <in_filename> <out_filename>
csso -i <in_filename> -o <out_filename>
csso --input <in_filename> --output <out_filename>
minimizes the CSS in <in_filename> and outputs the result to <out_filename>
csso -off
csso --restructure-off
turns structure minimization off
csso -h
csso --help
shows usage information
csso -v
csso --version
shows the version number
Example:
$ echo ".test { color: red; color: green }" > test.css
$ csso test.css
.test{color:green}
# 4. Minification (in a nutshell)
Safe transformations:
* Removal of whitespace
* Removal of trailing `;`
* Removal of comments
* Removal of invalid `@charset` и `@import` declarations
* Minification of color properties
* Minification of `0`
* Minification of multi-line strings
* Minification of the `font-weight` property
Structural optimizations:
* Merging blocks with identical selectors
* Merging blocks with identical properties
* Removal of overridden properties
* Removal of overridden shorthand properties
* Removal of repeating selectors
* Partial merging of blocks
* Partial splitting of blocks
* Removal of empty ruleset and at-rule
* Minification of `margin` and `padding` properties
The minification techniques are described in detail in the [manual](https://github.com/css/csso/blob/master/MANUAL.en.md).
# 5. Authors
* initial idea&nbsp;— Vitaly Harisov (<vitaly@harisov.name>)
* implementation&nbsp;— Sergey Kryzhanovsky (<skryzhanovsky@ya.ru>)
* english translation&nbsp;— Leonid Khachaturov (leonidkhachaturov@gmail.com)
# 6. And finally
* CSSO is licensed under [MIT](https://github.com/css/csso/blob/master/MIT-LICENSE.txt)
<!-- Yandex.Metrika counter -->
<img src="//mc.yandex.ru/watch/12831025" style="position:absolute; left:-9999px;" alt="" />
<!-- /Yandex.Metrika counter -->

139
node_modules/piler/node_modules/csso/README.ru.md generated vendored Normal file
View File

@ -0,0 +1,139 @@
# 1. Описание
CSSO (CSS Optimizer) является минимизатором CSS, выполняющим как минимизацию без изменения структуры, так и структурную минимизацию с целью получить как можно меньший текст.
Этот документ является инструкцией по установке и использованию. Если вам нужна детальная инструкция по минимизации, она находится [здесь](https://github.com/css/csso/blob/master/MANUAL.ru.md).
Замеченные ошибки лучше добавлять в [Issues](https://github.com/css/csso/issues) проекта.
Советы, предложения, отзывы, а также ошибки, которые почему-то лучше выслать письмом, высылайте на адрес <skryzhanovsky@ya.ru>.
# 2. Установка
## 2.1. Предварительные требования
* для использования из браузера: любая OS с современным браузером
* для использования из командной строки: OS Linux / Mac OS X / любая OS с работающим Node.js
## 2.2. Установка с помощью git
Предварительные требования:
* git&nbsp;— [http://git-scm.com/](http://git-scm.com/)
Установка:
* выполнить `git clone git://github.com/css/csso.git`
## 2.3. Установка с помощью npm
Предварительные требования:
* nodejs версии 0.4.x&nbsp;— [http://nodejs.org](http://nodejs.org)
* npm&nbsp;— [http://github.com/isaacs/npm/](http://github.com/isaacs/npm/)
Установка (глобально):
* выполнить `npm install csso -g`
Обновление:
* выполнить `npm update csso`
Удаление:
* выполнить `npm uninstall csso`
# 3. Использование
## 3.1. Через браузер (при установке с помощью git)
Открыть в браузере файл `web/csso.html` или [http://css.github.com/csso/csso.html](http://css.github.com/csso/csso.html).
**Работа CSSO в браузерах не гарантирована. Рекомендуемый путь использования этой утилиты&nbsp;— использование из командной строки или npm-модулей.**
## 3.2. Через npm-модуль (при установке с помощью npm)
Пример (`test.js`):
var csso = require('csso'),
css = '.test, .test { color: rgb(255, 255, 255) }';
console.log(csso.justDoIt(css));
Вывод (`> node test.js`):
.test{color:#fff}
Используйте `csso.justDoIt(css, true)`, если требуется выключить структурную минимизацию.
## 3.3. Через командную строку
При git-установке запускать `bin/csso`, но в таком случае потребуется nodejs версии 0.4.x&nbsp;— [http://nodejs.org](http://nodejs.org)
При npm-установке запускать `csso`.
Справка командной строки:
csso
показывает этот текст
csso <имя_файла>
минимизирует CSS из <имя_файла> и записывает результат в stdout
csso <in_имя_файла> <out_имя_файла>
csso -i <in_имя_файла> -o <out_имя_файла>
csso --input <in_имя_файла> --output <out_имя_файла>
минимизирует CSS из <in_имя_файла> и записывает результат в <out_имя_файла>
csso -off
csso --restructure-off
turns structure minimization off
csso -h
csso --help
показывает этот текст
csso -v
csso --version
показывает номер версии CSSO
Пример использования:
$ echo ".test { color: red; color: green }" > test.css
$ csso test.css
.test{color:green}
# 4. Минимизация (кратко)
Минимизация без изменения структуры:
* Удаление whitespace
* Удаление концевых `;`
* Удаление комментариев
* Удаление неправильных `@charset` и `@import`
* Минимизация цвета
* Минимизация `0`
* Слияние многострочных строк в однострочные
* Минимизация `font-weight`
Минимизация с изменением структуры:
* Слияние блоков с одинаковыми селекторами
* Слияние блоков с одинаковыми свойствами
* Удаление перекрываемых свойств
* Удаление перекрываемых shorthand-свойств
* Удаление повторяющихся селекторов
* Частичное слияние блоков
* Частичное разделение блоков
* Удаление пустых ruleset и at-rule
* Минимизация `margin` и `padding`
Детальное описание минимизации находится [здесь](https://github.com/css/csso/blob/master/MANUAL.ru.md).
# 5. Авторы
* идея и поддержка&nbsp;— Виталий Харисов (<vitaly@harisov.name>)
* реализация&nbsp;— Сергей Крыжановский (<skryzhanovsky@ya.ru>)
* перевод на английский язык&nbsp;— Leonid Khachaturov (leonidkhachaturov@gmail.com)
# 6. Остальное
* CSSO распространяется под [лицензией MIT](https://github.com/css/csso/blob/master/MIT-LICENSE.txt)
<!-- Yandex.Metrika counter -->
<img src="//mc.yandex.ru/watch/12831025" style="position:absolute; left:-9999px;" alt="" />
<!-- /Yandex.Metrika counter -->

37
node_modules/piler/node_modules/csso/USAGE generated vendored Normal file
View File

@ -0,0 +1,37 @@
Usage:
csso
shows usage information
csso <filename>
minimizes the CSS in <filename> and outputs the result to stdout
csso <in_filename> <out_filename>
csso -i <in_filename> -o <out_filename>
csso --input <in_filename> --output <out_filename>
minimizes the CSS in <in_filename> and outputs the result to <out_filename>
csso -off
csso --restructure-off
turns structure minimization off
csso -h
csso --help
shows usage information
csso -v
csso --version
shows the version number
Использование:
csso
показывает этот текст
csso <имя_файла>
минимизирует CSS из <имя_файла> и записывает результат в stdout
csso <in_имя_файла> <out_имя_файла>
csso -i <in_имя_файла> -o <out_имя_файла>
csso --input <in_имя_файла> --output <out_имя_файла>
минимизирует CSS из <in_имя_файла> и записывает результат в <out_имя_файла>
csso -off
csso --restructure-off
выключает структурную минимизацию
csso -h
csso --help
показывает этот текст
csso -v
csso --version
показывает номер версии CSSO

1
node_modules/piler/node_modules/csso/VERSION generated vendored Normal file
View File

@ -0,0 +1 @@
CSSO 1.2.18

14
node_modules/piler/node_modules/csso/bin/csso generated vendored Executable file
View File

@ -0,0 +1,14 @@
#!/usr/bin/env bash
SELF_PATH=$(cd -P -- "$(dirname -- "$0")" && pwd -P) && SELF_PATH="$SELF_PATH/$(basename -- "$0")"
while [ -h "$SELF_PATH" ]; do
DIR=$(dirname -- "$SELF_PATH")
SYM=$(readlink -- "$SELF_PATH")
SELF_PATH=$(cd -- "$DIR" && cd -- $(dirname -- "$SYM") && pwd)/$(basename -- "$SYM")
done
CSSO_HOME=$(dirname -- "$(dirname -- "$SELF_PATH")")
node $CSSO_HOME/lib/csso.js $@

View File

@ -0,0 +1,320 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
<!--Created by yFiles for Java 2.8-->
<key for="graphml" id="d0" yfiles.type="resources"/>
<key for="port" id="d1" yfiles.type="portgraphics"/>
<key for="port" id="d2" yfiles.type="portgeometry"/>
<key for="port" id="d3" yfiles.type="portuserdata"/>
<key attr.name="url" attr.type="string" for="node" id="d4"/>
<key attr.name="description" attr.type="string" for="node" id="d5"/>
<key for="node" id="d6" yfiles.type="nodegraphics"/>
<key attr.name="Description" attr.type="string" for="graph" id="d7"/>
<key attr.name="url" attr.type="string" for="edge" id="d8"/>
<key attr.name="description" attr.type="string" for="edge" id="d9"/>
<key for="edge" id="d10" yfiles.type="edgegraphics"/>
<graph edgedefault="directed" id="G">
<data key="d7"/>
<node id="n0">
<data key="d5"/>
<data key="d6">
<y:ShapeNode>
<y:Geometry height="47.0" width="124.0" x="76.5" y="-28.5"/>
<y:Fill color="#FFCC00" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="left" autoSizePolicy="content" borderDistance="0.0" fontFamily="Dialog" fontSize="13" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="49.931640625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="106.73681640625" x="8.631591796875" y="-1.4658203125">COMMENTS
clean comments</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<node id="n1">
<data key="d5"/>
<data key="d6">
<y:ShapeNode>
<y:Geometry height="70.0" width="110.0" x="83.5" y="281.5"/>
<y:Fill color="#FFCC00" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="left" autoSizePolicy="content" borderDistance="0.0" fontFamily="Dialog" fontSize="13" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="65.2421875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="96.828125" x="6.5859375" y="2.37890625">PREPARE
destroy delims
pretranslate</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<node id="n2">
<data key="d5"/>
<data key="d6">
<y:ShapeNode>
<y:Geometry height="30.0" width="88.0" x="286.0" y="9.5"/>
<y:Fill color="#99CC00" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" borderDistance="0.0" fontFamily="Dialog" fontSize="13" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="19.310546875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="51.9755859375" x="18.01220703125" y="5.3447265625">DISJOIN</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<node id="n3">
<data key="d5"/>
<data key="d6">
<y:ShapeNode>
<y:Geometry height="56.0" width="153.0" x="253.5" y="62.0"/>
<y:Fill color="#99CC00" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="left" autoSizePolicy="content" borderDistance="0.0" fontFamily="Dialog" fontSize="13" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="49.931640625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="132.9462890625" x="10.02685546875" y="3.0341796875">MARK SHORTHANDS
mark shorthands</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<node id="n4">
<data key="d5"/>
<data key="d6">
<y:ShapeNode>
<y:Geometry height="70.0" width="174.0" x="245.0" y="140.5"/>
<y:Fill color="#99CC00" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="left" autoSizePolicy="content" borderDistance="0.0" fontFamily="Dialog" fontSize="13" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="65.2421875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="137.6181640625" x="18.19091796875" y="2.37890625">CLEAN SHORTHANDS
clean shorthands
clean empty</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<node id="n5">
<data key="d5"/>
<data key="d6">
<y:ShapeNode>
<y:Geometry height="56.0" width="163.0" x="250.5" y="233.0"/>
<y:Fill color="#99CC00" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="left" autoSizePolicy="content" borderDistance="0.0" fontFamily="Dialog" fontSize="13" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="49.931640625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="139.306640625" x="11.8466796875" y="3.0341796875">RESTRUCTURE BLOCK
restructure block</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<node id="n6">
<data key="d5"/>
<data key="d6">
<y:ShapeNode>
<y:Geometry height="70.0" width="124.0" x="488.5" y="-35.0"/>
<y:Fill color="#FF99CC" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="left" autoSizePolicy="content" borderDistance="0.0" fontFamily="Dialog" fontSize="13" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="65.2421875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="104.34375" x="9.828125" y="2.37890625">REJOIN RULESET
rejoin ruleset
clean empty</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<node id="n7">
<data key="d5"/>
<data key="d6">
<y:ShapeNode>
<y:Geometry height="70.0" width="163.0" x="469.0" y="55.0"/>
<y:Fill color="#FF99CC" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="left" autoSizePolicy="content" borderDistance="0.0" fontFamily="Dialog" fontSize="13" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="65.2421875" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="150.78955078125" x="6.105224609375" y="2.37890625">RESTRUCTURE RULESET
restructure ruleset
clean empty</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<node id="n8">
<data key="d5"/>
<data key="d6">
<y:ShapeNode>
<y:Geometry height="83.0" width="110.0" x="495.5" y="258.5"/>
<y:Fill color="#FFCC00" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="left" autoSizePolicy="content" borderDistance="0.0" fontFamily="Dialog" fontSize="13" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="80.552734375" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="99.51318359375" x="5.243408203125" y="1.2236328125">FINALIZE
clean empty
delim selectors
delim blocks</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<node id="n9">
<data key="d5"/>
<data key="d6">
<y:ShapeNode>
<y:Geometry height="224.0" width="153.0" x="62.0" y="38.0"/>
<y:Fill color="#FFCC00" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="left" autoSizePolicy="content" borderDistance="0.0" fontFamily="Dialog" fontSize="13" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="218.34765625" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="144.23876953125" x="4.380615234375" y="2.826171875">COMPRESS
clean charset
clean import
clean whitespace
clean decldelim
compress number
compress color
compress dimension
compress string
compress fontweight
compress font
compress background
clean empty</y:NodeLabel>
<y:Shape type="rectangle"/>
</y:ShapeNode>
</data>
</node>
<node id="n10">
<data key="d5"/>
<data key="d6">
<y:ShapeNode>
<y:Geometry height="30.0" width="193.0" x="454.0" y="176.75"/>
<y:Fill color="#FF99CC" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.1328125" modelName="internal" modelPosition="c" textColor="#000000" visible="true" width="111.572265625" x="40.7138671875" y="5.93359375">Max compression?</y:NodeLabel>
<y:Shape type="parallelogram"/>
</y:ShapeNode>
</data>
</node>
<edge id="e0" source="n2" target="n3">
<data key="d9"/>
<data key="d10">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e1" source="n3" target="n4">
<data key="d9"/>
<data key="d10">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e2" source="n4" target="n5">
<data key="d9"/>
<data key="d10">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e3" source="n6" target="n7">
<data key="d9"/>
<data key="d10">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e4" source="n7" target="n10">
<data key="d9"/>
<data key="d10">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e5" source="n10" target="n8">
<data key="d9"/>
<data key="d10">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.1328125" modelName="six_pos" modelPosition="tail" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" visible="true" width="23.072265625" x="2.0" y="16.82379150390625">yes</y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e6" source="n10" target="n6">
<data key="d9"/>
<data key="d10">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0">
<y:Point x="660.0" y="191.75"/>
<y:Point x="660.0" y="0.0"/>
</y:Path>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.1328125" modelName="six_pos" modelPosition="tail" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" visible="true" width="18.818359375" x="24.6431884765625" y="-104.94140625">no</y:EdgeLabel>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e7" source="n0" target="n9">
<data key="d9"/>
<data key="d10">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e8" source="n9" target="n1">
<data key="d9"/>
<data key="d10">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e9" source="n5" target="n6">
<data key="d9"/>
<data key="d10">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0">
<y:Point x="433.5" y="261.0"/>
<y:Point x="433.5" y="0.0"/>
</y:Path>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
<edge id="e10" source="n1" target="n2">
<data key="d9"/>
<data key="d10">
<y:PolyLineEdge>
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0">
<y:Point x="230.0" y="316.5"/>
<y:Point x="230.0" y="24.5"/>
</y:Path>
<y:LineStyle color="#000000" type="line" width="1.0"/>
<y:Arrows source="none" target="standard"/>
<y:BendStyle smoothed="false"/>
</y:PolyLineEdge>
</data>
</edge>
</graph>
<data key="d0">
<y:Resources/>
</data>
</graphml>

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

1453
node_modules/piler/node_modules/csso/lib/compressor.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

70
node_modules/piler/node_modules/csso/lib/csso.js generated vendored Normal file
View File

@ -0,0 +1,70 @@
var fs = require('fs'),
print = require('util').print,
csso = require('./cssoapi.js'),
src, x;
var args = process.argv.slice(2),
opts = args.length ? getOpts(args, [
'-v', '--version',
'-h', '--help',
'-dp', '--parser',
'-off', '--restructure-off'
], [
'-r', '--rule',
'-i', '--input',
'-o', '--output'
]) : null,
single = opts && opts.single,
pairs = opts && opts.pairs,
other = opts && opts.other,
ro = single && single.contains(['-off', '--restructure-off']),
inFile = (pairs && (pairs['-i'] || pairs['--input'])) || (other && other[0]),
outFile = (pairs && (pairs['-o'] || pairs['--output'])) || (other && other[1]),
rule = pairs && (pairs['-r'] || pairs['--rule']) || 'stylesheet';
if (single && single.contains(['-v', '--version'])) {
printFile('VERSION');
} else if (!inFile || !opts || (single && single.contains(['-h', '--help'])) || other.length > 2) {
printFile('USAGE');
} else {
src = fs.readFileSync(inFile).toString().trim();
if (single.contains(['-dp', '--parser'])) csso.printTree(csso.cleanInfo(csso.parse(src, rule)));
else {
if (!outFile) print(csso.justDoIt(src, ro));
else fs.writeFileSync(outFile, csso.justDoIt(src, ro));
}
}
// Utils
function getOpts(argv, o_single, o_pairs) {
var opts = { single : [], pairs : {}, other : [] },
arg,
i = 0;
for (; i < argv.length;) {
arg = argv[i];
if (o_single && o_single.indexOf(arg) !== -1 && (!o_pairs || o_pairs.indexOf(arg) === -1)) {
opts.single.push(arg);
} else if (o_pairs && o_pairs.indexOf(arg) !== -1 && (!o_single || o_single.indexOf(arg) === -1)) {
opts.pairs[arg] = argv[++i];
} else opts.other.push(arg);
i++;
}
opts.single.contains = function(value) {
if (typeof value === 'string') {
return this.indexOf(value) !== -1;
} else {
for (var i = 0; i < value.length; i++) if (this.indexOf(value[i]) !== -1) return true;
}
return false;
};
return opts;
}
function printFile(filename) {
print(fs.readFileSync(__dirname.slice(0, __dirname.lastIndexOf('/')) + '/' + filename).toString());
}

20
node_modules/piler/node_modules/csso/lib/cssoapi.js generated vendored Normal file
View File

@ -0,0 +1,20 @@
var util = require('./util.js'),
parser = require('./parser.js'),
translator = require('./translator.js'),
compressor = require('./compressor.js');
var parse = exports.parse = parser.parse;
var cleanInfo = exports.cleanInfo = util.cleanInfo;
exports.treeToString = util.treeToString;
exports.printTree = util.printTree;
var translate = exports.translate = translator.translate;
var compress = exports.compress = compressor.compress;
exports.justDoIt = function(src, ro) {
return translate(cleanInfo(compress(parse(src, 'stylesheet'), ro)));
};

902
node_modules/piler/node_modules/csso/lib/parser.js generated vendored Normal file
View File

@ -0,0 +1,902 @@
function CSSOParser() {}
CSSOParser.prototype.parse = function(s, rule) {
this._src = s;
this._stack = [];
this._chains = [];
this._i = { f: 0, l: 0 };
var r = this.$()._o(rule)._();
return r ? r[0] : null;
};
CSSOParser.prototype._push = function(o) {
this._stack.push(o);
};
CSSOParser.prototype._last = function() {
return this._chains[this._chains.length - 1];
};
CSSOParser.prototype._fail = function() {
this._last().fail = true;
};
CSSOParser.prototype._failed = function() {
return this._last().fail;
};
CSSOParser.prototype._apply = function(s) {
switch (s.charAt(0)) {
case '.': return this._s(s.substr(1));
case ',': return this._r(s.substr(1));
default: return this[s]();
}
};
CSSOParser.prototype._gi = function() {
return this._last().l;
};
CSSOParser.prototype._si = function(i) {
if (this._chains.length) this._last().l = i;
};
CSSOParser.prototype._info = function() {
return { f: this._i.f, l: this._i.l };
};
CSSOParser.prototype.$ = function() {
var i = this._chains.length ? this._last().l + 1 : 0;
this._chains.push({ i: this._stack.length, fail: false, f: i, l: i - 1 });
return this;
};
CSSOParser.prototype._ = function() {
var c = this._chains.pop(),
r = this._stack.splice(c.i);
if (!c.fail) {
if (c.l >= c.f) this._si(c.l);
this._i = { f: c.f, l: c.l };
return r.length ? r : null;
}
};
CSSOParser.prototype._o = function() {
if (!this._failed()) {
var a = arguments, b = [], t;
for (var i = 0; i < a.length; i++) {
if (t = this._apply(a[i])) break;
}
t !== undefined ? this._push(t) : this._fail();
}
return this;
};
CSSOParser.prototype._om = function() {
if (!this._failed()) {
var a = arguments, t, n0, n1 = this._gi() + 1, b = [];
do {
n0 = n1;
for (var i = 0; i < a.length; i++) {
if (t = this._apply(a[i])) {
b.push(t);
n1 = this._gi() + 1;
break;
}
}
} while (n0 !== n1);
b.length ? this._push(b) : this._fail();
}
return this;
};
CSSOParser.prototype._zm = function() {
if (!this._failed()) {
var a = arguments, t, n0, n1 = this._gi() + 1, b = [];
do {
n0 = n1;
for (var i = 0; i < a.length; i++) {
if (t = this._apply(a[i])) {
b.push(t);
n1 = this._gi() + 1;
break;
}
}
} while (n0 !== n1);
if (b.length) this._push(b);
}
return this;
};
CSSOParser.prototype._zmn = function() {
if (!this._failed()) {
var i = this._gi() + 1;
this._zm.apply(this, arguments);
if (i === this._gi() + 1) this._push(null);
}
return this;
};
CSSOParser.prototype._zme = function() {
if (!this._failed()) {
var i = this._gi() + 1;
this._zm.apply(this, arguments);
if (i === this._gi() + 1) this._push([]);
}
return this;
};
CSSOParser.prototype._zo = function() {
if (!this._failed()) {
var a = arguments, t;
for (var i = 0; i < a.length; i++) {
if (t = this._apply(a[i])) break;
}
this._push(t ? t : null);
}
return this;
};
CSSOParser.prototype._not = function() {
if (!this._failed()) {
var f = this._gi() + 1,
s = this._src,
a = arguments,
p = new CSSOParser(),
_s, t, l = s.length + 1;
for (var i = f; i < l; i++) {
_s = s.substr(i);
for (var j = 0; j < a.length; j++) {
if ((t = p.parse(_s, a[j])) !== null) {
_s = s.substring(f, i);
i = l;
break;
}
}
}
if (_s) this._si(f + _s.length - 1);
this._push(_s);
}
return this;
};
CSSOParser.prototype._s = function(s) {
var sl = s.length,
f = this._gi() + 1;
if (this._src.substr(f, sl) === s) {
this._si(f + sl - 1);
return s;
}
};
CSSOParser.prototype._c = function() {
var s = this._src,
f = this._gi() + 1;
if (f <= s.length) {
this._si(f);
return s.charAt(f);
}
};
CSSOParser.prototype._r = function(r) {
var n = r.substr(0, r.indexOf(' ')),
f = this._gi() + 1,
s = n !== '0' ? this._src.substring(f, f + new Number(n)) : this._src.substr(f),
rr = new RegExp(r.substr(n.length + 1)).exec(s);
if (rr && rr.index === 0) {
this._si(f + rr[0].length - 1);
return rr[0];
}
};
CSSOParser.prototype._join = function(a) {
return a ? a.join('') : '';
};
CSSOParser.prototype._cc = function(x, y) {
y.forEach(function(e) {
x = x.concat(e);
});
return x;
};
CSSOParser.prototype.unknown = function() {
var _b_;
if (_b_ = this.$()._o('munknown')._()) {
return [this._info(), 'unknown', _b_[0]];
}
};
CSSOParser.prototype.mstring1 = function() {
var _b_;
if (_b_ = this.$()._not('."','.\\"')._()) {
return _b_[0];
}
};
CSSOParser.prototype.mstring2 = function() {
var _b_;
if (_b_ = this.$()._not('.\'','.\\\'')._()) {
return _b_[0];
}
};
CSSOParser.prototype.mstring = function() {
var _b_;
if (_b_ = this.$()._o('."')._zme('.\\"','mstring1')._o('."')._()) {
return ('"' + _b_[1].join('') + '"');
}
if (_b_ = this.$()._o('.\'')._zme('.\\\'','mstring2')._o('.\'')._()) {
return ("'" + _b_[1].join('') + "'");
}
};
CSSOParser.prototype.string = function() {
var _b_;
if (_b_ = this.$()._o('mstring')._()) {
return [this._info(), 'string', _b_[0]];
}
};
CSSOParser.prototype.escape = function() {
var _b_;
if (_b_ = this.$()._o('.\\')._o('_c')._()) {
return ('\\' + _b_[1]);
}
};
CSSOParser.prototype.ident = function() {
var _b_;
if (_b_ = this.$()._o('mident')._()) {
return [this._info(), 'ident', _b_[0]];
}
};
CSSOParser.prototype.atkeyword = function() {
var _b_;
if (_b_ = this.$()._o('.@')._o('ident')._()) {
return [this._info(), 'atkeyword', _b_[1]];
}
};
CSSOParser.prototype.shash = function() {
var _b_;
if (_b_ = this.$()._o('.#')._o('mname')._()) {
return [this._info(), 'shash', _b_[1]];
}
};
CSSOParser.prototype.vhash = function() {
var _b_;
if (_b_ = this.$()._o('.#')._o('mname2')._()) {
return [this._info(), 'vhash', _b_[1]];
}
};
CSSOParser.prototype.number = function() {
var _b_;
if (_b_ = this.$()._o('mnumber')._()) {
return [this._info(), 'number', _b_[0]];
}
};
CSSOParser.prototype.percentage = function() {
var _b_;
if (_b_ = this.$()._o('number')._o('.%')._()) {
return [this._info(), 'percentage', _b_[0]];
}
};
CSSOParser.prototype.ident2 = function() {
var _b_;
if (_b_ = this.$()._o('mname2')._()) {
return [this._info(), 'ident', _b_[0]];
}
};
CSSOParser.prototype.dimension = function() {
var _b_;
if (_b_ = this.$()._o('number')._o('ident2')._()) {
return [this._info(), 'dimension', _b_[0], _b_[1]];
}
};
CSSOParser.prototype.cdo = function() {
var _b_;
if (_b_ = this.$()._o('.<!--')._()) {
return [this._info(), 'cdo'];
}
};
CSSOParser.prototype.cdc = function() {
var _b_;
if (_b_ = this.$()._o('.-->')._()) {
return [this._info(), 'cdc'];
}
};
CSSOParser.prototype.s = function() {
var _b_;
if (_b_ = this.$()._om('mw')._()) {
return [this._info(), 's', _b_[0].join('')];
}
};
CSSOParser.prototype.attrselector = function() {
var _b_;
if (_b_ = this.$()._o('.=','.~=','.^=','.$=','.*=','.|=','.~')._()) {
return [this._info(), 'attrselector', _b_[0]];
}
};
CSSOParser.prototype.delim = function() {
var _b_;
if (_b_ = this.$()._o('.,')._()) {
return [this._info(), 'delim'];
}
};
CSSOParser.prototype.comment = function() {
var _b_;
if (_b_ = this.$()._o('mcomment1')._()) {
return [this._info(), 'comment', _b_[0]];
}
};
CSSOParser.prototype.sc = function() {
var _b_;
if (_b_ = this.$()._o('s','comment')._()) {
return _b_[0];
}
};
CSSOParser.prototype.tset = function() {
var _b_;
if (_b_ = this.$()._o('vhash','any','sc','operator')._()) {
return _b_[0];
}
};
CSSOParser.prototype.stylesheet = function() {
var _b_;
if (_b_ = this.$()._zme('cdo','cdc','sc','statement','unknown')._()) {
return [this._info(), 'stylesheet'].concat(_b_[0]);
}
};
CSSOParser.prototype.statement = function() {
var _b_;
if (_b_ = this.$()._o('ruleset','atrule')._()) {
return _b_[0];
}
};
CSSOParser.prototype.atruleb = function() {
var _b_;
if (_b_ = this.$()._o('atkeyword')._zme('tset')._o('block')._()) {
return [this._info(), 'atruleb', _b_[0]].concat(_b_[1], [_b_[2]]);
}
};
CSSOParser.prototype.atrules = function() {
var _b_;
if (_b_ = this.$()._o('atkeyword')._zme('tset')._o('.;')._()) {
return [this._info(), 'atrules', _b_[0]].concat(_b_[1]);
}
};
CSSOParser.prototype.atrulerq = function() {
var _b_;
if (_b_ = this.$()._zme('tset')._()) {
return [this._info(), 'atrulerq'].concat(_b_[0]);
}
};
CSSOParser.prototype.atrulers = function() {
var _b_;
if (_b_ = this.$()._zme('sc')._zme('ruleset')._zme('sc')._()) {
return [this._info(), 'atrulers'].concat(_b_[0], _b_[1], _b_[2]);
}
};
CSSOParser.prototype.atruler = function() {
var _b_;
if (_b_ = this.$()._o('atkeyword')._o('atrulerq')._o('.{')._o('atrulers')._o('.}')._()) {
return [this._info(), 'atruler', _b_[0], _b_[1], _b_[3]];
}
};
CSSOParser.prototype.atrule = function() {
var _b_;
if (_b_ = this.$()._o('atruler','atruleb','atrules')._()) {
return _b_[0];
}
};
CSSOParser.prototype.blockdecl = function() {
var _b_;
if (_b_ = this.$()._zme('sc')._o('filter','declaration')._o('decldelim')._zme('sc')._()) {
return [].concat(_b_[0], [_b_[1]], [_b_[2]], _b_[3]);
}
if (_b_ = this.$()._zme('sc')._o('filter','declaration')._zme('sc')._()) {
return [].concat(_b_[0], [_b_[1]], _b_[2]);
}
if (_b_ = this.$()._zme('sc')._o('decldelim')._zme('sc')._()) {
return [].concat(_b_[0], [_b_[1]], _b_[2]);
}
if (_b_ = this.$()._om('sc')._()) {
return _b_[0];
}
};
CSSOParser.prototype.decldelim = function() {
var _b_;
if (_b_ = this.$()._o('.;')._()) {
return [this._info(), 'decldelim'];
}
};
CSSOParser.prototype.block = function() {
var _b_;
if (_b_ = this.$()._o('.{')._zme('blockdecl')._o('.}')._()) {
return this._cc([this._info(), 'block'], _b_[1]);
}
};
CSSOParser.prototype.ruleset = function() {
var _b_;
if (_b_ = this.$()._zme('selector')._o('block')._()) {
return [this._info(), 'ruleset'].concat(_b_[0], [_b_[1]]);
}
};
CSSOParser.prototype.combinator = function() {
var _b_;
if (_b_ = this.$()._o('.+','.>','.~')._()) {
return [this._info(), 'combinator', _b_[0]];
}
};
CSSOParser.prototype.attrib = function() {
var _b_;
if (_b_ = this.$()._o('.[')._zme('sc')._o('ident')._zme('sc')._o('attrselector')._zme('sc')._o('ident','string')._zme('sc')._o('.]')._()) {
return [this._info(), 'attrib'].concat(_b_[1], [_b_[2]], _b_[3], [_b_[4]], _b_[5], [_b_[6]], _b_[7]);
}
if (_b_ = this.$()._o('.[')._zme('sc')._o('ident')._zme('sc')._o('.]')._()) {
return [this._info(), 'attrib'].concat(_b_[1], [_b_[2]], _b_[3]);
}
};
CSSOParser.prototype.clazz = function() {
var _b_;
if (_b_ = this.$()._o('..')._o('ident')._()) {
return [this._info(), 'clazz', _b_[1]];
}
};
CSSOParser.prototype.pseudoe = function() {
var _b_;
if (_b_ = this.$()._o('.::')._o('ident')._()) {
return [this._info(), 'pseudoe', _b_[1]];
}
};
CSSOParser.prototype.pseudoc = function() {
var _b_;
if (_b_ = this.$()._o('.:')._o('funktion','ident')._()) {
return [this._info(), 'pseudoc', _b_[1]];
}
};
CSSOParser.prototype.pseudo = function() {
var _b_;
if (_b_ = this.$()._o('pseudoe','pseudoc')._()) {
return _b_[0];
}
};
CSSOParser.prototype.nthf = function() {
var _b_;
if (_b_ = this.$()._o('.:')._o('.nth-')._o('.child','.last-child','.of-type','.last-of-type')._()) {
return [this._info(), 'ident', _b_[1] + _b_[2]];
}
};
CSSOParser.prototype.nth = function() {
var _b_;
if (_b_ = this.$()._om(',1 ^[\\d]','.n')._()) {
return [this._info(), 'nth', _b_[0].join('')];
}
if (_b_ = this.$()._o('.even','.odd')._()) {
return [this._info(), 'nth', _b_[0]];
}
};
CSSOParser.prototype.nthselector = function() {
var _b_;
if (_b_ = this.$()._o('nthf')._o('.(')._zme('sc','unary','nth')._o('.)')._()) {
return [this._info(), 'nthselector', _b_[0]].concat(_b_[2]);
}
};
CSSOParser.prototype.namespace = function() {
var _b_;
if (_b_ = this.$()._o('.|')._()) {
return [this._info(), 'namespace'];
}
};
CSSOParser.prototype.simpleselector = function() {
var _b_;
if (_b_ = this.$()._om('nthselector','combinator','attrib','pseudo','clazz','shash','any','sc','namespace')._()) {
return this._cc([this._info(), 'simpleselector'], [_b_[0]]);
}
};
CSSOParser.prototype.selector = function() {
var _b_;
if (_b_ = this.$()._om('simpleselector','delim')._()) {
return [this._info(), 'selector'].concat(_b_[0]);
}
};
CSSOParser.prototype.declaration = function() {
var _b_;
if (_b_ = this.$()._o('property')._o('.:')._o('value')._()) {
return [this._info(), 'declaration', _b_[0], _b_[2]];
}
};
CSSOParser.prototype.filtern = function() {
var _b_;
if (_b_ = this.$()._o('.-filter','.$filter','._filter','.*filter','.-ms-filter','.filter')._()) {
return [this._info(), 'ident', _b_[0]];
}
};
CSSOParser.prototype.filterp = function() {
var _b_;
if (_b_ = this.$()._o('filtern')._zme('sc')._()) {
return [this._info(), 'property', _b_[0]].concat(_b_[1]);
}
};
CSSOParser.prototype.progid0 = function() {
var _b_;
if (_b_ = this.$()._not('.)','mstring','mcomment2')._()) {
return _b_[0];
}
};
CSSOParser.prototype.progid1 = function() {
var _b_;
if (_b_ = this.$()._o('.progid:DXImageTransform.Microsoft.')._o(',25 ^[a-zA-Z]+')._o('.(')._om('mstring','mcomment2','progid0')._o('.)')._()) {
return [this._info(), 'raw', _b_[0] + _b_[1] + '(' + _b_[3].join('') + ')'];
}
};
CSSOParser.prototype.progid = function() {
var _b_;
if (_b_ = this.$()._zme('sc')._o('progid1')._zme('sc')._()) {
return [this._info(), 'progid'].concat(_b_[0], [_b_[1]], _b_[2]);
}
};
CSSOParser.prototype.filterv = function() {
var _b_;
if (_b_ = this.$()._om('progid')._()) {
return [this._info(), 'filterv'].concat(_b_[0]);
}
};
CSSOParser.prototype.filter = function() {
var _b_;
if (_b_ = this.$()._o('filterp')._o('.:')._o('filterv')._()) {
return [this._info(), 'filter', _b_[0], _b_[2]];
}
};
CSSOParser.prototype.identp = function() {
var _b_;
if (_b_ = this.$()._o('.//')._o('mident')._()) {
return [this._info(), 'ident', _b_[0] + _b_[1]];
}
};
CSSOParser.prototype.property = function() {
var _b_;
if (_b_ = this.$()._o('identp')._zme('sc')._()) {
return [this._info(), 'property', _b_[0]].concat(_b_[1]);
}
if (_b_ = this.$()._o('ident')._zme('sc')._()) {
return [this._info(), 'property', _b_[0]].concat(_b_[1]);
}
};
CSSOParser.prototype.important = function() {
var _b_;
if (_b_ = this.$()._o('.!')._zme('sc')._o('.important')._()) {
return [this._info(), 'important'].concat(_b_[1]);
}
};
CSSOParser.prototype.unary = function() {
var _b_;
if (_b_ = this.$()._o('.-','.+')._()) {
return [this._info(), 'unary', _b_[0]];
}
};
CSSOParser.prototype.operator = function() {
var _b_;
if (_b_ = this.$()._o('./','.,','.:','.=')._()) {
return [this._info(), 'operator', _b_[0]];
}
};
CSSOParser.prototype.uri0 = function() {
var _b_;
if (_b_ = this.$()._not('.)','mw')._()) {
return [this._info(), 'raw', _b_[0]];
}
};
CSSOParser.prototype.uri = function() {
var _b_;
if (_b_ = this.$()._o('.url(')._zme('sc')._o('string')._zme('sc')._o('.)')._()) {
return [this._info(), 'uri'].concat(_b_[1], [_b_[2]], _b_[3]);
}
if (_b_ = this.$()._o('.url(')._zme('sc')._o('uri0')._zme('sc')._o('.)')._()) {
return [this._info(), 'uri'].concat(_b_[1], [_b_[2]], _b_[3]);
}
};
CSSOParser.prototype.value = function() {
var _b_;
if (_b_ = this.$()._om('sc','vhash','any','block','atkeyword','operator','important')._()) {
return [this._info(), 'value'].concat(_b_[0]);
}
};
CSSOParser.prototype.functionBody = function() {
var _b_;
if (_b_ = this.$()._zme('tset')._()) {
return [this._info(), 'functionBody'].concat(_b_[0]);
}
};
CSSOParser.prototype.funktion = function() {
var _b_;
if (_b_ = this.$()._o('notselector')._()) {
return _b_[0];
}
if (_b_ = this.$()._o('ident')._o('.(')._o('functionBody')._o('.)')._()) {
return [this._info(), 'funktion', _b_[0], _b_[2]];
}
};
CSSOParser.prototype.notselectorident = function() {
var _b_;
if (_b_ = this.$()._o('.not')._()) {
return [this._info(), 'ident', _b_[0]];
}
};
CSSOParser.prototype.notselector = function() {
var _b_;
if (_b_ = this.$()._o('notselectorident')._o('.(')._o('notselectorBody')._o('.)')._()) {
return [this._info(), 'funktion', _b_[0], _b_[2]];
}
};
CSSOParser.prototype.notselectorBody = function() {
var _b_;
if (_b_ = this.$()._zo('simpleselector')._()) {
return [this._info(), 'functionBody', _b_[0]];
}
};
CSSOParser.prototype.braces = function() {
var _b_;
if (_b_ = this.$()._o('.(')._zme('tset')._o('.)')._()) {
return [this._info(), 'braces', '(', ')'].concat(_b_[1]);
}
if (_b_ = this.$()._o('.[')._zme('tset')._o('.]')._()) {
return [this._info(), 'braces', '[', ']'].concat(_b_[1]);
}
};
CSSOParser.prototype.jsLT = function() {
var _b_;
if (_b_ = this.$()._o('.\n','.\r')._()) {
return _b_[0];
}
};
CSSOParser.prototype.jsComment = function() {
var _b_;
if (_b_ = this.$()._o('jsMLComment','jsSLComment')._()) {
return _b_[0];
}
};
CSSOParser.prototype.jsMLComment = function() {
var _b_;
if (_b_ = this.$()._o('./*')._not('.*/')._o('.*/')._()) {
return (_b_[0] + (_b_[1] ? _b_[1] : '') + _b_[2]);
}
};
CSSOParser.prototype.jsSLComment = function() {
var _b_;
if (_b_ = this.$()._o('.//')._not('jsLT')._()) {
return ('//' + (_b_[1] ? _b_[1] : ''));
}
};
CSSOParser.prototype.jsString = function() {
var _b_;
if (_b_ = this.$()._o('."')._zme('jsDSChar')._o('."')._()) {
return ('"' + _b_[1].join('') + '"');
}
if (_b_ = this.$()._o('.\'')._zme('jsSSChar')._o('.\'')._()) {
return ('\'' + _b_[1].join('') + '\'');
}
};
CSSOParser.prototype.jsDSChar = function() {
var _b_;
if (_b_ = this.$()._not('."','.\\','jsLT','jsEscapeChar','jsLineContinuation')._()) {
return _b_[0];
}
if (_b_ = this.$()._o('jsEscapeChar')._()) {
return _b_[0];
}
if (_b_ = this.$()._o('jsLineContinuation')._()) {
return _b_[0];
}
};
CSSOParser.prototype.jsSSChar = function() {
var _b_;
if (_b_ = this.$()._not('.\'','.\\','jsLT','jsEscapeChar','jsLineContinuation')._()) {
return _b_[0];
}
if (_b_ = this.$()._o('jsEscapeChar')._()) {
return _b_[0];
}
if (_b_ = this.$()._o('jsLineContinuation')._()) {
return _b_[0];
}
};
CSSOParser.prototype.jsLineContinuation = function() {
var _b_;
if (_b_ = this.$()._o('.\\')._zme('jsLT')._()) {
return ('\\' + _b_[1].join(''));
}
};
CSSOParser.prototype.jsEscapeChar = function() {
var _b_;
if (_b_ = this.$()._o('.\\')._o('_c')._()) {
return ('\\' + _b_[1]);
}
};
CSSOParser.prototype.jsInBraceChar = function() {
var _b_;
if (_b_ = this.$()._not('.(','.)','jsComment','jsString','jsEscapeChar')._()) {
return _b_[0];
}
};
CSSOParser.prototype.jsBracesContent = function() {
var _b_;
if (_b_ = this.$()._om('jsComment','jsString','jsEscapeChar','jsInBraceChar')._()) {
return _b_[0].join('');
}
};
CSSOParser.prototype.feb = function() {
var _b_;
if (_b_ = this.$()._o('functionExpressionBody')._zme('jsBracesContent')._()) {
return (_b_[0] + _b_[1].join(''));
}
};
CSSOParser.prototype.functionExpressionBody = function() {
var _b_;
if (_b_ = this.$()._o('.(')._om('jsBracesContent')._zme('feb')._o('.)')._()) {
return ('(' + _b_[1].join('') + _b_[2].join('') + ')');
}
if (_b_ = this.$()._o('.(')._zme('feb')._o('.)')._()) {
return ('(' + _b_[1].join('') + ')');
}
if (_b_ = this.$()._om('jsBracesContent')._zme('feb')._()) {
return (_b_[0].join('') + _b_[1].join(''));
}
};
CSSOParser.prototype.functionExpression = function() {
var _b_;
if (_b_ = this.$()._o('.expression(')._zme('functionExpressionBody')._o('.)')._()) {
return [this._info(), 'functionExpression', _b_[1].join('')];
}
};
CSSOParser.prototype.any = function() {
var _b_;
if (_b_ = this.$()._o('braces','string','percentage','dimension','number','uri','functionExpression','funktion','ident','unary')._()) {
return _b_[0];
}
};
CSSOParser.prototype.mw = function() {
var s = this._src,
sl = s.length,
f = this._gi() + 1, c, i, v = '';
for (i = f; i < sl; i++) {
c = s.charAt(i);
if (/^[ \n\r\t\f]$/.test(c)) v += c;
else break;
}
if (v.length) {
this._si(f + v.length - 1);
return v;
}
};
CSSOParser.prototype.mnumber = function() {
var s = this._src,
sl = s.length,
f = this._gi() + 1, c, i, v = '',
n0 = '', d = '', n1 = '';
for (i = f; i < sl; i++) {
c = s.charAt(i);
if (/^[\d]$/.test(c)) n0 += c;
else break;
}
if (s[i++] === '.') {
d = '.';
for (; i < sl; i++) {
c = s.charAt(i);
if (/^[\d]$/.test(c)) n1 += c;
else break;
}
}
if ((v = n0 + d + n1).length) {
this._si(f + v.length - 1);
return v;
}
};
CSSOParser.prototype.mident = function() {
var s = this._src,
sl = s.length,
f = this._gi() + 1, i = f, v = '', c, n;
if (s.charAt(i) === '-') v = '-', i++; // special case
c = s.charAt(i); n = s.charAt(i + 1);
if (/^[_$a-zA-Z*]$/.test(c)) v += c; // first char
else if (c === '\\') {
v += c;
if (n) v += n, i++;
} else return;
i++;
for (; i < sl; i++) {
c = s.charAt(i);
n = s.charAt(i + 1);
if (/^[_a-zA-Z0-9\-]$/.test(c)) v += c;
else if (c === '\\') {
v += c;
if (n) v += n, i++;
} else break;
}
if (v && v !== '-') {
this._si(f + v.length - 1);
return v;
}
};
CSSOParser.prototype.mcomment1 = function() {
var s = this._src,
f = this._gi() + 1, v = '', i;
if (s.charAt(f) === '/' && s.charAt(f + 1) === '*') {
if ((i = s.indexOf('*/', f + 2)) !== -1) {
v = s.substring(f + 2, i);
this._si(f + v.length + 3);
} else {
v = s.substr(f + 2);
this._si(f + v.length + 1);
}
return v;
}
};
CSSOParser.prototype.mcomment2 = function() {
var s = this._src,
f = this._gi() + 1, v = '/*', i;
if (s.charAt(f) === '/' && s.charAt(f + 1) === '*') {
if ((i = s.indexOf('*/', f + 2)) !== -1) {
v += s.substring(f + 2, i) + '*/';
this._si(f + v.length - 1);
} else {
v += s.substr(f + 2);
this._si(f + v.length - 1);
}
return v;
}
};
CSSOParser.prototype.mname = function() {
var s = this._src,
sl = s.length,
f = this._gi() + 1, i = f, v = '', c, n;
for (; i < sl; i++) {
c = s.charAt(i);
n = s.charAt(i + 1);
if (/^[_a-zA-Z0-9\-]$/.test(c)) v += c;
else if (c === '\\') {
v += c;
if (n) v += n, i++;
} else break;
}
if (v) {
this._si(f + v.length - 1);
return v;
}
};
CSSOParser.prototype.mname2 = function() {
var s = this._src,
sl = s.length,
f = this._gi() + 1, i = f, v = '', c, n;
for (; i < sl; i++) {
c = s.charAt(i);
n = s.charAt(i + 1);
if (/^[_a-zA-Z0-9]$/.test(c)) v += c;
else if (c === '\\') {
v += c;
if (n) v += n, i++;
} else break;
}
if (v) {
this._si(f + v.length - 1);
return v;
}
};
CSSOParser.prototype.munknown = function() {
var s = this._src,
sl = s.length,
f = this._gi() + 1, i = f, v = '', c, n;
for (; i < sl; i++) {
c = s.charAt(i);
v += c;
if (c === '\n' || c === '\r') break;
}
if (v) {
this._si(f + v.length - 1);
return v;
}
};
exports.parse = function(s, rule) {
return new CSSOParser().parse(s, rule);
};

126
node_modules/piler/node_modules/csso/lib/translator.js generated vendored Normal file
View File

@ -0,0 +1,126 @@
function CSSOTranslator() {}
CSSOTranslator.prototype.translate = function(tree) {
return this._t(tree);
};
CSSOTranslator.prototype._m_simple = {
'unary': 1, 'nth': 1, 'combinator': 1, 'ident': 1, 'number': 1, 's': 1,
'string': 1, 'attrselector': 1, 'operator': 1, 'raw': 1, 'unknown': 1
};
CSSOTranslator.prototype._m_composite = {
'simpleselector': 1, 'dimension': 1, 'selector': 1, 'property': 1, 'value': 1,
'filterv': 1, 'progid': 1, 'ruleset': 1, 'atruleb': 1, 'atrulerq': 1, 'atrulers': 1,
'stylesheet': 1
};
CSSOTranslator.prototype._m_primitive = {
'cdo': 'cdo', 'cdc': 'cdc', 'decldelim': ';', 'namespace': '|', 'delim': ','
};
CSSOTranslator.prototype._t = function(tree) {
var t = tree[0];
if (t in this._m_primitive) return this._m_primitive[t];
else if (t in this._m_simple) return this._simple(tree);
else if (t in this._m_composite) return this._composite(tree);
return this[t](tree);
};
CSSOTranslator.prototype._composite = function(t, i) {
var s = '';
i = i === undefined ? 1 : i;
for (; i < t.length; i++) s += this._t(t[i]);
return s;
};
CSSOTranslator.prototype._simple = function(t) {
return t[1];
};
CSSOTranslator.prototype.percentage = function(t) {
return this._t(t[1]) + '%';
};
CSSOTranslator.prototype.comment = function(t) {
return '/*' + t[1] + '*/';
};
CSSOTranslator.prototype.clazz = function(t) {
return '.' + this._t(t[1]);
};
CSSOTranslator.prototype.atkeyword = function(t) {
return '@' + this._t(t[1]);
};
CSSOTranslator.prototype.shash = function(t) {
return '#' + t[1];
};
CSSOTranslator.prototype.vhash = function(t) {
return '#' + t[1];
};
CSSOTranslator.prototype.attrib = function(t) {
return '[' + this._composite(t) + ']';
};
CSSOTranslator.prototype.important = function(t) {
return '!' + this._composite(t) + 'important';
};
CSSOTranslator.prototype.nthselector = function(t) {
return ':' + this._simple(t[1]) + '(' + this._composite(t, 2) + ')';
};
CSSOTranslator.prototype.funktion = function(t) {
return this._simple(t[1]) + '(' + this._composite(t[2]) + ')';
};
CSSOTranslator.prototype.declaration = function(t) {
return this._t(t[1]) + ':' + this._t(t[2]);
};
CSSOTranslator.prototype.filter = function(t) {
return this._t(t[1]) + ':' + this._t(t[2]);
};
CSSOTranslator.prototype.block = function(t) {
return '{' + this._composite(t) + '}';
};
CSSOTranslator.prototype.braces = function(t) {
return t[1] + this._composite(t, 3) + t[2];
};
CSSOTranslator.prototype.atrules = function(t) {
return this._composite(t) + ';';
};
CSSOTranslator.prototype.atruler = function(t) {
return this._t(t[1]) + this._t(t[2]) + '{' + this._t(t[3]) + '}';
};
CSSOTranslator.prototype.pseudoe = function(t) {
return '::' + this._t(t[1]);
};
CSSOTranslator.prototype.pseudoc = function(t) {
return ':' + this._t(t[1]);
};
CSSOTranslator.prototype.uri = function(t) {
return 'url(' + this._composite(t) + ')';
};
CSSOTranslator.prototype.functionExpression = function(t) {
return 'expression(' + t[1] + ')';
};
exports.translate = function(tree) {
return new CSSOTranslator().translate(tree);
};
exports.translator = function() {
return new CSSOTranslator();
};

41
node_modules/piler/node_modules/csso/lib/util.js generated vendored Normal file
View File

@ -0,0 +1,41 @@
var $util = {};
$util.cleanInfo = function(tree) {
var r = [];
tree = tree.slice(1);
tree.forEach(function(e) {
r.push(Array.isArray(e) ? $util.cleanInfo(e) : e);
});
return r;
};
$util.treeToString = function(tree, level) {
var spaces = $util.dummySpaces(level),
level = level ? level : 0,
s = (level ? '\n' + spaces : '') + '[';
tree.forEach(function(e) {
s += (Array.isArray(e) ? $util.treeToString(e, level + 1) : e.f !== undefined ? $util.ircToString(e) : ('\'' + e.toString() + '\'')) + ', ';
});
return s.substr(0, s.length - 2) + ']';
};
$util.ircToString = function(o) {
return '{' + o.f + ',' + o.l + '}';
};
$util.dummySpaces = function(num) {
return ' '.substr(0, num * 2);
};
$util.printTree = function(tree) {
require('sys').print($util.treeToString(tree));
};
exports.cleanInfo = $util.cleanInfo;
exports.treeToString = $util.treeToString;
exports.printTree = $util.printTree;

35
node_modules/piler/node_modules/csso/package.json generated vendored Normal file
View File

@ -0,0 +1,35 @@
{
"name": "csso",
"description": "CSSO — CSS optimizer",
"version": "1.2.18",
"homepage": "http://github.com/css/csso",
"author": {
"name": "Sergey Kryzhanovsky",
"email": "skryzhanovsky@ya.ru",
"url": "http://github.com/afelix"
},
"repository": {
"type": "git",
"url": "http://github.com/css/csso.git"
},
"bin": {
"csso": "./bin/csso"
},
"main": "./lib/cssoapi",
"engines": {
"node": ">=0.4.0"
},
"licenses": [
{
"type": "MIT"
}
],
"readme": "# 1. Introduction\n\nCSSO (CSS Optimizer) is a CSS minimizer unlike others. In addition to usual minification techniques it can perform structural optimization of CSS files, resulting in smaller file size compared to other minifiers.\n\nThis document describes installation and usage of CSSO. If you want to learn more about the inner workings of CSSO, please consult the [manual] (https://github.com/css/csso/blob/master/MANUAL.en.md).\n\nPlease report issues on [Github] (https://github.com/css/csso/issues).\n\nFor feedback, suggestions, etc. write to <skryzhanovsky@ya.ru>.\n\n# 2. Installation\n\n## 2.1. Prerequisites\n\n* for browser use: any OS and a modern web browser\n* for command line use: Linux / Mac OS X / any OS with working Node.js\n\n## 2.2. Install using git\n\nPrerequisites:\n\n* git&nbsp;— [http://git-scm.com/](http://git-scm.com/)\n\nTo install:\n\n* run `git clone git://github.com/css/csso.git`\n\n## 2.3. Install using npm\n\nPrerequisites:\n\n* nodejs 0.4.x&nbsp;— [http://nodejs.org](http://nodejs.org)\n* npm&nbsp;— [http://github.com/isaacs/npm/](http://github.com/isaacs/npm/)\n\nTo install (global):\n\n* run `npm install csso -g`\n\nTo update:\n\n* run `npm update csso`\n\nTo uninstall:\n\n* run `npm uninstall csso`\n\n# 3. Usage\n\n## 3.1. In the browser\n\nOpen `web/csso.html` or [http://css.github.com/csso/csso.html](http://css.github.com/csso/csso.html) in your browser.\n\n**CSSO is not guaranteed to work in browsers. Preferred way to use this tool is to run it from the command line or via npm modules.**\n\n## 3.2. As an npm module\n\nSample (`test.js`):\n\n var csso = require('csso'),\n css = '.test, .test { color: rgb(255, 255, 255) }';\n\n console.log(csso.justDoIt(css));\nOutput (`> node test.js`):\n\n .test{color:#fff}\nUse `csso.justDoIt(css, true)` to turn structure minimization off.\n\n## 3.3. From the command line\n\nRun `bin/csso` (when installed from git), you will need to have nodejs 0.4.x installed&nbsp;— [http://nodejs.org](http://nodejs.org)\n\nRun `csso` (when installed from npm).\n\nUsage:\n\n csso\n shows usage information\n csso <filename>\n minimizes the CSS in <filename> and outputs the result to stdout\n csso <in_filename> <out_filename>\n csso -i <in_filename> -o <out_filename>\n csso --input <in_filename> --output <out_filename>\n minimizes the CSS in <in_filename> and outputs the result to <out_filename>\n csso -off\n csso --restructure-off\n turns structure minimization off\n csso -h\n csso --help\n shows usage information\n csso -v\n csso --version\n shows the version number\n\nExample:\n\n $ echo \".test { color: red; color: green }\" > test.css\n $ csso test.css\n .test{color:green}\n\n# 4. Minification (in a nutshell)\n\nSafe transformations:\n\n* Removal of whitespace\n* Removal of trailing `;`\n* Removal of comments\n* Removal of invalid `@charset` и `@import` declarations\n* Minification of color properties\n* Minification of `0`\n* Minification of multi-line strings\n* Minification of the `font-weight` property\n\nStructural optimizations:\n\n* Merging blocks with identical selectors\n* Merging blocks with identical properties\n* Removal of overridden properties\n* Removal of overridden shorthand properties\n* Removal of repeating selectors\n* Partial merging of blocks\n* Partial splitting of blocks\n* Removal of empty ruleset and at-rule\n* Minification of `margin` and `padding` properties\n\nThe minification techniques are described in detail in the [manual](https://github.com/css/csso/blob/master/MANUAL.en.md).\n\n# 5. Authors\n\n* initial idea&nbsp;— Vitaly Harisov (<vitaly@harisov.name>)\n* implementation&nbsp;— Sergey Kryzhanovsky (<skryzhanovsky@ya.ru>)\n* english translation&nbsp;— Leonid Khachaturov (leonidkhachaturov@gmail.com)\n\n# 6. And finally\n\n* CSSO is licensed under [MIT](https://github.com/css/csso/blob/master/MIT-LICENSE.txt)\n\n<!-- Yandex.Metrika counter -->\n<img src=\"//mc.yandex.ru/watch/12831025\" style=\"position:absolute; left:-9999px;\" alt=\"\" />\n<!-- /Yandex.Metrika counter -->\n",
"readmeFilename": "README.md",
"_id": "csso@1.2.18",
"dist": {
"shasum": "a0654d594cd5db4efe6d0defbb7995a3a90d7f23"
},
"_from": "csso@1.2.x",
"_resolved": "https://registry.npmjs.org/csso/-/csso-1.2.18.tgz"
}

View File

@ -0,0 +1,6 @@
var translator = require('./translator.js').translator(),
cleanInfo = require('./util.js').cleanInfo;
exports.compress = function(tree, ro) {
return new CSSOCompressor().compress(tree, ro);
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,2 @@
var translator = new CSSOTranslator(),
cleanInfo = $util.cleanInfo;

148
node_modules/piler/node_modules/csso/src/csso.other.js generated vendored Normal file
View File

@ -0,0 +1,148 @@
CSSOParser.prototype.mw = function() {
var s = this._src,
sl = s.length,
f = this._gi() + 1, c, i, v = '';
for (i = f; i < sl; i++) {
c = s.charAt(i);
if (/^[ \n\r\t\f]$/.test(c)) v += c;
else break;
}
if (v.length) {
this._si(f + v.length - 1);
return v;
}
};
CSSOParser.prototype.mnumber = function() {
var s = this._src,
sl = s.length,
f = this._gi() + 1, c, i, v = '',
n0 = '', d = '', n1 = '';
for (i = f; i < sl; i++) {
c = s.charAt(i);
if (/^[\d]$/.test(c)) n0 += c;
else break;
}
if (s[i++] === '.') {
d = '.';
for (; i < sl; i++) {
c = s.charAt(i);
if (/^[\d]$/.test(c)) n1 += c;
else break;
}
}
if ((v = n0 + d + n1).length) {
this._si(f + v.length - 1);
return v;
}
};
CSSOParser.prototype.mident = function() {
var s = this._src,
sl = s.length,
f = this._gi() + 1, i = f, v = '', c, n;
if (s.charAt(i) === '-') v = '-', i++; // special case
c = s.charAt(i); n = s.charAt(i + 1);
if (/^[_$a-zA-Z*]$/.test(c)) v += c; // first char
else if (c === '\\') {
v += c;
if (n) v += n, i++;
} else return;
i++;
for (; i < sl; i++) {
c = s.charAt(i);
n = s.charAt(i + 1);
if (/^[_a-zA-Z0-9\-]$/.test(c)) v += c;
else if (c === '\\') {
v += c;
if (n) v += n, i++;
} else break;
}
if (v && v !== '-') {
this._si(f + v.length - 1);
return v;
}
};
CSSOParser.prototype.mcomment1 = function() {
var s = this._src,
f = this._gi() + 1, v = '', i;
if (s.charAt(f) === '/' && s.charAt(f + 1) === '*') {
if ((i = s.indexOf('*/', f + 2)) !== -1) {
v = s.substring(f + 2, i);
this._si(f + v.length + 3);
} else {
v = s.substr(f + 2);
this._si(f + v.length + 1);
}
return v;
}
};
CSSOParser.prototype.mcomment2 = function() {
var s = this._src,
f = this._gi() + 1, v = '/*', i;
if (s.charAt(f) === '/' && s.charAt(f + 1) === '*') {
if ((i = s.indexOf('*/', f + 2)) !== -1) {
v += s.substring(f + 2, i) + '*/';
this._si(f + v.length - 1);
} else {
v += s.substr(f + 2);
this._si(f + v.length - 1);
}
return v;
}
};
CSSOParser.prototype.mname = function() {
var s = this._src,
sl = s.length,
f = this._gi() + 1, i = f, v = '', c, n;
for (; i < sl; i++) {
c = s.charAt(i);
n = s.charAt(i + 1);
if (/^[_a-zA-Z0-9\-]$/.test(c)) v += c;
else if (c === '\\') {
v += c;
if (n) v += n, i++;
} else break;
}
if (v) {
this._si(f + v.length - 1);
return v;
}
};
CSSOParser.prototype.mname2 = function() {
var s = this._src,
sl = s.length,
f = this._gi() + 1, i = f, v = '', c, n;
for (; i < sl; i++) {
c = s.charAt(i);
n = s.charAt(i + 1);
if (/^[_a-zA-Z0-9]$/.test(c)) v += c;
else if (c === '\\') {
v += c;
if (n) v += n, i++;
} else break;
}
if (v) {
this._si(f + v.length - 1);
return v;
}
};
CSSOParser.prototype.munknown = function() {
var s = this._src,
sl = s.length,
f = this._gi() + 1, i = f, v = '', c, n;
for (; i < sl; i++) {
c = s.charAt(i);
v += c;
if (c === '\n' || c === '\r') break;
}
if (v) {
this._si(f + v.length - 1);
return v;
}
};

190
node_modules/piler/node_modules/csso/src/csso.pecode generated vendored Normal file
View File

@ -0,0 +1,190 @@
pecode CSSOParser {
@t = [#.info, #.name],
@t0 = [#.info, #.name, #0],
@t1 = [#.info, #.name, #1],
@tc0 = [#.info, #.name].concat(#0),
unknown = munknown -> @t0,
mstring1 = !('"', '\\"') -> #0,
mstring2 = !("'", "\\'") -> #0,
mstring = '"' *('\\"', mstring1) '"' -> ('"' + #1.join('') + '"')
| "'" *("\\'", mstring2) "'" -> ("'" + #1.join('') + "'"),
string = mstring -> @t0,
escape = '\\' #char -> ('\\' + #1),
ident = mident -> @t0,
atkeyword = '@' ident -> @t1,
shash = '#' mname -> @t1,
vhash = '#' mname2 -> @t1,
number = mnumber -> @t0,
percentage = number '%' -> @t0,
ident2 = mname2 -> [#.info, 'ident', #0],
dimension = number ident2 -> [#.info, #.name, #0, #1],
cdo = '<!--' -> @t,
cdc = '-->' -> @t,
s = +mw -> [#.info, #.name, #0.join('')],
attrselector = ('=', '~=', '^=', '$=', '*=', '|=', '~') -> @t0,
delim = ',' -> @t,
comment = mcomment1 -> @t0,
sc = (s, comment) -> #0,
tset = (vhash, any, sc, operator) -> #0,
stylesheet = *(cdo, cdc, sc, statement, unknown) -> @tc0,
statement = (ruleset, atrule) -> #0,
atruleb = atkeyword *tset block -> [#.info, #.name, #0].concat(#1, [#2]),
atrules = atkeyword *tset ';' -> [#.info, #.name, #0].concat(#1),
atrulerq = *tset -> @tc0,
atrulers = *sc *ruleset *sc -> [#.info, #.name].concat(#0, #1, #2),
atruler = atkeyword atrulerq '{' atrulers '}' -> [#.info, #.name, #0, #1, #3],
atrule = (atruler, atruleb, atrules) -> #0,
blockdecl = *sc (filter, declaration) decldelim *sc -> [].concat(#0, [#1], [#2], #3)
| *sc (filter, declaration) *sc -> [].concat(#0, [#1], #2)
| *sc decldelim *sc -> [].concat(#0, [#1], #2)
| +sc -> #0,
decldelim = ';' -> @t,
block = '{' *blockdecl '}' -> this._cc([#.info, #.name], #1),
ruleset = *selector block -> [#.info, #.name].concat(#0, [#1]),
combinator = ('+', '>', '~') -> @t0,
attrib = '[' *sc ident *sc attrselector *sc (ident, string) *sc ']' -> [#.info, #.name].concat(#1, [#2], #3, [#4], #5, [#6], #7)
| '[' *sc ident *sc ']' -> [#.info, #.name].concat(#1, [#2], #3),
clazz = '.' ident -> @t1,
pseudoe = '::' ident -> @t1,
pseudoc = ':' (funktion, ident) -> @t1,
pseudo = (pseudoe, pseudoc) -> #0,
nthf = ':' 'nth-' ('child', 'last-child', 'of-type', 'last-of-type') -> [#.info, 'ident', #1 + #2],
nth = +(/^[\d]/1, 'n') -> [#.info, #.name, #0.join('')]
| ('even', 'odd') -> @t0,
nthselector = nthf '(' *(sc, unary, nth) ')' -> [#.info, #.name, #0].concat(#2),
namespace = '|' -> @t,
simpleselector = +(nthselector, combinator, attrib, pseudo, clazz, shash, any, sc, namespace) -> this._cc([#.info, #.name], [#0]),
selector = +(simpleselector, delim) -> @tc0,
declaration = property ':' value -> [#.info, #.name, #0, #2],
filtern = ('-filter', '$filter', '_filter', '*filter', '-ms-filter', 'filter') -> [#.info, 'ident', #0],
filterp = filtern *sc -> [#.info, 'property', #0].concat(#1),
progid0 = !(')', mstring, mcomment2) -> #0,
progid1 = 'progid:DXImageTransform.Microsoft.' /^[a-zA-Z]+/25 '(' +(mstring, mcomment2, progid0) ')' -> [#.info, 'raw', #0 + #1 + '(' + #3.join('') + ')'],
progid = *sc progid1 *sc -> [#.info, #.name].concat(#0, [#1], #2),
filterv = +progid -> @tc0,
filter = filterp ':' filterv -> [#.info, #.name, #0, #2],
identp = '//' mident -> [#.info, 'ident', #0 + #1],
property = identp *sc -> [#.info, #.name, #0].concat(#1)
| ident *sc -> [#.info, #.name, #0].concat(#1),
important = '!' *sc 'important' -> [#.info, #.name].concat(#1),
unary = ('-', '+') -> @t0,
operator = ('/', ',', ':', '=') -> @t0,
uri0 = !(')', mw) -> [#.info, 'raw', #0],
uri = 'url(' *sc string *sc ')' -> [#.info, #.name].concat(#1, [#2], #3)
| 'url(' *sc uri0 *sc ')' -> [#.info, #.name].concat(#1, [#2], #3),
value = +(sc, vhash, any, block, atkeyword, operator, important) -> @tc0,
functionBody = *tset -> @tc0,
funktion = notselector -> #0
| ident '(' functionBody ')' -> [#.info, #.name, #0, #2],
notselectorident = 'not' -> [#.info, 'ident', #0],
notselector = notselectorident '(' notselectorBody ')' -> [#.info, 'funktion', #0, #2],
notselectorBody = ?simpleselector -> [#.info, 'functionBody', #0],
braces = '(' *tset ')' -> [#.info, #.name, '(', ')'].concat(#1)
| '[' *tset ']' -> [#.info, #.name, '[', ']'].concat(#1),
jsLT = ('\n', '\r') -> #0,
jsComment = (jsMLComment, jsSLComment) -> #0,
jsMLComment = '/*' !'*/' '*/' -> (#0 + (#1 ? #1 : '') + #2),
jsSLComment = '//' !jsLT -> ('//' + (#1 ? #1 : '')),
jsString = '"' *jsDSChar '"' -> ('"' + #1.join('') + '"')
| '\'' *jsSSChar '\'' -> ('\'' + #1.join('') + '\''),
jsDSChar = !('"', '\\', jsLT, jsEscapeChar, jsLineContinuation) -> #0
| jsEscapeChar -> #0
| jsLineContinuation -> #0,
jsSSChar = !('\'', '\\', jsLT, jsEscapeChar, jsLineContinuation) -> #0
| jsEscapeChar -> #0
| jsLineContinuation -> #0,
jsLineContinuation = '\\' *jsLT -> ('\\' + #1.join('')),
jsEscapeChar = '\\' #char -> ('\\' + #1),
jsInBraceChar = !('(', ')', jsComment, jsString, jsEscapeChar) -> #0,
jsBracesContent = +(jsComment, jsString, jsEscapeChar, jsInBraceChar) -> #0.join(''),
feb = functionExpressionBody *jsBracesContent -> (#0 + #1.join('')),
functionExpressionBody = '(' +jsBracesContent *feb ')' -> ('(' + #1.join('') + #2.join('') + ')')
| '(' *feb ')' -> ('(' + #1.join('') + ')')
| +jsBracesContent *feb -> (#0.join('') + #1.join('')),
functionExpression = 'expression(' *functionExpressionBody ')' -> [#.info, #.name, #1.join('')],
any = (braces, string, percentage, dimension, number, uri, functionExpression, funktion, ident, unary) -> #0
}

View File

@ -0,0 +1,3 @@
exports.parse = function(s, rule) {
return new CSSOParser().parse(s, rule);
};

View File

@ -0,0 +1,7 @@
exports.translate = function(tree) {
return new CSSOTranslator().translate(tree);
};
exports.translator = function() {
return new CSSOTranslator();
};

View File

@ -0,0 +1,119 @@
function CSSOTranslator() {}
CSSOTranslator.prototype.translate = function(tree) {
return this._t(tree);
};
CSSOTranslator.prototype._m_simple = {
'unary': 1, 'nth': 1, 'combinator': 1, 'ident': 1, 'number': 1, 's': 1,
'string': 1, 'attrselector': 1, 'operator': 1, 'raw': 1, 'unknown': 1
};
CSSOTranslator.prototype._m_composite = {
'simpleselector': 1, 'dimension': 1, 'selector': 1, 'property': 1, 'value': 1,
'filterv': 1, 'progid': 1, 'ruleset': 1, 'atruleb': 1, 'atrulerq': 1, 'atrulers': 1,
'stylesheet': 1
};
CSSOTranslator.prototype._m_primitive = {
'cdo': 'cdo', 'cdc': 'cdc', 'decldelim': ';', 'namespace': '|', 'delim': ','
};
CSSOTranslator.prototype._t = function(tree) {
var t = tree[0];
if (t in this._m_primitive) return this._m_primitive[t];
else if (t in this._m_simple) return this._simple(tree);
else if (t in this._m_composite) return this._composite(tree);
return this[t](tree);
};
CSSOTranslator.prototype._composite = function(t, i) {
var s = '';
i = i === undefined ? 1 : i;
for (; i < t.length; i++) s += this._t(t[i]);
return s;
};
CSSOTranslator.prototype._simple = function(t) {
return t[1];
};
CSSOTranslator.prototype.percentage = function(t) {
return this._t(t[1]) + '%';
};
CSSOTranslator.prototype.comment = function(t) {
return '/*' + t[1] + '*/';
};
CSSOTranslator.prototype.clazz = function(t) {
return '.' + this._t(t[1]);
};
CSSOTranslator.prototype.atkeyword = function(t) {
return '@' + this._t(t[1]);
};
CSSOTranslator.prototype.shash = function(t) {
return '#' + t[1];
};
CSSOTranslator.prototype.vhash = function(t) {
return '#' + t[1];
};
CSSOTranslator.prototype.attrib = function(t) {
return '[' + this._composite(t) + ']';
};
CSSOTranslator.prototype.important = function(t) {
return '!' + this._composite(t) + 'important';
};
CSSOTranslator.prototype.nthselector = function(t) {
return ':' + this._simple(t[1]) + '(' + this._composite(t, 2) + ')';
};
CSSOTranslator.prototype.funktion = function(t) {
return this._simple(t[1]) + '(' + this._composite(t[2]) + ')';
};
CSSOTranslator.prototype.declaration = function(t) {
return this._t(t[1]) + ':' + this._t(t[2]);
};
CSSOTranslator.prototype.filter = function(t) {
return this._t(t[1]) + ':' + this._t(t[2]);
};
CSSOTranslator.prototype.block = function(t) {
return '{' + this._composite(t) + '}';
};
CSSOTranslator.prototype.braces = function(t) {
return t[1] + this._composite(t, 3) + t[2];
};
CSSOTranslator.prototype.atrules = function(t) {
return this._composite(t) + ';';
};
CSSOTranslator.prototype.atruler = function(t) {
return this._t(t[1]) + this._t(t[2]) + '{' + this._t(t[3]) + '}';
};
CSSOTranslator.prototype.pseudoe = function(t) {
return '::' + this._t(t[1]);
};
CSSOTranslator.prototype.pseudoc = function(t) {
return ':' + this._t(t[1]);
};
CSSOTranslator.prototype.uri = function(t) {
return 'url(' + this._composite(t) + ')';
};
CSSOTranslator.prototype.functionExpression = function(t) {
return 'expression(' + t[1] + ')';
};

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